Untitled

mail@pastecode.io avatar
unknown
python
2 months ago
2.7 kB
6
Indexable
Never
import random

class SnakeAndLadderGame:
    def __init__(self, num_players, board_size=10):
        self.num_players = num_players
        self.board_size = board_size
        self.players = {}
        self.board = [0] * (board_size * board_size)
        self.snakes = {}
        self.ladders = {}
        self.create_board()
        self.place_snakes_and_ladders()

    def create_board(self):
        for i in range(self.board_size * self.board_size):
            self.board[i] = i + 1

    def place_snakes_and_ladders(self):
        num_snakes = random.randint(self.board_size // 2, self.board_size)
        num_ladders = random.randint(self.board_size // 2, self.board_size)
        positions = random.sample(range(1, self.board_size * self.board_size + 1), num_snakes + num_ladders)
        snake_positions = positions[:num_snakes]
        ladder_positions = positions[num_snakes:]

        for i in range(num_snakes):
            start = snake_positions[i]
            end = random.randint(1, start - 1)
            self.snakes[start] = end

        for i in range(num_ladders):
            start = ladder_positions[i]
            end = random.randint(start + 1, self.board_size * self.board_size)
            self.ladders[start] = end

    def move_player(self, player):
        current_position = self.players[player]
        dice_roll = random.randint(1, 6)
        new_position = current_position + dice_roll

        if new_position in self.snakes:
            print(f"Oops! {player} encountered a snake from {new_position} to {self.snakes[new_position]}")
            new_position = self.snakes[new_position]

        if new_position in self.ladders:
            print(f"Wow! {player} found a ladder from {new_position} to {self.ladders[new_position]}")
            new_position = self.ladders[new_position]

        if new_position >= self.board_size * self.board_size:
            print(f"{player} reached the final position and won the game!")
            return True

        self.players[player] = new_position
        print(f"{player} rolled a {dice_roll} and moved to position {new_position}")
        return False

    def play(self):
        print("Welcome to Snake and Ladder Game!")
        for i in range(self.num_players):
            self.players[f"Player {i+1}"] = 1

        while True:
            for player in self.players:
                input(f"{player}, Press Enter to roll the dice...")
                if self.move_player(player):
                    return

# Start the game
num_players = int(input("Enter the number of players: "))
board_size = int(input("Enter the board size: "))
game = SnakeAndLadderGame(num_players, board_size)
game.play()
Leave a Comment