用Python编写一个带UI可对弈的五子棋游戏
时间: 2023-11-16 10:09:19 浏览: 85
好的,我可以为您提供一个简单的五子棋游戏代码,带有Python Tkinter GUI界面。下面是代码:
```python
import tkinter as tk
class Board:
def __init__(self, master):
self.master = master
self.master.title("五子棋")
self.canvas = tk.Canvas(self.master, width=480, height=480, bg="white")
self.canvas.pack(side=tk.TOP)
self.canvas.bind("<Button-1>", self.mouseClick)
self.canvas.bind("<Button-2>", self.resetBoard)
self.canvas.bind("<Button-3>", self.undo)
self.side = 30
self.margin = 20
self.board = [[0] * 15 for _ in range(15)]
self.color = 1
self.gameover = False
self.drawBoard()
def drawBoard(self):
for i in range(15):
self.canvas.create_line(self.margin+self.side*i, self.margin, self.margin+self.side*i, 15*self.side+self.margin, width=2)
for i in range(15):
self.canvas.create_line(self.margin, self.margin+self.side*i, 15*self.side+self.margin, self.margin+self.side*i, width=2)
def mouseClick(self, event):
if self.gameover:
return
x, y = event.x, event.y
if x < self.margin - self.side/2 or x > 15*self.side+self.margin + self.side/2 or \
y < self.margin - self.side/2 or y > 15*self.side+self.margin + self.side/2:
return
row, col = int((y-self.margin)/self.side), int((x-self.margin)/self.side)
if self.board[row][col] != 0:
return
self.board[row][col] = self.color
self.drawPiece(row, col, self.color)
if self.checkWin(row, col):
self.showResult()
self.gameover = True
return
self.color = 3 - self.color
def drawPiece(self, row, col, color):
x = col * self.side + self.margin
y = row * self.side + self.margin
if color == 1:
self.canvas.create_oval(x-self.side/2, y-self.side/2, x+self.side/2, y+self.side/2, fill="black")
else:
self.canvas.create_oval(x-self.side/2, y-self.side/2, x+self.side/2, y+self.side/2, fill="white")
def checkWin(self, row, col):
directions = [(0, 1), (1, 0), (1, 1), (1, -1)]
for d in directions:
count = 1
r, c = row, col
while r+d[0] >= 0 and r+d[0] < 15 and c+d[1] >= 0 and c+d[1] < 15 and self.board[r+d[0]][c+d[1]] == self.color:
count += 1
r, c = r+d[0], c+d[1]
r, c = row, col
while r-d[0] >= 0 and r-d[0] < 15 and c-d[1] >= 0 and c-d[1] < 15 and self.board[r-d[0]][c-d[1]] == self.color:
count += 1
r, c = r-d[0], c-d[1]
if count >= 5:
return True
return False
def showResult(self):
if self.color == 1:
message = "黑方胜利!"
else:
message = "白方胜利!"
self.canvas.create_text(240, 240, text=message, font=("Arial", 20, "bold"))
def resetBoard(self, event):
self.__init__(self.master)
def undo(self, event):
if self.gameover:
return
for row in range(15):
for col in range(15):
if self.board[row][col] != 0:
self.canvas.delete("piece"+str(row)+str(col))
self.board[row][col] = 0
root = tk.Tk()
board = Board(root)
root.mainloop()
```
运行后将会弹出一个五子棋游戏界面,您可以使用鼠标进行操作。左键为落子,右键为悔棋,中键为重新开始游戏。
阅读全文