Warning! It seems that you are using Dodona within another webpage, so not everything may work properly. Let your teacher know so that he can solve the problem by adjusting a setting in the learning environment. In the meantime, you can click this link to open Dodona in a new window.
Warning! The page was not fully loaded, probably because of a network issue. It could be that not all functionalities work as expected. Please try reloading the page.
Python exercise
Snakes and ladders
Sign in to hand in your solution and get feedback.
# Snakes and ladders program
# -------------------------
# Import libraries
# -------------------------
import random
# -------------------------
# Subprograms
# -------------------------
def play(board, players):
current_player = 0
game_won = False
while not game_won:
player_square = players[current_player]
print()
print("------------------------------------")
print("Player", current_player + 1, "it's your turn.")
print("You are on square", player_square)
print("Press Enter to roll the dice.")
wait = input()
dice = random.randint(1, 6)
print("You rolled a", dice)
player_square = player_square + dice
if player_square > len(board) - 1:
player_square = len(board) - 1
print("You moved to square", player_square)
board_square = board[player_square]
if board_square < player_square:
print("Oh no, you landed on a snake.")
player_square = board_square
print("You are now on square", player_square)
elif board_square > player_square:
print("Yay, you landed on a ladder.")
player_square = board_square
print("You are now on square", player_square)
if player_square >= len(board) - 1:
game_won = True
print("Player", current_player + 1, "wins the game!")
else:
players[current_player] = player_square
print("Press Enter for the next player to take their turn.")
wait = input()
current_player = (current_player + 1) % len(players)
def initialise_board(squares):
random.seed()
board = []
for square in range(squares + 1):
board.append(square)
board[4] = 7
board[6] = 15
board[18] = 23
board[19] = 2
board[24] = 17
return board
def initialise_players():
players = [1, 1]
return players
# -------------------------
# Main program
# -------------------------
board = initialise_board(25)
players = initialise_players()
play(board, players)