File size: 15,249 Bytes
3515cf9 e5492ea 3515cf9 e5492ea fec93e3 3515cf9 e5492ea 3515cf9 67b7441 e5492ea fec93e3 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 |
import gradio as gr
import numpy as np
import random
from PIL import Image, ImageDraw, ImageFont
import io
import base64
class LudoGame:
def __init__(self):
# Player colors
self.colors = ["red", "green", "yellow", "blue"]
self.color_codes = {
"red": "#FF5555",
"green": "#55FF55",
"yellow": "#FFFF55",
"blue": "#5555FF",
"white": "#FFFFFF",
"black": "#000000"
}
# Game state
self.reset_game()
def reset_game(self):
# Initialize game state
self.current_player = 0
self.dice_value = 1
self.dice_rolled = False
self.winner = None
# Initialize tokens (4 tokens per player)
self.tokens = {}
for i, color in enumerate(self.colors):
self.tokens[color] = [-1, -1, -1, -1] # -1 means in home
# Track if player can play after rolling
self.can_play = False
# Game messages
self.message = f"Game started! {self.colors[self.current_player].capitalize()}'s turn to roll."
def roll_dice(self):
"""Roll the dice and return the value"""
if self.winner:
return self.render_board()
if self.dice_rolled:
self.message = f"You already rolled a {self.dice_value}. Please move a token or pass."
return self.render_board()
self.dice_value = random.randint(1, 6)
self.dice_rolled = True
# Check if player can move any token
self.can_play = self._can_play()
if not self.can_play:
# If player rolled 6, give them another turn
if self.dice_value == 6:
self.message = f"{self.colors[self.current_player].capitalize()} rolled a 6 but can't move. Roll again!"
self.dice_rolled = False
else:
self.message = f"{self.colors[self.current_player].capitalize()} rolled {self.dice_value} but can't move. Next player's turn."
self._next_player()
else:
self.message = f"{self.colors[self.current_player].capitalize()} rolled {self.dice_value}. Choose a token to move."
return self.render_board()
def _can_play(self):
"""Check if current player can move any token"""
current_color = self.colors[self.current_player]
tokens = self.tokens[current_color]
for i, position in enumerate(tokens):
if position == -1 and self.dice_value == 6:
# Can move out of home
return True
elif position >= 0:
# Token is already on the board
return True
return False
def move_token(self, token_idx):
"""Move the selected token for the current player"""
if self.winner:
return self.render_board()
if not self.dice_rolled:
self.message = "Please roll the dice first."
return self.render_board()
if not self.can_play:
self.message = "You can't move any token. Please pass your turn."
return self.render_board()
current_color = self.colors[self.current_player]
current_pos = self.tokens[current_color][token_idx]
# Token still in home and not rolled a 6
if current_pos == -1 and self.dice_value != 6:
self.message = "Need to roll a 6 to move a token out of home."
return self.render_board()
# Token in home and rolled a 6
if current_pos == -1 and self.dice_value == 6:
# Put token on the board at starting position (different for each player)
self.tokens[current_color][token_idx] = self.current_player * 13
self.message = f"{current_color.capitalize()} token {token_idx+1} is now on the board."
self.dice_rolled = False
return self.render_board()
# Token already on board
new_pos = (current_pos + self.dice_value) % 52
# Check for token captures (simplistic implementation)
for color in self.colors:
if color != current_color:
for i, pos in enumerate(self.tokens[color]):
if pos == new_pos:
# Capture token
self.tokens[color][i] = -1
self.message = f"{current_color.capitalize()} captured {color}'s token!"
# Move token
self.tokens[current_color][token_idx] = new_pos
# Check if the player has won (simplistic - all tokens completed a full circle)
if self._check_winner():
self.winner = self.current_player
self.message = f"{current_color.capitalize()} wins the game!"
else:
self.message = f"{current_color.capitalize()} moved token {token_idx+1} to position {new_pos}."
# If player rolled 6, give them another turn
if self.dice_value == 6:
self.message += " Roll again!"
else:
self._next_player()
self.dice_rolled = False
return self.render_board()
def _check_winner(self):
"""Very simple win check - if all tokens made a complete circuit"""
current_color = self.colors[self.current_player]
starting_pos = self.current_player * 13
for pos in self.tokens[current_color]:
if pos < starting_pos: # Simplified win condition
return False
return True
def _next_player(self):
"""Move to the next player's turn"""
self.current_player = (self.current_player + 1) % 4
self.dice_rolled = False
self.message += f" {self.colors[self.current_player].capitalize()}'s turn to roll."
def pass_turn(self):
"""Pass the current player's turn"""
if self.winner:
return self.render_board()
if not self.dice_rolled:
self.message = "Please roll the dice first."
return self.render_board()
if self.can_play:
self.message = "You have valid moves available. Please move a token."
return self.render_board()
self._next_player()
return self.render_board()
def render_board(self):
"""Render the Ludo board as an image"""
# Create a new image with white background
width, height = 600, 600
board = Image.new('RGB', (width, height), color='white')
draw = ImageDraw.Draw(board)
# Draw the game board (simplified version)
# Draw the outer square
draw.rectangle([(50, 50), (550, 550)], outline='black', width=2)
# Draw the home squares for each player
home_squares = [
(50, 50, 250, 250), # Red (top-left)
(350, 50, 550, 250), # Green (top-right)
(50, 350, 250, 550), # Yellow (bottom-left)
(350, 350, 550, 550) # Blue (bottom-right)
]
for i, color in enumerate(self.colors):
draw.rectangle(home_squares[i], fill=self.color_codes[color], outline='black', width=2)
# Draw the center square
draw.rectangle([(250, 250), (350, 350)], fill='white', outline='black', width=2)
# Draw the path (simplified)
# Horizontal paths
draw.rectangle([(250, 50), (350, 250)], fill='white', outline='black', width=1) # Top
draw.rectangle([(250, 350), (350, 550)], fill='white', outline='black', width=1) # Bottom
draw.rectangle([(50, 250), (250, 350)], fill='white', outline='black', width=1) # Left
draw.rectangle([(350, 250), (550, 350)], fill='white', outline='black', width=1) # Right
# Draw the tokens
for color_idx, color in enumerate(self.colors):
for token_idx, position in enumerate(self.tokens[color]):
if position == -1:
# Token in home - draw in home area
home_x = home_squares[color_idx][0] + 50 + (token_idx % 2) * 100
home_y = home_squares[color_idx][1] + 50 + (token_idx // 2) * 100
draw.ellipse([(home_x-20, home_y-20), (home_x+20, home_y+20)],
fill=self.color_codes[color], outline='black', width=2)
else:
# Token on board - simplified position calculation
# This is a very basic mapping for illustration
board_positions = [
# Top row (left to right)
(100, 300), (150, 300), (200, 300), (250, 300), (300, 300), (350, 300), (400, 300), (450, 300), (500, 300),
# Right column (top to bottom)
(500, 350), (500, 400), (500, 450), (500, 500),
# Bottom row (right to left)
(450, 500), (400, 500), (350, 500), (300, 500), (250, 500), (200, 500), (150, 500), (100, 500),
# Left column (bottom to top)
(100, 450), (100, 400), (100, 350), (100, 300),
# Inner track (simplified approximation)
# Repeat the pattern for simplicity
(100, 300), (150, 300), (200, 300), (250, 300), (300, 300), (350, 300), (400, 300), (450, 300), (500, 300),
(500, 350), (500, 400), (500, 450), (500, 500),
(450, 500), (400, 500), (350, 500), (300, 500), (250, 500), (200, 500), (150, 500), (100, 500),
(100, 450), (100, 400), (100, 350), (100, 300),
]
if position < len(board_positions):
token_x, token_y = board_positions[position]
draw.ellipse([(token_x-15, token_y-15), (token_x+15, token_y+15)],
fill=self.color_codes[color], outline='black', width=2)
# Draw token number
draw.text((token_x-5, token_y-5), str(token_idx+1), fill='black')
# Draw the dice
dice_x, dice_y = 300, 300
draw.rectangle([(dice_x-25, dice_y-25), (dice_x+25, dice_y+25)], fill='white', outline='black', width=2)
# Draw dice pips based on value
if self.dice_value == 1:
draw.ellipse([(dice_x-5, dice_y-5), (dice_x+5, dice_y+5)], fill='black')
elif self.dice_value == 2:
draw.ellipse([(dice_x-15, dice_y-15), (dice_x-5, dice_y-5)], fill='black')
draw.ellipse([(dice_x+5, dice_y+5), (dice_x+15, dice_y+15)], fill='black')
elif self.dice_value == 3:
draw.ellipse([(dice_x-15, dice_y-15), (dice_x-5, dice_y-5)], fill='black')
draw.ellipse([(dice_x-5, dice_y-5), (dice_x+5, dice_y+5)], fill='black')
draw.ellipse([(dice_x+5, dice_y+5), (dice_x+15, dice_y+15)], fill='black')
elif self.dice_value == 4:
draw.ellipse([(dice_x-15, dice_y-15), (dice_x-5, dice_y-5)], fill='black')
draw.ellipse([(dice_x+5, dice_y-15), (dice_x+15, dice_y-5)], fill='black')
draw.ellipse([(dice_x-15, dice_y+5), (dice_x-5, dice_y+15)], fill='black')
draw.ellipse([(dice_x+5, dice_y+5), (dice_x+15, dice_y+15)], fill='black')
elif self.dice_value == 5:
draw.ellipse([(dice_x-15, dice_y-15), (dice_x-5, dice_y-5)], fill='black')
draw.ellipse([(dice_x+5, dice_y-15), (dice_x+15, dice_y-5)], fill='black')
draw.ellipse([(dice_x-5, dice_y-5), (dice_x+5, dice_y+5)], fill='black')
draw.ellipse([(dice_x-15, dice_y+5), (dice_x-5, dice_y+15)], fill='black')
draw.ellipse([(dice_x+5, dice_y+5), (dice_x+15, dice_y+15)], fill='black')
elif self.dice_value == 6:
draw.ellipse([(dice_x-15, dice_y-15), (dice_x-5, dice_y-5)], fill='black')
draw.ellipse([(dice_x+5, dice_y-15), (dice_x+15, dice_y-5)], fill='black')
draw.ellipse([(dice_x-15, dice_y-5), (dice_x-5, dice_y+5)], fill='black')
draw.ellipse([(dice_x+5, dice_y-5), (dice_x+15, dice_y+5)], fill='black')
draw.ellipse([(dice_x-15, dice_y+5), (dice_x-5, dice_y+15)], fill='black')
draw.ellipse([(dice_x+5, dice_y+5), (dice_x+15, dice_y+15)], fill='black')
# Draw the current player indicator
current_color = self.colors[self.current_player]
draw.rectangle([(20, 20), (40, 40)], fill=self.color_codes[current_color], outline='black', width=2)
# Draw game message
draw.text((50, 20), self.message, fill='black')
# Return the PIL Image directly - Gradio can handle PIL images
return board
# Create the Gradio interface
def create_ludo_game():
game = LudoGame()
def roll():
return game.roll_dice()
def move_token_0():
return game.move_token(0)
def move_token_1():
return game.move_token(1)
def move_token_2():
return game.move_token(2)
def move_token_3():
return game.move_token(3)
def pass_turn():
return game.pass_turn()
def reset():
game.reset_game()
return game.render_board()
with gr.Blocks() as ludo_app:
gr.Markdown("# Ludo Game")
gr.Markdown("### A classic 4-player board game")
with gr.Row():
with gr.Column():
image_output = gr.Image(type="pil", label="Ludo Board")
with gr.Row():
roll_button = gr.Button("Roll Dice")
with gr.Row():
token1_button = gr.Button("Move Token 1")
token2_button = gr.Button("Move Token 2")
token3_button = gr.Button("Move Token 3")
token4_button = gr.Button("Move Token 4")
with gr.Row():
pass_button = gr.Button("Pass Turn")
reset_button = gr.Button("Reset Game")
# Set up button click events
roll_button.click(roll, inputs=[], outputs=[image_output])
token1_button.click(move_token_0, inputs=[], outputs=[image_output])
token2_button.click(move_token_1, inputs=[], outputs=[image_output])
token3_button.click(move_token_2, inputs=[], outputs=[image_output])
token4_button.click(move_token_3, inputs=[], outputs=[image_output])
pass_button.click(pass_turn, inputs=[], outputs=[image_output])
reset_button.click(reset, inputs=[], outputs=[image_output])
# Initialize the board on load
ludo_app.load(fn=game.render_board, inputs=None, outputs=image_output)
return ludo_app
# Launch the app
if __name__ == "__main__":
app = create_ludo_game()
app.launch(share=True) |