1. # 导入必要的模块
2. import pygame, sys, random
3. from pygame.locals import *
4.
5. # 定义颜色
6. white = (255, 255, 255)
7. black = (0, 0, 0)
8. red = (255, 0, 0)
9. green = (0, 255, 0)
10. blue = (0, 0, 255)
11.
12. # 定义游戏区域大小
13. width = 800
14. height = 600
15.
16. # 定义蛇的大小
17. snake_size = 10
18.
19. # 初始化pygame
20. pygame.init()
21.
22. # 创建游戏区域
23. screen = pygame.display.set_mode((width, height))
24. pygame.display.set_caption('贪吃蛇')
25.
26. # 定义蛇的初始位置
27. snake_x = width / 2
28. snake_y = height / 2
29.
30. # 定义蛇的初始移动方向
31. snake_direction = 'right'
32.
33. # 定义蛇的初始长度
34. snake_length = 1
35.
36. # 定义蛇的身体
37. snake_body = []
38.
39. # 定义食物的初始位置
40. food_x = round(random.randrange(0, width - snake_size) / 10.0) * 10.0
41. food_y = round(random.randrange(0, height - snake_size) / 10.0) * 10.0
42.
43. # 定义游戏结束的标志
44. game_over = False
45.
46. # 定义游戏循环
47. while not game_over:
48. # 处理事件
49. for event in pygame.event.get():
50. if event.type == QUIT:
51. pygame.quit()
52. sys.exit()
53. elif event.type == KEYDOWN:
54. if event.key == K_LEFT and snake_direction != 'right':
55. snake_direction = 'left'
56. elif event.key == K_RIGHT and snake_direction != 'left':
57. snake_direction = 'right'
58. elif event.key == K_UP and snake_direction != 'down':
59. snake_direction = 'up'
60. elif event.key == K_DOWN and snake_direction != 'up':
61. snake_direction = 'down'
62.
63. # 移动蛇的身体
64. if snake_direction == 'right':
65. snake_x += snake_size
66. elif snake_direction == 'left':
67. snake_x -= snake_size
68. elif snake_direction == 'up':
69. snake_y -= snake_size
70. elif snake_direction == 'down':
71. snake_y += snake_size
72.
73. # 判断蛇是否吃到食物
74. if snake_x == food_x and snake_y == food_y:
75. # 生成新的食物位置
76. food_x = round(random.randrange(0, width - snake_size) / 10.0) * 10.0
77. food_y = round(random.randrange(0, height - snake_size) / 10.0) * 10.0
78. # 增加蛇的长度
79. snake_length += 1
80.
81. # 更新蛇的身体
82. snake_head = []
83. snake_head.append(snake_x)
84. snake_head.append(snake_y)
85. snake_body.append(snake_head)
86.
87. if len(snake_body) > snake_length:
88. del snake_body[0]
89.
90. # 判断蛇是否撞到自己
91. for block in snake_body[:-1]:
92. if block == snake_head:
93. game_over = True
94.
95. # 绘制游戏区域
96. screen.fill(black)
97.
98. # 绘制蛇的身体
99. for block in snake_body:
100. pygame.draw.rect(screen, green, [block[0], block[1], snake_size, snake_size])
101.
102. # 绘制食物
103. pygame.draw.rect(screen, red, [food_x, food_y, snake_size, snake_size])
104.
105. # 更新屏幕
106. pygame.display.update()
107.
108. # 判断蛇是否撞到边界
109. if snake_x >= width or snake_x < 0 or snake_y >= height or snake_y < 0:
110. game_over = True
111.
112. # 控制游戏速度
113. pygame.time.Clock().tick(20)
114.
115. # 退出游戏
116. pygame.quit()
117. sys.exit()