其他
如何用Python10分钟绘制贪吃蛇小游戏?
上下左右键控制蛇的方向,寻找食物,每吃到一次食物,就能得到一定的积分,而且蛇的身体会越来越长。随着蛇的身体变长,游戏的难度就会变大。当蛇碰到四周的墙壁,或者碰到自己的身体的某一个部位的时候,游戏就结束了。我们来看一下用Python编写这款游戏的主要思路。带上娃一起编程既好玩又增长知识。
程序界面
自定义函数
事件
声音
导入模块
2import random
3import sys
初始化设置
定义颜色变量
2GREEN = (0, 255, 0)
3DARKGREEN = (0, 185, 0)
4YELLOW = (255,255,0)
定义方向变量
2DOWN = 2
3LEFT = 3
4RIGHT = 4
定义窗口大小
2windowsHeight = 600
定义地图大小
2mapWidth = int(windowsWidth / cellSize) #地图的宽
3mapHeight = int(windowsHeight / cellSize) #地图的高
其他变量
2snakeSpeed = 7 #贪吃蛇的速度
基础函数
main()函数
2 pygame.init() # 模块初始化
3 screen = pygame.display.set_mode((windowsWidth, windowsHeight))
4 pygame.display.set_caption("贪吃蛇")
5 screen.fill(WHITE)
6 snakeSpeedClock = pygame.time.Clock()
7
8 startGame(screen) #游戏开始
9
10 while True:
11 music=pygame.mixer.Sound("snake.wav")
12 music.play(-1)
13 runGame(screen, snakeSpeedClock)
14 music.stop()
15 gameOver(screen) #游戏结束
startGame()函数
2 gameStart = pygame.image.load("gameStart.png")
3 screen.blit(gameStart, (70, 30))
4
5 font = pygame.font.SysFont("SimHei", 40)
6 tip = font.render("按任意键开始游戏", True, (65, 105, 225))
7 screen.blit(tip, (240, 550))
8
9 pygame.display.update()
10
11 while True: #键盘监听事件
12 for event in pygame.event.get(): #关闭窗口
13 if event.type == pygame.QUIT:
14 terminate()
15 elif event.type == pygame.KEYDOWN:
16 if (event.key == pygame.K_ESCAPE): #按下ESC键
17 terminate()
18 else:
19 return
runGame()函数
2 startX = random.randint(3, mapWidth - 8)
3 startY = random.randint(3, mapHeight - 8)
4 snakeCoords = [{"x": startX, "y": startY},
5 {"x": startX - 1, "y": startY},
6 {"x": startX - 2, "y": startY}]
7
8 direction = RIGHT
9
10 food = {"x": random.randint(0, mapWidth - 1), "y": random.randint(0, mapHeight - 1)}
11
12 while True:
13 for event in pygame.event.get():
14 if event.type == pygame.QUIT:
15 terminate()
16 elif event.type == pygame.KEYDOWN:
17 if event.key == pygame.K_LEFT and direction != RIGHT:
18 direction = LEFT
19 elif event.key == pygame.K_RIGHT and direction != LEFT:
20 direction = RIGHT
21 elif event.key == pygame.K_UP and direction != DOWN:
22 direction = UP
23 elif event.key == pygame.K_DOWN and direction != UP:
24 direction = DOWN
25 elif event.key == pygame.K_ESCAPE:
26 terminate()
27
28 moveSnake(direction, snakeCoords) #移动贪吃蛇
29
30 isEattingFood(snakeCoords, food) #判断贪吃蛇是否吃到食物
31
32 ret = isAlive(snakeCoords) #判断贪吃蛇是否还活着
33 if not ret:
34 break #贪吃蛇已经死了,游戏结束
35
36 gameRun = pygame.image.load("background.png")
37 screen.blit(gameRun, (0, 0))
38 drawFood(screen, food)
39 drawSnake(screen, snakeCoords)
40 drawScore(screen, len(snakeCoords) - 3)
41
42 pygame.display.update()
43 snakeSpeedClock.tick(snakeSpeed) #控制帧速率
drawFood()函数
2 x = food["x"] * cellSize
3 y = food["y"] * cellSize
4 pygame.draw.rect(screen, YELLOW, (x, y, cellSize, cellSize))
drawSnake()函数
2 for coord in snakeCoords:
3 x = coord["x"] * cellSize
4 y = coord["y"] * cellSize
5 pygame.draw.rect(screen, DARKGREEN, (x, y, cellSize, cellSize))
6 pygame.draw.rect(screen, GREEN,(x + 4, y + 4, cellSize - 8, cellSize - 8))
drawScore()函数
2 font = pygame.font.SysFont("SimHei", 30)
3 scoreSurf = font.render("得分: " + str(scoer), True, WHITE)
4 scoreRect = scoreSurf.get_rect()
5 scoreRect.topleft = (windowsWidth - 200, 50)
6 screen.blit(scoreSurf, scoreRect)
moveSnake()函数
2 if direction == UP:
3 newHead = {"x": snakeCoords[HEAD][ "x"], "y": snakeCoords[HEAD][ "y"] - 1}
4 elif direction == DOWN:
5 newHead = {"x": snakeCoords[HEAD][ "x"], "y": snakeCoords[HEAD][ "y"] + 1}
6 elif direction == LEFT:
7 newHead = {"x": snakeCoords[HEAD][ "x"] - 1, "y": snakeCoords[HEAD][ "y"]}
8 elif direction == RIGHT:
9 newHead = {"x": snakeCoords[HEAD][ "x"] + 1, "y": snakeCoords[HEAD][ "y"]}
10
11 snakeCoords.insert(0, newHead)
isEattingFood()函数
2 if snakeCoords[HEAD]["x"] == food["x"] and snakeCoords[HEAD]["y"] == food["y"]:
3 food["x"] = random.randint(0, mapWidth - 1)
4 food["y"] = random.randint(0, mapHeight - 1)
5 else:
6 del snakeCoords[-1]
isAlive()函数
2 tag = True
3 if snakeCoords[HEAD]["x"] == -1 or snakeCoords[HEAD]["x"] == mapWidth or snakeCoords[HEAD]["y"] == -1 or snakeCoords[HEAD]["y"] == mapHeight:
4 tag = False # 贪吃蛇碰壁
5 for snake_body in snakeCoords[1:]:
6 if snake_body["x"] == snakeCoords[HEAD]["x"] and snake_body["y"] == snakeCoords[HEAD]["y"]:
7 tag = False # 贪吃蛇碰到自己身体
8 return tag
gameOver()函数
2 #加载游戏结束图片
3 screen.fill(WHITE)
4 gameOver = pygame.image.load("gameover.png")
5 screen.blit(gameOver, (0, 0))
6 #加载游戏结束提示信息
7 font = pygame.font.SysFont("SimHei", 36)
8 tip = font.render("按Q或者ESC退出游戏, 按其他键重新开始游戏", True, (65, 105, 225))
9 screen.blit(tip, (30, 500))
10 #显示Surface对象上的内容
11 pygame.display.update()
12
13 while True:
14 for event in pygame.event.get():
15 if event.type == pygame.QUIT:
16 terminate()
17 elif event.type == pygame.KEYDOWN:
18 if event.key == pygame.K_ESCAPE or event.key == pygame.K_q:
19 terminate()
20 else:
21 return #结束此函数, 重新开始游戏
2 pygame.quit()
3 sys.exit()
调用入口函数
《Python少儿趣味编程》
李强 李若瑜 著扫码查看详情
编辑推荐
扫码加入码书群
码书群,是一个可以为你推荐书籍的交流群,在这里,你可以和不同技术的人进行交流,不知道选择什么样的技术书籍学习,也可在群里咨询哦,学习或者工作压力比较大,也可以在群里聊些轻松的话题,也可以在群里咨询物流信息~