python五子棋人机对战代码,绘图,并给出胜利条件
时间: 2023-11-12 11:19:59 浏览: 87
以下是一个简单的人机对战五子棋代码,使用Python实现。该代码使用tkinter库实现绘图,并通过判断连续五个相同颜色的棋子来确定胜利条件。
```python
import tkinter as tk
import random
# 初始化棋盘
board = [[0 for i in range(15)] for j in range(15)]
# 初始化窗口
window = tk.Tk()
window.title('五子棋')
window.geometry('450x500')
# 初始化画布
canvas = tk.Canvas(window, bg='white', width=450, height=450)
canvas.pack()
# 绘制棋盘
for i in range(15):
canvas.create_line(30, 30+i*30, 420, 30+i*30)
canvas.create_line(30+i*30, 30, 30+i*30, 420)
# 绘制棋子
def draw_piece(x, y, color):
if color == 'black':
canvas.create_oval(x*30+15, y*30+15, x*30+45, y*30+45, fill='black')
else:
canvas.create_oval(x*30+15, y*30+15, x*30+45, y*30+45, fill='white')
# 判断胜利条件
def check_win(x, y, color):
count = 1
# 横向
for i in range(x-1, -1, -1):
if board[i][y] == color:
count += 1
else:
break
for i in range(x+1, 15):
if board[i][y] == color:
count += 1
else:
break
if count >= 5:
return True
# 纵向
count = 1
for i in range(y-1, -1, -1):
if board[x][i] == color:
count += 1
else:
break
for i in range(y+1, 15):
if board[x][i] == color:
count += 1
else:
break
if count >= 5:
return True
# 斜向
count = 1
for i, j in zip(range(x-1, -1, -1), range(y-1, -1, -1)):
if board[i][j] == color:
count += 1
else:
break
for i, j in zip(range(x+1, 15), range(y+1, 15)):
if board[i][j] == color:
count += 1
else:
break
if count >= 5:
return True
# 反斜向
count = 1
for i, j in zip(range(x-1, -1, -1), range(y+1, 15)):
if board[i][j] == color:
count += 1
else:
break
for i, j in zip(range(x+1, 15), range(y-1, -1, -1)):
if board[i][j] == color:
count += 1
else:
break
if count >= 5:
return True
return False
# 人机对战
def play(x, y):
if board[x][y] == 0:
draw_piece(x, y, 'black')
board[x][y] = 'black'
if check_win(x, y, 'black'):
canvas.create_text(225, 225, text='你赢了!', font=('Arial', 20))
canvas.unbind('<Button-1>')
return
while True:
i = random.randint(0, 14)
j = random.randint(0, 14)
if board[i][j] == 0:
draw_piece(i, j, 'white')
board[i][j] = 'white'
if check_win(i, j, 'white'):
canvas.create_text(225, 225, text='电脑赢了!', font=('Arial', 20))
canvas.unbind('<Button-1>')
return
break
# 绑定鼠标事件
canvas.bind('<Button-1>', lambda event: play(event.x//30, event.y//30))
# 运行窗口
window.mainloop()
```
该代码实现了人机对战的五子棋游戏,并通过`check_win()`函数判断胜利条件。当有连续五个相同颜色的棋子时,游戏结束。
阅读全文