请使用PYTHON 写一个五子棋的程序
时间: 2023-12-10 09:06:21 浏览: 38
好的,下面是一个简单的五子棋实现的代码,你可以参考一下:
```python
import tkinter as tk
import tkinter.messagebox as msgbox
class Chessboard:
def __init__(self, canvas, size=15, width=30):
self.size = size
self.width = width
self.canvas = canvas
self.chess = [[0 for i in range(size)] for j in range(size)]
self.color = 1
self.draw_board()
self.canvas.bind('<Button-1>', self.click)
def draw_board(self):
for i in range(self.size):
self.canvas.create_line(self.width, self.width+i*self.width, self.width+self.size*self.width, self.width+i*self.width)
self.canvas.create_line(self.width+i*self.width, self.width, self.width+i*self.width, self.width+self.size*self.width)
for i, j in [(3, 3), (3, 11), (11, 3), (11, 11), (7, 7)]:
x, y = self.width+i*self.width, self.width+j*self.width
self.canvas.create_oval(x-3, y-3, x+3, y+3, fill='black')
def click(self, event):
x, y = event.x, event.y
i, j = round((y-self.width)/self.width), round((x-self.width)/self.width)
if i<0 or i>=self.size or j<0 or j>=self.size or self.chess[i][j] != 0:
return
self.chess[i][j] = self.color
self.draw_chess(i, j, self.color)
if self.check_win(i, j, self.color):
msgbox.showinfo('提示', '恭喜你,你赢了!')
self.canvas.unbind('<Button-1>')
return
self.color = 3 - self.color
self.ai_play()
def ai_play(self):
# 这里直接随机落子,可以替换为更复杂的AI算法
import random
i, j = random.randint(0, self.size-1), random.randint(0, self.size-1)
while self.chess[i][j] != 0:
i, j = random.randint(0, self.size-1), random.randint(0, self.size-1)
self.chess[i][j] = self.color
self.draw_chess(i, j, self.color)
if self.check_win(i, j, self.color):
msgbox.showinfo('提示', '很遗憾,你输了!')
self.canvas.unbind('<Button-1>')
return
self.color = 3 - self.color
def draw_chess(self, i, j, color):
x, y = self.width+j*self.width, self.width+i*self.width
if color == 1:
self.canvas.create_oval(x-15, y-15, x+15, y+15, fill='black')
else:
self.canvas.create_oval(x-15, y-15, x+15, y+15, fill='white')
def check_win(self, i, j, color):
directions = [(0, 1), (1, 0), (1, 1), (1, -1)]
for dx, dy in directions:
cnt = 1
for k in range(1, 5):
x, y = i+k*dx, j+k*dy
if x<0 or x>=self.size or y<0 or y>=self.size or self.chess[x][y] != color:
break
cnt += 1
for k in range(1, 5):
x, y = i-k*dx, j-k*dy
if x<0 or x>=self.size or y<0 or y>=self.size or self.chess[x][y] != color:
break
cnt += 1
if cnt >= 5:
return True
return False
root = tk.Tk()
root.title('五子棋')
canvas = tk.Canvas(root, width=480, height=480)
canvas.pack()
chessboard = Chessboard(canvas)
root.mainloop()
```
这个五子棋程序实现了基本的人机对战,你可以在Tk窗口中点击棋盘落子,计算机会随机落子,如果出现五子连珠,则弹出提示框。你可以根据自己的需求进行拓展和改进。