easygui怎样做一个五子棋游戏
时间: 2023-09-30 10:02:04 浏览: 36
你可以使用 Python 编程语言和 easygui 库来实现一个简单的五子棋游戏。下面是一个参考代码:
```python
import easygui
# 定义棋盘
chess_board = [[0] * 15 for i in range(15)]
player = 1 # 玩家1为黑棋,玩家2为白棋
game_over = False # 游戏是否结束,默认为 False
# 判断胜负的函数
def is_win(chess_board, row, col, player):
count = 0
# 判断行
for i in range(15):
if chess_board[row][i] == player:
count += 1
if count == 5:
return True
else:
count = 0
# 判断列
count = 0
for i in range(15):
if chess_board[i][col] == player:
count += 1
if count == 5:
return True
else:
count = 0
# 判断正斜线
count = 0
for i in range(-4, 5):
if row + i < 0 or row + i > 14 or col + i < 0 or col + i > 14:
continue
if chess_board[row + i][col + i] == player:
count += 1
if count == 5:
return True
else:
count = 0
# 判断反斜线
count = 0
for i in range(-4, 5):
if row + i < 0 or row + i > 14 or col - i < 0 or col - i > 14:
continue
if chess_board[row + i][col - i] == player:
count += 1
if count == 5:
return True
else:
count = 0
return False
# 显示棋盘
def show_chess_board():
for i in range(15):
for j in range(15):
if chess_board[i][j] == 0:
easygui.button("", (i+1)*40, (j+1)*40, 40, 40, background_color="burlywood")
elif chess_board[i][j] == 1:
easygui.button("", (i+1)*40, (j+1)*40, 40, 40, background_color="black")
elif chess_board[i][j] == 2:
easygui.button("", (i+1)*40, (j+1)*40, 40, 40, background_color="white")
# 执行游戏
while True:
easygui.msgbox("当前是玩家" + str(player) + "的回合,请落子")
msg = "请在棋盘上选择一个空位落子"
title = "五子棋"
choices = list(range(1, 16))
row = easygui.choicebox(msg, title, choices) - 1
col = easygui.choicebox(msg, title, choices) - 1
if chess_board[row][col] == 0:
chess_board[row][col] = player
show_chess_board()
if is_win(chess_board, row, col, player):
easygui.msgbox("玩家" + str(player) + "胜利!")
game_over = True
break
if player == 1:
player = 2
else:
player = 1
else:
easygui.msgbox("该位置已有棋子,请重新落子")
# 判断平局
count = 0
for i in range(15):
for j in range(15):
if chess_board[i][j] != 0:
count += 1
if count == 225:
easygui.msgbox("平局!")
game_over = True
break
```
这个代码使用 easygui 库来实现一个简单的五子棋游戏。首先定义一个棋盘(`chess_board`),然后通过交替落子来进行游戏,使用 `is_win` 函数来判断胜负,使用 `show_chess_board` 函数来显示当前的棋盘状态。
你可以直接复制这个代码并在 Python 环境中运行。注意,这个代码只是一个基本的实现,你可以根据自己的需要对其进行更改和优化。