Last active
April 4, 2016 03:02
-
-
Save exectails/7340e41ae6859c6d5d4207566a212bb8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Collections.Generic; | |
| using System.Linq; | |
| using System.Text; | |
| namespace ConsoleApplication1 | |
| { | |
| class Program | |
| { | |
| static FieldValue[,] fields = new FieldValue[3, 3]; | |
| static FieldValue turn = FieldValue.X; | |
| static void Main(string[] args) | |
| { | |
| while (true) | |
| { | |
| DisplayField(); | |
| var winner = CheckWinner(); | |
| if (winner != FieldValue.Empty) | |
| { | |
| Console.WriteLine(winner + " won!"); | |
| break; | |
| } | |
| Turn(); | |
| } | |
| Console.ReadLine(); | |
| } | |
| static void DisplayField() | |
| { | |
| Console.Clear(); | |
| for (int y = 0; y < 3; ++y) | |
| { | |
| for (int x = 0; x < 3; ++x) | |
| { | |
| var chr = fields[y, x] == FieldValue.Empty ? "_" : fields[y, x].ToString(); | |
| Console.Write(chr + " "); | |
| } | |
| Console.WriteLine(); | |
| Console.WriteLine(); | |
| } | |
| } | |
| static void Turn() | |
| { | |
| while (true) | |
| { | |
| if (turn == FieldValue.X) | |
| Console.Write("X: "); | |
| else | |
| Console.Write("O: "); | |
| var move = Console.ReadLine(); | |
| var split = move.Split(','); | |
| int x, y; | |
| if (split.Length != 2 || !int.TryParse(split[0], out x) || !int.TryParse(split[1], out y)) | |
| { | |
| Console.WriteLine("Invalid move, try again."); | |
| continue; | |
| } | |
| fields[y, x] = turn; | |
| turn = (turn == FieldValue.X ? FieldValue.O : FieldValue.X); | |
| break; | |
| } | |
| } | |
| static FieldValue CheckWinner() | |
| { | |
| for (int y = 0; y < 3; ++y) | |
| { | |
| if (fields[y, 0] != 0 && fields[y, 0] == fields[y, 1] && fields[y, 1] == fields[y, 2]) | |
| return fields[y, 0]; | |
| } | |
| for (int x = 0; x < 3; ++x) | |
| { | |
| if (fields[0, x] != 0 && fields[0, x] == fields[1, x] && fields[1, x] == fields[2, x]) | |
| return fields[0, x]; | |
| } | |
| if (fields[0, 0] != 0 && fields[0, 0] == fields[1, 1] && fields[1, 1] == fields[2, 2]) | |
| return fields[0, 0]; | |
| if (fields[0, 2] != 0 && fields[0, 2] == fields[1, 1] && fields[1, 1] == fields[2, 0]) | |
| return fields[0, 2]; | |
| return FieldValue.Empty; | |
| } | |
| enum FieldValue | |
| { | |
| Empty, | |
| X, | |
| O, | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment