Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116import gradio as grfrom PIL import Image, ImageDraw, ImageFontimport random, time# ConstantsDIRECTIONS = [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]# Initialize boarddef initialize_board():board = [[0]*8 for _ in range(8)]board[3][3], board[4][4] = 1, 1board[3][4], board[4][3] = -1, -1return board# Get flipsdef get_flips(board, r, c, p):if board[r][c] != 0: return []flips = []for dr, dc in DIRECTIONS:rr, cc = r+dr, c+dcbuf = []while 0 <= rr < 8 and 0 <= cc < 8 and board[rr][cc] == -p:buf.append((rr, cc)); rr += dr; cc += dcif buf and 0 <= rr < 8 and 0 <= cc < 8 and board[rr][cc] == p:flips.extend(buf)return flips# Apply movedef apply_move(board, r, c, p):flips = get_flips(board, r, c, p)if not flips: return Falseboard[r][c] = pfor rr, cc in flips:board[rr][cc] = preturn True# AI choose movedef choose_move(board, p):valid = [(r,c) for r in range(8) for c in range(8) if get_flips(board,r,c,p)]return random.choice(valid) if valid else None# Count scoredef count_score(board):black = sum(cell==-1 for row in board for cell in row)white = sum(cell==1 for row in board for cell in row)return black, white# Check game overdef is_game_over(board):return not any(get_flips(board,r,c,p) for p in (-1,1) for r in range(8) for c in range(8))# Render board imagedef board_to_image(board, state):board_state, player, last_user, last_ai = statesize, cell = 360, 360//8img = Image.new('RGB', (size, size+cell), 'darkgreen')draw = ImageDraw.Draw(img)font = ImageFont.load_default()# Scoreboardb, w = count_score(board_state)draw.text((10,2), f"B:{b}", font=font, fill='white')draw.text((size-40,2), f"W:{w}", font=font, fill='white')# Game endif is_game_over(board_state):winner = "Draw" if b==w else ("Black wins" if b>w else "White wins")draw.text((size//2-40, size//2), winner, font=font, fill='yellow')# Board grid and stonesfor r in range(8):for c in range(8):x0, y0 = c*cell, cell + r*cellx1, y1 = x0+cell, y0+celldraw.rectangle([x0,y0,x1,y1], outline='black')if board_state[r][c] == 1:draw.ellipse([x0+4,y0+4,x1-4,y1-4], fill='white')elif board_state[r][c] == -1:draw.ellipse([x0+4,y0+4,x1-4,y1-4], fill='black')return img# Click handlerdef click_handler(evt, state):# state: (board, player, last_user, last_ai)if state is None:state = (initialize_board(), -1, None, None)board, player, last_user, last_ai = statex, y = evt.indexcell = 360 // 8c, r = int(x//cell), int((y-cell)//cell)# Player moveif 0 <= r < 8 and 0 <= c < 8 and not is_game_over(board):if apply_move(board, r, c, player):last_user = (r, c)player = -player# AI moveif not is_game_over(board):ai_mv = choose_move(board, player)if ai_mv:apply_move(board, ai_mv[0], ai_mv[1], player)last_ai = ai_mvplayer = -playerreturn board_to_image(board, (board, player, last_user, last_ai)), (board, player, last_user, last_ai)# Mainwith gr.Blocks() as demo:state = gr.State((initialize_board(), -1, None, None))img = gr.Image(value=board_to_image(initialize_board(), (initialize_board(), -1, None, None)), interactive=True)img.select(click_handler, inputs=[state], outputs=[img, state])demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107import gradio as grfrom PIL import Image, ImageDraw, ImageFontimport randomtimeDIRECTIONS = [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]# Game logicdef initialize_board():board = [[0]*8 for _ in range(8)]board[3][3], board[4][4] = 1, 1board[3][4], board[4][3] = -1, -1return boarddef get_flips(board, r, c, p):if board[r][c] != 0: return []flips = []for dr, dc in DIRECTIONS:rr, cc = r+dr, c+dc; buf=[]while 0<=rr<8 and 0<=cc<8 and board[rr][cc] == -p:buf.append((rr,cc)); rr+=dr; cc+=dcif buf and 0<=rr<8 and 0<=cc<8 and board[rr][cc] == p:flips += bufreturn flipsdef apply_move(board, r, c, p):f = get_flips(board, r, c, p)if not f: return Falseboard[r][c] = pfor rr, cc in f: board[rr][cc] = preturn Truedef choose_move(board, p):moves = [(r,c) for r in range(8) for c in range(8) if get_flips(board,r,c,p)]return random.choice(moves) if moves else Nonedef count_score(board):b = sum(cell==-1 for row in board for cell in row)w = sum(cell==1 for row in board for cell in row)return b, wdef is_game_over(board):return not any(get_flips(board,r,c,p) for p in (-1,1) for r in range(8) for c in range(8))# Renderingdef board_to_image(board, state):board_state, player, last_user, last_ai = statesize = 400; board_size = 360; cell = board_size//8img = Image.new('RGB',(size, size), 'darkgreen')draw = ImageDraw.Draw(img)# Load fonttry:font = ImageFont.truetype('arial.ttf', 24)except:font = ImageFont.load_default()# Scoreboardb, w = count_score(board_state)draw.text((10, 10), f"Black: {b}", font=font, fill='white')draw.text((size-150, 10), f"White: {w}", font=font, fill='white')# Winner displayif is_game_over(board_state):result = 'DRAW' if b==w else ('BLACK WINS' if b>w else 'WHITE WINS')w_font = ImageFont.truetype('arial.ttf', 36) if hasattr(ImageFont, 'truetype') else fontdraw.text((size//2 - 100, size//2 - 18), result, font=w_font, fill='yellow')# Draw grid and stonesoffset = 40for r in range(8):for c in range(8):x0 = offset + c*celly0 = offset + r*cellx1, y1 = x0+cell, y0+celldraw.rectangle([x0,y0,x1,y1], outline='black')val = board_state[r][c]if val == 1:draw.ellipse([x0+4,y0+4,x1-4,y1-4], fill='white')elif val == -1:draw.ellipse([x0+4,y0+4,x1-4,y1-4], fill='black')return img# Handlersdef click_handler(evt: gr.SelectData, state):board, player, last_user, last_ai = state# Calculate cellx,y = evt.index; offset=40; cell=360//8c = int((x-offset)//cell); r = int((y-offset)//cell)if 0<=r<8 and 0<=c<8 and not is_game_over(board):if apply_move(board, r, c, player): last_user=(r,c); player=-player# AI move after delaytime.sleep(1)if not is_game_over(board):ai_mv = choose_move(board, player)if ai_mv:apply_move(board, ai_mv[0], ai_mv[1], player)last_ai = ai_mv; player=-playerreturn board_to_image(board, (board, player, last_user, last_ai)), (board, player, last_user, last_ai)def reset_game():return (initialize_board(), -1, None, None)# UIwith gr.Blocks() as demo:state = gr.State((initialize_board(), -1, None, None))img = gr.Image(value=board_to_image(initialize_board(), (initialize_board(),-1,None,None)), interactive=True)new_game = gr.Button("New Game")img.select(click_handler, inputs=[state], outputs=[img, state])new_game.click(fn=lambda: (initialize_board(), -1, None, None), outputs=[state])demo.launch()
app.py+57-66