python五子棋pygame代码
时间: 2023-12-15 12:32:19 浏览: 116
PYTHON 游戏:五子棋(利用pygame实现)
五子棋是一个双人对战的游戏,玩家轮流在棋盘上放置自己的棋子,当一方的棋子在横、竖、斜线上连成五个时,该方获胜。下面是一个简单的Python五子棋游戏代码,使用了pygame库:
首先,确保已经安装了pygame库,如果没有安装,可以使用以下命令安装:
```bash
pip install pygame
```
接下来是五子棋游戏的代码:
```python
import pygame
import sys
# 初始化pygame
pygame.init()
# 设置窗口大小和标题
size = width, height = 800, 800
screen = pygame.display.set_mode(size)
pygame.display.set_caption("五子棋")
# 设置棋盘大小和棋子半径
board_size = 15
cell_size = 50
stone_radius = 20
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
# 初始化棋盘
board = [[0 for _ in range(board_size)] for _ in range(board_size)]
# 加载字体
font = pygame.font.Font(None, 36)
def draw_board():
screen.fill(WHITE)
for i in range(board_size):
pygame.draw.line(screen, BLACK, (cell_size // 2 + i * cell_size, cell_size // 2), (cell_size // 2 + i * cell_size, height - cell_size // 2), 2)
pygame.draw.line(screen, BLACK, (cell_size // 2, cell_size // 2 + i * cell_size), (width - cell_size // 2, cell_size // 2 + i * cell_size), 2)
def draw_stone(x, y, color):
pygame.draw.circle(screen, color, (cell_size // 2 + x * cell_size, cell_size // 2 + y * cell_size), stone_radius)
def check_win(x, y, color):
directions = [(-1, 0), (0, -1), (-1, -1), (-1, 1)]
for dx, dy in directions:
count = 1
for i in range(1, 5):
nx, ny = x + i * dx, y + i * dy
if 0 <= nx < board_size and 0 <= ny < board_size and board[nx][ny] == color:
count += 1
else:
break
for i in range(1, 5):
nx, ny = x - i * dx, y - i * dy
if 0 <= nx < board_size and 0 <= ny < board_size and board[nx][ny] == color:
count += 1
else:
break
if count >= 5:
return True
return False
def main():
global board
turn = 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
x, y = event.pos
i, j = x // cell_size, y // cell_size
if board[i][j] == 0:
board[i][j] = turn % 2
turn += 1
draw_stone(i, j, BLACK if turn % 2 == 0 else RED)
if check_win(i, j, BLACK if turn % 2 == 0 else RED):
print("Player", turn % 2 + 1, "wins!")
sys.exit()
draw_board()
draw_board()
pygame.display.flip()
pygame.time.delay(1000 // 60)
if __name__ == "__main__":
main()
```
运行这段代码,即可开始五子棋游戏。游戏中
阅读全文