可运行的python五子棋代码
时间: 2023-12-04 13:00:39 浏览: 79
五子棋是一种非常经典的策略游戏,很适合用Python来编写。以下是一个可运行的Python五子棋代码示例:
```python
# 导入必要的模块
import pygame
import sys
# 初始化
pygame.init()
# 设置游戏界面大小
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
# 设置棋盘大小和行列数
grid_size = 30
grid_width, grid_height = width // grid_size, height // grid_size
# 初始化棋盘
chessboard = [[0 for _ in range(grid_width)] for _ in range(grid_height)]
# 画棋盘
def draw_board():
for x in range(0, width, grid_size):
pygame.draw.line(screen, (0, 0, 0), (x, 0), (x, height))
for y in range(0, height, grid_size):
pygame.draw.line(screen, (0, 0, 0), (0, y), (width, y))
# 画棋子
def draw_piece(row, col, is_black):
color = (0, 0, 0) if is_black else (255, 255, 255)
pygame.draw.circle(screen, color, (col*grid_size+grid_size//2, row*grid_size+grid_size//2), grid_size//2-2)
# 主循环
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
x, y = event.pos
row, col = y // grid_size, x // grid_size
if chessboard[row][col] == 0:
chessboard[row][col] = 1
draw_piece(row, col, True)
draw_board()
# 在屏幕上更新
pygame.display.flip()
```
以上就是一个简单的可运行的Python五子棋代码。在这个代码示例中,我们使用了pygame模块来创建游戏界面,并实现了五子棋的基本功能。玩家可以通过鼠标点击来下棋子,程序会实时更新界面。希望对你有所帮助!
阅读全文