python写五子棋GUI编程
时间: 2023-07-28 14:51:08 浏览: 97
python实现五子棋游戏程序
4星 · 用户满意度95%
要在Python中编写五子棋GUI程序,可以使用Tkinter这个Python标准库,它提供了一些GUI组件和方法,可以帮助我们快速构建一个简单的五子棋游戏。
以下是一个简单的五子棋GUI程序的示例代码:
``` python
import tkinter as tk
class ChessBoard:
def __init__(self, master):
self.master = master
self.board_size = 15
self.board = [[0 for _ in range(self.board_size)] for _ in range(self.board_size)]
self.current_player = 1
self.canvas = tk.Canvas(self.master, width=600, height=600)
self.canvas.pack()
self.draw_board()
self.canvas.bind("<Button-1>", self.play)
def draw_board(self):
for i in range(self.board_size):
self.canvas.create_line(50, 50 + i*40, 610, 50 + i*40)
self.canvas.create_line(50 + i*40, 50, 50 + i*40, 610)
self.canvas.create_oval(245, 245, 255, 255, fill="black")
self.canvas.create_oval(545, 245, 555, 255, fill="white")
self.canvas.create_text(100, 20, text="Black: player 1", font=("Helvetica", 14))
self.canvas.create_text(500, 20, text="White: player 2", font=("Helvetica", 14))
def play(self, event):
x = (event.x - 50) // 40
y = (event.y - 50) // 40
if 0 <= x < self.board_size and 0 <= y < self.board_size and self.board[x][y] == 0:
if self.current_player == 1:
self.canvas.create_oval(50 + x*40 - 17, 50 + y*40 - 17, 50 + x*40 + 17, 50 + y*40 + 17, fill="black")
self.board[x][y] = 1
self.current_player = 2
else:
self.canvas.create_oval(50 + x*40 - 17, 50 + y*40 - 17, 50 + x*40 + 17, 50 + y*40 + 17, fill="white")
self.board[x][y] = 2
self.current_player = 1
# check win
if self.check_win(x, y):
self.canvas.unbind("<Button-1>")
self.canvas.create_text(300, 300, text="Player {} wins!".format(self.board[x][y]), font=("Helvetica", 30))
def check_win(self, x, y):
directions = [(-1, 0), (0, -1), (-1, -1), (1, -1)]
for dx, dy in directions:
count = 1
tx, ty = x + dx, y + dy
while 0 <= tx < self.board_size and 0 <= ty < self.board_size and self.board[tx][ty] == self.board[x][y]:
count += 1
tx += dx
ty += dy
tx, ty = x - dx, y - dy
while 0 <= tx < self.board_size and 0 <= ty < self.board_size and self.board[tx][ty] == self.board[x][y]:
count += 1
tx -= dx
ty -= dy
if count >= 5:
return True
return False
root = tk.Tk()
root.title("Five in a Row")
game = ChessBoard(root)
root.mainloop()
```
这个程序使用了Tkinter的Canvas组件来绘制棋盘和棋子,并且用一个二维数组来表示棋盘上的状态。在每个玩家下棋时,程序会检查是否达到了胜利条件,如果是,就在屏幕上显示胜利信息。
阅读全文