public override ReadOnlyCollection<Move> GetValidMoves(Position from, bool returnIfAny, ChessGame game, Func<Move, bool> gameMoveValidator) { ChessUtilities.ThrowIfNull(from, "from"); List<Move> validMoves = new List<Move>(); Piece piece = game.GetPieceAt(from); int l0 = game.BoardHeight; int l1 = game.BoardWidth; for (int i = -7; i < 8; i++) { if (i == 0) continue; if (from.Rank + i > 0 && from.Rank + i <= l0) { Move move = new Move(from, new Position(from.File, from.Rank + i), piece.Owner); if (gameMoveValidator(move)) { validMoves.Add(move); if (returnIfAny) return new ReadOnlyCollection<Move>(validMoves); } } if ((int)from.File + i > -1 && (int)from.File + i < l1) { Move move = new Move(from, new Position(from.File + i, from.Rank), piece.Owner); if (gameMoveValidator(move)) { validMoves.Add(move); if (returnIfAny) return new ReadOnlyCollection<Move>(validMoves); } } } return new ReadOnlyCollection<Move>(validMoves); }
public bool startTurn() { iteration++; int count = 0; count = Client.getMoveCount(connection); moves = new Move[count]; for(int i = 0; i < count; i++) { moves[i] = new Move(Client.getMove(connection, i)); } count = Client.getPieceCount(connection); pieces = new Piece[count]; for(int i = 0; i < count; i++) { pieces[i] = new Piece(Client.getPiece(connection, i)); } count = Client.getPlayerCount(connection); players = new Player[count]; for(int i = 0; i < count; i++) { players[i] = new Player(Client.getPlayer(connection, i)); } if(!initialized) { initialized = true; init(); } return run(); }
public void MakeMove(Move move) { if (MoveReady != null) { MoveReady(this, new MoveReadyEventArgs(move)); } }
/// <summary> /// Tries to move in the direction of the specified move. /// </summary> /// <param name="move">The move indicating where to go.</param> /// <returns><code>true</code> if the move completed /// successfully, <code>false</code> otherwise.</returns> internal bool DoMove(Move move) { lock (moveLock) { return DoMoveAux(move); } }
// Use this for initialization void Start () { playerMovement = player.GetComponent<Move>(); initialPosition = transform.position; print ("Initial pos: " + initialPosition.ToString ()); print ("Dissaproval: " + disapproval.ToString ()); }
private static Move[][][][] GenerateDoublePushes() { Move[][][][] moves = new Move[2][][][]; moves[0] = new Move[8][][]; moves[1] = new Move[8][][]; moves[0][3] = new Move[256][]; moves[1][4] = new Move[256][]; for (int b = 0; b < 256; ++b) { moves[0][3][b] = GetPawnMoves(3, (byte)b, -16); moves[1][4][b] = GetPawnMoves(4, (byte)b, 16); } for (int rank = 0; rank < 8; ++rank) { if ((rank == 3) || (rank == 4)) continue; moves[0][rank] = new Move[256][]; moves[1][rank] = new Move[256][]; for (int b = 0; b < 256; ++b) { moves[0][rank][b] = new Move[0]; moves[1][rank][b] = new Move[0]; } } return moves; }
public void Damage(Pokemon otherPoke, Move move){ //this must take p account weakness and attributes (defense, attack, sp_Defense, sp_Attack) //this must be object oriented moveCast = move.moveType.ToString () ; switch(move.moveType){ //These attack type and stab are not included. They(included atkpower) will have to be be invoked directly from database and switch wont be required case MoveNames.Tackle:{ int atkPower = 35; damage = ((((2 * otherPoke.level / 5 + 2) * otherPoke.attack * atkPower / defence) / 50) + 2) * Random.Range(217,255)/255; //((2A/5+2)*B*C)/D)/50)+2)*X)*Y/10)*Z)/255 hp -= damage/TotalHP(); isHPZero(); currentHealth -= damage; GiveXP(10); break; } case MoveNames.Scratch:{ int atkPower = 35; damage = ((((2 * otherPoke.level / 5 + 2) * otherPoke.attack * atkPower / defence) / 50) + 2) * Random.Range(217,255)/255; //((2A/5+2)*B*C)/D)/50)+2)*X)*Y/10)*Z)/255 hp -= damage/TotalHP(); isHPZero(); GiveXP(10); break; } } }
protected override bool IsValidMove(Move move, bool validateCheck, bool careAboutWhoseTurnItIs) { ChessUtilities.ThrowIfNull(move, "move"); if (move.OriginalPosition.Equals(move.NewPosition)) return false; Piece piece = GetPieceAt(move.OriginalPosition.File, move.OriginalPosition.Rank); if (careAboutWhoseTurnItIs && move.Player != WhoseTurn) return false; if (piece.Owner != move.Player) return false; Piece pieceAtDestination = GetPieceAt(move.NewPosition); if (pieceAtDestination != null && (pieceAtDestination.Owner == move.Player || piece is King)) { return false; } if (!piece.IsValidMove(move, this)) { return false; } if (validateCheck && WouldBeSuicideOrInvalidSelfMoveInCheck(move, move.Player)) { return false; } else if (WouldBeSuicide(move, move.Player)) { return false; } return true; }
// Use this for initialization void Start() { move = GetComponent<Move>(); //target = GameObject.FindWithTag (targetTag); target = GameObject.Find(targetTag); //target = GameObject.FindGameObjectWithTag (targetTag); }
public Move Turn() { while(true) { Move move = new Move(new Location(random.Next(0,BoardSize),random.Next(0,BoardSize)),(MoveType)random.Next(0,7)); if(!Program.VerifyMove(move,BotNumber)) continue; return move; } }
void Awake() { //load from xml moves.Add(new Move()); move = moves[moves.Count-1]; move.name = "Punch Left"; move.hitTime = 0.1f; move.duration = 0.6f; move.damage = 7.5f; move.reach = 0.8f; move.forwardForce = 100; moves.Add(new Move()); move = moves[moves.Count-1]; move.name = "Punch Right"; move.hitTime = 0.1f; move.duration = 0.5f; move.damage = 10f; move.forwardForce = 125; moves.Add(new Move()); move = moves[moves.Count-1]; move.name = "Kick"; move.hitTime = 0.2f; move.duration = 0.7f; move.damage = 15f; move.reach = 1; move.forwardForce = 150; move.upForce = 100; move.restrictAirControl = 1; }
public void Move(Wizard self, World world, Game game, Move move) { #if DEBUG // один раз вызвать Begin*() vc.BeginPost(); #endif move.Speed = game.WizardForwardSpeed; move.StrafeSpeed = game.WizardStrafeSpeed; move.Turn = game.WizardMaxTurnAngle; move.Action = ActionType.MagicMissile; #if DEBUG // вывод отладочной информации vc.Text(self.X - 35, self.Y - 37, string.Format("{0:D} | {1:F0} : {2:F0}", self.RemainingCooldownTicksByAction[(int)ActionType.MagicMissile], self.X, self.Y)); vc.Line(self.X, self.Y, self.X + Math.Cos(self.Angle - game.StaffSector / 2f)*self.CastRange, self.Y + Math.Sin(self.Angle - game.StaffSector / 2f)*self.CastRange, 1f, 0.7f, 0.7f); vc.Line(self.X, self.Y, self.X + Math.Cos(self.Angle + game.StaffSector / 2f) * self.CastRange, self.Y + Math.Sin(self.Angle + game.StaffSector / 2f) * self.CastRange, 1f, 0.7f, 0.7f); vc.Arc(self.X, self.Y, self.CastRange, self.Angle - game.StaffSector / 2f, game.StaffSector, 1f, 0.7f, 0.7f); #endif move.Turn = 0.01; move.Speed = 3; move.Action = ActionType.MagicMissile; #if DEBUG // в конце вызвать End*() vc.EndPost(); #endif }
// Use this for initialization void Start () { player = FindObjectOfType<Move> (); //shoots the direction right if (player.transform.localScale.x < 0) speed = -speed; }
public BFSNode(BFSNode node) { board = node.board; parent = node.parent; blank_pos = node.blank_pos; move = node.move; }
/// <summary> /// Causes the player of this game to receive the given move. /// </summary> protected void ReceiveMove(Move Move, Board NewBoard) { if (this.MoveReceived != null) { this.MoveReceived(Move, NewBoard); } }
/** Record move as a failure. */ public void addFail(Position pos, Move m, int depth) { int p = pos.getPiece(m.from); int cnt = depth; countFail[p][m.to] += cnt; score[p][m.to] = -1; }
public BFSNode(Board nextBoard, Position blank_pos, BFSNode parent = null, Move move = null) { board = nextBoard; this.blank_pos = blank_pos; this.parent = parent; this.move = move; }
public override void EndGame(Virus percept) { if (learn) { double reward = 0; byte winner = percept.Winner; if (winner == playerNumber) reward = 1; else if (winner != playerNumber && winner != 0) reward = -1; else reward = 0; if (!N.ContainsKey(prevState.CustomHash())) N.Add(prevState.CustomHash(), new Dictionary<UInt32, int>()); if (!N[prevState.CustomHash()].ContainsKey(prevAction.CustomHash())) N[prevState.CustomHash()].Add(prevAction.CustomHash(), 0); N[prevState.CustomHash()][prevAction.CustomHash()]++; Q[prevState.CustomHash()][prevAction.CustomHash()] = Q[prevState.CustomHash()][prevAction.CustomHash()] + LearningRate(N[prevState.CustomHash()][prevAction.CustomHash()]) * (reward - Q[prevState.CustomHash()][prevAction.CustomHash()]); } prevState = default(VirusBoard); prevAction = default(Move); prevReward = 0; }
public BFSNode() { board = new Board(); blank_pos = new Position(); parent = null; move = new Move(); }
public Move(Move move) { this.To = move.To; this.From = move.From; this.Promote = move.Promote; this.Bits = move.Bits; }
private bool TryInputMove(out Move move) { move = null; var input = Console.ReadLine(); if (input == null) return false; var parts = input.Split(' '); if (parts.Length != 2) return false; int row, column; try { row = Convert.ToInt32(parts[0]); column = Convert.ToInt32(parts[1]); } catch (FormatException) { return false; } move = new Move(row, column); return true; }
public AStarNode(Board board, AStarNode parent, Position blank, Move move) { parent_ = parent; board_ = board; blank_pos_ = blank; move_ = move; }
public void EqualsReturnsFalseWhenBoardIsDifferent() { int[,] data1 = { {9,0,0, 0,0,5, 6,8,1 }, {0,6,0, 2,8,0, 7,0,0 }, {0,0,0, 0,0,6, 9,0,5 }, {0,8,0, 0,0,2, 0,4,6 }, {0,0,5, 0,0,0, 3,0,0 }, {1,9,0, 5,0,0, 0,7,0 }, {8,0,2, 9,0,0, 0,0,0 }, {0,0,9, 0,2,7, 0,6,0 }, {6,7,4, 8,0,0, 0,0,3 } }; int[,] data2 = { {9,0,0, 0,0,5, 6,8,1 }, {0,6,0, 2,8,0, 7,0,0 }, {0,0,0, 0,0,6, 9,0,5 }, {0,8,0, 0,0,2, 0,4,6 }, {0,0,5, 0,0,0, 3,0,0 }, {1,9,0, 5,0,0, 0,7,0 }, {8,0,2, 9,0,0, 0,0,0 }, {0,0,9, 0,2,7, 0,6,0 }, {6,7,4, 8,0,0, 0,1,3 } }; IBoard board1 = new Board(data1); IBoard board2 = new Board(data2); IMove move1 = new Move(board1, 0, 1, 2); IMove move2 = new Move(board2, 0, 1, 2); Assert.False(move1.Equals(move2)); Assert.False(move2.Equals(move1)); }
// Public Methods (1) /// <summary> /// Waits until the machine player figures what move to play /// </summary> /// <returns>Machine player's move</returns> public override Move WaitForMove() { Move theMove = null; Referee theReferee = new Referee(); int maxGrade = -100; for (int row = 0; row < GameBoard.Rows; row++) { for (int column = 0; column < GameBoard.Columns; column++) { if (this.GameBoard[row, column] == PlayerToken.Empty) { // Get a board clone GameBoard hypoBoard = this.GameBoard.Clone(); // Make the hypothetical move on the cloned board Move hypoMove = new Move(row, column, this.PlayerToken); theReferee.ApplyMove(hypoBoard, hypoMove); // Grade the new board int grade = this.Grade(hypoBoard); // Keep the move as a candid if it's got good grade if (grade > maxGrade) { maxGrade = grade; theMove = hypoMove; } } } } return theMove; }
public TimedMove(Move move, int wait_before, int wait_after) : base(move) { this.wait_before = wait_before; this.wait_after = wait_after; this.undo = false; }
public AStarNode() { parent_ = null; board_ = new Board(); blank_pos_ = new Position(); move_ = new Move(); }
private static IEnumerable<Move> BuildMoves(Move move) { var res = new List<Move> {new Move(move.R, move.C, move.S)}; for (int i = 1; i < 3; i++) { res.Add(new Move(move.R, move.C, move.S + i)); res.Add(new Move(move.R, move.C, move.S - i)); res.Add(new Move(move.R, move.C + i, move.S)); res.Add(new Move(move.R, move.C - i, move.S)); res.Add(new Move(move.R, move.C + i, move.S + i)); res.Add(new Move(move.R, move.C + i, move.S - i)); res.Add(new Move(move.R, move.C - i, move.S + i)); res.Add(new Move(move.R, move.C - i, move.S - i)); res.Add(new Move(move.R + i, move.C, move.S)); res.Add(new Move(move.R - i, move.C, move.S)); res.Add(new Move(move.R + i, move.C, move.S + i)); res.Add(new Move(move.R + i, move.C, move.S - i)); res.Add(new Move(move.R - i, move.C, move.S + i)); res.Add(new Move(move.R - i, move.C, move.S - i)); res.Add(new Move(move.R + i, move.C + i, move.S + i)); res.Add(new Move(move.R + i, move.C + i, move.S - i)); res.Add(new Move(move.R + i, move.C - i, move.S + i)); res.Add(new Move(move.R + i, move.C - i, move.S - i)); res.Add(new Move(move.R - i, move.C + i, move.S + i)); res.Add(new Move(move.R - i, move.C + i, move.S - i)); res.Add(new Move(move.R - i, move.C - i, move.S + i)); res.Add(new Move(move.R - i, move.C - i, move.S - i)); } return res.Where(m => m.IsValid()).ToList(); }
// Use this for initialization void Start () { moveDirection = states.STOP; player = GameObject.FindGameObjectWithTag("Player"); playerState = player.gameObject.GetComponent<Move> (); }
protected override bool CanBeatLegalMove(Move move) { if (move is DynamiteMove) return true; return false; }
//____________________________________________________________\\\\\\___MonoMethods___//////_______________________________________________________________ //_________________\\\\\\___Awake___//////_________________ // Calculates wall positions and goal posts + sets // character + resets path //‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ void Awake() { masterScript = GameObject.FindObjectOfType (typeof(MasterScript)) as MasterScript; gameScript = GameObject.FindObjectOfType (typeof(Game)) as Game; moveScript = GameObject.FindObjectOfType (typeof(Move)) as Move; sinCosMovementScript = GameObject.FindObjectOfType (typeof(SinCosMovement)) as SinCosMovement; linearRotationScript = GameObject.FindObjectOfType (typeof(LinearRotation)) as LinearRotation; sinCosRotationScript = GameObject.FindObjectOfType (typeof(SinCosRotation)) as SinCosRotation; this.name = "Projectile"; bounceCount = 0; wallTop = fieldHeight / 2; wallBottom = -fieldHeight / 2; wallRight = fieldWidth / 2; wallLeft = -fieldWidth / 2; goalTop = goalHeight / 2; goalBottom = -goalHeight / 2; p1char = masterScript.GetCharacter (1) - 1; p2char = masterScript.GetCharacter (2) - 1; this.ResetPath (); }
/// <summary> /// Indique au contrôleur du joueur que c'est à lui de jouer /// </summary> public abstract void Play(Move move);
/// <summary> /// 駒打ち(is_drop()==true)のときの打った駒 /// 先後の区別なし。PAWN~ROOKまでの値が返る。 /// </summary> public static Piece DroppedPiece(this Move m) { return (Piece)((m.ToInt() >> 7) & 0x7f); }
// Use this for initialization void Start() { move = GetComponent <Move>(); }
/// <summary> /// Donne au joueur le mouvement à effectuer /// </summary> /// <param name="move"></param> public abstract void Move(Move move);
// これ使わないのでコメントアウトしておく。 // RemoveNextNode()のように、KifuBranchの更新が必要だと思う。 /// <summary> /// currentNode(現在のnode)から、moveの指し手以降の枝を削除する /// </summary> /// <param name="move"></param> public void Remove(Move move) { currentNode.moves.RemoveAll((x) => x.nextMove == move); }
/// <summary> /// ある指し手に対する着手時刻を追加する。 /// </summary> /// <param name="move"></param> /// <param name="comment"></param> public void AddNodeMoveTime(Move move) => AddNodeMoveTime(move, DateTime.Now);
/// <summary> /// ある指し手に対する着手時刻を追加する。 /// </summary> /// <param name="move"></param> /// <param name="comment"></param> public void AddNodeMoveTime(Move move, DateTime movetime) { var m = currentNode.moves.FirstOrDefault((x) => x.nextMove == move); m.moveTime = movetime; }
/// <summary> /// ある指し手に対するノードコメントを追加する。 /// </summary> /// <param name="move"></param> /// <param name="comment"></param> public void AddNodeComment(Move move, string comment) { var m = currentNode.moves.FirstOrDefault((x) => x.nextMove == move); m.nextNode.comment = comment; }
/// <summary> /// 指し手mで進める。 /// mは、currentNodeのもつ指し手の一つであるものとする。 /// </summary> /// <param name="m"></param> public void DoMove(Move m) { DoMove(currentNode.moves.Find((x) => x.nextMove == m)); }
/// <summary> /// 対局していないときにUI上の操作で駒を動かす。 /// /// DoMove()に成功したならtrue。駒を動かせなかったならfalseが返る。 /// </summary> /// <param name="m"></param> public bool DoMoveUI(Move m, MiscSettings misc) { if (!position.IsLegal(m)) { return(false); } if (IsSpecialNode()) { // current nodeは、special moveによって到達したnodeであった。 // このことからlastMove() != nullが言える。 var last = LastMove(); var sm = last.nextMove; if (!(sm == Move.RESIGN || sm == Move.ILLEGAL_MOVE || sm == Move.INTERRUPT || sm == Move.TIME_UP)) { return(false); } // Move.DRAWとかMAX_MOVES_DRAWとかは、削除しても再度このnodeに到達してしまうのでこのspecial moveの // nodeで動かすわけにはいかない。 // 削除して問題なさげなので、このnodeを削除して、前の局面に戻れば良い。 UndoMove(); // この枝は、上記のRESIGNなどの枝なので、削除しておく。 currentNode.moves.Remove(last); } else if (IsNextNodeSpecialNode(true, misc) != Move.NONE) { return(false); } // このnodeはspecial nodeではないが、すでに千日手成立局面などに到達しているのであれば、 // この局面では何も出来ない。 var node_existed = currentNode.moves.Exists((x) => x.nextMove == m); // 現在の棋譜上の指し手なので棋譜ウィンドウの更新は不要である。 if (node_existed && kifuWindowMoves[pliesFromRoot].nextMove == m) { DoMove(m); return(true); } PropertyChangedEventEnable = false; // 新規nodeなので棋譜クリア ClearKifuForward(); var e = EnableKifuList; EnableKifuList = true; // 合法っぽいので受理して次の局面に行く if (node_existed) { // すでにあるのでそこを辿るだけにする。 // 現在棋譜ウィンドウの局面でないことは保証されている。 DoMove(m); // このあと、本譜の手順を選んでいき、このnodeに戻る int ply = 0; for (; currentNode.moves.Count != 0; ++ply) { DoMove(currentNode.moves[0]); } EnableKifuList = false; while (ply-- != 0) { UndoMove(); } } else { // -- 次のnodeとして存在しなかったのでnodeを生成して局面を移動する AddNode(m, KifuMoveTimes.Zero); DoMove(m); } // special nodeに到達してしまった。 m = IsNextNodeSpecialNode(true, misc); if (m != Move.NONE) { AddNode(m, KifuMoveTimes.Zero); DoMove(m); } // この結果、special nodeに到達する可能性があるが…。 EnableKifuList = false; PropertyChangedEventEnable = true; RaisePropertyChanged("KifuList", new List <KifuListRow>(KifuList)); RaisePropertyChanged("Position", position.Clone()); KifuDirty = true; // 新しいnodeに到達したので棋譜は汚れた扱い。 return(true); }
public Decision(Move move, double score) { m_move = move; m_score = score; }
public override bool MakeMove(Move m) { LastMoveIndex = m.MoveIndex; return(MovesAreValid); }
// Use this for initialization void Start() { move = GetComponent <Move>(); target_move = move.target.GetComponent <Move>(); }
/// <summary> /// ある指し手をCSA形式で出力する /// Move.ToSfen()のCSA版 /// </summary> /// <param name="pos"></param> /// <param name="move"></param> /// <param name="turnOut"></param> /// <returns></returns> public static string ToCSA(this Position pos, Move move, bool turnOut = true) { switch (move) { case Move.NONE: case Move.NULL: return("%ERROR"); case Move.RESIGN: return("%TORYO"); case Move.WIN: return("%WIN"); case Move.WIN_THEM: // これに対応するものがないので仕方がない。 return("%WIN"); case Move.INTERRUPT: return("%CHUDAN"); case Move.REPETITION_DRAW: return("%SENNICHITE"); case Move.MAX_MOVES_DRAW: return("%JISHOGI"); case Move.TIME_UP: return("%TIME_UP"); // ToDo: 他にも対応を確認 } if (move.IsSpecial()) { return(""); } StringBuilder csa = new StringBuilder(); // 手番 if (turnOut) { csa.Append(pos.sideToMove != Color.WHITE ? "+" : "-"); } // 打つ指し手のときは移動元の升は"00"と表現する。 // さもなくば、"77"のように移動元の升目をアラビア数字で表現。 if (move.IsDrop()) { csa.Append("00"); } else { csa.AppendFormat("{0}{1}", HW_NUMBER[move.From().ToFile().ToInt()], HW_NUMBER[move.From().ToRank().ToInt()]); } csa.AppendFormat("{0}{1}", HW_NUMBER[move.To().ToFile().ToInt()], HW_NUMBER[move.To().ToRank().ToInt()]); Piece p = move.IsDrop() ? move.DroppedPiece() : pos.PieceOn(move.From()); if (move.IsPromote()) { p |= Piece.PROMOTE; } csa.Append(csa_piece[p.ToInt()]); return(csa.ToString()); }
/// <summary> /// Funkce rekurzivně hádá čísla a pokud je uhodne špatně, vrací se zpět pomocí proměnné <see cref="pastMoves;"/>. /// </summary> /// <param name="x">Řádek aktuálního políčka</param> /// <param name="y">Sloupec aktuálního políčka</param> static void TakeGuess(int x, int y) { //pokud je políčko prázdné if (pole[x, y] == 0) { //for + podmínka projdou postupně všechny možné možnosti pro políčko (x,y) for (int number = 1; number < 10; number++) { if (hinty[x, y, number]) { //tento cyklus opouštím pouze přes returny v podmínkách while (true) { //toto číslo pouze hádám SetTile(x, y, number, true); MakeImplications(); //zjištění stavu tabulky správnost a kompletnost bool isComplete = IsSudokuComplete(); bool isValid = IsSudokuValid(true); //sudoku vyřešené if (isComplete && isValid) { //konec return; } //nevyřešené ale správně if (!isComplete && isValid) { //hádá další čísla TakeGuess(x, y); return; } //vrátím se zpět if (!isValid) { do { //vrátím všechny logické kroky Move lastMove = pastMoves[pastMoves.Count() - 1]; while (!lastMove.isGuess) { //vrátí krok pole[lastMove.row, lastMove.column] = 0; pastMoves.RemoveAt(pastMoves.Count() - 1); lastMove = pastMoves[pastMoves.Count() - 1]; } //a pak ještě ten který jsem hádal pole[lastMove.row, lastMove.column] = 0; x = lastMove.row; y = lastMove.column; number = lastMove.number + 1; pastMoves.RemoveAt(pastMoves.Count() - 1); depth--; } while (number > 9); // ^--- pokud se vrátím na políčko, kde jsem už vyčerpal všechny možnosti, je také špatně uhodnuté, tedy se musím vrátit ještě jednou //vypočítat znovu nápovědy ResetHints(); UpdateHints(); } } } } } //pokud dojdu sem, je jasné, že na políčku (x,y) je číslo => posunu se o políčko y++; if (y > 8) { x++; } y %= 9; if (y > 8 || x > 8) { return; } //hádám znovu TakeGuess(x, y); }
// JSON Kifu Format private string FromJkfString(string content, KifuFileType kf) { try { var CSA_PIECE = new string[] { " ", "FU", "KY", "KE", "GI", "KA", "HI", "KI", "OU", "TO", "NY", "NK", "NG", "UM", "RY", "QU", " ", "FU", "KY", "KE", "GI", "KA", "HI", "KI", "OU", "TO", "NY", "NK", "NG", "UM", "RY", "QU", }; var jsonObj = JkfUtil.FromString(content); if (jsonObj == null) { return("有効なデータが得られませんでした"); } if (jsonObj.header != null) { foreach (var key in jsonObj.header.Keys) { var trimedKey = key.Trim(' ', '\t', '\n', '\r', ' ', '\x0b', '\x00'); KifuHeader.header_dic[trimedKey] = jsonObj.header[key]; } } // Treeに局面をセットする void SetTree(BoardType bt) { Tree.SetRootBoardType(bt); } if (jsonObj.initial != null) { switch (jsonObj.initial.preset) { case "HIRATE": SetTree(BoardType.NoHandicap); break; case "KY": SetTree(BoardType.HandicapKyo); break; case "KY_R": SetTree(BoardType.HandicapRightKyo); break; case "KA": SetTree(BoardType.HandicapKaku); break; case "HI": SetTree(BoardType.HandicapHisya); break; case "HIKY": SetTree(BoardType.HandicapHisyaKyo); break; case "2": SetTree(BoardType.Handicap2); break; case "3": SetTree(BoardType.Handicap3); break; case "4": SetTree(BoardType.Handicap4); break; case "5": SetTree(BoardType.Handicap5); break; case "5_L": SetTree(BoardType.HandicapLeft5); break; case "6": SetTree(BoardType.Handicap6); break; case "8": SetTree(BoardType.Handicap8); break; case "10": SetTree(BoardType.Handicap10); break; case "OTHER": if (jsonObj.initial.data == null) { return("初期局面が指定されていません"); } var color = jsonObj.initial.data.color == 0 ? Color.BLACK : Color.WHITE; var board = new Piece[81]; for (File f = File.FILE_1; f <= File.FILE_9; ++f) { for (Rank r = Rank.RANK_1; r <= Rank.RANK_9; ++r) { var sqi = Util.MakeSquare(f, r).ToInt(); var p = jsonObj.initial.data.board[f.ToInt(), r.ToInt()]; switch (p.color) { case 0: switch (p.kind) { case "FU": board[sqi] = Piece.B_PAWN; break; case "KY": board[sqi] = Piece.B_LANCE; break; case "KE": board[sqi] = Piece.B_KNIGHT; break; case "GI": board[sqi] = Piece.B_SILVER; break; case "KA": board[sqi] = Piece.B_BISHOP; break; case "HI": board[sqi] = Piece.B_ROOK; break; case "KI": board[sqi] = Piece.B_GOLD; break; case "OU": board[sqi] = Piece.B_KING; break; case "TO": board[sqi] = Piece.B_PRO_PAWN; break; case "NY": board[sqi] = Piece.B_PRO_LANCE; break; case "NK": board[sqi] = Piece.B_PRO_KNIGHT; break; case "NG": board[sqi] = Piece.B_PRO_SILVER; break; case "UM": board[sqi] = Piece.B_HORSE; break; case "RY": board[sqi] = Piece.B_DRAGON; break; default: board[sqi] = Piece.NO_PIECE; break; } break; case 1: switch (p.kind) { case "FU": board[sqi] = Piece.W_PAWN; break; case "KY": board[sqi] = Piece.W_LANCE; break; case "KE": board[sqi] = Piece.W_KNIGHT; break; case "GI": board[sqi] = Piece.W_SILVER; break; case "KA": board[sqi] = Piece.W_BISHOP; break; case "HI": board[sqi] = Piece.W_ROOK; break; case "KI": board[sqi] = Piece.W_GOLD; break; case "OU": board[sqi] = Piece.W_KING; break; case "TO": board[sqi] = Piece.W_PRO_PAWN; break; case "NY": board[sqi] = Piece.W_PRO_LANCE; break; case "NK": board[sqi] = Piece.W_PRO_KNIGHT; break; case "NG": board[sqi] = Piece.W_PRO_SILVER; break; case "UM": board[sqi] = Piece.W_HORSE; break; case "RY": board[sqi] = Piece.W_DRAGON; break; default: board[sqi] = Piece.NO_PIECE; break; } break; default: board[sqi] = Piece.NO_PIECE; break; } } } var hands = new Hand[2] { Hand.ZERO, Hand.ZERO }; if (jsonObj.initial.data.hands != null && jsonObj.initial.data.hands.Count >= 2) { foreach (var c in new Color[] { Color.BLACK, Color.WHITE }) { if (jsonObj.initial.data.hands[c.ToInt()] != null) { foreach (var p in new Piece[] { Piece.PAWN, Piece.LANCE, Piece.KNIGHT, Piece.SILVER, Piece.GOLD, Piece.BISHOP, Piece.ROOK }) { int value; if (jsonObj.initial.data.hands[c.ToInt()].TryGetValue(CSA_PIECE[p.ToInt()], out value)) { hands[c.ToInt()].Add(p, value); } } } } } var sfen = Position.SfenFromRawdata(board, hands, color, 1); Tree.SetRootSfen(sfen); break; default: return("初期局面が不明です"); } } if (jsonObj.moves != null) { Move m = Move.NONE; foreach (var jkfMove in jsonObj.moves) { TimeSpan spend = (jkfMove.time != null && jkfMove.time.now != null) ? new TimeSpan(jkfMove.time.now.h ?? 0, jkfMove.time.now.m, jkfMove.time.now.s): TimeSpan.Zero; if (!string.IsNullOrWhiteSpace(jkfMove.special)) { switch (jkfMove.special) { case "TORYO": m = Move.RESIGN; break; case "CHUDAN": m = Move.INTERRUPT; break; case "SENNICHITE": m = Move.REPETITION_DRAW; break; case "TIME_UP": m = Move.TIME_UP; break; case "JISHOGI": m = Move.MAX_MOVES_DRAW; break; case "KACHI": m = Move.WIN; break; case "HIKIWAKE": m = Move.DRAW; break; case "TSUMI": m = Move.MATED; break; case "ILLEGAL_MOVE": m = Move.ILLEGAL_MOVE; break; case "+ILLEGAL_ACTION": m = Tree.position.sideToMove == Color.BLACK ? Move.ILLEGAL_ACTION_LOSE : Move.ILLEGAL_ACTION_WIN; break; case "-ILLEGAL_ACTION": m = Tree.position.sideToMove == Color.BLACK ? Move.ILLEGAL_ACTION_WIN : Move.ILLEGAL_ACTION_LOSE; break; // 以下、適切な変換先不明 case "ERROR": case "FUZUMI": case "MATTA": default: m = Move.NONE; break; } } else if (jkfMove.move == null) { m = Move.NONE; } else if (jkfMove.move.to == null) { m = Move.NONE; } else if (jkfMove.move.from == null) { File f = (File)(jkfMove.move.to.x - 1); Rank r = (Rank)(jkfMove.move.to.y - 1); if (f < File.FILE_1 || f > File.FILE_9 || r < Rank.RANK_1 || r > Rank.RANK_9) { m = Move.NONE; } else { Square sq = Util.MakeSquare(f, r); switch (jkfMove.move.piece) { case "FU": m = Util.MakeMoveDrop(Piece.PAWN, sq); break; case "KY": m = Util.MakeMoveDrop(Piece.LANCE, sq); break; case "KE": m = Util.MakeMoveDrop(Piece.KNIGHT, sq); break; case "GI": m = Util.MakeMoveDrop(Piece.SILVER, sq); break; case "KI": m = Util.MakeMoveDrop(Piece.GOLD, sq); break; case "KA": m = Util.MakeMoveDrop(Piece.BISHOP, sq); break; case "HI": m = Util.MakeMoveDrop(Piece.ROOK, sq); break; default: m = Move.NONE; break; } } } else { File frF = (File)(jkfMove.move.from.x - 1); Rank frR = (Rank)(jkfMove.move.from.y - 1); File toF = (File)(jkfMove.move.to.x - 1); Rank toR = (Rank)(jkfMove.move.to.y - 1); if ( frF < File.FILE_1 || frF > File.FILE_9 || frR < Rank.RANK_1 || frR > Rank.RANK_9 || frF < File.FILE_1 || toF > File.FILE_9 || frR < Rank.RANK_1 || toR > Rank.RANK_9 ) { m = Move.NONE; } else { Square frSq = Util.MakeSquare(frF, frR); Square toSq = Util.MakeSquare(toF, toR); if (jkfMove.move.promote == true) { m = Util.MakeMovePromote(frSq, toSq); } else { m = Util.MakeMove(frSq, toSq); } } } Tree.AddNode(m, KifuMoveTimes.Zero /*ToDo:あとでちゃんと書く*/ /* spend */); if (m.IsSpecial() || !Tree.position.IsLegal(m)) { break; } Tree.DoMove(m); } } // ToDo: 分岐棋譜を読み込む } catch (Exception e) { return(e.ToString()); } return(null); }
private string ToJkfString() { Jkf jkf = new Jkf(); jkf.header = new Dictionary <string, string>(); foreach (var key in KifuHeader.header_dic.Keys) { jkf.header[key] = KifuHeader.header_dic[key]; } jkf.initial = new Jkf.Initial(); var CSA_PIECE = new string[] { " ", "FU", "KY", "KE", "GI", "KA", "HI", "KI", "OU", "TO", "NY", "NK", "NG", "UM", "RY", "QU", " ", "FU", "KY", "KE", "GI", "KA", "HI", "KI", "OU", "TO", "NY", "NK", "NG", "UM", "RY", "QU", }; switch (Tree.rootBoardType) { case BoardType.NoHandicap: jkf.initial.preset = "HIRATE"; break; case BoardType.HandicapKyo: jkf.initial.preset = "KY"; break; case BoardType.HandicapRightKyo: jkf.initial.preset = "KY_R"; break; case BoardType.HandicapKaku: jkf.initial.preset = "KA"; break; case BoardType.HandicapHisya: jkf.initial.preset = "HI"; break; case BoardType.HandicapHisyaKyo: jkf.initial.preset = "HIKY"; break; case BoardType.Handicap2: jkf.initial.preset = "2"; break; case BoardType.Handicap3: jkf.initial.preset = "3"; break; case BoardType.Handicap4: jkf.initial.preset = "4"; break; case BoardType.Handicap5: jkf.initial.preset = "5"; break; case BoardType.HandicapLeft5: jkf.initial.preset = "5_L"; break; case BoardType.Handicap6: jkf.initial.preset = "6"; break; case BoardType.Handicap8: jkf.initial.preset = "8"; break; case BoardType.Handicap10: jkf.initial.preset = "10"; break; default: jkf.initial.preset = "OTHER"; jkf.initial.data = new Jkf.Data() { color = Tree.position.sideToMove == Color.BLACK ? 0 : 1, board = new Jkf.Board[9, 9], hands = new List <Dictionary <string, int> > { new Dictionary <string, int>(), new Dictionary <string, int>(), }, }; for (File f = File.FILE_1; f <= File.FILE_9; ++f) { for (Rank r = Rank.RANK_1; r <= Rank.RANK_9; ++r) { var p = Tree.position.PieceOn(Util.MakeSquare(f, r)); jkf.initial.data.board[f.ToInt(), r.ToInt()] = p == Piece.NO_PIECE ? new Jkf.Board(): new Jkf.Board() { kind = CSA_PIECE[p.PieceType().ToInt()], color = p.PieceColor() == Color.BLACK ? 0 : 1, }; } } foreach (var c in new Color[] { Color.BLACK, Color.WHITE }) { foreach (var p in new Piece[] { Piece.PAWN, Piece.LANCE, Piece.KNIGHT, Piece.SILVER, Piece.GOLD, Piece.BISHOP, Piece.ROOK }) { jkf.initial.data.hands[c.ToInt()][CSA_PIECE[p.ToInt()]] = Tree.position.Hand(c).Count(p); } } break; } { // 初期局面情報の出力 var root = new Jkf.MoveFormat() { comments = new List <string>(), }; foreach (var line in Tree.rootNode.comment.Split('\n')) { root.comments.Add(line); } foreach (var line in Tree.RootKifuLog.engineComment.Split('\n')) { root.comments.Add(line); } // 棋譜の出力 var outList = jkf.moves = new List <Jkf.MoveFormat>() { root }; var inStack = new Stack <Node>(); var outStack = new Stack <List <List <Jkf.MoveFormat> > >(); var endNode = false; Func <KifMoveInfo, string> relStr = (moveInfo) => { string rel, beh; switch (moveInfo.relative) { case KifMoveInfo.Relative.LEFT: rel = "L"; break; case KifMoveInfo.Relative.STRAIGHT: rel = "C"; break; case KifMoveInfo.Relative.RIGHT: rel = "R"; break; default: rel = ""; break; } switch (moveInfo.behavior) { case KifMoveInfo.Behavior.FORWARD: beh = "U"; break; case KifMoveInfo.Behavior.SLIDE: beh = "M"; break; case KifMoveInfo.Behavior.BACKWARD: beh = "D"; break; default: beh = ""; break; } // ToDo: 省略可能な駒打ちの場合に"H"と出力すべきか確認する // 省略可能な駒打ちの場合でも"H"と出力 string drop = moveInfo.drop == KifMoveInfo.Drop.NONE ? "" : "H"; // 省略可能な駒打ちの場合は"H"と出力しない //string drop = moveInfo.drop == KifMoveInfo.Drop.EXPLICIT ? "H" : ""; return(rel + beh + drop); }; while (!endNode || inStack.Count != 0) { int select = 0; var jkfMove = new Jkf.MoveFormat() { forks = new List <List <Jkf.MoveFormat> >(), }; if (endNode) { endNode = false; var inNode = inStack.Pop(); var outBranches = outStack.Pop(); outBranches.Add(outList = new List <Jkf.MoveFormat>()); while (inNode.ply < Tree.gamePly) { Tree.UndoMove(); } select = inNode.select; } else { int count = Tree.currentNode.moves.Count; if (count == 0) { endNode = true; continue; } if (count != 1) { for (int i = 1; i < count; ++i) { inStack.Push(new Node(Tree.gamePly, i)); outStack.Push(jkfMove.forks); } } } var kifMove = Tree.currentNode.moves[select]; Move m = kifMove.nextMove; if (m.IsSpecial()) { endNode = true; switch (m) { case Move.MATED: jkfMove.special = "TYORYO"; break; case Move.INTERRUPT: jkfMove.special = "CHUDAN"; break; case Move.REPETITION_WIN: jkfMove.special = "SENNICHITE"; break; case Move.REPETITION_DRAW: jkfMove.special = "SENNICHITE"; break; case Move.WIN: jkfMove.special = "KACHI"; break; case Move.WIN_THEM: jkfMove.special = "KACHI"; break; // ないので仕方がない.. case Move.MAX_MOVES_DRAW: jkfMove.special = "JISHOGI"; break; case Move.RESIGN: jkfMove.special = "TORYO"; break; case Move.TIME_UP: jkfMove.special = "TIME_UP"; break; default: continue; } } else { var moveInfo = new KifMoveInfo(Tree.position, kifMove.nextMove); jkfMove.move = new Jkf.Move() { color = Tree.position.sideToMove == Color.BLACK ? 0 : 1, from = m.IsDrop() ? null : new Jkf.PlaceFormat() { x = m.From().ToFile().ToInt() + 1, y = m.From().ToRank().ToInt() + 1, }, to = new Jkf.PlaceFormat() { x = m.To().ToFile().ToInt() + 1, y = m.To().ToRank().ToInt() + 1, }, piece = CSA_PIECE[moveInfo.fromPc.ToInt()], same = moveInfo.same, promote = (moveInfo.promote == KifMoveInfo.Promote.NONE) ? (bool?)null : (moveInfo.promote == KifMoveInfo.Promote.PROMOTE), capture = moveInfo.capPc == Piece.NO_PIECE ? null : CSA_PIECE[moveInfo.capPc.ToInt()], relative = relStr(moveInfo), }; } var turn = Tree.position.sideToMove; var kifuTime = kifMove.kifuMoveTimes.Player(turn); var thinkingTime = kifuTime.ThinkingTime; var totalTime = kifuTime.TotalTime; jkfMove.time = new Jkf.Time() { now = new Jkf.TimeFormat() { h = thinkingTime.Days * 24 + thinkingTime.Hours, m = thinkingTime.Minutes, s = thinkingTime.Seconds, }, total = new Jkf.TimeFormat() { h = totalTime.Days * 24 + totalTime.Hours, m = totalTime.Minutes, s = totalTime.Seconds, }, }; outList.Add(jkfMove); } } return(jkf.ToJson()); }
public override bool IsMoveValid(Move m) { return(MovesAreValid); }
/// <summary> /// Uint32型へ変換。 /// </summary> /// <param name="m"></param> /// <returns></returns> public static Int32 ToInt(this Move m) { return((Int32)m); }
private void OnTriggerEnter(Collider obj) { PrevMove = obj.GetComponent <MoveCharacter>().Player.Move; obj.GetComponent <MoveCharacter>().Player.Move = PowerUpTransfer.Transfer(); }
/// <summary> /// 指し手がおかしくないかをテストする /// ただし、盤面のことは考慮していない。 /// Move.NONEとspecial moveのみがfalse。その他はtrue。 /// </summary> /// <param name="m"></param> /// <returns></returns> public static bool IsOk(this Move m) { return(!(m == Move.NONE || m.IsSpecial())); }
/// <summary> /// 指し手がSPECIALな指し手(DoMove出来ない)であるかを判定する。 /// </summary> /// <param name="m"></param> /// <returns></returns> public static bool IsSpecial(this Move m) { return(m >= Move.SPECIAL); }
public override void Reset(string opponent) { lastMove = (Move)(rand.Next() % 3); }
//Virtual public virtual void OnMoveLate(Move move) { }
public Move GetMove() { return(Move.Get(name)); }
public override void SetMove(Move move) { Tally(lastMove, move); // track stats for fun lastMove = move; }
/// <summary> /// 指し手が駒打ちか? /// </summary> /// <param name="m"></param> /// <returns></returns> public static bool IsDrop(this Move m) { return (m.ToInt() & (UInt16)Move.DROP) != 0; }
/// <summary> /// 指し手が成りか? /// </summary> public static bool IsPromote(this Move m) { return (m.ToInt() & (UInt16)Move.PROMOTE) != 0; }
/// <summary> /// 指し手の移動先の升を返す。 /// </summary> /// <param name="m"></param> /// <returns></returns> public static Square To(this Move m) { return (Square)(m.ToInt() & 0x7f); }
// This is the MiniMax algorithm public Move MiniMaxAlgorithm(int[,] board2D, int playerTurn, int maxDepth, int currentDepth, int alpha, int beta) { // If game over or maxDepth is reached if (CheckForNine(board2D) == true || currentDepth == maxDepth) { return(new Move(-1, -1, EvaluateBoard(board2D))); } Move selectedMove = new Move(-1, -1, 0); // If white turn (Maximizer) if (playerTurn == 2) { selectedMove.score = int.MinValue; } // If black turn (Minimizer) else if (playerTurn == 1) { selectedMove.score = int.MaxValue; } List <Vector2> allMoves; if (playerTurn == 2) { allMoves = ValidMoves(board2D, 2); // Calculate a move for each vector in allMoves foreach (Vector2 move in allMoves) { // Get the next board for MiniMax int[,] newBoard = GetNextBoardState(board2D, playerTurn, (int)move.X, (int)move.Y); // Get the score from the next MiniMax algorithm int score = MiniMaxAlgorithm(newBoard, 1, maxDepth, (currentDepth + 1), alpha, beta).score; if (score > selectedMove.score) { selectedMove.row = (int)move.X; selectedMove.col = (int)move.Y; selectedMove.score = score; // Alpha if (alphaBetaOn == true) { if (selectedMove.score > alpha) { alpha = selectedMove.score; } if (alpha >= beta) { break; } } } } } else if (playerTurn == 1) { allMoves = ValidMoves(board2D, 1); // Calculate a move for each vector in allMoves foreach (Vector2 move in allMoves) { // Get the next board for MiniMax int[,] newBoard = GetNextBoardState(board2D, playerTurn, (int)move.X, (int)move.Y); // Get the score from the next MiniMax algorithm int score = MiniMaxAlgorithm(newBoard, 2, maxDepth, (currentDepth + 1), alpha, beta).score; if (score < selectedMove.score) { selectedMove.row = (int)move.X; selectedMove.col = (int)move.Y; selectedMove.score = score; // Beta if (alphaBetaOn == true) { if (selectedMove.score < beta) { beta = selectedMove.score; } if (beta <= alpha) { break; } } } } } return(selectedMove); }