public async Task<Game> PerformMoveAsync(long id, string playerID, long tokenID, Point point) { var game = await this.repository.GetAsync(id); var attacker = game.GameBoard.GetByID(tokenID); if (attacker == null) { throw new InvalidTokenException(string.Format("Token with ID {0} does not exist.", tokenID)); } else if (attacker.PlayerID != playerID) { throw new InvalidTokenException(string.Format("Token with ID {0} does not belong to player {1}.", tokenID, playerID)); } // Validate move var validMoves = game.GameBoard.GetValidMoves(attacker); if (!validMoves.Any()) { throw new InvalidMoveException(string.Format("No moves valid for token {0}.", tokenID)); } else if (!validMoves.Contains(point)) { throw new InvalidMoveException(string.Format("Move {{ {0} }} is not valid.", point)); } // Perform move var move = new GameMove(attacker, point); game.MoveToken(move); await repository.SaveAsync(game); return game; }
public static void Play([Required] string gameFile, [Required, FileExists] string movesFile) { Log.Logger = new LoggerConfiguration() .WriteTo.LiterateConsole() .MinimumLevel.Debug() .CreateLogger(); ImmutableBubbleBurstGrid grid; using (var stream = File.OpenRead($"Games//{gameFile}")) { grid = BubbleGridBuilder.Create(new StreamReader(stream)); } var state = new GameMove(grid); var movesJson = File.ReadAllText(movesFile); var moves = JsonConvert.DeserializeObject<List<Point>>(movesJson); state.GridState.Display(); var lastScore = 0; foreach (var move in moves) { Console.WriteLine(); Console.WriteLine($"({move.X}, {move.Y})"); state = state.BurstBubble(move); Console.WriteLine($"{state.Score - lastScore} points scored this time ({state.Score} total)"); state.GridState.Display(); Thread.Sleep(1000); lastScore = state.Score; } }
private void MakeMove(IGame game, GameMove move) { int playerInt = game.isPlayerOneTurn() ? 0 : 1; switch (move.type) { case MoveType.ADD: { game.PlayCard(playerInt, move.x1, move.y1, move.card); break; } case MoveType.SWAP: { game.SwapCards(playerInt, move.x1, move.y1, move.x2, move.y2); break; } case MoveType.REMOVE: { game.RemoveCard(playerInt, move.x1, move.y1); break; } case MoveType.PEEK: { game.addPeekToKnown(move.x1, move.x2); break; } } }
//点击反馈页面 private void TouchOnclick() { //选项页面隐藏 optionPanel.gameObject.SetActive(false); //帮助页面隐藏 helpPanel.gameObject.SetActive(false); //排行页面隐藏 rankingPanel.gameObject.SetActive(false); //红包页面隐藏 //liuliu.cardManager.redpagPanel.gameObject.SetActive(false); //红包生成物隐藏 //liuliu.cardManager.Tag.gameObject.SetActive(false); GameMove gameMove = MessageManager.GetInstance.GetUIDict <GameMove>(); if (gameMove != null) { //结算页面返回 gameMove.BackBtnOnclick(); //历史记录页面返回 gameMove.HistoryBunkoClose(); //上庄页面返回 gameMove.UPbankerBackBtnOnclick(); //中奖记录页面返回 gameMove.awardRecordBackOnclick(); } //触摸页面隐藏 TouchPanel.gameObject.SetActive(false); }
public void Player1MoveDoesNotBeatOrDrawWithPlayer2MovePlayer2Wins() { // Arrange const GameMove player1Move = GameMove.Rock; const GameMove player2Move = GameMove.Paper; var mockgameMoveOutcomeDataProvider = new Mock <IGameMoveOutcomeDataProvider>(); var gameMoveOutcomes = new List <GameMoveOutcomes> { new GameMoveOutcomes { Move = player1Move, Beats = new List <GameMove> { GameMove.Scissors } } }; mockgameMoveOutcomeDataProvider.Setup(m => m.AllGameMoveOutcomes).Returns(gameMoveOutcomes); var roundCalculator = new RoundCalculator(mockgameMoveOutcomeDataProvider.Object); // Act var result = roundCalculator.CalculateRoundResult(player1Move, player2Move); // Assert Assert.AreEqual(Result.Player2Wins, result); }
/// <summary> /// Add move into history before doing it on chessboard! /// </summary> /// <param name="move"></param> /// <param name="turn"></param> /// <param name="chessboard"></param> public void Add(GameMove move, ChessColor turn, Chessboard chessboard) { var chessPiece = chessboard.GetChessPiece(move.From); if (turn == ChessColor.White) { WhiteMoves.Add(move); } else { BlackMoves.Add(move); } CheckCastlingPossibility(chessPiece, move); var cacheCode = chessboard.Board.GetHashCode(); if (PositionsRepeatedTimes.ContainsKey(cacheCode)) { PositionsRepeatedTimes[cacheCode]++; } else { PositionsRepeatedTimes.Add(cacheCode, 1); } }
//本局开始 public override void start0() { CardManager cardManager = MessageManager.GetInstance.GetUIDict <CardManager>(); UIWanRenChang uIWanRenChang = MessageManager.GetInstance.GetUIDict <UIWanRenChang>(); GameMove gameMove = MessageManager.GetInstance.GetUIDict <GameMove>(); if (cardManager != null) { cardManager.BetCountdown(); cardManager.Clear(); } if (uIWanRenChang != null) { uIWanRenChang.Clear(2); } if (gameMove != null) { gameMove.Gamestaremove(); } if (cardManager != null) { //播放发牌动画 cardManager.deal(); } }
public GameMove PickGameMove(ref IGame game, GameMove prevPlayerMove) { if (prevPlayerMove != null) { foreach (SkyNetNode pMove in rootNode.children) { if (pMove.move.Equals(prevPlayerMove)) { curGameHead = pMove; string bStr = game.getBoardAsString(game.getBoard(), !game.isPlayerOneTurn()); string hStr = game.getHandAsString(!game.isPlayerOneTurn()); Debug.Assert((curGameHead.boardHash + curGameHead.hand).Equals(bStr + hStr)); } } } DateTime curTime = DateTime.UtcNow; DateTime endTime = DateTime.UtcNow.AddSeconds(maxWait); int curITer = 0; while (DateTime.Compare(curTime, endTime) < 0) { MCTSSingleIteration(game.CopyGame(), ref curGameHead, curITer, curGameHead.level); curITer++; curTime = DateTime.UtcNow; } SkyNetNode toRet = MCTSSelect(curGameHead, 1, 1); return(toRet.move); }
internal MakeMoveData( [NotNull] GameMove move, Piece movedPiece, Piece capturedPiece, [CanBeNull] GameMove castlingRookMove, [CanBeNull] Square?enPassantCapturedPieceSquare) { if (movedPiece == Piece.None) { throw new ArgumentException("Invalid moved piece.", nameof(movedPiece)); } if (castlingRookMove != null && enPassantCapturedPieceSquare.HasValue) { throw new ArgumentException("Castling and en passant capture could not occur simultaneously."); } if (castlingRookMove != null && capturedPiece != Piece.None) { throw new ArgumentException("Castling and capture could not occur simultaneously."); } Move = move ?? throw new ArgumentNullException(nameof(move)); MovedPiece = movedPiece; CapturedPiece = capturedPiece; CastlingRookMove = castlingRookMove; CapturedPieceSquare = enPassantCapturedPieceSquare ?? move.To; }
public override bool Equals(object obj) { if (obj != null && (obj is GameMove) && ((GameMove)obj).type == this.type) { GameMove other = (GameMove)obj; switch (this.type) { case MoveType.ADD: return((this.x1 == other.x1 && this.y1 == other.y1) && this.card.Equals(other.card)); case MoveType.SWAP: return((this.x1 == other.x1 && this.y1 == other.y1 && this.x2 == other.x2 && this.y2 == other.y2) || (this.x1 == other.x2 && this.y1 == other.y2 && this.x2 == other.x1 && this.y2 == other.y1)); case MoveType.REMOVE: return(this.x1 == other.x1 && this.y1 == other.y1); case MoveType.PEEK: return(this.x1 == other.x1 && this.y1 == other.y1); default: return(false); } } return(false); }
private void DoCastling(GameMove move) { if (!move.Castling.HasValue) { throw new ArgumentNullException(nameof(move.Castling)); } var castling = move.Castling.Value; var king = Chessboard.GetChessPiece(move.From); var lineNumber = king.Owner == ChessColor.White ? 1 : 8; if (castling == Castling.Short) { Chessboard.Move(new GameMove { From = new Coordinate('E', lineNumber), To = new Coordinate('G', lineNumber) }); Chessboard.Move(new GameMove { From = new Coordinate('H', lineNumber), To = new Coordinate('F', lineNumber) }); } else { Chessboard.Move(new GameMove { From = new Coordinate('E', lineNumber), To = new Coordinate('C', lineNumber) }); Chessboard.Move(new GameMove { From = new Coordinate('A', lineNumber), To = new Coordinate('D', lineNumber) }); } }
/// <summary> /// Handles the message received when the player requests a game move to be made /// </summary> /// <param name="msg">The message to handle</param> private void HandleGameMove(NetIncomingMessage msg) { // Reads move from the packet GameMove move = GameMove.DecodeFromClient(msg, myPlayers); // We only handle moves in game if (myState == ServerState.InGame) { // Check that the move came from the right client before handling if (move.Player == myPlayers[msg.SenderConnection]) { HandleMove(move); // Handle the move } else { Log("Bad packet received from \"{0}\" ({1})", myPlayers[msg.SenderConnection].Name, msg.SenderEndPoint); } } else { // We are not in the right state, notify client NotifyBadState(msg.SenderConnection, "Game is not currently running"); Log("Player \"{0}\" attempted move during non-game state", myPlayers[msg.SenderConnection].Name, msg.SenderEndPoint); } }
public void ReadFromFile() { try { using (StreamReader sr = File.OpenText(fileName)) { string line; line = sr.ReadLine(); firstplayerFSP = FigureStartingPosition.FromString(line); line = sr.ReadLine(); secondplayerFSP = FigureStartingPosition.FromString(line); bool evenLine = false; while ((line = sr.ReadLine()) != null) { if (evenLine) { secondPlayerGM.Add(GameMove.FromString(line)); } else { firstPlayerGM.Add(GameMove.FromString(line)); } evenLine = !evenLine; } } } catch (Exception e) { e.ToString(); } }
/// <summary> /// Determines if a given move is valid /// </summary> /// <param name="server">The server to excecute on</param> /// <param name="move">The move being played</param> /// <param name="reason">The reason that the move is invalid</param> /// <returns>True if the room is valid, false if otherwise</returns> public bool IsValidMove(GameServer server, GameMove move, ref string reason) { if (server.GameState.GetValueBool(Names.IS_ATTACKING)) { if (move.Player.PlayerId == server.GameState.GetValueByte(Names.ATTACKING_PLAYER)) { return(true); } if (server.GameState.GetValueBool(Names.REQUEST_HELP) && move.Player.PlayerId != server.GameState.GetValueByte(Names.DEFENDING_PLAYER)) { return(true); } } else { if (move.Player.PlayerId == server.GameState.GetValueByte(Names.DEFENDING_PLAYER)) { return(true); } } reason = "It is not your turn to " + (server.GameState.GetValueBool(Names.IS_ATTACKING) ? "attack." : "defend."); return(false); }
protected override VariationLine DoGetMove(GetMoveRequest request) { while (true) { request.CancellationToken.ThrowIfCancellationRequested(); lock (_syncLock) { var move = _move; if (move != null) { _move = null; return(move | VariationLine.Zero); } if (!_isAwaitingMove) { _isAwaitingMove = true; RaiseMoveRequestedAsync(); } } Thread.Sleep(10); } }
public void WhenPreviousMoveIsNullRandomGameMoveGeneratorShouldBeCalledOnce() { // Arrange const GameMove expectedGameMove = GameMove.Paper; var randomMoveGeneratorMock = new Mock <IRandomMoveGenerator>(); randomMoveGeneratorMock.Setup(m => m.GenerateRandomMove()).Returns(expectedGameMove); var tacticalMoveGeneratorMock = new Mock <ITacticalMoveGenerator>(); tacticalMoveGeneratorMock.Setup(m => m.GenerateTacticalMove(It.IsAny <GameMove>())).Returns(GameMove.Rock); var tacticalComputerPlayer = new TacticalComputerPlayer(tacticalMoveGeneratorMock.Object, randomMoveGeneratorMock.Object) { PreviousMove = null }; // Act tacticalComputerPlayer.GetComputerMove(); // Assert randomMoveGeneratorMock.Verify(m => m.GenerateRandomMove(), Times.Once); }
private void BoardSquare_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { var square = GetSquare(e.Source); if (!square.HasValue) { return; } if (ViewModel.SelectionMode == GameWindowSelectionMode.None) { return; } var movingPieceSquare = ViewModel.CurrentSourceSquare; if (ViewModel.SelectionMode != GameWindowSelectionMode.MovingPieceSelected || !movingPieceSquare.HasValue) { ViewModel.SetMovingPieceSelectionMode(square.Value); return; } if (movingPieceSquare.Value == square.Value) { ViewModel.ResetSelectionMode(); return; } var move = new GameMove(movingPieceSquare.Value, square.Value); MakeMove(move); }
private void QueryPawnPromotion(GameMove move) { PromotionContainerGrid.Width = BoardGrid.ActualWidth; PromotionContainerGrid.Height = BoardGrid.ActualHeight; PromotionContainerGrid.Visibility = Visibility.Visible; var promotionPopupClosed = new ValueContainer <EventHandler>(); promotionPopupClosed.Value = (sender, args) => { _promotionPopup.Closed -= promotionPopupClosed.Value; //// ReSharper disable once InvertIf if (_promotionPopup.Tag is PieceType promotion && promotion != PieceType.None) { var promotionMove = move.MakePromotion(promotion); MakeMoveInternal(promotionMove); } }; _promotionPopup.Closed += promotionPopupClosed.Value; _promotionPopup.Tag = PieceType.None; _promotionPopup.IsOpen = true; }
public void Barterbanker(Game2PositionPlayerInfoDto playerRoomBaseInfoDto) { //更换庄家名称等各项信息 Banker.GetChild(0).GetComponent <Text>().text = playerRoomBaseInfoDto.userName; Banker.GetChild(1).GetComponent <Text>().text = playerRoomBaseInfoDto.gold.ToString(); if (playerRoomBaseInfoDto.vipLv > 0) { Banker.GetChild(4).GetComponent <Image>().sprite = VIPImages[playerRoomBaseInfoDto.vipLv - 1]; Banker.GetChild(4).gameObject.SetActive(true); } else { Banker.GetChild(4).gameObject.SetActive(false); } LoadHeadImgUtils.Instance.LoadHeadImg(Banker.GetChild(3).GetComponent <Image>(), playerRoomBaseInfoDto.headUrl); otherbankerGold = playerRoomBaseInfoDto.gold; account = playerRoomBaseInfoDto.uid; GameMove gameMove = MessageManager.GetInstance.GetUIDict <GameMove>(); if (playerRoomBaseInfoDto.uid == PlayerCache.loginInfo.uid) { //显示下庄按钮 gameMove.IsBanker(true); } else { //不显示下庄按钮 gameMove.IsBanker(false); } }
/// <summary> /// Handles the invalid move packet /// </summary> /// <param name="inMsg">The message to decode</param> private void HandleInvalidMove(NetIncomingMessage inMsg) { GameMove move = GameMove.Decode(inMsg, myKnownPlayers); string reason = inMsg.ReadString(); OnInvalidMove?.Invoke(this, move.Move, reason); }
private void MakeMove(GameMove move) { var currentGameBoard = ViewModel.CurrentGameBoard; if (currentGameBoard is null) { return; } var isPawnPromotion = currentGameBoard.IsPawnPromotionMove(move); if (isPawnPromotion) { move = move.MakePromotion(ChessHelper.DefaultPromotion); } if (!currentGameBoard.IsValidMove(move)) { ViewModel.ResetSelectionMode(); return; } if (isPawnPromotion) { QueryPawnPromotion(move); return; } MakeMoveInternal(move); }
public bool Check(GameMove gameMove, GameMove[] occupiedPisition) { return(CheckHorizontal(gameMove, occupiedPisition) || CheckVertical(gameMove, occupiedPisition) || CheckBackwardSlash(gameMove, occupiedPisition) || CheckForwardSlash(gameMove, occupiedPisition)); }
private bool MCTSRandSimPlayout(SkyNetNode curNode) { Console.WriteLine("ENTERING MCTS SIM PLAYOUT"); IBoard tmpBoard = localBoard; bool curBoardTerminal = CheckTerminalNode(tmpBoard); Random rand = new Random(); bool playerOne = curNode.playerOne; while (!curBoardTerminal) { List <GameMove> availMoves = localGame.getAllPlayerMoves(tmpBoard, playerOne); int cnt = availMoves.Count; int randMoveInd = rand.Next(0, availMoves.Count); GameMove randMove = availMoves [randMoveInd]; Console.WriteLine(String.Format("Move Made!\nPlayer One's: {1}\nMove: {2}", playerOne.ToString(), randMove.ToString())); makeMove(tmpBoard, randMove); curBoardTerminal = CheckTerminalNode(tmpBoard); if (!curBoardTerminal) { playerOne = !playerOne; } } Console.WriteLine("Player One Win: " + playerOne.ToString()); Console.WriteLine("EXITING MCTS SIM PLAYOUT"); return(playerOne); }
private Boolean CheckVertical(GameMove move, GameMove[] occupiedPosition) { int counter = 1; int col = move.ColumnIndex; int row = move.RowIndex; String color = move.ColorInString; for (int i = row + 1; i <= 15; i++) { if (IsSame(i, col, color, occupiedPosition)) { counter++; } else { break; } } for (int i = row - 1; i >= 1; i--) { if (IsSame(i, col, color, occupiedPosition)) { counter++; } else { break; } } if (counter == 5) { return(true); } return(false); }
public void TestSampleGameSuccess() { OnVictoryFlag = false; OnFailureFlag = false; GameMove _guess = new GameMove( ColorSelection.FindColorSwatchByColorName("Blue"), ColorSelection.FindColorSwatchByColorName("Orange"), ColorSelection.FindColorSwatchByColorName("Red"), ColorSelection.FindColorSwatchByColorName("White")); GameMove _solution = new GameMove( ColorSelection.FindColorSwatchByColorName("Blue"), ColorSelection.FindColorSwatchByColorName("Orange"), ColorSelection.FindColorSwatchByColorName("Red"), ColorSelection.FindColorSwatchByColorName("White")); var game = GameEngine.CreateSampleGame(_solution); game.OnVictory += (s, e) => OnVictoryFlag = true; game.OnFailure += (s, e) => OnFailureFlag = true; var result = game.RecordGuess(_guess); Assert.AreEqual<int>(4, result.NumberOfReds, "Reds"); Assert.AreEqual<int>(0, result.NumberOfWhites, "Whites"); Assert.AreEqual<int>(0, result.NumberOfEmpties, "Empties"); Assert.IsTrue(result.IsSolved, "Solved"); Assert.IsTrue(OnVictoryFlag, "Victory"); Assert.IsFalse(OnFailureFlag, "Failure"); }
public void TestToUciNotation(string from, string to, PieceType promotionResult, string expectedResult) { var move = new GameMove(Square.FromAlgebraic(from), Square.FromAlgebraic(to), promotionResult); var actualResult = move.ToUciNotation(); Assert.That(actualResult, Is.EqualTo(expectedResult)); }
public void Move(GameMove move) { if (GameStatus == GameStatus.Finished) { throw new Exception("The game is finished."); } History.Add(move, Turn, Chessboard); if (move.Castling.HasValue) { DoCastling(move); } else { Chessboard.Move(move); } if (_gameMoveValidator.IsGameFinished(Chessboard, History, Turn)) { GameStatus = GameStatus.Finished; _gameResult = _gameMoveValidator.GetGameResult(Chessboard, History, Turn); } else { if (GameStatus == GameStatus.NotStarted) { GameStatus = GameStatus.Continues; } Turn = Turn.GetOppositeChessColor(); } }
public void CreateGame(GameMove move1, GameMove move2, GameMove move3) { var value = Nethereum.Util.UnitConversion.Convert.ToWei(1, Nethereum.Util.UnitConversion.EthUnit.Ether); HexBigInteger valueInHex = new HexBigInteger(value); var placeGameRequest = GetContract().GetFunction("placeGameRequest"); var result = placeGameRequest.SendTransactionAsync(_account.Address, DefaultGas, valueInHex, (int)move1, (int)move2, (int)move3).GetAwaiter().GetResult(); }
public static void ShowGame(Game game) { GameMove computerMove = GetComputerMove(); GameMove playerMove = GetPlayerMove(); Console.WriteLine($"You chose {playerMove}"); Console.WriteLine($"The computer chose {computerMove}"); GameResult gameResult = game.Evaluate(playerMove, computerMove); switch (gameResult) { case GameResult.FirstWin: Console.WriteLine("You won!!"); break; case GameResult.SecondWin: Console.WriteLine("Computer Won"); break; case GameResult.Tie: Console.WriteLine("Tie!!"); break; } game.RegisterResult(gameResult); Console.ReadLine(); }
//派发金币 private void SendBet(GameRankingListDto tOSettleRanking) { if (liuliu.SelfWeathDto != null) { if (liuliu.SelfWeathDto[1] > 0) { if (generatePos.childCount > 0) { for (int i = 0; i < generatePos.childCount; i++) { GameObject obj = generatePos.GetChild(i).gameObject; Tweener tweener = obj.transform.DOLocalMove (new Vector3(PlayerIma.transform.localPosition.x, PlayerIma.transform.localPosition.y), 0.5f); } } } } AudioManager.Instance.PlaySound("g2"); if (BankerChipPos.childCount > 0) { for (int i = 0; i < BankerChipPos.childCount; i++) { GameObject obj = BankerChipPos.GetChild(i).gameObject; Tweener tweener = obj.transform.DOLocalMove (new Vector3(OtherInfoBtn.transform.localPosition.x + 100, OtherInfoBtn.transform.localPosition.y), 0.5f); } } GameMove gameMove = MessageManager.GetInstance.GetUIDict <GameMove>(); AudioManager.Instance.PlaySound("g2"); gameMove.Settleaccounts(tOSettleRanking); }
public override GameMove <Move> DoMove(IGameStateProvider stateProvider) { var state = stateProvider.ProvideState <Move>(); var states = state.GameMoves; GameMove <Move> lastState = states[states.Length - 1]; string[][] board = lastState.State.Board; for (int r = 0; r < board.Length; r++) { string[] row = board[r]; for (int c = 0; c < row.Length; c++) { if (string.IsNullOrWhiteSpace(row[c])) { string[][] newBoard = board.Select(s => s.ToArray()).ToArray(); newBoard[r][c] = this.Id; return(new GameMove <Move>(this.Id, new Move { Board = newBoard })); } } } // If we got here then there was no valid move for us to make return(lastState); }
public override GameMove <T> DoMove(IGameStateProvider stateProvider) { string resultsDir = Path.Combine(this.cwd, this.id); Console.WriteLine($"Enure results directory exists: {resultsDir}"); Directory.CreateDirectory(resultsDir); string statePath = Path.Combine(resultsDir, "state.json"); string movePath = Path.Combine(resultsDir, "move.json"); string args = $"{this.id} \"{statePath}\" \"{movePath}\""; Console.WriteLine($"Write state to file: {statePath}"); File.WriteAllText(statePath, JsonConvert.SerializeObject(stateProvider.ProvideState <T>())); Console.WriteLine($"Starting player process: {this.exe} {string.Join(" ", args)}"); Process process = Process.Start(this.exe, args); process.WaitForExit(); Console.WriteLine($"Read new move from file: {movePath}"); GameMove <T> move = JsonConvert.DeserializeObject <GameMove <T> >(File.ReadAllText(movePath)); // TODO: clean up files return(move); }
public bool IsValidMove(CoreDurakGame core, GameMove move, ref string reason) { if (core.GameState.GetValueListInt(Names.WINNING_PLAYERS).Contains(move.Player.ID)) { reason = "You have already won!"; return(false); } else if (move.Move == null) { return(true); } else if (core.GameState.GetValueListInt(Names.THROWES_WITHOUT_CARDS).Contains(move.Player.ID)) { reason = "You haven`t cards, wait for the next round"; return(false); } else if (!move.Player.Hand.Contains(move.Move)) { reason = "Card is not in players hand"; return(false); } else { return(true); } }
public GameBoardWPF(int gameId, GameMove[] moves, bool confirmation) { InitializeComponent(); c = new ServiceClient(new InstanceContext(this)); this.gameId = gameId; this.moves = moves; this.confirmation = confirmation; boardSize = c.GetSizeGame(gameId); buttons1 = CreateButtons(); initGrid(); for (int i = 0; i < boardSize; i++) { for(int j = 0; j < boardSize; j++) { buttons1[i, j].IsEnabled = false; } } // print all moves on game board for (int i = 0; i < moves.Count(); i++) { int row = Convert.ToInt32(moves[i].row); int col = Convert.ToInt32(moves[i].col); string s = moves[i].Sign; buttons1[row, col].Content = s; buttons1[row, col].FontSize = 50; buttons1[row, col].IsEnabled = false; } }
public GameState Play(GameState gameState, GameMove move) { // TODO: Look at the gameState passed in to get the dice values to keep // the player can Bank, Roll or they Farkled and must move to the next player // modify the scores, current player and return the game state return new GameState(); }
public void MoveToken(GameMove move) { Token token = move.Token; Point moveTo = move.MoveTo; if (token.TokenType == TokenType.Empty || token.TokenType == TokenType.Flag || token.TokenType == TokenType.Bomb) { throw new InvalidMoveException(string.Format("Invalid move. Token type {0} cannot be moved.", token.TokenType)); } var defender = this.GameBoard.Get(moveTo); var result = token.Attack(defender); switch (result) { case GameMoveResultType.AttackerWins: this.GameBoard.Remove(defender.Point); token.SetPoint(moveTo); break; case GameMoveResultType.DefenderWins: this.GameBoard.Remove(token.Point); break; case GameMoveResultType.BothLose: this.GameBoard.Remove(token.Point); this.GameBoard.Remove(defender.Point); break; case GameMoveResultType.TokenMove: token.SetPoint(moveTo); break; } if (result != GameMoveResultType.FlagCapturedByAttacker) { var p1ActiveTokens = this.GameBoard.GetTokens().Count(x => x.PlayerID == Player1.ID && x.IsMovable()); var p2ActiveTokens = this.GameBoard.GetTokens().Count(x => x.PlayerID == Player2.ID && x.IsMovable()); if (p1ActiveTokens == 0) { if (p2ActiveTokens == 0) { result = GameMoveResultType.BothOutOfPieces; } else { result = GameMoveResultType.AttackerOutOfPieces; } } else if (p2ActiveTokens == 0) { result = GameMoveResultType.DefenderOutOfPieces; } } this.GameStatus = GameStatus.CreateForMove(this.GameStatus, move, result, token, defender); }
public static GameStatus CreateForMove(GameStatus status, GameMove move, GameMoveResultType result, Token attacker, Token defender) { var active = !result.IsGameOver(); var winner = result.GetWinner(status.CurrentPlayer, status.OtherPlayer); // switch current player var currentPlayer = status.OtherPlayer; var otherPlayer = status.CurrentPlayer; return new GameStatus(currentPlayer, otherPlayer, winner, active, move, result, attacker, defender); }
public void GameMove_Test_Equals() { var m1 = new GameMove(); var m2 = new GameMove(); var m3 = new GameMove(null, new Point(1, 1)); Assert.AreEqual(m1, m2, "m1 and m2 should be equal"); Assert.AreNotEqual(m1, m3, "m1 and m3 should not be equal"); Assert.IsTrue(m1 == m2, "m1 and m2 should be equal via equals operator"); Assert.IsTrue(m1 != m3, "m1 and m3 not equals operator should be true"); }
public void DuplicateColorInSolutionTwoRedTwoWhite() { GameMove _guess = new GameMove( ColorSelection.FindColorSwatchByColorName("Blue"), ColorSelection.FindColorSwatchByColorName("Red"), ColorSelection.FindColorSwatchByColorName("Blue"), ColorSelection.FindColorSwatchByColorName("White")); GameMove _solution = new GameMove( ColorSelection.FindColorSwatchByColorName("Blue"), ColorSelection.FindColorSwatchByColorName("White"), ColorSelection.FindColorSwatchByColorName("Blue"), ColorSelection.FindColorSwatchByColorName("Red")); var result = GameEngine.TestGuessAgainstSolution(_guess, _solution); Assert.AreEqual<int>(2, result.NumberOfReds, "Reds"); Assert.AreEqual<int>(2, result.NumberOfWhites, "Whites"); Assert.AreEqual<int>(0, result.NumberOfEmpties, "Empties"); Assert.IsFalse(result.IsSolved); }
public void OneWhiteOneRed() { GameMove _guess = new GameMove( ColorSelection.FindColorSwatchByColorName("Green"), ColorSelection.FindColorSwatchByColorName("Red"), ColorSelection.FindColorSwatchByColorName("Red"), ColorSelection.FindColorSwatchByColorName("White")); GameMove _solution = new GameMove( ColorSelection.FindColorSwatchByColorName("Red"), ColorSelection.FindColorSwatchByColorName("Blue"), ColorSelection.FindColorSwatchByColorName("Red"), ColorSelection.FindColorSwatchByColorName("Yellow")); var result = GameEngine.TestGuessAgainstSolution(_guess, _solution); Assert.AreEqual<int>(1, result.NumberOfReds, "Reds"); Assert.AreEqual<int>(1, result.NumberOfWhites, "Whites"); Assert.AreEqual<int>(2, result.NumberOfEmpties, "Empties"); Assert.IsFalse(result.IsSolved); }
public void DuplicateWhitePegsResultingInOne() { GameMove _guess = new GameMove( ColorSelection.FindColorSwatchByColorName("Blue"), ColorSelection.FindColorSwatchByColorName("Blue"), ColorSelection.FindColorSwatchByColorName("Blue"), ColorSelection.FindColorSwatchByColorName("White")); GameMove _solution = new GameMove( ColorSelection.FindColorSwatchByColorName("White"), ColorSelection.FindColorSwatchByColorName("Orange"), ColorSelection.FindColorSwatchByColorName("White"), ColorSelection.FindColorSwatchByColorName("Red")); var result = GameEngine.TestGuessAgainstSolution(_guess, _solution); Assert.AreEqual<int>(0, result.NumberOfReds, "Reds"); Assert.AreEqual<int>(1, result.NumberOfWhites, "Whites"); Assert.AreEqual<int>(3, result.NumberOfEmpties, "Blanks"); Assert.IsFalse(result.IsSolved); }
public GameStatus( Player currentPlayer, Player otherPlayer, Player winner, bool gameActive, GameMove currentMove, GameMoveResultType currentMoveResult, Token attackerToken, Token defenderToken) { this.CurrentPlayer = currentPlayer; this.OtherPlayer = otherPlayer; this.Winner = winner; this.GameActive = gameActive; this.CurrentMove = currentMove; this.CurrentMoveResult = currentMoveResult; this.AttackerToken = attackerToken; this.DefenderToken = defenderToken; }
public void CreateFromGrid_TakeMove_ShouldPopCorrectly() { var expected = BubbleGridBuilder.Create(new[] { new[] {Bubble.Blue,Bubble.None , Bubble.None, Bubble.Blue}, new[] {Bubble.Red, Bubble.Green, Bubble.Cyan, Bubble.Green}, new[] {Bubble.Red, Bubble.Green, Bubble.Red, Bubble.Cyan}, new[] {Bubble.Red, Bubble.Cyan, Bubble.Cyan, Bubble.Cyan, } }); var move = new GameMove(_grid); _grid.Display(); Console.WriteLine("Taking move (2,2).."); var next = move.BurstBubble(new Point(2, 2)); next.GridState.Display(); Assert.IsTrue(expected.Equals(next.GridState)); }
public void CreateFromGrid_TakeTwoMoves_ShouldInheritState() { var expected = BubbleGridBuilder.Create(new[] { new[] {Bubble.Blue, Bubble.None, Bubble.None, Bubble.None, }, new[] {Bubble.Red, Bubble.Green, Bubble.Cyan,Bubble.None }, new[] {Bubble.Red, Bubble.Green, Bubble.Red, Bubble.Blue }, new[] {Bubble.Red, Bubble.Yellow, Bubble.Yellow, Bubble.Green } }); var secondExpected = BubbleGridBuilder.Create(new[] { new[] {Bubble.Blue, Bubble.None, Bubble.None, Bubble.None,}, new[] {Bubble.Red, Bubble.None, Bubble.None, Bubble.None}, new[] {Bubble.Red, Bubble.Green, Bubble.Cyan, Bubble.Blue}, new[] {Bubble.Red, Bubble.Green, Bubble.Red, Bubble.Green} }); var move = new GameMove(_grid); _grid.Display(); Console.WriteLine("Taking move (3,3).."); var threeThree = move.BurstBubble(new Point(3,3)); threeThree.GridState.Display(); Assert.IsTrue(expected.Equals(threeThree.GridState)); Console.WriteLine("Taking move (2,3)"); var twoThree = threeThree.BurstBubble(new Point(2, 3)); twoThree.GridState.Display(); Assert.IsTrue(secondExpected.Equals(twoThree.GridState)); }
public void TestSampleGameFailure() { OnVictoryFlag = false; OnFailureFlag = false; GameMove _solution = new GameMove( ColorSelection.FindColorSwatchByColorName("Blue"), ColorSelection.FindColorSwatchByColorName("Orange"), ColorSelection.FindColorSwatchByColorName("Red"), ColorSelection.FindColorSwatchByColorName("White")); GameMove _guess = new GameMove( ColorSelection.FindColorSwatchByColorName("Blue"), ColorSelection.FindColorSwatchByColorName("Blue"), ColorSelection.FindColorSwatchByColorName("Blue"), ColorSelection.FindColorSwatchByColorName("Blue")); var game = GameEngine.CreateSampleGame(_solution); game.OnVictory += (s, e) => OnVictoryFlag = true; game.OnFailure += (s, e) => OnFailureFlag = true; GameMoveResult result = new GameMoveResult(); for (int i = 0; i < Game.MAX_MOVES_ALLOWED; i++) { result = game.RecordGuess(_guess); } // just test the last one Assert.AreEqual<int>(1, result.NumberOfReds, "Reds"); Assert.AreEqual<int>(0, result.NumberOfWhites, "Whites"); Assert.AreEqual<int>(3, result.NumberOfEmpties, "Empties"); Assert.IsFalse(result.IsSolved, "Solved"); Assert.IsFalse(OnVictoryFlag, "OnVictory"); Assert.IsTrue(OnFailureFlag, "OnFailure"); }
/* * add move game to moves table */ public void AddMove(int gameId, string sign, int row, int col) { boardGame[row, col] = sign; GameMove move = new GameMove(); move.Game_Id = gameId; move.Sign = sign; move.row = row; move.col = col; db.GameMoves.InsertOnSubmit(move); db.SubmitChanges(); }
static public void UpdatePos(Pod[] pod, GameMove[] move) { for (int i = 0; i < 4; i++) { if (move[i].Shield) pod[i].WaitToThrust = 3; else pod[i].WaitToThrust--; if (pod[i].WaitToThrust > 0) move[i].Thrust = 0; } // 1. Target: UpdateAngle(pod, move); // 2. Thrust: PointD[] dV = new PointD[4]; for (int i = 0; i < 4; i++) { // possible optimization - pump Sin values for all degrees 0..90 into array // + transformation to get all 0..360 dV[i] = GetVector(pod[i].Angle, move[i].Thrust); pod[i].v += new Point(dV[i]); } bool[] collided = new bool[4]; // 3. Movement (+collision): // TODO: multiple simultaneous collisions case for (int i = 0; i < 3; i++) { for (int j = i + 1; j < 4; j++) { Point pos1 = pod[i].p + (pod[i].v - pod[j].v); long denom = Dist(pod[i].p, pos1); long b = (pod[i].VX - pod[j].VX) * (pod[i].X - pod[j].X) + (pod[i].VY - pod[j].VY) * (pod[i].Y - pod[j].Y); double sD = Math.Sqrt(b * b - denom * (Dist(pod[i].p, pod[j].p) - 640000)); double alpha1 = (-b + sD) / denom; double alpha2 = (-b - sD) / denom; bool bam = true; if (alpha1 > 0 && alpha1 < 1) { if (alpha2 > 0 && alpha2 < alpha1) { // alpha2 - point of collision ProcessCollision(ref pod[i], ref pod[j], move[i], move[j], alpha2); } else { // alpha1 - point of collision ProcessCollision(ref pod[i], ref pod[j], move[i], move[j], alpha1); } } else if (alpha2 > 0 && alpha2 < 1) { // alpha2 - point of collision ProcessCollision(ref pod[i], ref pod[j], move[i], move[j], alpha2); } else { bam = false; } //no collision if (bam) { collided[i] = true; collided[j] = true; //Console.Error.WriteLine("pod {0} and pod {1} collided; bf speed 1:({2},{3}), 2:({4},{5})", // i, j, pod[i].VX, pod[i].VY, pod[j].VX, pod[j].VY); } } } for (int i = 0; i < 4; i++) { if (!collided[i]) { pod[i].p += pod[i].v; } if (pod[i].CrossedCP(100 * ((3 - i) / 2))) { if (pod[i].NextCP == 0) { pod[i].Lap++; //if (pod[i].Lap > laps) //{ // // game over // // pod[i] is winner //} } pod[i].NextCP = (pod[i].NextCP + 1) % C; } } // 4. Friction: for (int i = 0; i < 4; i++) { pod[i].VX = (int)Math.Truncate(pod[i].VX * Friction); pod[i].VY = (int)Math.Truncate(pod[i].VY * Friction); } }
static public List<GameMove[]> GenerateMoves(GameMove[] moves) { List<GameMove[]> list = new List<GameMove[]>(); //int j1 = 0; int step = 30; for (int j1 = -step; j1 <= step; j1 += step) { //int j2 = 0; for (int j2 = -step; j2 <= step; j2 += step) { if (moves[0].Thrust + j1 <= 200 && moves[0].Thrust + j1 >= 0) { if (moves[1].Thrust + j2 <= 200 && moves[1].Thrust + j2 >= 0) { GameMove[] moves2 = new GameMove[4]; Copy(moves, moves2, 2); //Array.Copy(moves, moves2, 2); moves2[0].Thrust += j1; moves2[1].Thrust += j2; for (int degree1 = -18; degree1 <= 18; degree1 += 6) { for (int degree2 = -18; degree2 <= 18; degree2 += 6) { GameMove[] moves3 = new GameMove[4]; Copy(moves2, moves3, 2); moves3[0].AddDegree(degree1); moves3[1].AddDegree(degree2); list.Add(moves3); } } } } } } return list; }
protected void AddMove(GameMove gameMove) { Moves.Add(gameMove); NextPlayer = gameMove.Player.Opposite; }
public GameMove[] GetMoves(Pod[] pod, Pod[] opp) { GameMove[] moves = new GameMove[4]; moves[0] = GetMove(pod[0]); moves[1] = GetMove(pod[1]); return moves; }
public GameMove[] GetMoves(Pod[] pod, Pod[] opp) { GameMove[] moves = new GameMove[4]; moves = (new SimpleStrategy()).GetMoves(pod, opp); List<GameMove[]> altMoves = GameMove.GenerateMoves(moves); Simulator sim = new Simulator(); double maxU = Double.MinValue; int maxInd = 0; for (int i = 0; i < altMoves.Count; i++) { Situation situation = sim.Simulate(pod[0], pod[1], opp[0], opp[1], altMoves[i], Opp); //Console.Error.WriteLine("thrust1: {0}, thrust2: {1}", altMoves[i][0].Thrust, altMoves[i][1].Thrust); //situation.Print(); double utility = situation.Utility(); //Console.Error.WriteLine("Utility {0} = {1}", i, utility); if (utility > maxU) { maxU = utility; maxInd = i; } } GameMove moveWithShield = GameMove.MoveWithShield(altMoves[maxInd][0]); Situation sit = sim.Simulate(pod[0], pod[1], opp[0], opp[1], new GameMove[] { moveWithShield, altMoves[maxInd][1], altMoves[maxInd][2], altMoves[maxInd][3]}); if (sit.Utility() > maxU + 30 && !(pod[0].Lap == laps && pod[0].NextCP == 0)) { //moveWithShield.Print(); altMoves[maxInd][0] = moveWithShield; } moveWithShield = GameMove.MoveWithShield(altMoves[maxInd][1]); sit = sim.Simulate(pod[0], pod[1], opp[0], opp[1], new GameMove[] { altMoves[maxInd][0], moveWithShield, altMoves[maxInd][2], altMoves[maxInd][3]}); if (sit.Utility() > maxU + 40 && !(pod[1].Lap == laps && pod[1].NextCP == 0)) { //moveWithShield.Print(); altMoves[maxInd][1] = moveWithShield; } return altMoves[maxInd]; }
public Situation Simulate(Pod pod1, Pod pod2, Pod opp1, Pod opp2, GameMove[] moves, bool Opp = false) { var strategy = new SimpleStrategy(); Console.SetError(StreamWriter.Null); var fastStrat = new FastStrategy(OppDepth); if (!Opp) { moves[2] = strategy.GetMove(opp1); moves[3] = strategy.GetMove(opp2); } else { GameMove[] oppMoves = fastStrat.GetMoves(new Pod[] { opp1, opp2 }, new Pod[] { pod1, pod2 }); moves[2] = oppMoves[0]; moves[3] = oppMoves[1]; } var standardError = new StreamWriter(Console.OpenStandardError()); standardError.AutoFlush = true; Console.SetError(standardError); Pod[] sPod = new Pod[4]; sPod[0] = new Pod(pod1); sPod[1] = new Pod(pod2); sPod[2] = new Pod(opp1); sPod[3] = new Pod(opp2); Pod.UpdatePos(sPod, moves); GameMove[] moves2 = new GameMove[4]; GameMove.Copy(moves, moves2, 4); for (int i = 0; i < SimpleSimDepth; i++) { moves2[0] = strategy.GetMove(sPod[0]); moves2[1] = strategy.GetMove(sPod[1]); moves2[2] = strategy.GetMove(sPod[2]); moves2[3] = strategy.GetMove(sPod[3]); Pod.UpdatePos(sPod, moves2); } return new Situation(sPod); }
public Situation SimulateHR(Pod pod1, Pod pod2, Pod opp1, Pod opp2, GameMove[] moves, int runner) { var strategy = new SimpleStrategy(); Console.SetError(StreamWriter.Null); var fastStrat = new FastStrategy(OppDepth); moves[2] = strategy.GetMove(opp1); moves[3] = strategy.GetMove(opp2); var standardError = new StreamWriter(Console.OpenStandardError()); standardError.AutoFlush = true; Console.SetError(standardError); Pod[] sPod = new Pod[4]; sPod[0] = new Pod(pod1); sPod[1] = new Pod(pod2); sPod[2] = new Pod(opp1); sPod[3] = new Pod(opp2); Pod.UpdatePos(sPod, moves); GameMove[] moves2 = new GameMove[4]; GameMove.Copy(moves, moves2, 4); for (int i = 0; i < SimpleSimDepth; i++) { moves2[runner] = strategy.GetMove(sPod[runner]); moves2[runner ^ 1] = strategy.GetMoveHit(sPod, runner ^ 1); moves2[2] = strategy.GetMove(sPod[2]); moves2[3] = strategy.GetMove(sPod[3]); Pod.UpdatePos(sPod, moves2); } return new Situation(sPod); }
static public void ProcessCollision(ref Pod pod1, ref Pod pod2, GameMove move1, GameMove move2, double alpha) { //Console.Error.WriteLine("pre: speed1 ({0},{1}), speed2 ({2},{3})", pod1.VX, pod1.VY, pod2.VX, pod2.VY); pod1.p += new Point(pod1.v * alpha); pod2.p += new Point(pod2.v * alpha); //double d = Math.Sqrt(Math.Pow(pod1.X - pod2.X, 2) + Math.Pow(pod1.Y - pod2.Y, 2)); double d = (pod1.p - pod2.p).Module(); PointD n = (pod2.p - pod1.p) * (1.0 / d); int m1 = 1 + (move1.Shield ? 9 : 0); int m2 = 1 + (move2.Shield ? 9 : 0); double p = 2.0 * (pod1.v * n - pod2.v * n) / (m1 + m2); PointD deltaV1 = n * (p * m2); PointD deltaV2 = n * (p * m1); double deltaImpulse = Math.Sqrt(deltaV1.x * deltaV1.x + deltaV1.y * deltaV1.y); if (deltaImpulse < 240) { double beta = ((240 - deltaImpulse) / 2.0) / deltaImpulse; p += p * beta; } PointD w1 = pod1.v - deltaV1; PointD w2 = pod2.v + deltaV2; pod1.v = new Point(w1); pod2.v = new Point(w2); pod1.p += new Point(pod1.v * (1 - alpha)); pod2.p += new Point(pod2.v * (1 - alpha)); }
public void TestExactSolution() { GameMove _guess = new GameMove( ColorSelection.FindColorSwatchByColorName("Blue"), ColorSelection.FindColorSwatchByColorName("Orange"), ColorSelection.FindColorSwatchByColorName("Red"), ColorSelection.FindColorSwatchByColorName("White")); GameMove _solution = new GameMove( ColorSelection.FindColorSwatchByColorName("Blue"), ColorSelection.FindColorSwatchByColorName("Orange"), ColorSelection.FindColorSwatchByColorName("Red"), ColorSelection.FindColorSwatchByColorName("White")); var result = GameEngine.TestGuessAgainstSolution(_guess, _solution); Assert.AreEqual<int>(4, result.NumberOfReds, "Reds"); Assert.AreEqual<int>(0, result.NumberOfWhites, "Whites"); Assert.AreEqual<int>(0, result.NumberOfEmpties, "Empties"); Assert.IsTrue(result.IsSolved); }
static public GameMove MoveWithShield(GameMove move) { return new GameMove(move.Destination, true); }
static void Main(string[] args) { InitialInput(); Simulator sim = new Simulator(); int count = 0; int mainDepth = C - 1; while (true) { count++; for (int i = 0; i < 2; i++) { pod[i].Update(Console.ReadLine()); } for (int i = 0; i < 2; i++) { opp[i].Update(Console.ReadLine()); } var strategy = new SimpleStrategy(); GameMove[] moves = new GameMove[4]; if (count < 7) { moves[0] = strategy.GetMove(pod[0]); moves[1] = strategy.GetMove(pod[1]); } else if (count < 50) { var faststrategy = new FastStrategy(); moves = faststrategy.GetMoves(pod, opp); } else { var hitandrun = new HitStrategy(); moves = hitandrun.GetMoves(pod, opp); } if (count == 1) { moves[0].Thrust = 200; moves[1].Thrust = 200; } moves[0].Print(); moves[1].Print(); } }
static public void Copy(GameMove[] from, GameMove[] to, int length) { for (int i = 0; i < length; i++) { to[i] = new GameMove(from[i].Destination, from[i].Thrust, from[i].Shield, from[i].msg); //to[i].Destination = from[i].Destination; //to[i].Thrust = from[i].Thrust; //to[i].Shield = from[i].Shield; } }
public void TestAllSameColorSolution() { GameMove _solution = new GameMove( ColorSelection.FindColorSwatchByColorName("Blue"), ColorSelection.FindColorSwatchByColorName("Blue"), ColorSelection.FindColorSwatchByColorName("Blue"), ColorSelection.FindColorSwatchByColorName("Blue")); GameMove _guess = new GameMove( ColorSelection.FindColorSwatchByColorName("Orange"), ColorSelection.FindColorSwatchByColorName("Blue"), ColorSelection.FindColorSwatchByColorName("Orange"), ColorSelection.FindColorSwatchByColorName("Blue")); var result = GameEngine.TestGuessAgainstSolution(_guess, _solution); // just test the last one Assert.AreEqual<int>(2, result.NumberOfReds, "Reds"); Assert.AreEqual<int>(0, result.NumberOfWhites, "Whites"); Assert.AreEqual<int>(2, result.NumberOfEmpties, "Empties"); }
static public void UpdateAngle(Pod[] pod, GameMove[] move) { for (int i = 0; i < 4; i++) { double angle1 = SpeedAngle(move[i].Destination - pod[i].p); double angleDiff = angle1 - pod[i].Angle; if (angleDiff > 180) angleDiff -= 360; else if (angleDiff < -180) angleDiff += 360; if (angleDiff > 18) angleDiff = 18; else if (angleDiff < -18) angleDiff = -18; pod[i].Angle = (int)Math.Round(pod[i].Angle + angleDiff) % 360; if (pod[i].Angle < 0) pod[i].Angle += 360; } //for (int i = 0; i < 2; i++) //{ // Console.Error.WriteLine("New angle = {0}", pod[i].Angle); //} }