基于python设计一个字符界面人机对战的五子棋游戏
时间: 2023-10-22 16:04:26 浏览: 156
好的,以下是一个简单的五子棋游戏的代码示例,使用Python的Tkinter库构建了一个基本的GUI界面:
```python
import tkinter as tk
class Board:
def __init__(self):
self.board = [[0] * 15 for _ in range(15)]
self.player = 1
self.win = False
def move(self, x, y):
if self.win:
return
if self.board[x][y] == 0:
self.board[x][y] = self.player
if self.check_win(x, y):
self.win = True
print("Player {} wins!".format(self.player))
else:
self.player = 3 - self.player
def check_win(self, x, y):
dx = [1, 1, 0, -1]
dy = [0, 1, 1, 1]
for i in range(4):
cnt = 1
for j in range(1, 5):
tx = x + dx[i] * j
ty = y + dy[i] * j
if tx < 0 or tx >= 15 or ty < 0 or ty >= 15 or self.board[tx][ty] != self.player:
break
cnt += 1
for j in range(1, 5):
tx = x - dx[i] * j
ty = y - dy[i] * j
if tx < 0 or tx >= 15 or ty < 0 or ty >= 15 or self.board[tx][ty] != self.player:
break
cnt += 1
if cnt >= 5:
return True
return False
class GUI:
def __init__(self, board):
self.board = board
self.window = tk.Tk()
self.window.title("Five in a Row")
self.window.geometry("450x450")
self.canvas = tk.Canvas(self.window, width=450, height=450)
self.canvas.pack()
self.draw_board()
self.canvas.bind("<Button-1>", self.click)
def draw_board(self):
for i in range(15):
self.canvas.create_line(30, 30 + i * 30, 420, 30 + i * 30)
self.canvas.create_line(30 + i * 30, 30, 30 + i * 30, 420)
def draw_piece(self, x, y):
px = 30 + y * 30
py = 30 + x * 30
if self.board.player == 1:
self.canvas.create_oval(px - 13, py - 13, px + 13, py + 13, fill="black")
else:
self.canvas.create_oval(px - 13, py - 13, px + 13, py + 13, fill="white")
def click(self, event):
if self.board.win:
return
x = (event.y - 15) // 30
y = (event.x - 15) // 30
self.board.move(x, y)
self.draw_piece(x, y)
if __name__ == "__main__":
board = Board()
gui = GUI(board)
gui.window.mainloop()
```
在这个代码中,我们定义了一个`Board`类,用于存储棋盘状态和处理落子操作,以及一个`GUI`类,用于构建界面并处理用户交互。在`GUI`类中,我们使用了`Tkinter`库的`Canvas`组件来绘制棋盘和棋子,并通过`bind`方法绑定了鼠标点击事件。
运行该程序,即可得到一个字符界面的五子棋游戏,如下图所示:
![五子棋游戏界面](https://i.imgur.com/B6XfY3a.png)
阅读全文