五子棋编程怎么做

时间:2025-01-25 12:00:55 游戏攻略

五子棋编程可以通过多种编程语言实现,例如Python、C语言等。下面我将分别提供Python和C语言编写的五子棋编程示例。

Python示例

```python

import pygame

import sys

初始化Pygame

pygame.init()

设置窗口大小和标题

width, height = 600, 600

screen = pygame.display.set_mode((width, height))

pygame.display.set_caption("五子棋大战")

定义颜色

black = (0, 0, 0)

white = (255, 255, 255)

棋盘大小和格子大小

board_size = 15

grid_size = width // board_size

棋盘数据

board = [ * board_size for _ in range(board_size)]

current_player = 1

game_over = False

绘制棋盘

def draw_board():

screen.fill(white)

for i in range(board_size):

pygame.draw.line(screen, black, (grid_size * i, 0), (grid_size * i, height))

pygame.draw.line(screen, black, (0, grid_size * i), (width, grid_size * i))

落子

def place_chess(x, y):

if board[x][y] == 0:

board[x][y] = current_player

return True

return False

判断胜负

def check_win(x, y):

directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]

for dx, dy in directions:

count = 1

for i in range(1, 5):

if board[x + i * dx][y + i * dy] == current_player:

count += 1

else:

break

for i in range(1, 5):

if board[x - i * dx][y + i * dy] == current_player:

count += 1

else:

break

for i in range(1, 5):

if board[x + i * dx][y - i * dy] == current_player:

count += 1

else:

break

for i in range(1, 5):

if board[x - i * dx][y - i * dy] == current_player:

count += 1

else:

break

if count >= 5:

return True

return False

游戏主循环

def game_run():

while not game_over:

draw_board()

for event in pygame.event.get():

if event.type == pygame.QUIT:

pygame.quit()

sys.exit()

elif event.type == pygame.KEYDOWN:

if event.key == pygame.K_SPACE:

x, y = (grid_size * (board_size // 2), grid_size * (board_size // 2))

if place_chess(x, y):

if check_win(x, y):

game_over = True

print("玩家 %d 赢了!" % current_player)

else:

current_player = 3 - current_player

开始游戏

game_run()

```

C语言示例