用python写一个字符界面人机对战的五子棋游戏
时间: 2024-05-01 07:21:31 浏览: 131
基于python实现五子棋人机对战
5星 · 资源好评率100%
好的,我可以给你提供一个简单的示例代码,基于Python的Tkinter模块实现字符界面人机对战的五子棋游戏。
```python
import tkinter as tk
from tkinter.messagebox import showinfo
class ChessBoard(tk.Frame):
def __init__(self, master=None, **kw):
super().__init__(master, **kw)
self.master = master
self.grid()
self.create_widgets()
self.turn = 0
self.chess = [[0] * 15 for i in range(15)]
self.player = 1
def create_widgets(self):
self.canvas = tk.Canvas(self, bg="#F7DC6F", width=450, height=450)
self.canvas.grid(row=0, column=0)
for i in range(15):
self.canvas.create_line(15 + i * 30, 15, 15 + i * 30, 435, width=2)
self.canvas.create_line(15, 15 + i * 30, 435, 15 + i * 30, width=2)
self.canvas.create_text(225, 225, text='五子棋', font=('Arial', 20))
self.canvas.bind('<Button-1>', self.click)
def click(self, event):
if self.turn == 0:
x, y = (event.x - 15) // 30, (event.y - 15) // 30
if x < 0 or x > 14 or y < 0 or y > 14 or self.chess[x][y] != 0:
return
if self.player == 1:
self.canvas.create_oval(x * 30 + 15 - 13, y * 30 + 15 - 13, x * 30 + 15 + 13, y * 30 + 15 + 13,
fill="#000000")
self.chess[x][y] = 1
if self.check_win(x, y, 1):
showinfo('游戏结束', '黑方获胜!')
self.canvas.unbind('<Button-1>')
return
self.player = 2
else:
self.canvas.create_oval(x * 30 + 15 - 13, y * 30 + 15 - 13, x * 30 + 15 + 13, y * 30 + 15 + 13,
fill="#FFFFFF")
self.chess[x][y] = 2
if self.check_win(x, y, 2):
showinfo('游戏结束', '白方获胜!')
self.canvas.unbind('<Button-1>')
return
self.player = 1
self.turn += 1
def check_win(self, x, y, player):
count = 1
for i in range(1, 5):
if y + i > 14 or self.chess[x][y + i] != player:
break
count += 1
for i in range(1, 5):
if y - i < 0 or self.chess[x][y - i] != player:
break
count += 1
if count >= 5:
return True
count = 1
for i in range(1, 5):
if x + i > 14 or self.chess[x + i][y] != player:
break
count += 1
for i in range(1, 5):
if x - i < 0 or self.chess[x - i][y] != player:
break
count += 1
if count >= 5:
return True
count = 1
for i in range(1, 5):
if x + i > 14 or y + i > 14 or self.chess[x + i][y + i] != player:
break
count += 1
for i in range(1, 5):
if x - i < 0 or y - i < 0 or self.chess[x - i][y - i] != player:
break
count += 1
if count >= 5:
return True
count = 1
for i in range(1, 5):
if x + i > 14 or y - i < 0 or self.chess[x + i][y - i] != player:
break
count += 1
for i in range(1, 5):
if x - i < 0 or y + i > 14 or self.chess[x - i][y + i] != player:
break
count += 1
if count >= 5:
return True
return False
if __name__ == '__main__':
root = tk.Tk()
root.title('五子棋')
ChessBoard(root).grid()
root.mainloop()
```
这个代码中,我们使用了Tkinter模块来创建游戏界面。在界面中,我们使用Canvas小部件来绘制棋盘和棋子。同时,我们也实现了简单的游戏逻辑,可以让用户与电脑进行对战。
这段代码只是一个简单的示例,你可以根据自己的需要进行修改和扩展,例如增加AI算法让电脑变得更加智能。
阅读全文