📄 c4state.java
字号:
class C4State {
private static boolean[][][] map;
private int[][] score = new int[2][winPlaces];
public static final int winPlaces = 69, maxPieces = 42, Empty = 2;
private int numPieces;
public int[][] board = new int[7][6];
public C4State() {
// Initialize the map
int i, j, k, count = 0;
if (map == null) {
map = new boolean[7][6][winPlaces];
for (i = 0; i < 7; i++)
for (j = 0; j < 6; j++)
for (k = 0; k < winPlaces; k++)
map[i][j][k] = false;
// Set the horizontal win positions
for (i = 0; i < 6; i++)
for (j = 0; j < 4; j++) {
for (k = 0; k < 4; k++)
map[j + k][i][count] = true;
count++;
}
// Set the vertical win positions
for (i = 0; i < 7; i++)
for (j = 0; j < 3; j++) {
for (k = 0; k < 4; k++)
map[i][j + k][count] = true;
count++;
}
// Set the forward diagonal win positions
for (i = 0; i < 3; i++)
for (j = 0; j < 4; j++) {
for (k = 0; k < 4; k++)
map[j + k][i + k][count] = true;
count++;
}
// Set the backward diagonal win positions
for (i = 0; i < 3; i++)
for (j = 6; j >= 3; j--) {
for (k = 0; k < 4; k++)
map[j - k][i + k][count] = true;
count++;
}
}
// Initialize the board
for (i = 0; i < 7; i++)
for (j = 0; j < 6; j++)
board[i][j] = Empty;
// Initialize the scores
for (i = 0; i < 2; i++)
for (j = 0; j < winPlaces; j++)
score[i][j] = 1;
numPieces = 0;
}
public boolean isWinner(int player) {
// See whether the player has won
for (int i = 0; i < winPlaces; i++)
if (score[player][i] == 16)
return true;
return false;
}
public boolean isTie() {
// See whether there is a tie
return (numPieces == maxPieces);
}
public int dropPiece(int player, int xPos) {
// See whether the slot has room for the piece
int yPos = 0;
while ((board[xPos][yPos] != Empty) && (++yPos < 6))
;
// The slot is full
if (yPos == 6)
return -1;
// The slot has room, so drop the piece
board[xPos][yPos] = player;
numPieces++;
updateScore(player, xPos, yPos);
return yPos;
}
private void updateScore(int player, int x, int y) {
// Update the score for the specified piece
for (int i = 0; i < winPlaces; i++)
if (map[x][y][i]) {
score[player][i] <<= 1;
score[1 - player][i] = 0;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -