- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在开发一个 Android 应用程序,一个简单的井字棋副项目。我正在使用极小极大算法,并且每次尝试计算移动时都需要克隆棋盘。
我面临的问题是,每次克隆我的对象并操作克隆的属性时,它也会更改原始对象的属性,在本例中是游戏的棋盘。
我不明白为什么,因为它在我的单元测试中运行良好,但在我集成和玩游戏时却运行不佳。
使用 AI(Minimax) 类计算最佳位置的计算机类:
public class ComputerPlayer extends Player {
private String token;
AI AI;
public ComputerPlayer() {
super();
AI AI = null;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
this.initializeAI();
}
public void autoToken(String token) {
if(token.equals("X")) {
this.setToken("O");
} else {
this.setToken("X");
}
}
public void play(Board board) throws CloneNotSupportedException {
Board clone = (Board) board.clone();
int spot = AI.getBestSpot(clone);
play(board, spot);
}
public void play(Board board, int spot) {
board.setSpot(spot, token);
}
public void initializeAI() {
if( token != null ) {
this.AI = new AI(token);
}
}
}
具有克隆方法的板类:
public Board() {
this.grid = new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8"};
this.winCombinations = new int[][]{{0,1,2}, {3,4,5}, {6,7,8}, {0,3,6}, {1,4,7,}, {2,5,8}, {0,4,8}, {2,4,6}};
}
public String[] getGrid() {
return grid;
}
public int[][] getWinCombinations() {
return winCombinations;
}
public String[] getAvailableSpots() {
ArrayList<String> resultList = new ArrayList<String>();
for(int i = 0; i < grid.length; i++) {
if(!grid[i].equals("X") && !grid[i].equals("O")) {
resultList.add(grid[i]);
}
}
return resultList.toArray(new String[resultList.size()]);
}
public void reset() {
grid = new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8"};
}
public void setSpot(int i, String token) {
grid[i] = token;
}
public void setGrid(String[] grid) {
this.grid = grid;
}
@Override
public Object clone() {
Board boardClone = null;
try {
boardClone = (Board) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return boardClone;
}
}
人工智能类:
public class AI {
private String token;
GameState gameState;
private String opponentToken;
public AI(String token) {
this.token = token;
this.gameState = new GameState();
this.opponentToken = null;
setOpponentToken();
}
public String getToken() {
return token;
}
public String getOpponentToken() {
return opponentToken;
}
public void setOpponentToken() {
if(this.token == "X") {
opponentToken = "O";
} else {
opponentToken = "X";
}
}
public int getBestSpot(Board board) throws CloneNotSupportedException {
String[] grid = board.getGrid();
if( !grid[4].equals("X") && !grid[4].equals("O")) {
return 4;
} else {
return Integer.parseInt((String) this.maximizedSpot(board)[0]);
}
}
public Object[] maximizedSpot(Board board) throws CloneNotSupportedException {
Board boardClone = (Board) board.clone();
int bestScore = 0;
String bestSpot = null;
int score;
String[] availableSpots = boardClone.getAvailableSpots();
for(String availableSpot: availableSpots) {
int spot = Integer.parseInt(availableSpot);
boardClone.setSpot(spot, this.token);
if( gameState.finished(boardClone) ) {
score = this.getScore(boardClone);
} else {
Object[] minimizedSpot = this.minimizedSpot(boardClone);
score = (int) minimizedSpot[1];
}
boardClone = (Board) board.clone();
if( bestScore == 0 || score > bestScore ) {
bestScore = score;
bestSpot = availableSpot;
}
}
return new Object[]{bestSpot, bestScore};
}
public Object[] minimizedSpot(Board board) throws CloneNotSupportedException {
Board boardClone = (Board) board.clone();
int bestScore = 0;
String bestSpot = null;
int score;
String[] availableSpots = boardClone.getAvailableSpots();
for(String availableSpot: availableSpots) {
int spot = Integer.parseInt(availableSpot);
boardClone.setSpot(spot, this.opponentToken);
if ( gameState.finished(boardClone) ) {
score = this.getScore(boardClone);
} else {
Object[] maximizedSpot = this.maximizedSpot(boardClone);
score = (int) maximizedSpot[1];
}
boardClone = (Board) board.clone();
if (bestScore == 0 || score < bestScore) {
bestScore = score;
bestSpot = availableSpot;
}
}
return new Object[]{bestSpot, bestScore};
}
public int getScore(Board board) {
if( gameState.finished(board) ) {
String winnerToken = (gameState.getWinnerToken());
if( winnerToken == token ) {
return 1;
} else if ( winnerToken == opponentToken ) {
return -1;
}
}
return 0;
}
}
集成测试失败:
@Test
public void testCanUseAI() {
String[] newGrid = new String[]{"0", "1", "2",
"3", "X", "5",
"6", "7", "8"};
board.setGrid(newGrid);
try {
computerPlayer.play(board);
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
String[] result = new String[]{"0", "1", "O",
"3", "X", "5",
"6", "7", "8"};
System.out.print(board.getGrid()[1]);
System.out.print(result[1]);
assertTrue( Arrays.deepEquals(board.getGrid(), result) );
}
}
最佳答案
您的克隆方法似乎失败了。它不进行实际的克隆。它将引发一个异常,您应该在控制台上看到该异常作为堆栈跟踪。
不再推荐克隆方法本身。相反,您应该创建一个将源对象作为参数的构造函数。在此构造函数中,您应该制作源对象的深拷贝。以下是如何在您的情况下执行此操作的示例:
public class Board {
private String[] grid;
private int[][] winCombinations;
public Board() {
this.grid = new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8" };
this.winCombinations = new int[][] { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 }, { 0, 3, 6 }, { 1, 4, 7, },
{ 2, 5, 8 }, { 0, 4, 8 }, { 2, 4, 6 } };
}
/**
* Cloning constructor to make a deep copy of the original source
* @param sourceBoard Object to be deep copied to a new instance
*/
public Board(Board sourceBoard) {
this();
System.arraycopy(sourceBoard.grid, 0, this.grid, 0, sourceBoard.grid.length);
for (int i = 0; i < winCombinations.length; i++) {
int[] line = winCombinations[i];
System.arraycopy(sourceBoard.winCombinations[i], 0, line, 0, line.length);
}
}
请记住,您自己负责复制每个对象。如果您只是复制对对象的引用,两个实例将指向同一个对象,并且数据将像您提到的那样混合。
这是一个使用克隆构造函数的简单示例:
public static void main(String[] args) {
Board board = new Board();
String[] newGrid = new String[] { "0", "1", "2", "3", "X", "5", "6", "7", "8" };
board.setGrid(newGrid);
// Instead of using clone methods, create new instance from source object
Board clone = new Board(board);
System.out.println(clone.getGrid() == board.getGrid()); // false => deep copy done
}
我希望这能帮助您推进您的项目。快乐编码!
关于Java克隆方法未按预期工作(极小极大算法案例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50102252/
我想了解 Ruby 方法 methods() 是如何工作的。 我尝试使用“ruby 方法”在 Google 上搜索,但这不是我需要的。 我也看过 ruby-doc.org,但我没有找到这种方法。
Test 方法 对指定的字符串执行一个正则表达式搜索,并返回一个 Boolean 值指示是否找到匹配的模式。 object.Test(string) 参数 object 必选项。总是一个
Replace 方法 替换在正则表达式查找中找到的文本。 object.Replace(string1, string2) 参数 object 必选项。总是一个 RegExp 对象的名称。
Raise 方法 生成运行时错误 object.Raise(number, source, description, helpfile, helpcontext) 参数 object 应为
Execute 方法 对指定的字符串执行正则表达式搜索。 object.Execute(string) 参数 object 必选项。总是一个 RegExp 对象的名称。 string
Clear 方法 清除 Err 对象的所有属性设置。 object.Clear object 应为 Err 对象的名称。 说明 在错误处理后,使用 Clear 显式地清除 Err 对象。此
CopyFile 方法 将一个或多个文件从某位置复制到另一位置。 object.CopyFile source, destination[, overwrite] 参数 object 必选
Copy 方法 将指定的文件或文件夹从某位置复制到另一位置。 object.Copy destination[, overwrite] 参数 object 必选项。应为 File 或 F
Close 方法 关闭打开的 TextStream 文件。 object.Close object 应为 TextStream 对象的名称。 说明 下面例子举例说明如何使用 Close 方
BuildPath 方法 向现有路径后添加名称。 object.BuildPath(path, name) 参数 object 必选项。应为 FileSystemObject 对象的名称
GetFolder 方法 返回与指定的路径中某文件夹相应的 Folder 对象。 object.GetFolder(folderspec) 参数 object 必选项。应为 FileSy
GetFileName 方法 返回指定路径(不是指定驱动器路径部分)的最后一个文件或文件夹。 object.GetFileName(pathspec) 参数 object 必选项。应为
GetFile 方法 返回与指定路径中某文件相应的 File 对象。 object.GetFile(filespec) 参数 object 必选项。应为 FileSystemObject
GetExtensionName 方法 返回字符串,该字符串包含路径最后一个组成部分的扩展名。 object.GetExtensionName(path) 参数 object 必选项。应
GetDriveName 方法 返回包含指定路径中驱动器名的字符串。 object.GetDriveName(path) 参数 object 必选项。应为 FileSystemObjec
GetDrive 方法 返回与指定的路径中驱动器相对应的 Drive 对象。 object.GetDrive drivespec 参数 object 必选项。应为 FileSystemO
GetBaseName 方法 返回字符串,其中包含文件的基本名 (不带扩展名), 或者提供的路径说明中的文件夹。 object.GetBaseName(path) 参数 object 必
GetAbsolutePathName 方法 从提供的指定路径中返回完整且含义明确的路径。 object.GetAbsolutePathName(pathspec) 参数 object
FolderExists 方法 如果指定的文件夹存在,则返回 True;否则返回 False。 object.FolderExists(folderspec) 参数 object 必选项
FileExists 方法 如果指定的文件存在返回 True;否则返回 False。 object.FileExists(filespec) 参数 object 必选项。应为 FileS
我是一名优秀的程序员,十分优秀!