python双人五子棋
时间: 2023-06-21 11:20:21 浏览: 43
下面是一个简单的Python双人五子棋实现,使用tkinter库实现图形界面:
``` python
import tkinter as tk
class Game:
def __init__(self):
self.board_size = 15 # 棋盘大小
self.grid_size = 30 # 每个格子的大小
self.r = self.grid_size // 2 - 2 # 棋子半径
self.current_player = 1 # 当前玩家
self.board = [[0] * self.board_size for _ in range(self.board_size)] # 棋盘
self.win = False # 是否有一方玩家获胜
def play(self, x, y):
if self.win:
return
if self.board[x][y] != 0:
return
self.board[x][y] = self.current_player
self.check_win(x, y)
self.current_player = 3 - self.current_player
def check_win(self, x, y):
# 横向
count = 0
for i in range(max(0, y - 4), min(self.board_size, y + 5)):
if self.board[x][i] == self.current_player:
count += 1
if count >= 5:
self.win = True
return
else:
count = 0
# 纵向
count = 0
for i in range(max(0, x - 4), min(self.board_size, x + 5)):
if self.board[i][y] == self.current_player:
count += 1
if count >= 5:
self.win = True
return
else:
count = 0
# 左上到右下
count = 0
for i, j in zip(range(max(0, x - 4), min(self.board_size, x + 5)), range(max(0, y - 4), min(self.board_size, y + 5))):
if self.board[i][j] == self.current_player:
count += 1
if count >= 5:
self.win = True
return
else:
count = 0
# 右上到左下
count = 0
for i, j in zip(range(max(0, x - 4), min(self.board_size, x + 5)), range(min(self.board_size - 1, y + 4), max(0, y - 5), -1)):
if self.board[i][j] == self.current_player:
count += 1
if count >= 5:
self.win = True
return
else:
count = 0
class Gobang:
def __init__(self):
self.game = Game()
self.root = tk.Tk()
self.canvas = tk.Canvas(self.root, bg="white", width=self.game.board_size * self.game.grid_size, height=self.game.board_size * self.game.grid_size)
self.canvas.pack()
self.draw_board()
self.canvas.bind("<Button-1>", self.click)
self.root.mainloop()
def draw_board(self):
for i in range(self.game.board_size):
self.canvas.create_line(self.game.grid_size // 2, (i + 0.5) * self.game.grid_size, (self.game.board_size - 0.5) * self.game.grid_size, (i + 0.5) * self.game.grid_size)
self.canvas.create_line((i + 0.5) * self.game.grid_size, self.game.grid_size // 2, (i + 0.5) * self.game.grid_size, (self.game.board_size - 0.5) * self.game.grid_size)
def draw_piece(self, x, y):
if self.game.current_player == 1:
color = "black"
else:
color = "white"
self.canvas.create_oval((y + 0.5 - self.game.r) * self.game.grid_size, (x + 0.5 - self.game.r) * self.game.grid_size, (y + 0.5 + self.game.r) * self.game.grid_size, (x + 0.5 + self.game.r) * self.game.grid_size, fill=color)
def click(self, event):
x = int(event.y // self.game.grid_size)
y = int(event.x // self.game.grid_size)
self.game.play(x, y)
if self.game.win:
self.canvas.create_text(self.game.board_size * self.game.grid_size // 2, self.game.board_size * self.game.grid_size // 2, text="Player {} Wins!".format(self.game.current_player), font=("Arial", 20))
else:
self.draw_piece(x, y)
if __name__ == "__main__":
Gobang()
```
以上代码实现了一个简单的双人五子棋游戏,在终端中执行即可开始游戏。