Tic Tac Toe Game的胜利条件

时间:2013-12-09 12:03:54

标签: java processing

我有一个tic tac toe游戏的代码,我需要一些帮助,因为我不知道该怎么做。 (使用Processing 2.0)

1)我需要写一个获胜条件测试。由玩家1和玩家2填充的完整行。

它看起来应该是这样的

int rowFilledByPlayer(int row){// code

}

2)然后我需要用于测试列和对角线的函数,类似于1)

中的函数

然后我必须结合所有功能

我该怎么做?我希望有人可以帮助我。

提前致谢。

这是我的代码

// Global variables

int board [][] = new int [3][3]; // Game board 3x3 array
int cellWidth, cellHeight;       // Cell size computed from window size
int player = 1;
int rowFilledByPlayer;

void setup() {
  size (400, 400);
  rectMode(CORNER);
  ellipseMode(CORNER);
  // Divide window in 3 by 3 cells
  cellWidth = width / 3; 
  cellHeight = height / 3;

  clearBoard();
}

void draw() {
  background(255);
  drawBoard();
  if (boardFilled())
    drawGameOver();
}

void drawGameOver() {
  fill(0, 102, 153);
  textSize(width / 7);
  textAlign(CENTER, CENTER);
  text("Game Over!", width / 2, height / 2);
}

void mouseClicked() {
  if (boardFilled())
    clearBoard();
  else
    playerMove();
}

void clearBoard() {
  for (int row=0; row<3; row++)
    for (int col=0; col<3; col++)
      board[row][col] = 0;
}

void drawBoard() {
  for (int row=0; row<3; row++)
    for (int col=0; col<3; col++)
      drawCell(row, col);
}

void drawCell(int row, int col) {

  noFill();
  stroke(0);
  rect (col * cellWidth, row * cellHeight, cellWidth, cellHeight);

  switch (board[row][col]) {
    case 1:
      ellipse(col * cellWidth, row * cellHeight, cellWidth, cellHeight);
    break;
    case 2:
      line(col * cellWidth, row * cellHeight, (col+1) * cellWidth, (row+1) * cellHeight);
      line((col+1) * cellWidth, row * cellHeight, col * cellWidth, (row+1) * cellHeight);
    break;

  }
}


void playerMove() {
  int row = mouseY / cellHeight;
  int col = mouseX / cellWidth;

  if (board[row][col] == 0) {
    board[row][col] = player;
    player = oppositePlayer();
  }
}

int oppositePlayer() {
  return player = 3 - player;
}

boolean boardFilled() {
  for (int row = 0; row < 3; row++) {
    if (!rowFilled(row))
      return false;
  }
  return true;
}

boolean rowFilled(int row) {
  for (int col = 0; col < 3; col++) {
    if (board[row][col] == 0) return false;
  }
  return true;  
}

void CheckRows();

1 个答案:

答案 0 :(得分:0)

首先,如果填充,则必须查找三行和三列。 之后你必须检查两个对角线。 另外,我建议通过 boardFilled 方法传递播放器变量以获得更清晰的代码!

此方法将取代您的方法 boardFilled rowFilled CheckRows

boolean boardFilled(int player) {
  for (int i = 0; i < 3; i++) {
    if (board[i][0] == player && board[i][1] == player && board[i][2] == player) {
      return true;
    }

    if (board[0][i] == player && board[1][i] == player && board[2][i] == player) {
      return true;
    }
  }

  if (board[0][0] == player && board[1][1] == player && board[2][2] == player) {
      return true;
  }

  if (board[0][2] == player && board[1][1] == player && board[2][0] == player) {
      return true;
  }

  return false;
}