java if 赋值语句_java – 将赋值语句放在if语句的错误实践中?

基于下面的代码片段(为了清晰起见,它们已被缩短).

scoreBoardState方法的目的是用于确定minimax算法中叶节点处游戏状态的分数,该算法将被传递以确定AI进行的最佳移动.

hasThreeInARowAndTwoOpenSpaces_Horizo​​ntal是ScoreBoardState调用的许多类似方法之一,用于确定是否满足某些条件(例如连续3个令牌的玩家).如果为真,则返回满足该条件的玩家的数量,然后增加该玩家(人类玩家或AI)的得分.

需要在if语句中调用该方法以检查返回的值是否不为零(这意味着应该添加一些分数).我可以在if语句中设置方法返回的值(我在代码片段中做了),或者如果它不返回0,我可以再次调用该方法,然后将其设置为变量.显然,第二种方法效率较低,但它更易于人类阅读,更容易注意到正在发生的事情.

问题是,设置由if语句中调用的方法返回的变量被认为是不好的做法吗?或者它没关系,因为它更有效率?

注意:第二种方法的低效率增长相当快,因为​​它在for循环中,并且在测试每个条件时会出现这种情况很多次.它也是在minimax算法中为每个叶节点完成的(每个节点可以有7个分支)意味着深度只有3(我使用的最小值)有343个叶子节点和7个深度(目前我最高)使用)有近825,000个叶节点.

/* scores the board state of a root node in a minimax algorithm

* @gameState a 2 dimensional array that stores values for each space on the

* board. Stores 0 for empty or 1 or 2 if position is taken by a player

*/

int scoreBoardState (int[][] boardState) {

int aiScore = 0;

int playerScore = 0;

int player = -1;

for (int i = 0; i < boardState.length; i++) {

for (int j = 0; j < boardState[i].length - 4; j++) {

if (j < boardState[i].length - 5 && (player = hasThreeInARowAndTwoOpenSpaces_Horizontal(boardState, i, j)) != 0) {

if (player == AI)

aiScore += 1000; //magic number entered for clarity

else if (player == PLAYER)

playerScore += 1000;

}

else if (i < boardState.length - 4 && j > 2 && (player = hasThreeInARowAndOneOpenSpace_Diagonal_UpperRightToLowerLeft(boardState, i, j)) != 0) {

if (player == AI)

aiScore += SCORE_THREE_IAR_ONE_OS;

else if (player == PL)

playerScore += SCORE_THREE_IAR_ONE_OS;

}

}

}

return aiScore - playerScore;

}

/*

* checks if, starting from the passed in coordinates, whether there are 3

* spaces taken by the same player with an empty space on either side in a horizontal direction (left to right).

*

* returns the player number if the result is true. returns 0 if the result

*is false or all spaces are empty

*/

int hasThreeInARowAndTwoOpenSpaces_Horizontal(int[][] boardState, int row, int col) {

if (boardState[row][col] == 0

&& boardState[row][col + 1] == boardState[row][col + 2] && boardState[row][col + 2] == boardState[row][col + 3]

&& boardState[row][col + 4] == 0)

{

return boardState[row][col + 1];

}

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值