给我用Python编写一段五子棋的游戏显示代码。
时间: 2024-10-29 16:12:12 浏览: 8
python代码开发实现五子棋附源码.docx
在Python中,我们可以使用`pygame`库来创建一个基本的五子棋游戏。以下是一个简单的示例,它会在9x9的格子上显示棋盘并让用户交替下棋。请注意,这个示例仅提供基础框架,实际完整游戏还需要处理更多的逻辑,比如判断胜负和循环等待玩家输入等。
```python
import pygame
import sys
# 初始化pygame
pygame.init()
# 设置窗口大小
WINDOW_SIZE = (600, 600)
screen = pygame.display.set_mode(WINDOW_SIZE)
# 棋盘颜色
BORDER_COLOR = (0, 0, 0)
BACKGROUNDCOLOR = (255, 255, 255)
GRID_COLOR = (150, 150, 150)
# 棋子大小和位置
STONE_SIZE = 100
ROW_NUM = 9
COLUMN_NUM = 9
stone_positions = [[None] * COLUMN_NUM for _ in range(ROW_NUM)]
def draw_grid():
for i in range(ROW_NUM):
for j in range(COLUMN_NUM):
pygame.draw.rect(screen, GRID_COLOR, (j * STONE_SIZE, i * STONE_SIZE, STONE_SIZE, STONE_SIZE), 1)
def draw_stone(x, y, color):
stone = pygame.Rect(x, y, STONE_SIZE, STONE_SIZE)
pygame.draw.rect(screen, color, stone)
def main():
running = True
player = 'X'
while running:
screen.fill(BACKGROUNDCOLOR)
draw_grid()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
x, y = pygame.mouse.get_pos()
row, col = y // STONE_SIZE, x // STONE_SIZE
if stone_positions[row][col] is None:
stone_positions[row][col] = player
draw_stone(col * STONE_SIZE + STONE_SIZE//2, row * STONE_SIZE + STONE_SIZE//2, {'X': (255, 0, 0), 'O': (0, 0, 255)}[player])
# 更新屏幕
pygame.display.flip()
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()
```
阅读全文