python tkinter库做五子棋代码
时间: 2023-08-18 15:05:07 浏览: 78
python使用tkinter库实现五子棋游戏
好的,以下是一个简单的五子棋代码:
```
import tkinter as tk
class Game:
def __init__(self):
self.board = [[0] * 15 for _ in range(15)]
self.player = 1
self.game_over = False
def get_winner(self, row, col):
directions = [(0, 1), (1, 0), (1, 1), (-1, 1)]
for d in directions:
count = 1
for i in range(1, 5):
r = row + d[0] * i
c = col + d[1] * i
if r < 0 or r >= 15 or c < 0 or c >= 15 or self.board[r][c] != self.player:
break
count += 1
for i in range(1, 5):
r = row - d[0] * i
c = col - d[1] * i
if r < 0 or r >= 15 or c < 0 or c >= 15 or self.board[r][c] != self.player:
break
count += 1
if count >= 5:
return self.player
return 0
def play(self, row, col):
if self.game_over:
return
if self.board[row][col] != 0:
return
self.board[row][col] = self.player
winner = self.get_winner(row, col)
if winner != 0:
print("Player", self.player, "wins!")
self.game_over = True
else:
self.player = 3 - self.player
class Board:
def __init__(self, game):
self.game = game
self.window = tk.Tk()
self.window.title("Five in a Row")
self.canvas = tk.Canvas(self.window, width=450, height=450)
self.canvas.pack()
self.canvas.bind("<Button-1>", self.click)
for i in range(15):
self.canvas.create_line(15 + i * 30, 15, 15 + i * 30, 435)
self.canvas.create_line(15, 15 + i * 30, 435, 15 + i * 30)
def start(self):
self.window.mainloop()
def draw_piece(self, row, col):
x = col * 30 + 15
y = row * 30 + 15
if self.game.player == 1:
self.canvas.create_oval(x - 13, y - 13, x + 13, y + 13, fill="black")
else:
self.canvas.create_oval(x - 13, y - 13, x + 13, y + 13, fill="white")
def click(self, event):
if self.game.game_over:
return
x = event.x
y = event.y
row = round((y - 15) / 30)
col = round((x - 15) / 30)
self.game.play(row, col)
self.draw_piece(row, col)
game = Game()
board = Board(game)
board.start()
```
运行该代码,可以得到一个简单的五子棋游戏界面。玩家可以点击棋盘上的空位,将自己的棋子放在该位置。当有一方连成五子时,游戏结束。
阅读全文