IDLE五子棋游戏代码
时间: 2023-07-03 09:12:59 浏览: 148
以下是一个简单的五子棋游戏代码示例,使用 Python 的 Tkinter 库实现游戏界面和交互:
```python
import tkinter as tk
class Board:
def __init__(self):
self.size = 15
self.board = [[0 for _ in range(self.size)] for _ in range(self.size)]
self.turn = 1
self.win = False
def move(self, x, y):
if self.board[x][y] == 0:
self.board[x][y] = self.turn
self.turn = 3 - self.turn
self.check_win(x, y)
def check_win(self, x, y):
directions = [(1, 0), (0, 1), (1, 1), (1, -1)]
for dx, dy in directions:
count = 1
for i in range(1, 5):
nx, ny = x + i * dx, y + i * dy
if not (0 <= nx < self.size and 0 <= ny < self.size and self.board[nx][ny] == self.turn):
break
count += 1
for i in range(1, 5):
nx, ny = x - i * dx, y - i * dy
if not (0 <= nx < self.size and 0 <= ny < self.size and self.board[nx][ny] == self.turn):
break
count += 1
if count >= 5:
self.win = True
def reset(self):
self.__init__()
class Game:
def __init__(self):
self.board = Board()
self.root = tk.Tk()
self.canvas = tk.Canvas(self.root, width=480, height=480)
self.canvas.pack()
self.canvas.bind("<Button-1>", self.on_click)
self.draw_board()
self.root.mainloop()
def draw_board(self):
self.canvas.delete("all")
for i in range(self.board.size):
self.canvas.create_line(40, 40 + i * 30, 440, 40 + i * 30)
self.canvas.create_line(40 + i * 30, 40, 40 + i * 30, 440)
for i in range(self.board.size):
for j in range(self.board.size):
if self.board.board[i][j] == 1:
self.canvas.create_oval(25 + j * 30, 25 + i * 30, 55 + j * 30, 55 + i * 30, fill="black")
elif self.board.board[i][j] == 2:
self.canvas.create_oval(25 + j * 30, 25 + i * 30, 55 + j * 30, 55 + i * 30, fill="white")
def on_click(self, event):
if not self.board.win:
x, y = (event.y - 25) // 30, (event.x - 25) // 30
if 0 <= x < self.board.size and 0 <= y < self.board.size:
self.board.move(x, y)
self.draw_board()
if self.board.win:
print("Player {} wins!".format(3 - self.board.turn))
self.board.reset()
game = Game()
```
运行代码后,将出现一个 15x15 的棋盘界面,玩家可通过鼠标点击来下棋,黑方先手。当有一方连成五子,游戏结束并打印胜者。可以通过 `board.reset()` 方法重新开始游戏。
阅读全文