gpt4 book ai didi

java - 井字游戏的 isEmpty 方法

转载 作者:太空宇宙 更新时间:2023-11-04 07:04:59 26 4
gpt4 key购买 nike

public class TicTacToeModel {

double xpos,ypos,xr,yr;
char[][] position = {{' ',' ',' '},
{' ',' ',' '},
{' ',' ',' '}};

/**
* Turns row, col into the center of the cells of any screen of resolution h by w.
* This is ideal for the view.
*/
public void computePos(int row, int col, int h, int w){
xpos=(col+0.5)*w/3.0;
ypos=(row+0.5)*h/3.0;
xr=w/8.0;
yr=h/8.0;
}
如果 xpos ypos 处的单元格为空,

isEmpty() 返回 true。这并不能验证 xpos 和 ypos 是否在范围内,我知道如何做到这一点吗?

public boolean isEmpty(int xpos, int ypos){
boolean isPosWithinRange = xpos>=0 && xpos<9 && ypos>=0 && ypos<9;
return (position[xpos][ypos] == ' ' && isPosWithinRange);
}

在位置 xpos 和 ypos 处放置一个 O。无需额外验证。

public void placeO(int xpos, int ypos) {
if(isEmpty(xpos, ypos)) {
position[xpos][ypos]='O';
}

}

最佳答案

首先,您应该测试 xposypos 是否在 0-2 之间:

boolean isPosWithinRange = xpos>=0 && xpos<3 && ypos>=0 && ypos<3;

其次,如果不是,则不应检查单元格的值,因为它是无效的。使用short circuit && 的属性,通过更改 return 语句中的检查顺序:

return isPosWithinRange && position[xpos][ypos] == ' ';

关于java - 井字游戏的 isEmpty 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21561295/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com