C# use of unassigned variable? - c#

So basically I have a class for a TicTacToe game and a derived class just to practice using inheritance. The class has several methods and all should work perfectly fine but in the main function, when I finally make three objects of the derived class I get three errors "use of unassigned local variable 'boardOne'" "use of unassigned local variable 'boardTwo'" and "use of unassigned local variable 'boardThree'". I do not understand why this is, they are objects, not variables.
public class TicTacToe
{
protected char[] boardCells = new char[9];
public int boardSpacesUsed;
public TicTacToe() //constructor
{
boardCells[0] = '1';
boardCells[1] = '2';
boardCells[2] = '3';
boardCells[3] = '4';
boardCells[4] = '5';
boardCells[5] = '6';
boardCells[6] = '7';
boardCells[7] = '8';
boardCells[8] = '9';
boardCells[9] = '\0';
int boardSpacesUsed = 0;
}
public void playerOneMove()
{
bool space = false;
char cell = '\0';
while (space == false)
{
Console.WriteLine("Please enter cell number you wish to mark: ");
cell = Convert.ToChar(Console.ReadLine());
switch (cell)
{
case '1':
if (boardCells[0] == 'X' || boardCells[0] == 'O')
{
Console.WriteLine("Illegal Move");
}
else
{
boardCells[0] = 'X';
space = true;
}
break;
case '2':
if (boardCells[1] == 'X' || boardCells[1] == 'O')
Console.WriteLine("Illegal Move");
else
{
boardCells[1] = 'X';
space = true;
}
break;
case '3':
if (boardCells[2] == 'X' || boardCells[2] == 'O')
Console.WriteLine("Illegal Move");
else
{
boardCells[2] = 'X';
space = true;
}
break;
case '4':
if (boardCells[3] == 'X' || boardCells[3] == 'O')
Console.WriteLine("Illegal Move");
else
{
boardCells[3] = 'X';
space = true;
}
break;
case '5':
if (boardCells[4] == 'X' || boardCells[4] == 'O')
Console.WriteLine("Illegal Move");
else
{
boardCells[4] = 'X';
space = true;
}
break;
case '6':
if (boardCells[5] == 'X' || boardCells[5] == 'O')
Console.WriteLine("Illegal Move");
else
{
boardCells[5] = 'X';
space = true;
}
break;
case '7':
if (boardCells[6] == 'X' || boardCells[6] == 'O')
Console.WriteLine("Illegal Move");
else
{
boardCells[6] = 'X';
space = true;
}
break;
case '8':
if (boardCells[7] == 'X' || boardCells[7] == 'O')
Console.WriteLine("Illegal Move");
else
{
boardCells[7] = 'X';
space = true;
}
break;
case '9':
if (boardCells[8] == 'X' || boardCells[8] == 'O')
Console.WriteLine("Illegal Move");
else
{
boardCells[8] = 'X';
space = true;
}
break;
default:
Console.WriteLine("Cell Does NOT Exist!");
break;
}// end of switch statement
}//end of while loop
boardSpacesUsed++;
}// end of playerOneMove();
public void CPUMove() //method marks cell for CPU
{
int iCell = 0;
bool space = false;
while (space == false)
{
Random rand = new Random();
iCell = rand.Next(1, 9);
switch (iCell) //switch statement to mark the cell
{
case 1:
if (boardCells[0] == 'X' || boardCells[0] == 'O')
{
space = false;
}
else
{
boardCells[0] = 'O';
space = true;
}
break;
case 2:
if (boardCells[1] == 'X' || boardCells[1] == 'O')
space = false;
else
{
boardCells[1] = 'O';
space = true;
}
break;
case 3:
if (boardCells[2] == 'X' || boardCells[2] == 'O')
space = false;
else
{
boardCells[2] = 'O';
space = true;
}
break;
case 4:
if (boardCells[3] == 'X' || boardCells[3] == 'O')
space = false;
else
{
boardCells[3] = 'O';
space = true;
}
break;
case 5:
if (boardCells[4] == 'X' || boardCells[4] == 'O')
space = false;
else
{
boardCells[4] = 'O';
space = true;
}
break;
case 6:
if (boardCells[5] == 'X' || boardCells[5] == 'O')
space = false;
else
{
boardCells[5] = 'O';
space = true;
}
break;
case 7:
if (boardCells[6] == 'X' || boardCells[6] == 'O')
space = false;
else
{
boardCells[6] = 'O';
space = true;
}
break;
case 8:
if (boardCells[7] == 'X' || boardCells[7] == 'O')
space = false;
else
{
boardCells[7] = 'O';
space = true;
}
break;
case 9:
if (boardCells[8] == 'X' || boardCells[8] == 'O')
space = false;
else
{
boardCells[8] = 'O';
space = true;
}
break;
}
}
boardSpacesUsed++;
}
public void getBoardCells()
{
Console.WriteLine(" " + " " + " | " + " " + " | " + " ");
Console.WriteLine(" " + boardCells[0] + " | " + boardCells[1] + " | " + boardCells[2]);
Console.WriteLine("__" + "_" + "__|__" + "_" + "__|__" + "_");
Console.WriteLine(" " + " " + " | " + " " + " | " + " ");
Console.WriteLine(" " + boardCells[3] + " | " + boardCells[4] + " | " + boardCells[5]);
Console.WriteLine("__" + "_" + "__|__" + "_" + "__|__" + "_");
Console.WriteLine(" " + " " + " | " + " " + " | " + " ");
Console.WriteLine(" " + boardCells[6] + " | " + boardCells[7] + " | " + boardCells[8]);
Console.WriteLine(" " + " " + " | " + " " + " | " + " ");
}
public bool playerOneWinCheck(ref int score)
{
bool check = false;
if (boardCells[0] == 'X' && boardCells[1] == 'X' && boardCells[2] == 'X')
{
check = true;
score++;
}
if (boardCells[3] == 'X' && boardCells[4] == 'X' && boardCells[5] == 'X')
{
check = true;
score++;
}
if (boardCells[6] == 'X' && boardCells[7] == 'X' && boardCells[8] == 'X')
{
check = true;
score++;
}
if (boardCells[0] == 'X' && boardCells[3] == 'X' && boardCells[6] == 'X')
{
check = true;
score++;
}
if (boardCells[1] == 'X' && boardCells[4] == 'X' && boardCells[7] == 'X')
{
check = true;
score++;
}
if (boardCells[2] == 'X' && boardCells[5] == 'X' && boardCells[8] == 'X')
{
check = true;
score++;
}
if (boardCells[0] == 'X' && boardCells[4] == 'X' && boardCells[8] == 'X')
{
check = true;
score++;
}
if (boardCells[6] == 'X' && boardCells[4] == 'X' && boardCells[2] == 'X')
{
check = true;
score++;
}
if (check == true)
return true;
else
return false;
}
public bool CPUWinCheck(ref int score) //Method to check to see if CPU won INCRAMENTS SCORE UP ONE IF ANYTHING HOLDS TRUE
{
bool check = false;
if (boardCells[0] == 'O' && boardCells[1] == 'O' && boardCells[2] == 'O')
{
check = true;
score++;
}
if (boardCells[3] == 'O' && boardCells[4] == 'O' && boardCells[5] == 'O')
{
check = true;
score++;
}
if (boardCells[6] == 'O' && boardCells[7] == 'O' && boardCells[8] == 'O')
{
check = true;
score++;
}
if (boardCells[0] == 'O' && boardCells[3] == 'O' && boardCells[6] == 'O')
{
check = true;
score++;
}
if (boardCells[1] == 'O' && boardCells[4] == 'O' && boardCells[7] == 'O')
{
check = true;
score++;
}
if (boardCells[2] == 'O' && boardCells[5] == 'O' && boardCells[8] == 'O')
{
check = true;
score++;
}
if (boardCells[0] == 'O' && boardCells[4] == 'O' && boardCells[8] == 'O')
{
check = true;
score++;
}
if (boardCells[6] == 'O' && boardCells[4] == 'O' && boardCells[2] == 'O')
{
check = true;
score++;
}
if (check == true)
return true;
else
return false;
}
~TicTacToe()
{
for (int c = 0; c <= 10; c++)
{
boardCells[c] = '\0';
}
boardSpacesUsed = 0;
}
}
public class ThreeD : TicTacToe
{
public void threeDWinCheck(ThreeD boardOne, ThreeD boardTwo, ThreeD boardThree, ref int score) //new function to check to see ThreeD wins
{
if (boardOne.boardCells[0] == 'X' && boardTwo.boardCells[0] == 'X' && boardThree.boardCells[0] == 'X')
{
score++;
Console.WriteLine("did it make it");
}
if (boardOne.boardCells[1] == 'X' && boardTwo.boardCells[1] == 'X' && boardThree.boardCells[1] == 'X')
score++;
if (boardOne.boardCells[2] == 'X' && boardTwo.boardCells[2] == 'X' && boardThree.boardCells[2] == 'X')
score++;
if (boardOne.boardCells[3] == 'X' && boardTwo.boardCells[3] == 'X' && boardThree.boardCells[3] == 'X')
score++;
if (boardOne.boardCells[4] == 'X' && boardTwo.boardCells[4] == 'X' && boardThree.boardCells[4] == 'X')
score++;
if (boardOne.boardCells[5] == 'X' && boardTwo.boardCells[5] == 'X' && boardThree.boardCells[5] == 'X')
score++;
if (boardOne.boardCells[6] == 'X' && boardTwo.boardCells[6] == 'X' && boardThree.boardCells[6] == 'X')
score++;
if (boardOne.boardCells[7] == 'X' && boardTwo.boardCells[7] == 'X' && boardThree.boardCells[7] == 'X')
score++;
if (boardOne.boardCells[8] == 'X' && boardTwo.boardCells[8] == 'X' && boardThree.boardCells[8] == 'X')
score++;
if (boardOne.boardCells[0] == 'X' && boardTwo.boardCells[1] == 'X' && boardThree.boardCells[2] == 'X')
score++;
if (boardOne.boardCells[2] == 'X' && boardTwo.boardCells[1] == 'X' && boardThree.boardCells[0] == 'X')
score++;
if (boardOne.boardCells[3] == 'X' && boardTwo.boardCells[4] == 'X' && boardThree.boardCells[5] == 'X')
score++;
if (boardOne.boardCells[5] == 'X' && boardTwo.boardCells[4] == 'X' && boardThree.boardCells[3] == 'X')
score++;
if (boardOne.boardCells[6] == 'X' && boardTwo.boardCells[7] == 'X' && boardThree.boardCells[8] == 'X')
score++;
if (boardOne.boardCells[8] == 'X' && boardTwo.boardCells[7] == 'X' && boardThree.boardCells[6] == 'X')
score++;
if (boardOne.boardCells[0] == 'X' && boardTwo.boardCells[3] == 'X' && boardThree.boardCells[6] == 'X')
score++;
if (boardOne.boardCells[6] == 'X' && boardTwo.boardCells[3] == 'X' && boardThree.boardCells[0] == 'X')
score++;
if (boardOne.boardCells[1] == 'X' && boardTwo.boardCells[4] == 'X' && boardThree.boardCells[7] == 'X')
score++;
if (boardOne.boardCells[7] == 'X' && boardTwo.boardCells[4] == 'X' && boardThree.boardCells[1] == 'X')
score++;
if (boardOne.boardCells[2] == 'X' && boardTwo.boardCells[5] == 'X' && boardThree.boardCells[8] == 'X')
score++;
if (boardOne.boardCells[8] == 'X' && boardTwo.boardCells[5] == 'X' && boardThree.boardCells[2] == 'X')
score++;
if (boardOne.boardCells[0] == 'X' && boardTwo.boardCells[4] == 'X' && boardThree.boardCells[8] == 'X')
score++;
if (boardOne.boardCells[8] == 'X' && boardTwo.boardCells[4] == 'X' && boardThree.boardCells[0] == 'X')
score++;
if (boardOne.boardCells[2] == 'X' && boardTwo.boardCells[4] == 'X' && boardThree.boardCells[6] == 'X')
score++;
if (boardOne.boardCells[6] == 'X' && boardTwo.boardCells[4] == 'X' && boardThree.boardCells[2] == 'X')
score++;
}
public void CPUThreeDWinCheck(ThreeD boardOne, ThreeD boardTwo, ThreeD boardThree, ref int score) //new function to check CPU ThreeD wins
{
if (boardOne.boardCells[0] == 'O' && boardTwo.boardCells[0] == 'O' && boardThree.boardCells[0] == 'O')
score++;
if (boardOne.boardCells[1] == 'O' && boardTwo.boardCells[1] == 'O' && boardThree.boardCells[1] == 'O')
score++;
if (boardOne.boardCells[2] == 'O' && boardTwo.boardCells[2] == 'O' && boardThree.boardCells[2] == 'O')
score++;
if (boardOne.boardCells[3] == 'O' && boardTwo.boardCells[3] == 'O' && boardThree.boardCells[3] == 'O')
score++;
if (boardOne.boardCells[4] == 'O' && boardTwo.boardCells[4] == 'O' && boardThree.boardCells[4] == 'O')
score++;
if (boardOne.boardCells[5] == 'O' && boardTwo.boardCells[5] == 'O' && boardThree.boardCells[5] == 'O')
score++;
if (boardOne.boardCells[6] == 'O' && boardTwo.boardCells[6] == 'O' && boardThree.boardCells[6] == 'O')
score++;
if (boardOne.boardCells[7] == 'O' && boardTwo.boardCells[7] == 'O' && boardThree.boardCells[7] == 'O')
score++;
if (boardOne.boardCells[8] == 'O' && boardTwo.boardCells[8] == 'O' && boardThree.boardCells[8] == 'O')
score++;
if (boardOne.boardCells[0] == 'O' && boardTwo.boardCells[1] == 'O' && boardThree.boardCells[2] == 'O')
score++;
if (boardOne.boardCells[2] == 'O' && boardTwo.boardCells[1] == 'O' && boardThree.boardCells[0] == 'O')
score++;
if (boardOne.boardCells[3] == 'O' && boardTwo.boardCells[4] == 'O' && boardThree.boardCells[5] == 'O')
score++;
if (boardOne.boardCells[5] == 'O' && boardTwo.boardCells[4] == 'O' && boardThree.boardCells[3] == 'O')
score++;
if (boardOne.boardCells[6] == 'O' && boardTwo.boardCells[7] == 'O' && boardThree.boardCells[8] == 'O')
score++;
if (boardOne.boardCells[8] == 'O' && boardTwo.boardCells[7] == 'O' && boardThree.boardCells[6] == 'O')
score++;
if (boardOne.boardCells[0] == 'O' && boardTwo.boardCells[3] == 'O' && boardThree.boardCells[6] == 'O')
score++;
if (boardOne.boardCells[6] == 'O' && boardTwo.boardCells[3] == 'O' && boardThree.boardCells[0] == 'O')
score++;
if (boardOne.boardCells[1] == 'O' && boardTwo.boardCells[4] == 'O' && boardThree.boardCells[7] == 'O')
score++;
if (boardOne.boardCells[7] == 'O' && boardTwo.boardCells[4] == 'O' && boardThree.boardCells[1] == 'O')
score++;
if (boardOne.boardCells[2] == 'O' && boardTwo.boardCells[5] == 'O' && boardThree.boardCells[8] == 'O')
score++;
if (boardOne.boardCells[8] == 'O' && boardTwo.boardCells[5] == 'O' && boardThree.boardCells[2] == 'O')
score++;
if (boardOne.boardCells[0] == 'O' && boardTwo.boardCells[4] == 'O' && boardThree.boardCells[8] == 'O')
score++;
if (boardOne.boardCells[8] == 'O' && boardTwo.boardCells[4] == 'O' && boardThree.boardCells[0] == 'O')
score++;
if (boardOne.boardCells[2] == 'O' && boardTwo.boardCells[4] == 'O' && boardThree.boardCells[6] == 'O')
score++;
if (boardOne.boardCells[6] == 'O' && boardTwo.boardCells[4] == 'O' && boardThree.boardCells[2] == 'O')
score++;
}
~ThreeD()
{
for (int c = 0; c < 10; c++)
{
boardCells[c] = '\0';
}
}
}
static void Main(string[] args)
{
ThreeD boardOne; //1st of three objects for first board
ThreeD boardTwo; //2nd
ThreeD boardThree; //3rd
int boardSelection = 0; //picks witch object to mark in
int counter = 0; //counter for while loop
int playerOneScore = 0; //score for user
int CPUScore = 0; //score for cpu
int CPUBoardSelection = 0;
Random rand = new Random();
int randomNum = rand.Next(1, 2);
if (randomNum == 1) // if randomNum = 1, user goes first
{
Console.WriteLine("You first");
while (true)
{
boardOne.getBoardCells();
boardTwo.getBoardCells();
boardThree.getBoardCells();
Console.WriteLine("Choose which board you wish to mark in. (1 - 3)"); //promts you to pick board
bool board = false;

Yes, the compiler is right: you're trying to use unassigned variables:
static void Main(string[] args)
{
// It's just a declaration; no value assigned to boardOne; boardOne contains trash
ThreeD boardOne;
// It's just a declaration; no value assigned to boardTwo; boardTwo contains trash
ThreeD boardTwo;
// It's just a declaration; no value assigned to boardThree; boardThree contains trash
ThreeD boardThree;
....
if (randomNum == 1)
{
Console.WriteLine("You first");
while (true)
{
boardOne.getBoardCells(); // <- And here you're trying to access the trash
It should be something like that:
static void Main(string[] args)
{
// boardOne is declared and assigned
ThreeD boardOne = new ThreeD();
// boardTwo is declared and assigned
ThreeD boardTwo = new ThreeD();
// boardThree is declared and assigned
ThreeD boardThree = new ThreeD();
....
if (randomNum == 1)
{
Console.WriteLine("You first");
while (true)
{
boardOne.getBoardCells(); // <- Quite OK

Firstly, boardOne, boardTwo and boardThree are variables, in this case are local variables scoped to the Main() method. Like any other variable, they need a valid data type, in your case the type is the ThreeD class. But this alone don't makes them objects, only defines their data type.
The variables only become objects when you use this class to create a new instance (a new single object in memory). So they must be initialized:
ThreeD boardOne = new ThreeD();
ThreeD boardTwo = new ThreeD();
ThreeD boardThree = new ThreeD();
This way, when the method getBoardCells() is called, each variable points to the object in memory they represent, which contains that method. Without the assignment, the variables are equal null by default. And of course, as null haven't a method getBoardCells() the compiler error you got makes all sense.

You need to instantiate the class:
ThreeD boardOne = new ThreeD();
ThreeD boardTwo = new ThreeD();
ThreeD boardThree = new ThreeD();
If you don't do this you cannot access the non-static class members.

In order to use a local variable, you have to initialize it:
var boardOne = new ThreeD();
var boardTwo = new ThreeD();
...

You have to initialize your board objects becuase C# compiler does not allow the use of uninitialized variables. Check this link : Compiler Error CS0165
static void Main(string[] args)
{
ThreeD boardOne = new ThreeD(); //1st of three objects for first board
ThreeD boardTwo = new ThreeD(); //2nd
ThreeD boardThree = new ThreeD();
//..............
// ..............
}

your missing creating object instance
ThreeD boardOne = new ThreeD();
ThreeD boardTwo = new ThreeD();
ThreeD boardThree = new ThreeD();

Related

How can I prevent players from overwriting one another in tic tac toe?

I have tried to program a tic tac toe game in C# (with the help of tutorials). Overall it seems to be working fine (although the amount of code seems very excessive so sorry for that) but there appears to be one problem: Say, player 1 decides on row 1, column 1 and player 2 does the same afterwards, then player 2 overwrites player 1.
So far, this is the code:
namespace TicTacToe
{
class Program
{
static int turns = 1;
static char[] board =
{
' ',' ',' ',' ',' ',' ',' ',' ',' '
};
static char playerSignature = 'X';
private static void Introduction()
{
Console.WriteLine("This is a simple TicTacToe game. Enter y if you have played before and n if you are new to this.");
string input1 = Console.ReadLine();
Console.Clear();
if (input1 == "n")
{
Console.WriteLine("TicTacToeRules:");
Console.WriteLine("1. The game is played on a grid that's 3 squares by 3 squares.");
Console.WriteLine("2. You are X, your friend is O. Players take turns putting their marks in empty squares.");
Console.WriteLine("3. The first player to get 3 of her marks in a row (up, down, across, or diagonally) is the winner.");
Console.WriteLine("4. When all 9 squares are full, the game is over.");
Console.WriteLine("If you have read the rules, press any key to continue.");
Console.ReadKey();
Console.Clear();
DrawBoard(board);
}
else
{
Console.WriteLine("Alright, let's get started, you are X, your friend is O.");
DrawBoard(board);
}
}
private static void PlayAgain()
{
Console.WriteLine("Play again? y/n");
string playagain = Console.ReadLine();
switch (playagain)
{
case "n":
Console.WriteLine("Thanks for playing!");
Console.Clear();
break;
case "y":
Console.Clear();
ResetBoard();
break;
}
}
private static void DrawBoard(char[] board)
{
string row = "| {0} | {1} | {2} |";
string sep = "|___|___|___|";
Console.WriteLine(" ___ ___ ___ ");
Console.WriteLine(row, board[0], board[1], board[2]);
Console.WriteLine(sep);
Console.WriteLine(row, board[3], board[4], board[5]);
Console.WriteLine(sep);
Console.WriteLine(row, board[6], board[7], board[8]);
Console.WriteLine(sep);
}
private static void ResetBoard()
{
char[] newBoard =
{
' ',' ',' ',' ',' ',' ',' ',' ',' '
};
board = newBoard;
DrawBoard(board);
turns = 0;
}
private static void Draw()
{
Console.WriteLine("It's a draw!\n" +
"Press any key to play again.");
Console.ReadKey();
ResetBoard();
//DrawBoard(board);
}
public static void Main()
{
Introduction();
while(true)
{
bool isrow = false;
bool iscol = false;
int row = 0;
int col = 0;
while (!isrow)
{
Console.WriteLine("Choose a row (1-3): ");
try
{
row = Convert.ToInt32(Console.ReadLine());
}
catch
{
Console.WriteLine("Please enter a number between 1 and 3.");
}
if (row == 1 || row == 2 || row == 3)
{
isrow = true;
}
else
{
Console.WriteLine("\nInvalid row!");
}
}
while (!iscol)
{
Console.WriteLine("Choose a column (1-3): ");
try
{
col = Convert.ToInt32(Console.ReadLine());
}
catch
{
Console.WriteLine("Please enter a number between 1 and 3.");
}
if (col == 1 || col == 2 || col == 3)
{
iscol = true;
}
else
{
Console.WriteLine("\nInvalid column!");
}
}
int[] input = { row, col };
int player = 2;
if (player == 2)
{
player = 1;
XorO(player, input);
}
else
{
player = 2;
XorO(player, input);
}
DrawBoard(board);
turns++;
CheckForDiagonal();
CheckForVertical();
CheckForHorizontal();
if (turns == 10 && (board[0] == playerSignature && board[1] == playerSignature && board[2] == playerSignature && board[3] == playerSignature &&
board[4] == playerSignature && board[5] == playerSignature && board[6] == playerSignature && board[7] == playerSignature && board[8] == playerSignature))
{
Draw();
}
}
}
private static void CheckForVertical()
{
char[] PlayerSignature = { 'O', 'X' };
foreach (char Signature in PlayerSignature)
{
if (board[0] == playerSignature && board[3] == playerSignature && board[6] == playerSignature ||
board[1] == playerSignature && board[4] == playerSignature && board[7] == playerSignature ||
board[2] == playerSignature && board[5] == playerSignature && board[8] == playerSignature)
{
if (playerSignature == 'X')
{
Console.WriteLine("Congratulations Player 1, that's a vertical win!\n" +
"Play again (y/n)?");
string playagain = Console.ReadLine();
if (playagain == "y")
{
Console.Clear();
ResetBoard();
turns = 0;
}
else
{
Console.Clear();
}
}
else
{
Console.WriteLine("Congratulations Player 2, that's a vertical win!\n" +
"Play again (y/n)?");
string playagain = Console.ReadLine();
if (playagain == "y")
{
Console.Clear();
ResetBoard();
turns = 0;
}
else
{
Console.Clear();
}
}
}
}
}
private static void CheckForHorizontal()
{
char[] PlayerSignature = { 'O', 'X' };
foreach (char Signature in PlayerSignature)
{
if (board[0] == playerSignature && board[1] == playerSignature && board[2] == playerSignature ||
board[3] == playerSignature && board[4] == playerSignature && board[5] == playerSignature ||
board[6] == playerSignature && board[7] == playerSignature && board[8] == playerSignature)
{
if (playerSignature == 'X')
{
Console.WriteLine("Congratulations Player 1, that's a horizontal win!\n" +
"Play again (y/n)?");
string playagain = Console.ReadLine();
if (playagain == "y")
{
Console.Clear();
ResetBoard();
turns = 0;
}
else
{
Console.Clear();
}
}
else
{
Console.WriteLine("Congratulations Player 2, that's a horizontal win!\n" +
"Play again (y/n)?");
string playagain = Console.ReadLine();
if (playagain == "y")
{
Console.Clear();
ResetBoard();
turns = 0;
}
else
{
Console.Clear();
}
}
}
}
}
private static void CheckForDiagonal()
{
char[] PlayerSignature = { 'O', 'X' };
foreach (char Signature in PlayerSignature)
{
if (board[6] == playerSignature && board[4] == playerSignature && board[2] == playerSignature ||
board[0] == playerSignature && board[4] == playerSignature && board[8] == playerSignature)
{
if (playerSignature == 'X')
{
Console.WriteLine("Congratulations Player 1, that's a diagonal win!\n" +
"Play again (y/n)?");
string playagain = Console.ReadLine();
if (playagain == "y")
{
Console.Clear();
ResetBoard();
turns = 0;
}
else
{
Console.Clear();
}
}
else
{
Console.WriteLine("Congratulations Player 2, that's a diagonal win!\n" +
"Play again (y/n)?");
string playagain = Console.ReadLine();
if (playagain == "y")
{
Console.Clear();
ResetBoard();
turns = 0;
}
else
{
Console.Clear();
}
}
}
}
}
private static void XorO(int player, int[] input)
{
if (player == 1)
{
playerSignature = 'X';
}
else if (player == 2)
{
playerSignature = 'O';
}
if (input[0] == 1 && input[1] == 1)
{
board[0] = playerSignature;
}
else if (input[0] == 1 && input[1] == 2)
{
board[1] = playerSignature;
}
else if (input[0] == 1 && input[1] == 3)
{
board[2] = playerSignature;
}
else if (input[0] == 2 && input[1] == 1)
{
board[3] = playerSignature;
}
else if (input[0] == 2 && input[1] == 2)
{
board[4] = playerSignature;
}
else if (input[0] == 2 && input[1] == 3)
{
board[5] = playerSignature;
}
else if (input[0] == 3 && input[1] == 1)
{
board[6] = playerSignature;
}
else if (input[0] == 3 && input[1] == 2)
{
board[7] = playerSignature;
}
else if (input[0] == 3 && input[1] == 3)
{
board[8] = playerSignature;
}
}
}
}
I have tried adding something like this: if(input[0] == 1 && input[1] == 1 && (board[0] != 'X' && board[0] != 'O') in the XorO method. But that didn't solve my issue.
Does somebody maybe have some suggestions as to how I can fix that?
You are doing way too much work in some of those methods...
For instance, here's a shorter XorO() method that also makes sure the spot is BLANK before assigning it to a player:
private static void XorO(int player, int[] input)
{
playerSignature = (player == 1) ? 'X' : 'O';
int index = ((input[0] - 1) * 3) + (input[1] - 1);
if (board[index] == ' ') {
board[index] = playerSignature;
}
else {
// ... output an error message? ...
Console.WriteLine("That spot is already taken!");
}
}
Could you maybe explain why you set index the way you did?
Sure! Here is the layout of the board, 3 rows with 3 cols, and the corresponding Index value of each position:
1 2 3
1 0 1 2
2 3 4 5
3 6 7 8
Note that because there are 3 columns, the value of the Index as we move down from one row to the next in the same column goes up by 3. Also note that the starting values in column 1 for each row are 0, 3, and 6, which are all multiples of 3. So to convert your row value from 1, 2, and 3 into 0, 3, and 6, we first subtract 1 from the row value and then multiply it by 3.
Next, each column simply increments by one as you move to the right. Thus we subtract one from the column value and add that to the computed beginning row value. This maps the (row, col) to the indices 0 through 8, seen here as a single dimension array:
1,1 | 1,2 | 1,3 | 2,1 | 2,2 | 2,3 | 3,1 | 3,2 | 3,3
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8
But how was am I supposed to think of something like that? I would
never have thought of that.
It's a fairly common setup to represent a 2D structure in a single dimensional array, known as a compact layout. The math involved to convert a row/column to the equivalent index value or vice-versa is just something that all programmers learn at some point.
Lot of refactoring here, look closely:
class Program
{
static int turns;
static char[] board;
static bool playerOne;
public static void Main(string[] args)
{
Introduction();
bool playAgain = true;
while (playAgain)
{
ResetBoard();
bool gameOver = false;
while (!gameOver)
{
DrawBoard(board);
int row = getNumber(true);
int col = getNumber(false);
if (XorO(row, col)) {
turns++; // valid move was made
String msg = "";
String playerNumber = playerOne ? "1" : "2";
if (CheckForDiagonal())
{
gameOver = true;
msg = "Congratulations Player " + playerNumber + ", that's a diagonal win!";
}
else if (CheckForVertical())
{
gameOver = true;
msg = "Congratulations Player " + playerNumber + ", that's a vertical win!";
}
else if (CheckForHorizontal())
{
gameOver = true;
msg = "Congratulations Player " + playerNumber + ", that's a horizontal win!";
}
else if (turns == 9)
{
gameOver = true;
msg = "It's a draw!";
}
else
{
playerOne = !playerOne;
}
if (gameOver)
{
DrawBoard(board); // show last move
Console.WriteLine(msg);
}
}
}
Console.WriteLine("Play again (y/n)?");
string response = Console.ReadLine().ToLower();
playAgain = (response == "y");
}
}
private static void ResetBoard()
{
turns = 0;
playerOne = true;
board = new char[] {
' ',' ',' ',' ',' ',' ',' ',' ',' '
};
}
private static void Introduction()
{
Console.WriteLine("This is a simple TicTacToe game.\nEnter y if you have played before and n if you are new to this.");
string input1 = Console.ReadLine().ToLower();
Console.Clear();
if (input1 == "n")
{
Console.WriteLine("TicTacToeRules:");
Console.WriteLine("1. The game is played on a grid that's 3 squares by 3 squares.");
Console.WriteLine("2. You are X, your friend is O. Players take turns putting their marks in empty squares.");
Console.WriteLine("3. The first player to get 3 of her marks in a row (up, down, across, or diagonally) is the winner.");
Console.WriteLine("4. When all 9 squares are full, the game is over.");
Console.WriteLine("If you have read the rules, press any key to continue.");
Console.ReadKey();
Console.Clear();
}
else
{
Console.WriteLine("Alright, let's get started, you are X, your friend is O.");
}
}
private static void DrawBoard(char[] board)
{
Console.WriteLine(" ___ ___ ___ ");
for(int r=1; r<=3;r++)
{
Console.Write("|");
for(int c=1; c<=3; c++)
{
Console.Write(" {0} |", board[(r - 1) * 3 + (c - 1)]);
}
Console.WriteLine();
Console.WriteLine("|___|___|___|");
}
}
private static int getNumber(bool row)
{
int value = -1;
string description = row ? "row" : "column";
bool isValid = false;
while (!isValid)
{
Console.Write("Player '" + (playerOne ? "X" : "O") + "', choose a " + description + " (1-3): ");
if (int.TryParse(Console.ReadLine(), out value))
{
if (value >= 1 && value <= 3)
{
isValid = true;
}
else
{
Console.WriteLine("Please enter a number between 1 and 3.");
}
}
else
{
Console.WriteLine("\nInvalid " + description + "!");
}
}
return value;
}
private static bool XorO(int row, int col)
{
int index = ((row - 1) * 3) + (col - 1);
if (board[index] == ' ')
{
board[index] = playerOne ? 'X' : 'O';
return true;
}
else
{
Console.WriteLine("That spot is already taken!");
return false;
}
}
private static bool CheckForDiagonal()
{
return ((board[6] != ' ' && board[4] == board[6] && board[2] == board[6]) ||
(board[0] != ' ' && board[4] == board[0] && board[8] == board[0]));
}
private static bool CheckForVertical()
{
for(int c=0; c<=2; c++)
{
if (board[c] != ' ' && board[c+3] == board[c] && board[c+6] == board[c])
{
return true;
}
}
return false;
}
private static bool CheckForHorizontal()
{
for (int r=0; r<=6; r=r+3)
{
if (board[r] != ' ' && board[r + 1] == board[r] && board[r + 2] == board[r])
{
return true;
}
}
return false;
}
}

Only state once

I am making an RPG sort of text adventure in Visual Studio C# console.
I am trying to create a piece of code that will detect your location. I want it to then respond in the necessary format. I know you can probably do this more effectively with arrays but I'm happy with how it is now. What I want to do is stop it from constantly repeating the message "It worked.". If it only states it once then it has worked. I have tried multiple methods. Please offer a solution to my issues.
Code Here or Underneath
using System;
namespace RPG
{
class MainClass
{
public static void Main(string[] args)
{
//Done(); will check if Cords are at end of game
//variables
string response = "";
string name = "";
bool hastyped = false;
//Coordinates
int xCord = 0; int yCord = 0;
void Done()
{
if (yCord == 5 && xCord == 7)
{
Console.WriteLine("Thanks for playing! You did it!");
}
}
void Move()
{
if (hastyped == true)
{
if (response == "E")
{
xCord = xCord + 1;
}
else if (response == "W")
{
xCord = xCord - 1;
}
else if (response == "N")
{
xCord = xCord + 1;
}
else if (response == "S")
{
xCord = xCord - 1;
}
else
{
Console.WriteLine("That movement is invalid.");
}
hastyped = false;
response = "";
Done();
}
}
//FANCY START LOGO
Console.WriteLine(#"
____________ _____
| ___ \ ___ \ __ \
| |_/ / |_/ / | \/
| /| __/| | __
| |\ \| | | |_\ \
\_| \_\_| \____/
"
);
System.Threading.Thread.Sleep(2500);
while (response != "Y")
{
Console.WriteLine("Please answer with Y for yes and N for no. Please try to answer all questions as simply as possible.\nPlease type N for north, E for east, S for south and W for west.");
Console.WriteLine("Ok?");
response = Console.ReadLine();
if (response == "Y")
{
Console.WriteLine("Well lets start:");
}
else
{
Console.WriteLine("Please try again.");
}
}
//Instructions
Console.WriteLine("LOADING...");
Console.WriteLine("7%");
System.Threading.Thread.Sleep(200);
Console.WriteLine("26 %");
System.Threading.Thread.Sleep(100);
Console.WriteLine("48%");
System.Threading.Thread.Sleep(200);
Console.WriteLine("76%");
System.Threading.Thread.Sleep(600);
Console.WriteLine("87%");
System.Threading.Thread.Sleep(400);
Console.WriteLine("99%");
System.Threading.Thread.Sleep(20);
Console.WriteLine("100%");
//Loading...
Console.WriteLine("Hey buddy, you took that hit pretty hard. Are you alright?");
Console.ReadLine();
Console.WriteLine("Well we need to get you to a hospital.\nSorry, what was your name?");
name = Console.ReadLine();
Console.WriteLine("Well " + name + ", I wish we were meeting under better circumstances.");
Console.WriteLine("Anyway, I'm Dave. Off to the East is a path that looks pretty safe, the only other direction is back to the west where I just found you. So we won't go there.");
Console.WriteLine("YOU MOVED EAST!!!");
xCord = xCord + 1;
//Intro
//GAMEPLAY
while (true)
{
//1,0
if (xCord == 1 && yCord == 0)
{
Console.WriteLine("Hit E then enter for testing.");
response = Console.ReadLine();
hastyped = !string.IsNullOrWhiteSpace(response);
if (hastyped == true)
{
Move();
}
}
//2,0
if (xCord == 2 && yCord == 0)
{
Console.WriteLine("It worked.");
}
//3,0
if (xCord == 3 && yCord == 0)
{
}
//-1,0
if (xCord == -1 && yCord == 0)
{
}
//-2,0
if (xCord == -2 && yCord == 0)
{
}
//-3,0
if (xCord == -3 && yCord == 0)
{
}
//1,1
if (xCord == 1 && yCord == 1)
{
}
//2,1
if (xCord == 2 && yCord == 1)
{
}
//3,1
if (xCord == 3 && yCord == 1)
{
}
//-1,1
if (xCord == -1 && yCord == 1)
{
}
//-2,1
if (xCord == -2 && yCord == 1)
{
}
//-3,1
if (xCord == -3 && yCord == 1)
{
}
//1,2
if (xCord == 1 && yCord == 2)
{
}
//2,2
if (xCord == 2 && yCord == 2)
{
}
//3,2
if (xCord == 3 && yCord == 2)
{
}
//-1,2
if (xCord == -1 && yCord == 2)
{
}
//-2,2
if (xCord == -2 && yCord == 2)
{
}
//-3,2
if (xCord == -3 && yCord == 2)
{
}
//1,3
if (xCord == 1 && yCord == 3)
{
}
//2,3
if (xCord == 2 && yCord == 3)
{
}
//3,3
if (xCord == 3 && yCord == 3)
{
}
//-1,3
if (xCord == -1 && yCord == 3)
{
}
//-2,3
if (xCord == -2 && yCord == 3)
{
}
//-3,3
if (xCord == -3 && yCord == 3)
{
}
//1,-1
if(xCord == 1 && yCord == -1)
{
}
//2,-1
if (xCord == 2 && yCord == -1)
{
}
//3,-1
if (xCord == 3 && yCord == -1)
{
}
//-1,-1
if (xCord == -1 && yCord == -1)
{
}
//-2,-1
if (xCord == -2 && yCord == -1)
{
}
//-3,-1
if (xCord == -3 && yCord == -1)
{
}
//1,-2
if (xCord == 1 && yCord == -2)
{
}
//2,-2
if (xCord == 2 && yCord == -2)
{
}
//3,-2
if (xCord == 3 && yCord == -2)
{
}
//-1,-2
if (xCord == -1 && yCord == -2)
{
}
//-2,-2
if (xCord == -2 && yCord == -2)
{
}
//-3,-2
if (xCord == -3 && yCord == -2)
{
}
//1,-3
if (xCord == 1 && yCord == -3)
{
}
//2,-3
if (xCord == 2 && yCord == -3)
{
}
//3,-3
if (xCord == 3 && yCord == -3)
{
}
//-1,-3
if (xCord == -1 && yCord == -3)
{
}
//-2,-3
if (xCord == -2 && yCord == -3)
{
}
//-3,-3
if (xCord == -3 && yCord == -3)
{
}
//0,3
if (xCord == 0 && yCord == 3)
{
}
//0,2
if (xCord == 0 && yCord == 2)
{
}
//0,1
if (xCord == 0 && yCord == 1)
{
}
//0,0
if (xCord == 0 && yCord == 0)
{
}
//0,-1
if (xCord == 0 && yCord == -1)
{
}
//0,-2
if (xCord == 0 && yCord == -2)
{
}
//0,-3
if (xCord == 0 && yCord == -3)
{
}
//BOUNDARIES:
//RIGHT
if (xCord == 4)
{
Console.WriteLine("This area doesn't exist.");
xCord = xCord - 1;
}
//LEFT
if (xCord == -4)
{
Console.WriteLine("This area doesn't exist.");
xCord = xCord + 1;
}
//TOP
if (yCord == 4)
{
Console.WriteLine("This area doesn't exist.");
yCord = yCord - 1;
}
//BOTTOM
if (yCord == -4)
{
Console.WriteLine("This area doesn't exist.");
yCord = yCord + 1;
}
}
}
}
}
This is a lot of code in one main loop, I would suggest splitting the functionality into more functions.
To answer your question; the reason your console is spamming "It Worked!". Is because your "if" statement is inside a continuous while-loop. You could try adding an extra boolean to your if statement, as such:
//GAMEPLAY
boolean hasMoved = false;
while (true)
{
//2,0
if (xCord == 2 && yCord == 0 && !hasMoved)
{
Console.WriteLine("It worked.");
hasMoved = true;
}
else{
hasMoved = false;
}
why dont you use switch case in place of if else .
also, you can use break; after printing it worked

C# route example

I have a problem with my program. I have no other idea to make it.
Here is my attempt:
public static string routegen(string filename)
{
string[] directions = readwrite.linesread(filename);
int beginx = int.Parse(directions[0].Substring(0,1));
int beginy = int.Parse(directions[0].Substring(2));
string inwhich = "dodecagon";
int dbsquare = 0;
for (int i = 1; i < directions.Length; ++i)
{
if (inwhich == "dodecagon")
{
if (directions[i] == "N") ++beginy;
if (directions[i] == "S") --beginy;
if (directions[i] == "E") ++beginx;
if (directions[i] == "W") --beginx;
if (directions[i] == "WSW" || directions[i] == "ESE") inwhich = "triangletop";
if (directions[i] == "WNW" || directions[i] == "ENE") inwhich = "trianglebottom";
if (directions[i] == "NNE" || directions[i] == "SSE") inwhich = "triangleleft";
if (directions[i] == "NNW" || directions[i] == "SSW") inwhich = "triangleright";
}
if (inwhich == "square")
{
++dbsquare;
if (directions[i] == "N")
{
inwhich = "triangletop";
++beginy;
}
if (directions[i] == "S")
{
inwhich = "trianglebottom";
--beginy;
}
if (directions[i] == "W")
{
inwhich = "triangleleft";
--beginx;
}
if (directions[i] == "E")
{
inwhich = "triangleright";
++beginx;
}
}
if (inwhich == "triangletop")
{
if (directions[i] == "WNW")
{
--beginx;
inwhich = "dodecagon";
}
if (directions[i] == "ENE")
{
++beginx;
inwhich = "dodecagon";
}
if (directions[i] == "S")
{
//--beginy;
inwhich = "square";
}
}
if (inwhich == "trianglebottom")
{
if (directions[i] == "WSW")
{
--beginx;
inwhich = "dodecagon";
}
if (directions[i] == "ESE")
{
++beginx;
inwhich = "dodecagon";
}
if (directions[i] == "N")
{
//++beginy;
inwhich = "square";
}
}
if (inwhich == "triangleleft")
{
if (directions[i] == "NNW")
{
++beginy;
inwhich = "dodecagon";
}
if (directions[i] == "SSW")
{
--beginy;
inwhich = "dodecagon";
}
if (directions[i] == "E")
{
//++beginx;
inwhich = "square";
}
}
if (inwhich == "triangleright")
{
if (directions[i] == "NNE")
{
++beginy;
inwhich = "dodecagon";
}
if (directions[i] == "SSE")
{
--beginy;
inwhich = "dodecagon";
}
if (directions[i] == "W")
{
//--beginx;
inwhich = "square";
}
}
There are dodecagons and between them there are triangles and squares. The program gets the start coordinates from a text file first line ( ex. 1 1 ) and from the other lines it gets the directions ( there are 12 direction: N NNE ENE E ESE SSE S SSW WSW W WNW NNW N).
The task is to give back the final dodecagon coordinates, the number of the squares in the route and the number of the dodecagons which occured more than once.
I attached a picture with an example.
The directions: 1 1 ENE N N ENE E WSW D E SSE
Here is the picture: http://i.stack.imgur.com/ZnxIc.png
The solution: final coordinates: 3 1 squares: 2 decagons occured more than once: 0
Thank you for your help in advance!

C# Validation of Period

I want to ask if anyone knows how to limit the period allowed for a textbox. I'm using C# Visual Studio 2010.
My problem is I need to find validation codes that will ensure that only a single period is allowed for the textbox Middle Initial of the user. And if the user type another period, then the period will not be shown in the textbox. No error messages is needed. Example is the validation code that accept letters only. Here is my code for this example:
private void txtFirstName_KeyPress(object sender, KeyPressEventArgs e)
{
byte num = Convert.ToByte(e.KeyChar);
if ((num >= 65 && num <= 90) || (num >= 97 && num <= 122) || (num == 8) || (num == 32))
{
}
else if (num == 13)
{
e.Handled = true;
SendKeys.Send("{Tab}");
}
else
{
e.Handled = true;
}
}
I have the following codes currently for my txtboxMI:
private void txtMI_KeyPress(object sender, KeyPressEventArgs e)
{
byte num = Convert.ToByte(e.KeyChar);
if ((num >= 65 && num <= 90) || (num >= 97 && num <= 122) || (num == 8) || (num == 32))
{
}
else if (num == 13)
{
e.Handled = true;
SendKeys.Send("{Tab}");
}
else
{
e.Handled = true;
}
}
Do you have to make it server-side?
You can use regular expression validator.
[a-zA-Z_-.] should give you what you want.
Try this:
var txt = (TextBox)sender;
if ((e.KeyChar >= 'A' && e.KeyChar <= 'Z') || (e.KeyChar >= 'a' && e.KeyChar <= 'z') || e.KeyChar == 8 || e.KeyChar == 32) {
} else if (txt.Text.Contains('.') && e.KeyChar == '.') {
e.Handled = true;
} else if (e.KeyChar == '\t') {
e.Handled = true;
SendKeys.Send("{Tab}");
}

Why is this while loop getting stuck?

I just wrote a simple c# code for calculating the factorial of a number but the the program is getting stuck on the last name. Could someone why it's getting stuck?
Thanks,
Omin
using System;
//1. Write a program which finds the factorial of a number entered by the user.
namespace Beginner1{
class ProblemOne
{
static void Main (string[] args)
{
bool play = true;
while ( play ) {
Console.Write ("Type in the number you would like to find Factorial of: ");
int num = Convert.ToInt16( Console.ReadLine ());
int sum = 1;
for (int i = 2; i <= num; i++) {
sum = sum * i;
}
Console.WriteLine ("The Factorial of {0} is {1}", num, sum);
Console.Write ( "Would you like to play again? (Y or N): " );
string ans = Console.ReadLine();
do {
if( ans == "Y" || ans == "y" ) {
play = true;
//break;
}
else if( ans == "N" || ans == "n" ) {
play = false;
//break;
}
else
{
Console.Write( "You have entered an invalid answer. Please choose from either Y or N: ");
ans = Console.ReadLine();
}
} while ( (ans != "Y") || (ans != "y") || (ans != "N") || (ans != "n") );
}
}
}
}
`
Look at your while condition:
while ( (ans != "Y") || (ans != "y") || (ans != "N") || (ans != "n") )
In order to break out, all of those sub-conditions have to be false (so that the overall value is false).
The only way for the first condition to be true is if ans is "Y"... which means it definitely won't be equal to "y"...
In other words, your loop is equal to:
while (!(ans == "Y" && ans == "y" && ans == "N" && ans == "n"))
It would have to be a pretty special string to be equal to all four values.
You actually want:
while (ans != "Y" && ans != "y" && ans != "N" || ans != "n")
In other words, keep going while the value is not equal to any of the desired values. (An alternative would be to keep a set of "good answers"...
do {
string ans = Console.ReadLine();
if( ans == "Y" || ans == "y" ) {
play = true;
//break;
}
else if( ans == "N" || ans == "n" ) {
play = false;
//break;
}
else
{
Console.Write( "You have entered an invalid answer. Please choose from either Y or N: ");
//ans = Console.ReadLine();
}
} while ( (ans != "Y") && (ans != "y") && (ans != "N") && (ans != "n") );
I would do something like this:
bool isValid = false;
do
{
if( ans == "Y" || ans == "y" ) {
play = true;
isValid = true;
//break;
}
else if( ans == "N" || ans == "n" ) {
play = false;
isValid = true;
//break;
}
else
{
Console.Write( "You have entered an invalid answer. Please choose from either Y or N: ");
ans = Console.ReadLine();
isValid = false;
}
}while(isValid == false);
Relevant fiddle:https://dotnetfiddle.net/bxHY27

Categories

Resources