用processing代码做个五子棋小游戏
时间: 2023-09-04 07:06:32 浏览: 173
好的,下面是一个简单的五子棋小游戏的Processing代码:
```java
int[][] board = new int[15][15]; // 棋盘
int player = 1; // 当前玩家,1为黑子,2为白子
boolean gameOver = false; // 游戏是否结束的标志
void setup() {
size(450, 450);
strokeWeight(2);
textAlign(CENTER, CENTER);
textSize(20);
}
void draw() {
background(255);
drawBoard(); // 绘制棋盘
if (gameOver) {
fill(0);
text("游戏结束!", width/2, height/2);
} else {
fill(player == 1 ? 0 : 255);
text("当前玩家:" + (player == 1 ? "黑子" : "白子"), width/2, 20);
}
}
void drawBoard() {
for (int i = 0; i < 15; i++) {
line(30, 30 + i * 30, 420, 30 + i * 30);
line(30 + i * 30, 30, 30 + i * 30, 420);
}
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
if (board[i][j] == 1) {
fill(0);
ellipse(30 + i * 30, 30 + j * 30, 25, 25);
} else if (board[i][j] == 2) {
fill(255);
ellipse(30 + i * 30, 30 + j * 30, 25, 25);
}
}
}
}
void mousePressed() {
if (gameOver) {
return;
}
int x = mouseX / 30;
int y = mouseY / 30;
if (x < 0 || x >= 15 || y < 0 || y >= 15) {
return;
}
if (board[x][y] != 0) {
return;
}
board[x][y] = player;
if (checkWin(x, y)) {
gameOver = true;
}
player = player == 1 ? 2 : 1;
}
boolean checkWin(int x, int y) {
int count = 1;
for (int i = x + 1; i < 15 && board[i][y] == player; i++) {
count++;
}
for (int i = x - 1; i >= 0 && board[i][y] == player; i--) {
count++;
}
if (count >= 5) {
return true;
}
count = 1;
for (int j = y + 1; j < 15 && board[x][j] == player; j++) {
count++;
}
for (int j = y - 1; j >= 0 && board[x][j] == player; j--) {
count++;
}
if (count >= 5) {
return true;
}
count = 1;
for (int i = x + 1, j = y + 1; i < 15 && j < 15 && board[i][j] == player; i++, j++) {
count++;
}
for (int i = x - 1, j = y - 1; i >= 0 && j >= 0 && board[i][j] == player; i--, j--) {
count++;
}
if (count >= 5) {
return true;
}
count = 1;
for (int i = x + 1, j = y - 1; i < 15 && j >= 0 && board[i][j] == player; i++, j--) {
count++;
}
for (int i = x - 1, j = y + 1; i >= 0 && j < 15 && board[i][j] == player; i--, j++) {
count++;
}
if (count >= 5) {
return true;
}
return false;
}
```
代码中使用了一个二维数组来表示棋盘,其中0表示空位,1表示黑子,2表示白子。鼠标点击时,根据当前玩家在相应的位置放置棋子,并检查是否有玩家胜利。如果有,则游戏结束。在绘制棋盘和棋子时,使用了Processing的一些基本绘图函数,如line()和ellipse()等。
阅读全文