剖析:
奥赛罗有如下主要步骤:
1. Game()为主函数,来管理游戏中的所有活动
2.构造函数对游戏进行初始化
3.获取第一个玩家的输入
4.验证输入
5.更改棋盘格局
6.检验是否有人获胜了
7.获取第二个玩家的输入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | public class Question { private final int white = 1; private final int black = 2; private int[][] board;
/* Sets up the board in the standard othello starting positions, * and starts the game */ public void start () { ... }
/* Returns the winner, if any. If there are no winners, returns * 0 */ private int won() { if (!canGo (white) && !canGo (black)) { int count = 0; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if (board [i] [j] == white) { count++; } if (board [i] [j] == black) { count--; } } } if (count > 0) return white; if (count < 0) return black; return 3; } return 0; }
/* Returns whether the player of the specified color has a valid * move in his turn. This will return false when * 1. none of his pieces are present * 2. none of his moves result in him gaining new pieces * 3. the board is filled up */ private boolean canGo(int color) { ... }
/* Returns if a move at coordinate (x,y) is a valid move for the * specified player */ private boolean isValid(int color, int x, int y) { ... }
/* Prompts the player for a move and the coordinates for the move. * Throws an exception if the input is not valid or if the entered * coordinates do not make a valid move. */ private void getMove (int color) throws Exception { ... }
/* Adds the move onto the board, and the pieces gained from that * move. Assumes the move is valid. */ private void add (int x, int y, int color) { ... }
/* The actual game: runs continuously until a player wins */ private void game() { printBoard(); while (won() == 0) { boolean valid = false; while (!valid) { try { getMove(black); valid = true; } catch (Exception e) { System.out.println (“Enter a valid coordinate!”); } } valid = false; printBoard(); while (!valid) { try { getMove(white); valid = true; } catch (Exception e) { System.out.println (“Enter a valid coordinate!”); } } printBoard (); }
if (won()!=3) { System.out.println (won () == 1 ? “white” : “black” + “ won!”); } else { System.out.println(“It’s a draw!”); } } }
参考:http://wenku.baidu.com/view/47eda066f8c75fbfc67db27f.html |