public void Init() { board = new OthelloBoard(); player1 = new Player("Emily", "black"); player2 = new Player("Berry", "white"); game = new Game(board, player1, player2); }
public void NewHistory() { // New board MoveHistory is empty. OthelloBoard board = new OthelloBoard(); board.MoveHistory.Should().BeEmpty("New board has no history"); }
/// <summary> /// Apply a move in a board /// </summary> /// <param name="move">a given move</param> /// <returns>A tree node with the applied operator</returns> public TreeNode ApplyOp(Tuple <int, int> move) { OthelloBoard newOB = new OthelloBoard(board.GetBoard()); // Make a copy of the board newOB.PlayMove(move.Item1, move.Item2, isWhitePlayer); return(new TreeNode(newOB, !isWhitePlayer)); }
public OthelloView(OthelloBoard myboard, int centerx = 300, int centery = 300, int targetwidth = 480) { _myboard = myboard; // prepare graphics: cell = new AnimationSprite[myboard._height, myboard._width]; for (int row = 0; row < _myboard._height; row++) { for (int col = 0; col < _myboard._width; col++) { AnimationSprite newcell = new AnimationSprite("../../assets/tileset.png", 3, 1); newcell.x = col * newcell.width; newcell.y = row * newcell.width; AddChild(newcell); newcell.SetFrame((_myboard[row, col] + 3) % 3); cell [row, col] = newcell; } } float realwidth = cell [0, 0].width * _myboard._width; scaleX = targetwidth / realwidth; scaleY = targetwidth / realwidth; x = centerx - targetwidth / 2; y = centery - targetwidth / 2; // assuming that we have a square board // set callbacks: _myboard.OnCellChange += CellChangeHandler; _myboard.OnMark += MarkHandler; //_myboard.OnWin += WinHandler; wincells = new List <AnimationSprite> (); }
void Start() { currentField = new OthelloCell[BoardSize, BoardSize]; for (int i = 0; i < BoardSize; i++) { for (int j = 0; j < BoardSize; j++) { currentField[i, j] = new OthelloCell(); } } instance = this; OthelloBoardIsSquareSize(); OthelloCells = new OthelloCell[BoardSize, BoardSize]; float cellAnchorSize = 1.0f / BoardSize; for (int y = 0; y < BoardSize; y++) { for (int x = 0; x < BoardSize; x++) { CreateNewCell(x, y, cellAnchorSize); } } // Nextを出す CreateNewCell(10, 6, cellAnchorSize, false); ScoreBoard.GetComponent <RectTransform>().SetSiblingIndex(BoardSize * BoardSize + 1); GameObject.Destroy(Template); InitializeGame(); }
public void NewValue() { // New board Value is 0. OthelloBoard board = new OthelloBoard(); board.Value.Should().Be(0, "New board value is 0"); }
void Start() { instance = this; OthelloBoardIsSquareSize(); OthelloCells = new OthelloCell[BoardSize, BoardSize]; float cellAnchorSize = 1.0f / BoardSize; for (int y = 0; y < BoardSize; y++) { for (int x = 0; x < BoardSize; x++) { CreateNewCell(x, y, cellAnchorSize); } } ScoreBoard.GetComponent <RectTransform>().SetSiblingIndex(BoardSize * BoardSize + 1); GameObject.Destroy(Template); InitializeGame(); WhiteTurnText.text = "White Turn"; WhiteChipNumberText.text = "Stones\n\n" + WhiteChipNumber; BlackChipNumberText.text = "Stones\n\n" + BlackChipNumber; OthelloCells[2, 2].CellEffectText.text = TurnNumber.ToString(); OthelloCells[3, 3].CellEffectText.text = TurnNumber.ToString(); OthelloCells[2, 3].CellEffectText.text = TurnNumber.ToString(); OthelloCells[3, 2].CellEffectText.text = TurnNumber.ToString(); }
public void NewValue() { // New board Value is 0. OthelloBoard board = new OthelloBoard(); board.CurrentAdvantage.Advantage.Should().Be(0, "New board value is 0"); }
public double Execute(OthelloBoard board, bool max, int depth) { if (depth == MaxDepth) { return(board.HeuristicUtility()); } var children = board.Expand(max ? 1 : 2); if (children.Count == 0) { return(board.HeuristicUtility()); } var result = !max ? double.MaxValue : double.MinValue; foreach (var othelloBoard in children) { var value = Execute(othelloBoard, !max, depth + 1); othelloBoard.UtilityValue = value; result = max ? Math.Max(value, result) : Math.Min(value, result); } if (depth == 0) { _resultMove = children.First(c => c.UtilityValue == result).MoveFrom; } return(result); }
public void APieceCanOnlyBePlacedIfALineEndsInAPieceOfTheSameColour() { var board = new OthelloBoard(); var counter1 = new Counter { Colour = "black" }; var counter2 = new Counter { Colour = "white" }; var counter3 = new Counter { Colour = "black" }; var counter4 = new Counter { Colour = "white" }; board.AcceptPlay("E3", counter1); Assert.That(board.ViewBoardSquare("E3"), Is.Not.EqualTo(counter1)); board.AcceptPlay("D3", counter1); Assert.That(board.ViewBoardSquare("D3"), Is.EqualTo(counter1)); board.AcceptPlay("D2", counter2); Assert.That(board.ViewBoardSquare("D2"), Is.Not.EqualTo(counter2)); board.AcceptPlay("C3", counter2); Assert.That(board.ViewBoardSquare("C3"), Is.EqualTo(counter2)); board.AcceptPlay("C4", counter3); Assert.That(board.ViewBoardSquare("C4"), Is.EqualTo(counter3)); board.AcceptPlay("E3", counter4); Assert.That(board.ViewBoardSquare("E3"), Is.EqualTo(counter4)); }
int ChooseOthelloMove(OthelloBoard current) { List <int> moves = current.GetMoves(); int ID = current.GetActivePlayer(); int bestscore = -64; // worst possible score int bestmoveindex = 0; for (int i = 0; i < moves.Count; i++) { OthelloBoard clone = (OthelloBoard)current.Clone(); clone.MakeMove(moves [i]); int newscore = clone.CountStones() * ID; // Grabbing corners = always good: if (moves [i] == 0 || moves [i] == 7 || moves [i] == 56 || moves [i] == 63) { newscore += 50; } if (newscore > bestscore) { bestscore = newscore; bestmoveindex = i; } } return(moves[bestmoveindex]); }
/// <summary> /// Recovers the game /// </summary> /// <param name="state">String representing the state of the board to be recovered</param> /// <param name="isWhiteMove">Bool represeting who is on the move (true if it's whites move, false if it's blacks move)</param> /// <param name="isHost">Bool representing if the person whos game is beeing recovered was host (true if the client was host, otherwise false)</param> public void RecoverGame(string state, bool isWhiteMove, bool isHost) { OthelloBoard game = GameObject.Find("Board").GetComponent <OthelloBoard>(); Client c = FindObjectOfType <Client>(); c.isHost = isHost; game.RecoverGame(state, isWhiteMove); }
/// <summary> /// Score function. Return a score for a given board. /// </summary> /// <returns>Returns a score for a given board</returns> public int Score() { int score = 0; int[,] theBoard = board.GetBoard(); int playerVal = isWhitePlayer ? 1 : 0; // Get the player value in the board array for (int i = 0; i < theBoard.GetLength(1); i++) { for (int j = 0; j < theBoard.GetLength(0); j++) { int boardValue = theBoard[j, i]; if (boardValue != -1) { if (boardValue == playerVal) { score += OthelloBoard.SCORE_MATRIX[j, i]; // Add the matrix score if is the correct player } else { score -= OthelloBoard.SCORE_MATRIX[j, i]; // Substract the matrix score if is the other player } } } } Tuple <int, int> nbPawns = OthelloBoard.CountPawn(theBoard, playerVal); score += 25 * ((nbPawns.Item1 + nbPawns.Item2 + 1) % 2); //Add a weight if the current user play the last move score += 25 * ((nbPawns.Item1 - nbPawns.Item2) / (nbPawns.Item1 + nbPawns.Item2)); //Add a weight from the pawn parity Tuple <int, int> nbCorners = OthelloBoard.CountCorner(theBoard, playerVal); if (nbCorners.Item1 + nbCorners.Item2 != 0) { score += 100 * (nbCorners.Item1 - nbCorners.Item2) / (nbCorners.Item1 + nbCorners.Item2);//Add weight from the number of captured corner } // If the state is final if (IsFinal()) { // If the score is positive, the user win if (score > 0) { return(Int32.MaxValue - 1); } else // If the score is negative, the user loose { return(Int32.MinValue + 1); } } return(score); }
/// <summary> /// Called when the start button is pressed <para/> /// Initialises the <see cref="mcts"/> tree search object and instantiates the root node <para/> /// Also creates as many starting nodes as the user specified /// </summary> public void StartButtonPressed() { //Create an empty board instance, which will have whatever game the user chooses assigned to it Board board; //Assign whatever game board the user has chosen to the board instance switch (HashUIController.GetGameChoice) { case 0: board = new TTTBoard(); displayBoardModel = false; break; case 1: board = new C4Board(); displayBoardModel = true; //Create a C4 Board GameObject and obtain a reference to its BoardModelController Component GameObject boardModel = Instantiate(Resources.Load("C4 Board", typeof(GameObject))) as GameObject; boardModelController = boardModel.GetComponent <BoardModelController>(); boardModelController.Initialise(); break; case 2: board = new OthelloBoard(); displayBoardModel = false; break; default: throw new System.Exception("Unknown game type index has been input"); } mcts = new TreeSearch <Node>(board); //Calculate the position of the root node and add an object for it to the scene Vector3 rootNodePosition = BoardToPosition(mcts.Root.GameBoard); GameObject rootNode = Instantiate(Resources.Load("HashNode"), rootNodePosition, Quaternion.identity) as GameObject; rootNode.transform.parent = transform; rootNode.GetComponent <HashNode>().AddNode(null, mcts.Root, false); rootNode.GetComponent <HashNode>().Initialise(rootNodePosition); //Add the root node to the position and object map nodePositionMap.Add(rootNodePosition, rootNode); nodeObjectMap.Add(mcts.Root, rootNode); //Create the amount of starting nodes specified by the user for (int i = 0; i < HashUIController.GetStartingNodeInput(); i++) { PerformStep(true); } //Swap out the current menu panels HashUIController.SetMenuPanelActive(false); HashUIController.SetNavigationPanelActive(true); }
public void ValueAfterMultiDirectionMove() { // Value updated correctly after doing a multi-directional move. OthelloBoard board = new OthelloBoard(); board.ApplyMove(new OthelloMove(new BoardPosition(3, 2))); board.ApplyMove(new OthelloMove(new BoardPosition(4, 2))); board.Value.Should().Be(0); board.ApplyMove(new OthelloMove(new BoardPosition(5, 2))); board.Value.Should().Be(5); }
public void APieceCanOnlyBePlacedNextToAPieceOfTheOppositeColour(string gridRef, bool result) { var board = new OthelloBoard(); var counter = new Counter { Colour = "black" }; board.AcceptPlay(gridRef, counter); Assert.That(board.ViewBoardSquare(gridRef) == counter, Is.EqualTo(result)); }
public OthelloViewModel() { mBoard = new OthelloBoard(); mSquares = new ObservableCollection <OthelloSquare>( BoardPosition.GetRectangularPositions(8, 8) .Select(p => new OthelloSquare() { Position = p, Player = mBoard.GetPlayerAtPosition(p) }) ); PossibleMoves = new HashSet <BoardPosition>(mBoard.GetPossibleMoves().Select(m => m.Position)); }
public OthelloBoard(OthelloBoard orig) : base(orig._width, orig._height) { feasiblemove = new byte[_height, _width]; feasiblemovelist = new List <int> (); for (int i = 0; i < _height; i++) { for (int j = 0; j < _width; j++) { board [i, j] = orig.board[i, j]; } } activeplayer = orig.activeplayer; movesmade = orig.movesmade; }
public ActionResult StartGame(string playerOneName, string playerTwoName) { var gameBoard = new OthelloBoard(); var playerOne = new Player(playerOneName, "black"); var playerTwo = new Player(playerTwoName, "white"); var newGame = new Game(gameBoard, playerOne, playerTwo); var gameModel = new GameModel { Board = gameBoard, Player1 = playerOne, Player2 = playerTwo, Game = newGame }; Session["currentGame"] = gameModel; return(View(gameModel)); }
public OthelloViewModel() { mBoard = new OthelloBoard(); mSquares = new ObservableCollection <OthelloSquare>( from pos in ( from r in Enumerable.Range(0, 8) from c in Enumerable.Range(0, 8) select new BoardPosition(r, c) ) select new OthelloSquare() { Position = pos, Player = mBoard.GetPieceAtPosition(pos) } ); PossibleMoves = new HashSet <BoardPosition>(mBoard.GetPossibleMoves().Select(m => m.Position)); }
public string BoardToString(OthelloBoard board) { StringBuilder str = new StringBuilder(); str.AppendLine("- 0 1 2 3 4 5 6 7"); for (int i = 0; i < OthelloBoard.BOARD_SIZE; i++) { str.Append(i); str.Append(" "); for (int j = 0; j < OthelloBoard.BOARD_SIZE; j++) { int space = board.GetPlayerAtPosition(new BoardPosition(i, j)); str.Append(LABELS[space]); str.Append(" "); } str.AppendLine(); } return(str.ToString()); }
public OthelloViewModel() { mBoard = new OthelloBoard(); // Initialize the squares objects based on the board's initial state. mSquares = new ObservableCollection <OthelloSquare>( BoardPosition.GetRectangularPositions(8, 8) .Select(pos => new OthelloSquare() { Position = pos, Player = mBoard.GetPlayerAtPosition(pos) }) ); PossibleMoves = new HashSet <BoardPosition>( from OthelloMove m in mBoard.GetPossibleMoves() select m.Position ); }
void Start() { instance = this; OthelloBoardIsSquareSize(); OthelloCells = new OthelloCell[BoardSize, BoardSize]; float cellAnchorSize = 1.0f / BoardSize; for (int y = 0; y < BoardSize; y++) { for (int x = 0; x < BoardSize; x++) { CreateNewCell(x, y, cellAnchorSize); } } ScoreBoard.GetComponent <RectTransform>().SetSiblingIndex(BoardSize * BoardSize + 1); GameObject.Destroy(Template); InitializeGame(); }
public OthelloViewModel() { mBoard = new OthelloBoard(); // Initialize the squares objects based on the board's initial state. mSquares = new ObservableCollection <OthelloSquare>( from pos in ( from r in Enumerable.Range(0, 8) from c in Enumerable.Range(0, 8) select new BoardPosition(r, c) ) select new OthelloSquare() { Position = pos, Player = mBoard.GetPieceAtPosition(pos) } ); PossibleMoves = new HashSet <BoardPosition>( from OthelloMove m in mBoard.GetPossibleMoves() select m.Position ); }
// Start is called before the first frame update /// <summary> /// Generates start chips, initializes game varibales and visualises legal moves /// </summary> void Start() { Instance = this; client = FindObjectOfType <Client>(); if (client) { isWhite = !client.isHost; } else { isWhite = false; } isWhiteTurn = false; legalMoveDotsContainer = new GameObject(); legalMoveDotsContainer.name = "LegalMoves"; GenerateStartChips(); legalMoves = CalculateLegalMoves(chips, isWhiteTurn); VisualiseLegalMoves(); }
public static void Main(string[] args) { IGameBoard board = null; IConsoleView view = null; // Use a game name from the command line, or default to chess. string gameName = args.Length == 1 ? args[0] : "chess"; switch (gameName) { case "othello": board = new OthelloBoard(); view = new OthelloConsoleView(); break; case "chess": board = new ChessBoard(); view = new ChessConsoleView(); break; } while (!board.IsFinished) { Console.WriteLine(view.BoardToString(board)); Console.WriteLine(); Console.WriteLine("Possible moves:"); IEnumerable <IGameMove> possMoves = board.GetPossibleMoves(); Console.WriteLine(string.Join(", ", possMoves.Select(view.MoveToString))); Console.WriteLine("It is {0}'s turn.", view.PlayerToString(board.CurrentPlayer)); Console.WriteLine("Enter a command: "); string input = Console.ReadLine(); if (input.StartsWith("move")) { IGameMove toApply = view.ParseMove(input.Substring(5)); IGameMove foundMove = possMoves.SingleOrDefault(toApply.Equals); if (foundMove == null) { Console.WriteLine("Sorry, that move is invalid."); } else { board.ApplyMove(foundMove); } } else if (input.StartsWith("undo")) { if (!int.TryParse(input.Split(' ')[1], out int undoCount)) { undoCount = 1; } for (int i = 0; i < undoCount && board.MoveHistory.Count > 0; i++) { board.UndoLastMove(); } } else if (input.StartsWith("history")) { Console.WriteLine("Move history:"); Console.WriteLine(string.Join(Environment.NewLine, board.MoveHistory.Reverse().Select( m => view.PlayerToString(m.Player) + ":" + view.MoveToString(m)))); } else if (input.StartsWith("advantage")) { var adv = board.CurrentAdvantage; if (adv.Player == 0) { Console.WriteLine("No player has an advantage."); } else { Console.WriteLine("{0} has an advantage of {1}.", view.PlayerToString(adv.Player), adv.Advantage); } } Console.WriteLine(); Console.WriteLine(); } }
public void SimulateTest() { OthelloBoard board = new OthelloBoard(); board.SimulateUntilEnd(); }
/// <summary> /// Constructor of TreeNode /// </summary> /// <param name="board">Instance of the primary board</param> /// <param name="isWhitePlayer">indicated if the player is white or black</param> public TreeNode(OthelloBoard board, bool isWhitePlayer) { this.isWhitePlayer = isWhitePlayer; this.board = board; }
public void PossibleMovesTest() { OthelloBoard board = new OthelloBoard(); Assert.AreEqual(board.PossibleMoves().Count, 4); }
static void Main(string[] args) { // The model and view for the game. OthelloBoard board = new OthelloBoard(); OthelloView view = new OthelloView(); while (true) { // Print the view. Console.WriteLine(); Console.WriteLine(); view.PrintView(Console.Out, board); Console.WriteLine(); Console.WriteLine(); // Print the possible moves. var possMoves = board.GetPossibleMoves(); Console.WriteLine("Possible moves:"); Console.WriteLine(String.Join(", ", possMoves)); // Print the turn indication. Console.WriteLine(); Console.Write("{0}'s turn: ", view.GetPlayerString(board.CurrentPlayer)); // Parse user input and apply their command. string input = Console.ReadLine(); if (input.StartsWith("move ")) { // Parse the move and validate that it is one of the possible moves before applying it. OthelloMove move = view.ParseMove(input.Substring(5)); bool foundMove = false; foreach (var poss in possMoves) { if (poss.Equals(move)) { board.ApplyMove(poss); foundMove = true; break; } } if (!foundMove) { Console.WriteLine("That is not a possible move, please try again."); } } else if (input.StartsWith("undo ")) { // Parse the number of moves to undo and repeatedly undo one move. int undoCount = Convert.ToInt32(input.Substring(5)); while (undoCount > 0 && board.MoveHistory.Count > 0) { board.UndoLastMove(); undoCount--; } } else if (input == "showHistory") { // Show the move history in reverse order. Console.WriteLine("History:"); bool playerIsBlack = board.CurrentPlayer != 1; // if board.CurrentPlayer == 1, then black is CURRENT player, not the most recent player. foreach (var move in board.MoveHistory.Reverse()) { Console.WriteLine("{0}: {1}", move.Player == 1 ? "Black" : "White", move); } } else if (input == "showAdvantage") { Console.WriteLine("Advantage: {0} in favor of {1}", board.CurrentAdvantage.Advantage, board.CurrentAdvantage.Player == 1 ? "Black" : "White"); } } }