使用python制作一个五子棋游戏
时间: 2024-03-17 15:47:12 浏览: 116
好的,下面是使用Python语言制作一个简单的五子棋游戏的基本步骤:
1.导入必要的模块和库:
```
import numpy as np
import pygame as pg
```
2.定义一些必要的变量和常量:
```
pg.init()
WIDTH, HEIGHT = 640, 640
ROWS, COLS = 15, 15
SQUARE_SIZE = HEIGHT // ROWS
RADIUS = SQUARE_SIZE // 2 - 5
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
board = np.zeros((ROWS, COLS))
player = 1
game_over = False
```
3.绘制棋盘:
```
def draw_board():
for r in range(ROWS):
for c in range(COLS):
pg.draw.rect(screen, (128, 128, 128), (c*SQUARE_SIZE, r*SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE))
pg.draw.circle(screen, (0, 0, 0), (c*SQUARE_SIZE+SQUARE_SIZE//2, r*SQUARE_SIZE+SQUARE_SIZE//2), RADIUS)
```
4.绘制棋子:
```
def draw_piece(row, col, player):
if player == 1:
pg.draw.circle(screen, BLACK, (col*SQUARE_SIZE+SQUARE_SIZE//2, row*SQUARE_SIZE+SQUARE_SIZE//2), RADIUS)
else:
pg.draw.circle(screen, WHITE, (col*SQUARE_SIZE+SQUARE_SIZE//2, row*SQUARE_SIZE+SQUARE_SIZE//2), RADIUS)
```
5.检查胜利条件:
```
def is_win(player):
# 检查行
for r in range(ROWS):
for c in range(COLS-4):
if board[r][c] == player and board[r][c+1] == player and board[r][c+2] == player and board[r][c+3] == player and board[r][c+4] == player:
return True
# 检查列
for r in range(ROWS-4):
for c in range(COLS):
if board[r][c] == player and board[r+1][c] == player and board[r+2][c] == player and board[r+3][c] == player and board[r+4][c] == player:
return True
# 检查斜线
for r in range(ROWS-4):
for c in range(COLS-4):
if board[r][c] == player and board[r+1][c+1] == player and board[r+2][c+2] == player and board[r+3][c+3] == player and board[r+4][c+4] == player:
return True
for r in range(4, ROWS):
for c in range(COLS-4):
if board[r][c] == player and board[r-1][c+1] == player and board[r-2][c+2] == player and board[r-3][c+3] == player and board[r-4][c+4] == player:
return True
return False
```
6.编写主程序:
```
def main():
global screen, board, player, game_over
screen = pg.display.set_mode((WIDTH, HEIGHT))
pg.display.set_caption('五子棋游戏')
while not game_over:
for event in pg.event.get():
if event.type == pg.QUIT:
game_over = True
if event.type == pg.MOUSEBUTTONDOWN:
if player == 1:
col = int(pg.mouse.get_pos()[0] // SQUARE_SIZE)
row = int(pg.mouse.get_pos()[1] // SQUARE_SIZE)
if board[row][col] == 0:
board[row][col] = player
draw_piece(row, col, player)
if is_win(player):
pg.display.set_caption('黑方获胜')
game_over = True
player = 2
else:
col = int(pg.mouse.get_pos()[0] // SQUARE_SIZE)
row = int(pg.mouse.get_pos()[1] // SQUARE_SIZE)
if board[row][col] == 0:
board[row][col] = player
draw_piece(row, col, player)
if is_win(player):
pg.display.set_caption('白方获胜')
game_over = True
player = 1
draw_board()
pg.display.update()
pg.quit()
if __name__ == '__main__':
main()
```
这样就可以使用Python语言制作一个简单的五子棋游戏了。希望对你有帮助。
阅读全文