16×16大小棋盘的五子棋小程序 Java实现
程序员文章站
2022-03-10 17:57:55
16×16大小棋盘的五子棋小程序 Java实现记录一下每天的学习。import java.util.Random;import java.util.Scanner;/** * @author hxf * * @date 2020/12/7 */public class Test { public static void main(String[] args) { Chessboard chessboard = new Chessboard(); ch...
16×16大小棋盘的五子棋小程序 Java实现
记录一下每天的学习。
import java.util.Random;
import java.util.Scanner;
/**
* @author hxf
* * @date 2020/12/7
*/
public class Test {
public static void main(String[] args) {
Chessboard chessboard = new Chessboard();
chessboard.offensive();
while (true){
chessboard.chess();
chessboard.show();
if (chessboard.check()){
System.out.println(chessboard.player+"号选手获胜");
break;
}
chessboard.exchange();
}
}
}
class Chessboard{
int size = 16;
int[][] chessBoard = new int[size+1][size+1];
int player1 = 1;
int player2 = 2;
int player;
int row;
int column;
int number = 5;
int count = 0;
Scanner in = new Scanner(System.in);
Chessboard(){
for (int i = 0; i < chessBoard.length; i++){
chessBoard[i][0] = i;
chessBoard[0][i] = i;
}
}
void show(){
for (int[] row: chessBoard) {
for (int column: row) {
System.out.print(column+"\t");
}
System.out.println();
}
}
void offensive(){
Random random = new Random();
if (random.nextBoolean()){
player = player1;
}else {
player = player2;
}
System.out.println(player+"号先行");
}
void chess(){
System.out.println(player+"号请落子:(先输入行,在输入列,空格隔开,数值为1-16)");
row = in.nextInt();
column = in.nextInt();
chessBoard[row][column] = player;
}
void exchange(){
if (player == player2){
player = player1;
}else{
player = player2;
}
}
boolean checkRow(){
count = 0;
for (int i = Math.max(1, column-number+1); i <= Math.min(size, column+number-1); i++){
if (chessBoard[row][i] == player){
count++;
if (count == number){
return true;
}
}else{
count = 0;
}
}
return false;
}
boolean checkColumn(){
count = 0;
for (int i = Math.max(1, row-number+1); i <= Math.min(size, row+number-1); i++){
if (chessBoard[i][column] == player){
count++;
if (count == number){
return true;
}
}else{
count = 0;
}
}
return false;
}
boolean checkLeftward(){
count = 0;
int temp;
for (int i = Math.max(1, row-number+1); i <= Math.min(size, row+number-1); i++){
temp = column - row + i;
if (temp <1 || temp > 16){
continue;
}
if (chessBoard[i][temp] == player){
count++;
if (count == number){
return true;
}
}else{
count = 0;
}
}
return false;
}
boolean checkRightward(){
count = 0;
int temp;
for (int i = Math.max(1, row-number+1); i <= Math.min(size, row+number-1); i++){
temp = column + row - i;
if (temp <1 || temp > 16){
continue;
}
if (chessBoard[i][temp] == player){
count++;
if (count == number){
return true;
}
}else{
count = 0;
}
}
return false;
}
boolean check(){
return checkRow() || checkColumn() || checkLeftward() || checkRightward();
}
}
本文地址:https://blog.csdn.net/helloworld370629/article/details/110849088