亲自试过,只要安装了pygame一定可以运行
import pygame
import sys
import random# 棋盘
BOARD_SIZE = 30
# 格子
GRID_SIZE = 80
# 屏幕
SCREEN_WIDTH = BOARD_SIZE * GRID_SIZE
SCREEN_HEIGHT = BOARD_SIZE * GRID_SIZE# 颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BACKGROUND = (150, 150, 150)# 初始化
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("五子棋")
game_over = False
current_player = 1 # 1 代表黑方,2 代表白方# 棋盘数组,0 表示空,1 表示黑棋,2 表示白棋
board = [[0 for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]def check_win(x, y, player):
count = 0
for i in range(BOARD_SIZE):
if board[x][i] == player:
count += 1
if count >= 5:
return True
else:
count = 0
count = 0
for i in range(BOARD_SIZE):
if board[i][y] == player:
count += 1
if count >= 5:
return True
else:
count = 0
count = 0
i, j = x, y
while i >= 0 and i < BOARD_SIZE and j >= 0 and j < BOARD_SIZE:
if board[i][j] == player:
count += 1
if count >= 5:
return True
else:
count = 0
i -= 1
j -= 1i, j = x, y
while i >= 0 and i < BOARD_SIZE and j >= 0 and j < BOARD_SIZE:
if board[i][j] == player:
count += 1
if count >= 5:
return True
else:
count = 0
i += 1
j += 1
count = 0
i, j = x, y
while i >= 0 and i < BOARD_SIZE and j >= 0 and j < BOARD_SIZE:
if board[i][j] == player:
count += 1
if count >= 5:
return True
else:
count = 0
i -= 1
j += 1i, j = x, y
while i >= 0 and i < BOARD_SIZE and j >= 0 and j < BOARD_SIZE:
if board[i][j] == player:
count += 1
if count >= 5:
return True
else:
count = 0
i += 1
j -= 1return False
def draw_board():
for x in range(BOARD_SIZE):
pygame.draw.line(screen, BLACK, [x * GRID_SIZE, 0], [x * GRID_SIZE, SCREEN_HEIGHT], 2)
for y in range(BOARD_SIZE):
pygame.draw.line(screen, BLACK, [0, y * GRID_SIZE], [SCREEN_WIDTH, y * GRID_SIZE], 2)def draw_pieces():
for x in range(BOARD_SIZE):
for y in range(BOARD_SIZE):
if board[x][y] == 1:
pygame.draw.circle(screen, BLACK, [x * GRID_SIZE + GRID_SIZE // 2, y * GRID_SIZE + GRID_SIZE // 2], GRID_SIZE // 2 - 5)
elif board[x][y] == 2:
pygame.draw.circle(screen, WHITE, [x * GRID_SIZE + GRID_SIZE // 2, y * GRID_SIZE + GRID_SIZE // 2], GRID_SIZE // 2 - 5)def make_move(x, y):
global current_player
if board[x][y] == 0:
board[x][y] = current_player
if check_win(x, y, current_player):
game_over = True
print(f"Player {current_player} wins!")
current_player = 3 - current_player # 切换玩家while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN and not game_over:
x = event.pos[0] // GRID_SIZE
y = event.pos[1] // GRID_SIZE
make_move(x, y)screen.fill(BACKGROUND)
draw_board()
draw_pieces()
pygame.display.flip()