编写五子棋的完整python代码_python实现五子棋程序
时间: 2023-07-23 16:10:13 浏览: 208
好的,下面是一个简单的五子棋Python代码,其中使用了Tkinter来实现图形界面:
```python
import tkinter as tk
from tkinter import messagebox
class Board:
def __init__(self):
self.board = [[0] * 15 for _ in range(15)] # 棋盘,0表示空,1表示黑子,2表示白子
self.current_player = 1 # 当前玩家,初始为黑方
self.game_over = False
def move(self, row, col):
if self.board[row][col] != 0: # 如果该位置已有棋子,则不能落子
return False
self.board[row][col] = self.current_player # 落子
if self.check_win(row, col): # 检查游戏是否结束
self.game_over = True
messagebox.showinfo('游戏结束', '恭喜玩家{}获胜!'.format('黑' if self.current_player == 1 else '白'))
else:
self.current_player = 3 - self.current_player # 切换玩家
return True
def check_win(self, row, col):
directions = [(0, 1), (1, 0), (1, 1), (1, -1)] # 四个方向
for dx, dy in directions:
cnt = 1
for i in range(1, 5):
r, c = row + i * dx, col + i * dy
if r < 0 or r >= 15 or c < 0 or c >= 15 or self.board[r][c] != self.current_player: # 越界或不是当前玩家的棋子
break
cnt += 1
for i in range(1, 5):
r, c = row - i * dx, col - i * dy
if r < 0 or r >= 15 or c < 0 or c >= 15 or self.board[r][c] != self.current_player:
break
cnt += 1
if cnt >= 5:
return True
return False
class Game:
def __init__(self, board):
self.board = board
def start(self):
self.root = tk.Tk()
self.root.title('五子棋')
self.canvas = tk.Canvas(self.root, width=450, height=450)
self.canvas.pack()
self.canvas.bind('<Button-1>', self.click)
self.draw_board()
self.root.mainloop()
def click(self, event):
if self.board.game_over:
return
x, y = event.x, event.y
row, col = y // 30, x // 30
if self.board.move(row, col):
self.draw_piece(row, col)
def draw_board(self):
for i in range(15):
self.canvas.create_line(15, 15 + i * 30, 435, 15 + i * 30)
self.canvas.create_line(15 + i * 30, 15, 15 + i * 30, 435)
def draw_piece(self, row, col):
if self.board.board[row][col] == 1:
self.canvas.create_oval(col * 30 + 2, row * 30 + 2, col * 30 + 28, row * 30 + 28, fill='black')
else:
self.canvas.create_oval(col * 30 + 2, row * 30 + 2, col * 30 + 28, row * 30 + 28, fill='white')
if __name__ == '__main__':
board = Board()
game = Game(board)
game.start()
```
这个代码实现了一个简单的五子棋游戏,可以通过运行`python filename.py`来启动游戏。
阅读全文