Skip to content

Instantly share code, notes, and snippets.

@tolmicl
Created February 4, 2017 05:37
Show Gist options
  • Save tolmicl/41327a6db3e446a798142c0ff90a31f1 to your computer and use it in GitHub Desktop.
Save tolmicl/41327a6db3e446a798142c0ff90a31f1 to your computer and use it in GitHub Desktop.
p1010
// TicTacToe program
using System;
class p1010
{
private int[,] board = new int[3, 3];
public p1010() //constructor
{
// initialize board with all zeros
for (int i = 0; i < 3; i++) // rows
{
for (int j = 0; j < 3; j++) // columns
{
board[i, j] = 0; // initialize empty board
}
}
}
public void player1Move(int row, int column)
{
board[row, column] = 1;
}
public void player2Move(int row, int column)
{
board[row, column] = 2;
}
public bool checkPlayer1Win()
{
// all possibilities for player 1 to win
return (board[0, 0] == 1 && board[0, 1] == 1 && board[0, 2] == 1
|| board[1, 0] == 1 && board[1, 1] == 1 && board[1, 2] == 1
|| board[2, 0] == 1 && board[2, 1] == 1 && board[0, 2] == 1
|| board[0, 0] == 1 && board[1, 0] == 1 && board[2, 0] == 1
|| board[0, 1] == 1 && board[1, 1] == 1 && board[2, 1] == 1
|| board[0, 2] == 1 && board[1, 2] == 1 && board[2, 2] == 1
// diagonal
|| board[2, 0] == 1 && board[1, 1] == 1 && board[0, 2] == 1
|| board[0, 0] == 1 && board[1, 1] == 1 && board[2, 2] == 1);
}
public bool checkPlayer2Win()
{
// all possibilites for player 2 to win
return (board[0, 0] == 2 && board[0, 1] == 2 && board[0, 2] == 2
|| board[1, 0] == 2 && board[1, 1] == 2 && board[1, 2] == 2
|| board[2, 0] == 2 && board[2, 1] == 2 && board[0, 2] == 2
|| board[0, 0] == 2 && board[1, 0] == 2 && board[2, 0] == 2
|| board[0, 1] == 2 && board[1, 1] == 2 && board[2, 1] == 2
|| board[0, 2] == 2 && board[1, 2] == 2 && board[2, 2] == 2
// diagonal
|| board[2, 0] == 2 && board[1, 1] == 2 && board[0, 2] == 2
|| board[0, 0] == 2 && board[1, 1] == 2 && board[2, 2] == 2);
}
public bool checkEmpty(int row, int col)
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
// if there is a 1 or 2 in the selected row and column
// then this square is not empty or available
if (board[row, col] == 1 || board[row, col] == 2)
{
return false;
}
}
}
return true;
}
public bool checkDraw()
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
// if there is any place within the board
// that has a zero, there are available spots
// so there is not yet a draw
if (board[i, j] == 0)
{
return false;
}
}
}
return true;
}
public void displayBoard()
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
Console.Write(board[i, j] + " ");
}
Console.WriteLine();
}
Console.WriteLine();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment