python五子棋代码
由于五子棋是一种游戏,属于交互式应用程序,需要图形界面,因此需要使用一些图形库。以下是一个使用 Tkinter 模块实现五子棋的 Python 代码示例:
import tkinter as tk
class Chessboard(tk.Canvas):
def __init__(self, master=None, **kwargs):
super().__init__(master, **kwargs)
self.master = master
self.init_chessboard()
self.draw_chessboard()
self.bind_events()
def init_chessboard(self):
self.n = 15 # 棋盘大小
self.step = 30 # 棋盘格子大小
self.stone_r = self.step // 2 - 2 # 棋子半径
self.board = [[0] * self.n for _ in range(self.n)] # 初始化棋盘状态
self.color = 1 # 当前下棋方,0 表示黑方,1 表示白方
self.game_over = False # 游戏是否结束
self.winner = None # 获胜方
def draw_chessboard(self):
for i in range(self.n):
self.create_line(self.step // 2, self.step // 2 + i * self.step,
self.step // 2 + (self.n - 1) * self.step, self.step // 2 + i * self.step)
self.create_line(self.step // 2 + i * self.step, self.step // 2,
self.step // 2 + i * self.step, self.step // 2 + (self.n - 1) * self.step)
def bind_events(self):
self.bind("<Button-1>", self.place_stone)
def place_stone(self, event):
if self.game_over: # 如果游戏已经结束,无法再下棋
return
x = round((event.x - self.step / 2) / self.step)
y = round((event.y - self.step / 2) / self.step)
if x < 0 or x >= self.n or y < 0 or y >= self.n:
return
if self.board[y][x] != 0: # 如果该位置已经有棋子,无法再下棋
return
self.board[y][x] = self.color
if self.check_win(x, y, self.color): # 如果当前下棋方获胜,游戏结束
self.game_over = True
self.winner = self.color
self.color = 1 - self.color # 下一步改变下棋方
self.draw_stone(x, y, self.color)
def draw_stone(self, x, y, color):
if color == 0:
fill_color = "black"
else:
fill_color = "white"
self.create_oval(x * self.step + self.step // 2 - self.stone_r,
y * self.step + self.step // 2 - self.stone_r,
x * self.step + self.step // 2 + self.stone_r,
y * self.step + self.step // 2 + self.stone_r,
fill=fill_color, outline="black", width=1)
def check_win(self, x, y, color):
directions = [(1, 0), (0, 1), (1, 1), (1, -1)]
for dx, dy in directions:
cnt = 1
for step in (1, -1):
nx, ny = x + step * dx, y + step * dy
while 0 <= nx < self.n and 0 <= ny < self.n and self.board[ny][nx] == color:
cnt += 1
nx, ny = nx + step * dx, ny + step * dy
if cnt >= 5:
return True
return False
class App(tk.Tk):
def __init__(self):
super().__init__()
self.geometry("500x500")
self.title("五子棋")
self.chessboard = Chessboard(self, width=450, height=450)
self.chessboard.pack(side="top", fill="both", expand=True)
if __name__ == "__main__":
app = App()
app.mainloop()
这是一个基本的五子棋交互式应用程序,你可以在棋盘上单击鼠标下棋,程序会自动检查是否有一方获胜或者平局。