Python 贪吃蛇(pygame)
前言
源代码参考B站: BV1cs411T7wW
效果展示
部分代码
框架
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# 初始化
pygame.init()
W = 800
H = 600
ROW = 30
COL = 40
size = (W, H)
window = pygame.display.set_mode(size)
pygame.display.set_caption("贪吃蛇")
bg_color = (255, 255, 255)
# 绘制
def rect(point, color):
left = point.col * W / COL
top = point.row * H / ROW
pygame.draw.rect(
window, color,
(left, top, W / COL, H / ROW)
)
pass
# 游戏循环
quit = True
while quit:
# 处理事件
for event in pygame.event.get():
# print(event) # 鼠标测试
if event.type == pygame.QUIT:
quit = False
# 背景
pygame.draw.rect(window, bg_color, (0, 0, W, H))
pygame.display.flip()小键盘
1
2
3
4
5
6
7
8
9
10
11
12
13# 小键盘 # wasd
if event.key == 1073741906 or event.key == 82: # if event.key==273 or event.key==119:
if direct == "left" or direct == "right":
direct = "up"
elif event.key == 1073741905 or event.key == 81: # elif event.key==274 or event.key==115:
if direct == "left" or direct == "right":
direct = "down"
elif event.key == 1073741904 or event.key == 80: # elif event.key==273 or event.key==119:
if direct == "up" or direct == "down":
direct = "left"
elif event.key == 1073741903 or event.key == 79: # elif event.key==273 or event.key==119:
if direct == "up" or direct == "down":
direct = "right"碰撞判定
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16# 碰撞判定
dead = False
# 撞墙
if head.col < 0 or head.row < 0 or head.col >= COL or head.row >= ROW:
dead = True
# 撞自己
for snake in snakes:
if head.col == snake.col and head.row == snake.row:
dead = True
break
# 死亡
if dead:
print("game over")
quit = FalseFPS
1
2
3
4clock = pygame.time.Clock()
# FPS
clock.tick(20)
完整代码
1 | # 工程:test |
Invitation
Reverse
835786725
created:06/08/2022
HY Group
HY Group , Entertainment first , Just be happy . SuiXing Originality Parking Iot . Ruan Fan Ying Chi Herbal Tea Shop .
Internet Of Things .
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Reverse!
评论
WalineTwikoo