1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
| import pygame
pygame.init()
size = width, height = 640, 640 screen = pygame.display.set_mode(size) pygame.display.set_caption('五子棋')
grid_size = 40 board_size = 15
BLACK = (0, 0, 0) WHITE = (255, 255, 255) BROWN = (205, 133, 63)
def create_board(size): return [['.' for _ in range(size)] for _ in range(size)]
def print_board(board): for row in board: print(" ".join(row))
def draw_board(screen, grid_size, board_size): screen.fill(BROWN) for i in range(board_size): pygame.draw.line(screen, BLACK, (grid_size + grid_size * i, grid_size), (grid_size + grid_size * i, height - grid_size), 1) pygame.draw.line(screen, BLACK, (grid_size, grid_size + grid_size * i), (width - grid_size, grid_size + grid_size * i), 1)
def place_piece(screen, grid_size, x, y, player_color): pygame.draw.circle(screen, player_color, (x * grid_size + grid_size // 2, y * grid_size + grid_size // 2), grid_size // 2 - 2)
def check_win(board, player, x, y): directions = [(0, 1), (1, 0), (1, 1), (1, -1)] for dx, dy in directions: count = 0 for i in range(-4, 5): nx, ny = x + dx * i, y + dy * i if 0 <= nx < len(board) and 0 <= ny < len(board) and board[nx][ny] == player: count += 1 if count == 5: return True else: count = 0 return False
def main(): running = True board = create_board(board_size) player = 'X' game_over = False
while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.MOUSEBUTTONDOWN and not game_over: mouseX, mouseY = pygame.mouse.get_pos() grid_x = mouseX // grid_size grid_y = mouseY // grid_size
if board[grid_x][grid_y] == '.': board[grid_x][grid_y] = player if check_win(board, player, grid_x, grid_y): print(f"Player {player} wins!") game_over = True player = 'O' if player == 'X' else 'X'
draw_board(screen, grid_size, board_size)
for x in range(board_size): for y in range(board_size): if board[x][y] == 'X': place_piece(screen, grid_size, x, y, BLACK) elif board[x][y] == 'O': place_piece(screen, grid_size, x, y, WHITE)
pygame.display.flip()
if __name__ == "__main__": main() pygame.quit()
|