Click here to Skip to main content
15,888,984 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Quote:
I want to get the whole program running time normally and with a few threads, but I do not know where to write the code.please help me write code with threading an serial


What I have tried:

C#
<blockquote class="quote"><div class="op">Quote:</div>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace WindowsFormsApp2
{
    public partial class frm_main : Form
    {
        int shoutCount = 0;//تعداد موشک های شلیک شده
        int missShout = 0;//تعدا موشک های خطا رفته

        PictureBox[,] enemies;//ماتریس دشمنان
        int enemiesRow = 0;//تعداد سطر های دشمنان
        int enemiesCol = 0;//تعداد ستون های دشمنان

        int verticalSpace = 0;//فاصله عمودی بین دشمنان
        int horizontalSpace = 0;//فاصله افقی بین دشمنان
        int sizeOfEnemies = 0;//اندازه دشمنان
        int totalSize = 0;//مجموع کل اندازه ماتریس

        int speed = 0;//برای کنترل سرعت دشمنان استفاده می شود
        int slider = 0;//برای کنترل خارح نشدن دشمنان از صفحه استفاده می شود 
        bool isItEndOfPage = true;

        //string Theme = "";

        int playerScore = 0;//برای نگاه داری امتیاز کاربر
        string path = @"C:\Users\Y\Desktop\yazdan.txt";//مسیر ذخیره اطلاعات بازیکن

        public frm_main()//اولین متدی که در هنگام ساخت فرم نمایش داده می شود
        {
            
            InitializeComponent();
            cmb_Theme.SelectedIndex = 0;//برای اینکه اولین عضو انتخاب شود
            rdb_Keyboard.Checked = true;//شلیک با کیبورد را بطور پیش فرض در نظر می گیرد
            this.Size = new Size(1280, 800);//سایز صفحه رو درست تنظیم می کنیم تا در رزولشون های مختلف خراب نشود
        }

        private void frm_main_Load(object sender, EventArgs e)
        {
            //اضافه کردن کنترل ها به ptb_backGround
            ptb_backGround.Controls.Add(ptb_spaceShip);
            ptb_backGround.Controls.Add(lbl_shoutCount);
            ptb_backGround.Controls.Add(lbl_shoutCountText);
            ptb_backGround.Controls.Add(lbl_missShout);
            ptb_backGround.Controls.Add(lbl_missShoutText);
            //ptb_backGround.Controls.Add(lblScore);
            //ptb_backGround.Controls.Add(lblScoreText);
            load();
        }

        private void btn_start_Click(object sender, EventArgs e)
        {
            ListViewItem item = new ListViewItem(new[] { "MajidOnline", "1000", "2015/12/09" });
            lsv_playerScoreAsc.Items.Add(item);
            ListViewItem item2 = new ListViewItem(new[] { "Artiman Studio", "900", "2015/12/09" });
            lsv_playerScoreAsc.Items.Add(item2);

            //تنظیمات اولیه بازی
            gpb_userInfo.Enabled = false;
            gpb_gameInfo.Enabled = false;
            btn_start.Enabled = false;
            btn_stop.Enabled = true;
            ptb_backGround.Enabled = true;
            ptb_spaceShip.Visible = true;
            ptb_spaceShip.Focus();
            lbl_shoutCount.Visible = true;
            lbl_shoutCountText.Visible = true;
            lbl_missShout.Visible = true;
            lbl_missShoutText.Visible = true;
            //lblScore.Visible = true;
            //lblScoreText.Visible = true;

            tmr_main.Start();//با فراخوانی این متد تایمر شروع به کار می کند

            totalSize = (enemiesCol * sizeOfEnemies) + ((enemiesCol - 1) * horizontalSpace);//محاسبه طول کل ماتریس

            if (totalSize >= 900 || totalSize <= 0)
            {
                enemiesCol = 5;
                enemiesRow = 4;
                sizeOfEnemies = 50;
                horizontalSpace = verticalSpace = 20;
                totalSize = (enemiesCol * sizeOfEnemies) + ((enemiesCol - 1) * horizontalSpace);
            }
            slider = totalSize;
            speed = 5;

            enemies = new PictureBox[enemiesCol, enemiesRow];

            for (int i = 0; i < enemiesCol; i++)
            {
                for (int j = 0; j < enemiesRow; j++)
                {
                    enemies[i, j] = new PictureBox();
                    enemies[i, j].Size = new Size(sizeOfEnemies, sizeOfEnemies);

                    ptb_backGround.Controls.Add(enemies[i, j]);
                    int x = i * (sizeOfEnemies + horizontalSpace);
                    int y = j * (sizeOfEnemies + verticalSpace);
                    enemies[i, j].Location = new Point(x, y);

                }

            }
        }

        private void btn_exit_Click(object sender, EventArgs e)
        {
            save();
            exitFromTheGame();//فراخوانی تابع خروج از برنامه
        }

        public static void exitFromTheGame()
        {
            Application.Exit();
        }

        private void btn_stop_Click(object sender, EventArgs e)
        {
            frm_pauseMessage f = new frm_pauseMessage();//ساخت فرم نمایش پیغام
            f.ShowDialog();//نمایش فرم نمایش پیغام
        }

        private void ptb_backGround_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.X <= ptb_spaceShip.Size.Width / 2)//زمانی که 
            {
                ptb_spaceShip.Location = new Point(0, ptb_spaceShip.Location.Y);
            }
            else if (e.X + ptb_spaceShip.Size.Width / 2 >= ptb_backGround.Size.Width)
            {
                ptb_spaceShip.Location = new Point(ptb_backGround.Size.Width - ptb_spaceShip.Size.Width, ptb_spaceShip.Location.Y);

            }
            else
                ptb_spaceShip.Location = new Point(e.X - (ptb_spaceShip.Size.Width / 2), ptb_spaceShip.Location.Y);
        }

        private void ptb_backGround_Click(object sender, EventArgs e)
        {
            if (rdb_Mouse.Checked == true)
                fire();
        }
        void fire()
        {
            Button rocket = new Button();
            rocket.Size = new Size(30, 30);


            rocket.Location = ptb_spaceShip.Location;
            rocket.FlatStyle = FlatStyle.Flat;
            rocket.FlatAppearance.BorderSize = 0;


            //****************موقعیت دهی موشک****************************************


            //برای ساده تر شدن موقعیت دهی به موشک از این متغییرها استفاده می کنیم
            //در جلسه دهم قسمت موقعیت موشک توضیح داده شده است

            //SSPX mokhafaf shode ye SpaceShipLocationX ast
            int SSLX = ptb_spaceShip.Location.X;//موقعیت افقی سفینه

            //SSPX mokhafaf shode ye SpaceShipLocationY ast
            int SSLY = ptb_spaceShip.Location.Y;//موقعیت عمودی سفینه

            //SSW mokhafaf shode ye SpaceShipWidth ast
            int SSW = ptb_spaceShip.Width;//عرض سفینه

            //RW mokhafaf shode ye RocketWidth ast
            int RW = rocket.Width;//عرض موشک

            //موقعیت دادن به موشک با استفاده از متغییرهای کمکی بالا
            rocket.Location = new Point(SSLX + ((SSW / 2) - RW / 2), SSLY);

            //*************************************************************************
            ptb_backGround.Controls.Add(rocket);
            shoutCount++;
            lbl_shoutCount.Text = shoutCount.ToString();
        }
        private void frm_main_KeyDown(object sender, KeyEventArgs e)
        {
            if (rdb_Keyboard.Checked == true)

                if (e.KeyData == Keys.Space)

                    fire();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            foreach (Control element in ptb_backGround.Controls)
            {
                if (element is Button)
                {
                    element.Location = new Point(element.Location.X, element.Location.Y - 10);

                    if (element.Location.Y <= (enemiesRow * sizeOfEnemies) + (enemiesRow * verticalSpace) - verticalSpace)
                    {
                        for (int i = 0; i < enemiesCol; i++)
                        {
                            for (int j = 0; j < enemiesRow; j++)
                            {

                                if (!enemies[i, j].IsDisposed)
                                {

                                    //******************تعریف متغییرهای کمکی جهت سادگی کد********************

                                    //elementLY mokhafaf shode ye elementLocationY ast.
                                    int elementLY = element.Location.Y;//موقعیت عمودی موشک را در خود دارد      

                                    //مختصات افقی نقطه میانی موشک را در خود نگه داری می کند
                                    int elementMiddlePoint = element.Location.X + (element.Size.Width / 2);


                                    //مختصات نقطه شروع دشمن را روی محور عمودی در خود نگه داری می کند
                                    int startEnemieY = enemies[i, j].Location.Y;

                                    //مختصات نقطه شروع دشمن را روی محور افقی در خود نگه داری می کند
                                    int startEnemyX = enemies[i, j].Location.X;

                                    //مختصات نقطه پایان دشمن را روی محور عمودی در خود نگه داری می کند
                                    int endEnemyY = startEnemieY + enemies[i, j].Size.Height;

                                    //مختصات نقطه شروع پایان را روی محور افقی در خود نگه داری می کند
                                    int endEnemyX = startEnemyX + enemies[i, j].Size.Width;

                                    //****************************************************************************

                                    if (elementLY >= startEnemieY && elementLY <= endEnemyY)
                                    {
                                        if (elementMiddlePoint >= startEnemyX && elementMiddlePoint <= endEnemyX)
                                        {
                                            ptb_backGround.Controls.Remove(element);//موشک را از لیست کنترل های پس زمینه کسر می کنیم
                                            ptb_backGround.Controls.Remove(enemies[i, j]);//دشمن را از لیست کنترل های پس زمینه کسر می کنیم

                                            element.Dispose();//منابع در اختیار موشک را آزاد کردیم
                                            enemies[i, j].Dispose();//منابع در اختیار دشمن را آزاد کردیم

                                            playerScore += 5;
                                            lblScore.Text = playerScore.ToString();
                                        }
                                    }
                                }
                            }
                        }

                    }


                    if (element.Location.Y <= 0)
                    {
                        ptb_backGround.Controls.Remove(element);
                        element.Dispose();
                        missShout++;
                        lbl_missShout.Text = missShout.ToString();

                        if (playerScore > 0)
                        {
                            playerScore -= 5;
                            lblScore.Text = playerScore.ToString();
                        }

                    }
                }

                if (element is PictureBox && element.Name != "ptb_spaceShip")
                {
                    if (isItEndOfPage == true)
                        element.Location = new Point(element.Location.X + speed, element.Location.Y);

                    else if (isItEndOfPage == false)
                        element.Location = new Point(element.Location.X - speed, element.Location.Y);
                }

            }
            if (slider >= spc_main.Panel2.Size.Width)
                isItEndOfPage = false;

            else if (slider < totalSize)
                isItEndOfPage = true;

            if (isItEndOfPage == true)
                slider += speed;

            else if (isItEndOfPage == false)
                slider -= speed;
        }

        void save()
        {
            //عملیات ذخیره سازی در این متد انجام می شود
            File.AppendAllText(path, txt_username.Text + "\\" + playerScore.ToString() +
                                    "\\" + DateTime.Now.ToShortDateString() + Environment.NewLine);

            tmr_main.Stop();
            MessageBox.Show("Name : " + txt_username.Text + "\n" + "Score : " + playerScore.ToString());

        }

        void load()
        {
            try
            {
                if (File.Exists(path))
                {
                    string[] list = File.ReadAllLines(path);
                    foreach (string data in list)
                    {
                        string[] part = data.Split('\\');
                        ListViewItem item = new ListViewItem(new[] { part[0], part[1], part[2] });
                        lsv_playerScoreAsc.Items.Add(item);

                    }
                }
            }
            catch
            {
                MessageBox.Show("یک مشکل در برقراری ارتباط با فایل ذخیره سازی بوجود آمده است");
            }
            //عملیات بازیابی در این متد نوشته می شود
        }
    }
      
}
</blockquote>
Posted
Updated 22-Dec-21 8:19am

I would recommend you start with background worker instead. And if you need more control you should use asynchronous Tasks instead:
Task Class (System.Threading.Tasks) | Microsoft Docs[^]
 
Share this answer
 
Your game seems pretty simple. It doesn't look like threading is going to help you at all.

You cannot draw or otherwise touch controls from a background thread and that's where most of your time is spent. Very little of your code is handling user input and updating game state.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900