前言

使用python实现了贪吃蛇和五子棋,之后我会给它们加上ai.

思路

贪吃蛇不能碰到墙壁和自己的身体,这是游戏规则。
ai方面我仅仅了解哈密顿回路和贪心算法。
五子棋要注意五子连成一线游戏结束。
ai方面是极大极小值算法和减枝算法。

程序

贪吃蛇

写的很烂,功能也不齐全,但这是我写的第一个python游戏。

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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
import pygame
import sys
import random
import time

pygame.init()

BLACK = pygame.Color(0, 0, 0)
WHITE = pygame.Color(255, 255, 255)
RED = pygame.Color(255, 0, 0)
GREEN = pygame.Color(0, 255, 0)
BLUE = pygame.Color(0, 0, 255)

FRAME_SIZE_X = 640
FRAME_SIZE_Y = 480

pygame.display.set_caption('贪吃蛇')
game_window = pygame.display.set_mode((FRAME_SIZE_X, FRAME_SIZE_Y))

fps_controller = pygame.time.Clock()

snake_pos = [100, 50]
snake_body = [[100, 50], [90, 50], [80, 50]]

food_pos = [random.randrange(1, (FRAME_SIZE_X // 10)) * 10, random.randrange(1, (FRAME_SIZE_Y // 10)) * 10]
food_spawn = True

direction = 'RIGHT'
change_to = direction

score = 0


def game_over():
my_font = pygame.font.SysFont('times new roman', 90)
game_over_surface = my_font.render('false', True, RED)
game_over_rect = game_over_surface.get_rect()
game_over_rect.midtop = (FRAME_SIZE_X / 2, FRAME_SIZE_Y / 4)
game_window.fill(BLACK)
game_window.blit(game_over_surface, game_over_rect)
show_score(0)
pygame.display.flip()
time.sleep(5)
pygame.quit()
sys.exit()


def show_score(choice):
score_font = pygame.font.SysFont('consolas', 35)
score_surface = score_font.render('SCORE:' + str(score), True, WHITE)
score_rect = score_surface.get_rect()
if choice == 1:
score_rect.midtop = (FRAME_SIZE_X / 10, 15)
else:
score_rect.midtop = (FRAME_SIZE_X / 2, FRAME_SIZE_Y / 1.25)
game_window.blit(score_surface, score_rect)
pygame.display.flip()


while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP or event.key == ord('w'):
change_to = 'UP'
if event.key == pygame.K_DOWN or event.key == ord('s'):
change_to = 'DOWN'
if event.key == pygame.K_LEFT or event.key == ord('a'):
change_to = 'LEFT'
if event.key == pygame.K_RIGHT or event.key == ord('d'):
change_to = 'RIGHT'
# 按ESC退出游戏
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()

if change_to == 'UP' and direction != 'DOWN':
direction = 'UP'
if change_to == 'DOWN' and direction != 'UP':
direction = 'DOWN'
if change_to == 'LEFT' and direction != 'RIGHT':
direction = 'LEFT'
if change_to == 'RIGHT' and direction != 'LEFT':
direction = 'RIGHT'

if direction == 'UP':
snake_pos[1] -= 10
if direction == 'DOWN':
snake_pos[1] += 10
if direction == 'LEFT':
snake_pos[0] -= 10
if direction == 'RIGHT':
snake_pos[0] += 10

snake_body.insert(0, list(snake_pos))
if snake_pos[0] == food_pos[0] and snake_pos[1] == food_pos[1]:
score += 1
food_spawn = False
else:
snake_body.pop()

if not food_spawn:
food_pos = [random.randrange(1, (FRAME_SIZE_X // 10)) * 10, random.randrange(1, (FRAME_SIZE_Y // 10)) * 10]
food_spawn = True

# BlACK BLACK
game_window.fill(BLACK)

for pos in snake_body:
pygame.draw.rect(game_window,GREEN,pygame.Rect(pos[0],pos[1],10,10))

pygame.draw.rect(game_window,WHITE,pygame.Rect(food_pos[0],food_pos[1],10,10))


if snake_pos[0] <0 or snake_pos[0] > FRAME_SIZE_X-10:
game_over()
if snake_pos[1] < 0 or snake_pos[1] > FRAME_SIZE_Y - 10:
game_over()
for block in snake_body[1:]:
if snake_pos[0] == block[0] and snake_pos[1] == block[1]:
game_over()

show_score(1)
pygame.display.update()
fps_controller.tick(25)

五子棋

这个更烂。

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
pygame.init()

# 设置窗口大小和标题
size = width, height = 640, 640
screen = pygame.display.set_mode(size)
pygame.display.set_caption('五子棋')

# 设置棋盘参数
grid_size = 40 # 网格大小
board_size = 15 # 15x15的棋盘

# 定义颜色
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()