I am a novice programmer (5 days experience), I am making a simple tic tac toe code to learn more about C#.
My problem is the value of variable Turn doesn't change after returning a new value from the method PlayerTurn.
I guess the problem is from this static vs non static which is so confusing to me
MainClass
using gamemainbody;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MehdiTicTacToe
{
class Program
{
static void Main(string[] args)
{
GameMainBody GMB = new GameMainBody();
int Turn = 0; // 1 if player turn else 0
string[] TheBoard = new string[9];
GMB.PlayerTurn(Turn);
Console.WriteLine(Turn);
GMB.Board(TheBoard);
Console.ReadLine();
}
}
}
Class 1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace gamemainbody
{
class GameMainBody
{
private string[] theBoard;
private int turn;
public int Turn {
get => turn;
set => turn = value; }
public string[] TheBoard {
get => theBoard;
set => theBoard = value; }
public void Board(string[] TheBoard)
{
this.TheBoard = TheBoard;
Console.WriteLine(" | | ");
Console.WriteLine(" {0} | {1} | {2}", TheBoard[0], TheBoard[1], TheBoard[2]);
Console.WriteLine("_____|_____|_____ ");
Console.WriteLine(" | | ");
Console.WriteLine(" {0} | {1} | {2}", TheBoard[3], TheBoard[4], TheBoard[5]);
Console.WriteLine("_____|_____|_____ ");
Console.WriteLine(" | | ");
Console.WriteLine(" {0} | {1} | {2}", TheBoard[6], TheBoard[7], TheBoard[8]);
Console.WriteLine(" | | ");
}
public int PlayerTurn(int Turn)
{
this.Turn = Turn;
Console.WriteLine("Type X if you chose X");
Console.WriteLine("Type O if you chose O");
string UserInput = Console.ReadLine();
if (UserInput == "X" || UserInput == "x")
{
Console.WriteLine("PlayerTurn");
Turn += 1;
return Turn;
}
if (UserInput == "O" || UserInput == "o")
{
Turn = 0;
Console.WriteLine("AI Turn");
return Turn;
}
else
{
Turn -= 1;
return Turn;
}
}
public void GameCore(int Turn, string[] Board)
{
}
}
}
After running this code, i printed the value of variable Turn and it's value was 0 still.
Thanks for helping!