用Python设计五子棋
时间: 2024-04-09 22:23:35 浏览: 83
基于Python实现的五子棋游戏设计.zip
以下是用Python设计五子棋的步骤:
1.导入必要的库和模块
```python
import numpy as np
import pygame as pg
```
2.初始化游戏界面
```python
pg.init()
size = width, height = 640, 640
screen = pg.display.set_mode(size)
pg.display.set_caption("五子棋")
```
3.定义游戏所需的变量和常量
```python
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
ROW = 15
COLUMN = 15
SPACE = 40
RADIUS = 15
chessboard = np.zeros((ROW, COLUMN))
player = 1
game_over = False
```
4.绘制棋盘和棋子
```python
def draw_chessboard():
for i in range(ROW):
pg.draw.line(screen, BLACK, (SPACE, SPACE + i * SPACE), (SPACE + (COLUMN - 1) * SPACE, SPACE + i * SPACE), 2)
pg.draw.line(screen, BLACK, (SPACE + i * SPACE, SPACE), (SPACE + i * SPACE, SPACE + (ROW - 1) * SPACE), 2)
def draw_chessman():
for i in range(ROW):
for j in range(COLUMN):
if chessboard[i][j] == 1:
pg.draw.circle(screen, BLACK, (SPACE + i * SPACE, SPACE + j * SPACE), RADIUS)
elif chessboard[i][j] == 2:
pg.draw.circle(screen, WHITE, (SPACE + i * SPACE, SPACE + j * SPACE), RADIUS)
```
5.判断胜负
```python
def check_win(player):
for i in range(ROW - 4):
for j in range(COLUMN):
if chessboard[i][j] == player and chessboard[i + 1][j] == player and chessboard[i + 2][j] == player and chessboard[i + 3][j] == player and chessboard[i + 4][j] == player:
return True
for i in range(ROW):
for j in range(COLUMN - 4):
if chessboard[i][j] == player and chessboard[i][j + 1] == player and chessboard[i][j + 2] == player and chessboard[i][j + 3] == player and chessboard[i][j + 4] == player:
return True
for i in range(ROW - 4):
for j in range(COLUMN - 4):
if chessboard[i][j] == player and chessboard[i + 1][j + 1] == player and chessboard[i + 2][j + 2] == player and chessboard[i + 3][j + 3] == player and chessboard[i + 4][j + 4] == player:
return True
for i in range(4, ROW):
for j in range(COLUMN - 4):
if chessboard[i][j] == player and chessboard[i - 1][j + 1] == player and chessboard[i - 2][j + 2] == player and chessboard[i - 3][j + 3] == player and chessboard[i - 4][j + 4] == player:
return True
return False
```
6.游戏主循环
```python
while not game_over:
for event in pg.event.get():
if event.type == pg.QUIT:
game_over = True
if event.type == pg.MOUSEBUTTONDOWN:
if event.button == 1:
x, y = event.pos
i = int(round((x - SPACE) / SPACE))
j = int(round((y - SPACE) / SPACE))
if chessboard[i][j] == 0:
chessboard[i][j] = player
if check_win(player):
print("Player %d wins!" % player)
game_over = True
player = 3 - player
screen.fill(WHITE)
draw_chessboard()
draw_chessman()
pg.display.flip()
pg.quit()
```
阅读全文