Vishwas1's picture
Update app.py
d6abb83 verified
raw
history blame
3.44 kB
import random
import streamlit as st
from PIL import Image, ImageDraw
import requests
from io import BytesIO
def roll_dice():
"""Simulates rolling a six-sided dice."""
return random.randint(1, 6)
def update_player_position(player_pos, dice, board):
"""Updates player position based on the dice roll and board."""
original_pos = player_pos
player_pos += dice
if player_pos in board:
player_pos = board[player_pos]
if player_pos > original_pos:
st.write("Yay! You climbed a ladder.")
elif player_pos < original_pos:
st.write("Oops! You encountered a snake")
return player_pos
def calculate_player_coordinates(position):
"""Calculates approximate x, y coordinates for the player position."""
row = (position - 1) // 10
col = (position - 1) % 10
# Adjust for snake and ladder board layout
if row % 2 == 1:
col = 9 - col
x = 50 + col * 50 # Adjust these values as necessary
y = 450 - row * 50 # Adjust these values as necessary
return x, y
def display_game_board(player_position):
board_image_url = "https://upload.wikimedia.org/wikipedia/commons/thumb/8/8f/Snakes_and_ladders_board_simple.svg/1920px-Snakes_and_ladders_board_simple.svg.png"
try:
response = requests.get(board_image_url, stream=True)
response.raise_for_status()
board_image = Image.open(BytesIO(response.content)).convert("RGBA")
# Calculate player position coordinates
player_x, player_y = calculate_player_coordinates(player_position)
# Create a drawing context
draw = ImageDraw.Draw(board_image)
# Draw a circle to represent the player at their position
radius = 15
draw.ellipse((player_x - radius, player_y - radius, player_x + radius, player_y + radius), fill='red')
st.image(board_image, caption="Snake and Ladder Board", width=500)
except requests.exceptions.RequestException as e:
st.write(f"Could not load the game board image. Please check your internet connection or try again later. {e}")
except Exception as e:
st.write(f"An error occurred: {e}")
def snake_and_ladder():
st.title("Snake and Ladder Game")
board = {
1: 1, 4: 25, 8: 13, 11: 6, 14: 30,
16: 10, 19: 3, 22: 37, 24: 16,
26: 12, 28: 43, 33: 2, 35: 17,
39: 50, 41: 20, 46: 5, 48: 63,
52: 81, 55: 18, 57: 59, 60: 32,
62: 65, 64: 45, 67: 71, 73: 69,
76: 44, 78: 54, 80: 99, 82: 89,
84: 21, 87: 100, 91: 68, 93: 70,
95: 23, 98: 79
}
if 'player_pos' not in st.session_state:
st.session_state.player_pos = 1
player_pos = st.session_state.player_pos
display_game_board(player_pos)
if player_pos < 100:
if st.button("Roll Dice"):
dice = roll_dice()
st.write(f"You rolled a {dice}")
player_pos = update_player_position(player_pos, dice, board)
if player_pos > 100:
player_pos -= dice
st.write("You need to get to 100 to win, Try Again!")
else:
st.write(f"Your position is {player_pos}")
st.session_state.player_pos = player_pos
st.rerun()
else:
st.success("Congratulations! You won!")
if st.button("Play Again"):
st.session_state.player_pos = 1
st.rerun()
snake_and_ladder()