人机对抗代码 五子棋的简单算法——评分法( 四 )

< this.chessboard.length && y + 1 < this.chessboard.length) {position[0] = this.chessboard[x + 1][y + 1];} else {position[0] = 0;}if (x + 2 < this.chessboard.length && y + 2 < this.chessboard.length) {position[1] = this.chessboard[x + 2][y + 2];} else {position[1] = 0;}if (x + 3 < this.chessboard.length && y + 3 < this.chessboard.length) {position[2] = this.chessboard[x + 3][y + 3];} else {position[2] = 0;}if (x + 4 < this.chessboard.length && y + 4 < this.chessboard.length) {position[3] = this.chessboard[x + 4][y + 4];} else {position[3] = 0;}sum += calculate2(position);// 右斜上方向if (x - 1 >= 0 && y + 1 < this.chessboard.length) {position[0] = this.chessboard[x - 1][y + 1];} else {position[0] = 0;}if (x - 2 >= 0 && y + 2 < this.chessboard.length) {position[1] = this.chessboard[x - 2][y + 2];} else {position[1] = 0;}if (x - 3 >= 0 && y + 3 < this.chessboard.length) {position[2] = this.chessboard[x - 3][y + 3];} else {position[2] = 0;}if (x - 4 >= 0 && y + 4 < this.chessboard.length) {position[3] = this.chessboard[x - 4][y + 4];} else {position[3] = 0;}sum += calculate2(position);// 右斜下if (x + 1 < this.chessboard.length && y - 1 >= 0) {position[0] = this.chessboard[x + 1][y - 1];} else {position[0] = 0;}if (x + 2 < this.chessboard.length && y - 2 >= 0) {position[1] = this.chessboard[x + 2][y - 2];} else {position[1] = 0;}if (x + 3 < this.chessboard.length && y - 3 >= 0) {position[2] = this.chessboard[x + 3][y - 3];} else {position[2] = 0;}if (x + 4 < this.chessboard.length && y - 4 >= 0) {position[3] = this.chessboard[x + 4][y - 4];} else {position[3] = 0;}sum += calculate2(position);return sum;}//打印棋盘public void print() {for (int i = 0; i < chessboard.length; i++) {for (int j = 0; j < chessboard.length; j++) {System.out.print(this.chessboard[i][j]+"");}System.out.println();}}//判断输赢public Boolean isWin(int x,int y) {return false;}//判断棋盘是否满了public Boolean isFull() {int judge=1;for (int i = 0; i < chessboard.length; i++) {for (int j = 0; j < chessboard.length; j++) {if(this.chessboard[i][j]==0) {judge=0;}}}return judge==1?true:false;}}
3、创建测试类,代码如下:
package chess;import java.util.Scanner;public class chessTest {public static void main(String[] args) {Scanner sc=new Scanner(System.in);chess ch=new chess();System.out.println("请输入棋盘大小n(n行n列):");int size=sc.nextInt();ch.setGame(size,2);ch.print();while (true) {System.out.println("请输入你想下的位置");int x=sc.nextInt();int y=sc.nextInt();ch.getMove(x, y);}}}
测试结果图:
算法大概就是这样子了,算法很简单,效果差强人意吧 。
PS:后面发现chess类里面有个判断胜负的方法没写,也懒得补上了(就循环判断,很简单,就是耗点时间),希望大家不会介意 。