面向对象 五子棋
Game类
package com.lanou.wuziqi;
import java.util.Scanner;
public class Game {
private int[][] game;
private int role = 1;
public Game(int row, int col) {
game = new int[row][col];
}
public void start() {
int row = 0;
int col = 0;
Scanner scanner = new Scanner(System.in);
do {
printGame();
System.out.println("请玩家" + role + "下棋:");
System.out.println("请玩家输入行:");
row = scanner.nextInt();
System.out.println("请玩家输入列:");
col = scanner.nextInt();
if (!playChest(row, col)) {
row = 0;
col = 0;
continue;
}
} while (!isSuccess(row, col));
printGame();
System.out.println("恭喜" + (3 - role) + "号玩家胜利!!!");
}
private void printGame() {
System.out.println();
System.out.println("现棋盘如下:");
for (int[] items : game) {
for (int item : items) {
System.out.print(item + " ");
}
System.out.println();
}
}
// 判断落子位置是否有效并落子
private boolean playChest(int row, int col) {
if (row < 0 || row >= game.length || col < 0 || col >= game[row].length) {
System.out.println("落子位置超出棋盘!!!!!");
return false;
} else if (game[row][col] != 0) {
System.out.println("落子位置已经有棋子!!!!!");
return false;
} else {
game[row][col] = role;
role = 3 - role;
return true;
}
}
// 判断输赢
private boolean isSuccess(int row, int col) {
return isOne(row, col) || isTwo(row, col) || isThree(row, col) || isFour(row, col);
}
// 横向判断输赢
private boolean isOne(int row, int col) {
int count = 0;
int i = 0;
int tempRole = 3 - role;
while (col - i >= 0 && game[row][col - i] == tempRole) {// 横着往左走
count++;
i++;
}
i = 0;
while (col + i < game[row].length && game[row][col + i] == tempRole) {// 横着往右走
count++;
i++;
}
return count >= 6;
}
// 竖向判断输赢
private boolean isTwo(int row, int col) {
int count = 0;
int i = 0;
int tempRole = 3 - role;
while (row - i >= 0 && game[row - i][col] == tempRole) {// 竖着向上走
count++;
i++;
}
i = 0;
while (row + i < game.length && game[row + i][col] == tempRole) {// 竖着向下走
count++;
i++;
}
return count >= 6;
}
// 判断 “/” 方向
private boolean isThree(int row, int col) {
int count = 0;
int i = 0;
int tempRole = 3 - role;
while (row - i >= 0 && col + i < game[row].length && game[row - i][col + i] == tempRole) {// 往右上
count++;
i++;
}
i = 0;
while (row + i < game.length && col - i >= 0 && game[row + i][col - i] == tempRole) {// 往左下
count++;
i++;
}
return count >= 6;
}
// 判断 “\” 方向
private boolean isFour(int row, int col) {
int count = 0;
int i = 0;
int tempRole = 3 - role;
while (row - i >= 0 && col - i >= 0 && game[row - i][col - i] == tempRole) {// 向左上
count++;
i++;
}
i = 0;
while (row + i < game.length && col + i < game[row].length && game[row + i][col + i] == tempRole) {// 向右下
count++;
i++;
}
return count >= 6;
}
}
调用:
package com.lanou.wuziqi;
public class Main {
public static void main(String[] args) {
Game game =new Game(15, 15);
game.start();
}
}