Untitled

 avatar
unknown
python
10 months ago
2.7 kB
9
Indexable
import pygame
import random

# Define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

# Initialize Pygame
pygame.init()

# Set the width and height of the screen [width, height]
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))

# Set the title of the window
pygame.display.set_caption("Snake and Ladder")

# Clock to control how fast the screen updates
clock = pygame.time.Clock()

# Font for displaying text
font = pygame.font.SysFont(None, 36)

# Function to draw text on the screen
def draw_text(text, color, x, y):
    text_surface = font.render(text, True, color)
    screen.blit(text_surface, (x, y))

# Function to draw the board
def draw_board():
    screen.fill(WHITE)
    pygame.draw.rect(screen, GREEN, (50, 50, 700, 500), 0)
    pygame.draw.rect(screen, BLACK, (50, 50, 700, 500), 2)

    # Draw vertical lines
    for i in range(1, 10):
        pygame.draw.line(screen, BLACK, (50 + i * 70, 50), (50 + i * 70, 550), 2)

    # Draw horizontal lines
    for i in range(1, 10):
        pygame.draw.line(screen, BLACK, (50, 50 + i * 50), (750, 50 + i * 50), 2)

# Function to draw players
def draw_players(player_positions):
    for player, position in player_positions.items():
        row = 9 - (position - 1) // 10
        col = (position - 1) % 10
        pygame.draw.circle(screen, BLUE if "Player 1" in player else RED, (int(50 + col * 70 + 35), int(50 + row * 50 + 25)), 20)

# Function to roll the dice
def roll_dice():
    return random.randint(1, 6)

# Main game loop
def main():
    player_positions = {"Player 1": 1, "Player 2": 1}
    running = True
    current_player = "Player 1"

    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        screen.fill(WHITE)
        draw_board()
        draw_players(player_positions)

        draw_text(f"Current Player: {current_player}", BLACK, 50, 10)
        draw_text("Press Space to Roll Dice", BLACK, 50, 560)

        keys = pygame.key.get_pressed()
        if keys[pygame.K_SPACE]:
            dice_roll = roll_dice()
            draw_text(f"Dice Roll: {dice_roll}", BLACK, 600, 10)
            player_positions[current_player] += dice_roll

            if player_positions[current_player] >= 100:
                draw_text(f"{current_player} Wins!", RED, 300, 300)
                running = False

            current_player = "Player 2" if current_player == "Player 1" else "Player 1"

        pygame.display.flip()
        clock.tick(30)

    pygame.quit()

if __name__ == "__main__":
    main()
Leave a Comment