I am trying to do a coding exercise which consists in playing snake and ladders between 2 players, so in the play function i try to use another function to advance or decrease the player if they land in a ladder or snake, it works once with player 1, but not after that turn:
class SnakesLadders():
def __init__(self):
self.current_player = "1"
self.player1_counter = 0
self.player2_counter = 0
def play(self, die1, die2):
def get_value(current_square):
ladders_snakes_dict = {2:38, 7:14, 8:31, 15:26, 21:42, 28:84, 51:67, 71:91, 78:98,
15:6, 46:25, 49:11, 62:19, 64:60, 74:53, 89:68, 92:88, 95:75, 99:80}
for key, value in ladders_snakes_dict.items():
if current_square == key:
return value
else:
return current_square
if self.current_player == "1":
self.player1_counter += (die1 + die2)
self.player1_counter = get_value(self.player1_counter)
player_position = "Player " + self.current_player + " is on square " + str(self.player1_counter)
if die1 == die2:
self.current_player = "1"
else:
self.current_player = "2"
return player_position
elif self.current_player == "2":
self.player2_counter += (die1 + die2)
self.player2_counter = get_value(self.player2_counter)
player_position = "Player " + self.current_player + " is on square " + str(self.player2_counter)
if die1 == die2:
self.current_player = "2"
else:
self.current_player = "1"
return player_position
The tests return:
Should return: 'Player 1 is on square 38' Correct
Should return: 'Player 1 is on square 44' Correct
Should return: 'Player 2 is on square 31'
'Player 2 is on square 8' should equal 'Player 2 is on square 31'
Should return: 'Player 1 is on square 25'
'Player 1 is on square 46' should equal 'Player 1 is on square 25'
As for me all your problem makes
else:
return current_square
inside for
-loop which is executed on first element but you should run it after loop when all elements are checked
for key, value in ladders_snakes_dict.items():
if current_square == key:
return value
# after `for`-loop
return current_square
BTW: you can write it without for
-loop
if current_square in ladders_snakes_dict:
return ladders_snakes_dict[current_square]
return current_square
Or you can use .get(key, default_value)
return ladders_snakes_dict.get(current_square, current_square)
BTW: I see one mistake in dictionary - you have 15:26
and 15:6
but dictionary can't keep two elements with the same key so you will have only last one 15:6
. You have mistake in one key. Game can't have ladder
and snake
in the same field 15
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.