Jump to content

Need help with Threads

Go to solution Solved by Nineshadow,

Debug it a little yourself.

Does the AI thread resume when it should? Use a debugger or print/write something everytime that happens.

Some comments would help , like what each attribute of MainWindow represents , and what each function should do broadly.

Hey guys,

 

So after I have finished up Hangman I am right now working on TicTacToe. Currently I am working on an AI which you can play against. Right now I am just doing an Easy Ai which has no intelligence at all and only does it with random numbers. Right now I got the problem that sometimes the AI doesn't respond at all for some reason. I used events to Resume/Pause the Thread instead of using Suspend and Resume. The thing is without the Resume/Pause event I do not have the problem of the Ai doing nothing suddenly, but why I am doing Pausing and Resuming is to save the processor work if I am right, because it stops checking if's and so on and my Thread doesn't get processor time. The other reason would be that my turn stuff so that the AI or the Players turn it is in a new game. But that doesn't work always too.

 

My Code:

I added a spoiler because it is abit of code  :DxD. Right now I am still working with WPF but after I finished this project I will redo it with MVVM. Would be nice if you could give me input if there is something I am doing completely wrong code wise. Pls be aware I am still in the learning phase and I appriciate every input.

[spoiler = My Code]

namespace TicTacToe{    /// <summary>    /// Interaction logic for MainWindow.xaml    /// </summary>    public partial class MainWindow : Window    {        char turn = 'p', PvPoPvA = 'p', Dif = 'E';                 //PvPoPvA means Player vs Player or Player vs AI        int clickedfield = 0, P1Score = 0, P2Score = 0;        public char[] Fieldcontent = new char[] {'0', '0', '0', '0', '0', '0', '0', '0', '0', };   //Reference to the 3x3 field        public int WIDTH, HEIGHT, Aifield;        public bool checkeddif = false;        public Random rnd = new Random();        public ImageSource Image;        public Thread WinCheck, AI;        public ManualResetEvent _pauseEventAI = new ManualResetEvent(true), _pauseEventWC = new ManualResetEvent(true);        public MainWindow()        {            InitializeComponent();            WinCheck = new Thread(new ThreadStart(WC_Main));            WinCheck.IsBackground = true;            WinCheck.Start();            AI = new Thread(new ThreadStart(ArtificialIntelligence));            AI.IsBackground = true;            WIDTH = (int)BrTL.ActualWidth;            HEIGHT = (int)BrTL.ActualHeight;        }        private void NextGame_Click(object sender, RoutedEventArgs e)        {            //Setting every Image and Button back to defaultsettings.            DefaultSettings();            //Setting back the reference to the content inside of the images to 0            for(int i = 0; i < Fieldcontent.Length; i++)            {                Fieldcontent[i] = '0';            }            Checking if Playing vs Ai was selected and if it is AI's turn            if(PvPoPvA == 'a' && turn == 'a')            {                //Starting the AI Thread                _pauseEventAI.Set();            }            BTL.IsEnabled = true;            BML.IsEnabled = true;            BBL.IsEnabled = true;            BTM.IsEnabled = true;            BMM.IsEnabled = true;            BBM.IsEnabled = true;            BTR.IsEnabled = true;            BMR.IsEnabled = true;            BBR.IsEnabled = true;            NextGame.Visibility = Visibility.Hidden;            //Starting the Wincheck Thread(Basically checks if somebody won).            _pauseEventWC.Set();        }       public void Turn()        {            //Checking if the turn is player1 and if the gamemode Player vs Player was selected            if(turn == 'p' && PvPoPvA == 'p')            {                FigureCross();                turn = 'a';                Fieldcontent[clickedfield] = 'x';            }            //Checking if the turn is player2 and if the gamemode Player vs Player was selected            else if(turn == 'a' && PvPoPvA == 'p')            {                FigureCircle();                turn = 'p';                Fieldcontent[clickedfield] = 'o';            }            //Checking if the turn is player and if the gamemode Player vs AI was selected            else if (turn == 'p' && PvPoPvA == 'a')            {                FigureCross();                //setting turn to a so the programm knows it is AI's turn                turn = 'a';                //Putting a x inside of the clicked field, represents players Cross                Fieldcontent[clickedfield] = 'x';                //Checking if AI Thread is already started                if(AI.IsAlive == false)                {                    //if AI thread was not started then start now                    AI.Start();                }                //Resuming AI Thread because it will be AI's turn                _pauseEventAI.Set();            }        }         //Thread for the AI        public void ArtificialIntelligence()        {            while(true)            {                //Wait event, so the Thread doesn't get Processing time while not needed                _pauseEventAI.WaitOne();                //Using Dispatcher to check if the RadioButton was checked.                Dispatcher.Invoke((Action)delegate                {                    if (Easy.IsChecked == true && checkeddif == false)                    {                        Dif = 'E';                        checkeddif = true;                    }                });                Dispatcher.Invoke((Action)delegate                {                    if (Middle.IsChecked == true && checkeddif == false)                    {                        Dif = 'M';                        checkeddif = true;                    }                });                Dispatcher.Invoke((Action)delegate                {                    if (Hard.IsChecked == true && checkeddif == false)                    {                        Dif = 'H';                        checkeddif = true;                    }                });                //Checking if current turn is AI                if(turn == 'a')                {                    //Checking which Difficulty was selected                    switch (Dif)                    {                        case 'E':                            AIEasy();                            break;                        case 'M':                            AIMiddle();                            break;                        case 'H':                            AIHard();                            break;                    }                    //Pausing AI thread, waiting for Player to click again.                    _pauseEventAI.Reset();                }            }        }}

 

Back to the topic now. Can anybody help me why I got problems with the Resume/Pause Event. Be aware that the event which has problems is _pauseEventAI. I added everything which had to do with the change of the turn variable cause I thought that could be another problem why the AI is not responding but I didnt find anything D:

 

Hope you guys can help me out,

RockyLocky

Link to comment
https://linustechtips.com/topic/520453-need-help-with-threads/
Share on other sites

Link to post
Share on other sites

Debug it a little yourself.

Does the AI thread resume when it should? Use a debugger or print/write something everytime that happens.

Some comments would help , like what each attribute of MainWindow represents , and what each function should do broadly.

i5 4670k @ 4.2GHz (Coolermaster Hyper 212 Evo); ASrock Z87 EXTREME4; 8GB Kingston HyperX Beast DDR3 RAM @ 2133MHz; Asus DirectCU GTX 560; Super Flower Golden King 550 Platinum PSU;1TB Seagate Barracuda;Corsair 200r case. 

Link to comment
https://linustechtips.com/topic/520453-need-help-with-threads/#findComment-6920306
Share on other sites

Link to post
Share on other sites

Debug it a little yourself.

Does the AI thread resume when it should? Use a debugger or print/write something everytime that happens.

Some comments would help , like what each attribute of MainWindow represents , and what each function should do broadly.

oh ok look into it again.

Link to comment
https://linustechtips.com/topic/520453-need-help-with-threads/#findComment-6922561
Share on other sites

Link to post
Share on other sites

@Nineshadow updated the code and did some comments.

 

 

EDIT: I found my mistake. For everybody who is intrested my mistake was that If the random number of the field which the AI is trying to change already has a x or an o in it it will skip my switch then it will just Pause my thread and my thread will never place anything so I just changed it with a flag.

 

 

@Nineshadow Would you mind if I ask you something?

Link to comment
https://linustechtips.com/topic/520453-need-help-with-threads/#findComment-6923403
Share on other sites

Link to post
Share on other sites

@Nineshadow Would you mind if I ask you something?

Sure, go ahead.

i5 4670k @ 4.2GHz (Coolermaster Hyper 212 Evo); ASrock Z87 EXTREME4; 8GB Kingston HyperX Beast DDR3 RAM @ 2133MHz; Asus DirectCU GTX 560; Super Flower Golden King 550 Platinum PSU;1TB Seagate Barracuda;Corsair 200r case. 

Link to comment
https://linustechtips.com/topic/520453-need-help-with-threads/#findComment-6923535
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×