Skip to content

Instantly share code, notes, and snippets.

@inxanedev
Created April 5, 2020 20:14
Show Gist options
  • Save inxanedev/03f19a83a1fa855eb5e4a71517c09541 to your computer and use it in GitHub Desktop.
Save inxanedev/03f19a83a1fa855eb5e4a71517c09541 to your computer and use it in GitHub Desktop.
TicTacToe by inxane (C#)
using System;
using System.Text;
namespace TicTacToe
{
class Program
{
static void Main(string[] args)
{
Random rand = new Random();
char[,] board = new char[3, 3];
char currentPlayer, winner;
currentPlayer = rand.Next(0, 2) == 0 ? 'X' : 'O'; // Random player
for (int x = 0; x < 3; x++) {
for (int y = 0; y < 3; y++) {
board[x, y] = ' ';
}
}
while (true) {
Console.SetCursorPosition(0, 0);
DrawBoard(ref board);
Console.WriteLine("Current turn: " + currentPlayer);
bool swapPlayer = HandleKey(ref board, int.Parse(Console.ReadKey(true).KeyChar.ToString()), currentPlayer);
if (swapPlayer) currentPlayer = currentPlayer == 'X' ? 'O' : 'X'; // Swap player
winner = CheckWins(ref board);
if (winner == 'X' || winner == 'O' || winner == 'D') break;
}
Console.Clear();
if (winner != 'D') {
Console.WriteLine(winner + " wins!");
} else {
Console.WriteLine("No one won - it's a draw!");
}
Console.ReadKey(true);
}
static void DrawBoard(ref char[,] board)
{
StringBuilder output = new StringBuilder();
for (int x = 0; x < 3; x++) {
output.Append(String.Format(" {0} | {1} | {2}\n",
board[x, 0],
board[x, 1],
board[x, 2]
));
if (x != 2) output.Append("-----------\n");
}
Console.WriteLine(output.ToString());
}
static bool HandleKey(ref char[,] board, int key, char player)
{
int row = -1;
int column = -1;
if (key >= 7 && key <= 9) {
row = 0;
column = key - 7;
} else if (key >= 4 && key <= 6) {
row = 1;
column = key - 4;
} else if (key >= 1 && key <= 3) {
row = 2;
column = key - 1;
}
if (row != -1 && column != -1 && board[row, column] == ' ') {
board[row, column] = player;
return true;
} else {
return false;
}
}
static char CheckWins(ref char[,] board)
{
// Horizontal
for (int x = 0; x <= 2; x++) {
if (TripleEqual(board[x, 0], board[x, 1], board[x, 2])) {
return board[x, 0];
}
}
// Vertical
for (int x = 0; x <= 2; x++) {
if (TripleEqual(board[0, x], board[1, x], board[2, x])) {
return board[0, x];
}
}
// Diagonal Top-Left
if (TripleEqual(board[0, 0], board[1, 1], board[2, 2])) {
return board[0, 0];
}
// Diagonal Top-Right
if (TripleEqual(board[0, 2], board[1, 1], board[2, 0])) {
return board[0, 2];
}
// Draw
bool draw = true;
for (int x = 0; x <= 2; x++) {
for (int y = 0; y <= 2; y++) {
if (board[x, y] == ' ') {
draw = false;
}
}
}
if (draw) return 'D';
return ' ';
}
static bool TripleEqual(char a, char b, char c)
{
return (a == b && b == c);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment