gpt4 book ai didi

Javascript 棋盘游戏 - 在船上寻找可能的位置

转载 作者:数据小太阳 更新时间:2023-10-29 04:14:57 26 4
gpt4 key购买 nike

我正在使用 Javascript 开发 HTML5 table 游。

我如何找到(递归)我可以得到的骰子数?

示例:我从骰子中得到 4,我的位置是 11。可能的位置是 22157

Example shows that I'm at position 11 and positions I can get to are 22, 15 and 7

我已经试过了;它工作得很好,但将错误数字返回到控制台:

$(function(){
// Initialize
var pos = 11;
var dice = 4;
var diceMax = 4;
var postPlaces = [];
var places = [];

// List of gameboard's numbers: from where to where
numbers = {
1 : [25,21,2],
2 : [1,3],
3 : [2,4],
4 : [3,5],
5 : [4,6],
6 : [5,19,7],
7 : [6,8],
8 : [7,9],
9 : [10,8],
10 : [11,9],
11 : [10,12],
12 : [11,13],
13 : [12,14],
14 : [13,15,22],
15 : [14,16],
16 : [15,17],
17 : [16,20,18],
18 : [17,19],
19 : [18,6],
20 : [17,21],
21 : [1,20],
22 : [14,23],
23 : [22,24],
24 : [23,25],
25 : [24,1]
};

// List all numbers where is possible to go with dice number we got
function findPlaces(number){
dice -= 1;
$.each(numbers[number],function(i,v){
if(postPlaces.indexOf(v) == -1){
postPlaces.push(v);
if(dice>0){
findPlaces(v);
}else{
places.push(v);
}
}
});
dice = diceMax;
}

// When the button get pressed
$("button").click(function(){
postPlaces = [];
places = [];
dice = diceMax;
findPlaces(pos);
console.log(places);
});
});

最佳答案

findPlaces() 中有一些错误 - 以下代码应该可以工作,请参阅评论

function findPlaces(number){
dice -= 1;

// moved here so that initial number (11) gets
// stored to postPlaces and we do not step on that number again
postPlaces.push(number);

$.each(numbers[number],function(i,v){
if(postPlaces.indexOf(v) == -1){
if(dice>0){
findPlaces(v);
}else{
places.push(v);
}
}
});

// we are going back one level higher,
// must remove the 'number' from postPlaces
// AND increase the dice (number of steps to go)
postPlaces.pop();
dice += 1;
}

当然,正如@plaix 指出的那样,13 个数字邻居是错误的

关于Javascript 棋盘游戏 - 在船上寻找可能的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16263347/

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