use*_*823 6 algorithm data-structures
我遇到了一个采访问题"建议你将用于蛇和梯子游戏的数据结构?"
我会使用2D数组(与我们在国际象棋中一样)来设计每个游戏块.但是有可能用一维阵列设计它吗?很多人建议这样做,但没有人解释过如何做到这一点.
gee*_*eks 15
蛇与梯的规则是:
我们只传递一个HashMap,它包含当前位置作为键,下一个位置作为值.我认为一个HashMap将完成Ladder and Snake的所有要求,
int playSnakeAndLadder(HashMap<Integer, Integer> hashMap){
int player1=1, player2=1;// Initial position of players
int chance=0;// This value show the change of players if chance is odd then player1 will play
// if chance is even then player2 will play
while(1){
if((player1==100)||(player2==100))// if any of player's position is 100 return chance;
return chance;// Here chance shows who win the game, if chance is even player1 wins other //wise player2 wins
int roll=Randon(6);// this will generate random number from 1 to 6.
if(chance%2==0){
int key=roll+player1;// new position of player1
boolean isLadder=false;// This is for checking the turn current player if againTurn is ture
// then the current player will player again.
if(hashMap.contains(Key)){
player1=hashMap.getValue(Key);
// Here player current position will automatically update according to the hashMap.
// if there is a snake the key value is greater than it mapping value.
// if there is a ladder then key value is less than it mapping value.
if(Key<hashMap.getValue(Key))
isLadder=true;// Here player gets ladder.
if(isLadder==true && roll==6 || isLadder==true)
chance=chance;
else
chance=(chance+1)%2;
}
else if(player1+roll>100 && roll!=6)
chance=(chance+1)%2;
else if(player1+roll>100 && roll==6)
chance=chance;
else if(roll==6){
player1=player1+roll;
chance=chance;
}
else{
player1=player1+roll;
chance1=(chance1+1)%2;
}
}
else{// Now similarly for player2
{
int key=roll+player2;// new position of player2
boolean isLadder=false;// This is for checking the turn current player if againTurn is ture
// then the current player will player again.
if(hashMap.contains(Key)){
player2=hashMap.getValue(Key);
// Here player current position will automatically update according to the hashMap.
// if there is snake the key value is greater than it mapping value.
// if there is ladder then key value is less than it mapping value.
if(Key<hashMap.getValue(Key))
isLadder=true;// Here player gets ladder.
if(isLadder==true && roll==6 || isLadder==true)
chance=chance;
else
chance=(chance+1)%2;
}
else if(player2+roll>100 && roll!=6)
chance=(chance+1)%2;
else if(player2+roll>100 && roll==6)
chance=chance;
else if(roll==6){
player2=player2+roll;
chance=chance;
}
else{
player2=player2+roll;
chance=(chance+1)%2;
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)