Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Threading;
- using System.Linq;
- using static System.Console;
- class Program {
- public static void Main() {
- new Board("Niggy1", "Niggy2").Start();
- }
- }
- class Board {
- private class Block {
- public string Mark;
- public int Number { get; }
- public bool IsOccupied => Mark != Number.ToString();
- public Block(int number) {
- Number = number;
- Mark = number.ToString();
- }
- public override string ToString()
- => Mark;
- }
- private class Player {
- public string Mark { get; }
- public string Name;
- public Player(char mark)
- => Mark = mark.ToString();
- }
- const string Seperator = "+---+---+---+";
- const string RowFormat = "| {0} | {1} | {2} |";
- Player Player1 { get; } = new Player('X');
- Player Player2 { get; } = new Player('O');
- Block[] blocks = Enumerable.Range(1, 10).Select(i => new Block(i)).ToArray();
- (int Index, int Step)[] winSeqs = { (0, 1), (3, 1), (6, 1), (0, 3), (1, 3), (2, 3), (0, 4), (6, -2) };
- (int Index, int Step) winningSequence = default;
- public Board(string p1Name = "Player1", string p2Name = "Player2") {
- Player1.Name = p1Name;
- Player2.Name = p2Name;
- }
- public void Start() {
- Player[] players = { Player1, Player2 };
- int turn = 0;
- while(true) {
- if(turn == 9) {
- Clear();
- WriteLine("\x1B[31mNIGGERS!\x1B[0m");
- break;
- }
- Clear();
- var p = players[turn++ % 2];
- Display();
- Write($"{ p.Name }'s turn: ");
- if(! int.TryParse(ReadLine(), out int c) || ! Update(c - 1, p.Mark)) {
- WriteLine("Try again, nigger.");
- turn--;
- Thread.Sleep(1000);
- continue;
- }
- if(CheckWin()) {
- DisplayWinner(p);
- break;
- }
- }
- }
- public bool Update(int index, string mark) {
- if(index < 0 || index > 8 || blocks[index].IsOccupied)
- return false;
- blocks[index].Mark = mark;
- return true;
- }
- public void Display() {
- DisplayRow(prevLine: Seperator, rowIndex: 0, nextLine: Seperator);
- DisplayRow(1, nextLine: Seperator);
- DisplayRow(2, nextLine: Seperator);
- }
- public bool CheckWin() {
- winningSequence = winSeqs.SingleOrDefault(s => CheckSequence(s.Index, s.Step));
- return winningSequence.Step != 0;
- }
- bool CheckSequence(int index, int step) {
- bool check(int i) => blocks[i].Mark == blocks[index].Mark;
- return new[] { index, index + step, index + step + step}.All(check);
- }
- void DisplayRow(int rowIndex, string prevLine = "", string nextLine = "") {
- int i = rowIndex * 3;
- if(prevLine != "") WriteLine(prevLine);
- WriteLine(string.Format(RowFormat, blocks[i++], blocks[i++], blocks[i]));
- WriteLine(nextLine);
- }
- void DisplayWinner(Player p) {
- Clear();
- int i = winningSequence.Index, s = winningSequence.Step;
- blocks[i].Mark = blocks[i+s].Mark = blocks[i+s+s].Mark = $"\x1B[32m{p.Mark}\x1B[0m";
- Display();
- WriteLine($"\x1B[32mA WINRAR IS {p.Name}!\x1B[0m");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement