鱼C论坛

 找回密码
 立即注册
查看: 2616|回复: 5

[作品展示] 【python作业】贪吃蛇-pygame

[复制链接]
发表于 2020-2-22 14:50:15 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 gascd 于 2020-2-22 14:51 编辑

github项目地址

  1. import sys
  2. import pygame
  3. import random

  4. WindowSize = ( 720, 480 )
  5. fontSize = 20
  6. cellSize = 16
  7. mpSize = int(WindowSize[0]/cellSize), int(WindowSize[1]/cellSize)
  8. #蛇的速度
  9. snakeSpeed = 10

  10. #颜色定义
  11. colorBlack = ( 0, 0, 0)
  12. colorRed = ( 255, 0, 0)
  13. colorGreen = ( 0, 255, 0)
  14. colorBlue = ( 0, 0, 255)
  15. colorDarkBlue = ( 0, 0, 120)

  16. #方向定义
  17. left = 0
  18. down = 1
  19. up = 2
  20. right = 3

  21. #入口函数
  22. def main():
  23.     pygame.init()
  24.     screen = pygame.display.set_mode(WindowSize)
  25.     pygame.display.set_caption("贪吃蛇小游戏~~")
  26.     snakeClock = pygame.time.Clock()
  27.     imgGameStart = pygame.image.load('./img/gameStart.jpg')

  28.     while 1:
  29.         showGameStartInfo(screen, imgGameStart)
  30.         gameRunning(screen, snakeClock)
  31.         
  32. #展示游戏开始信息
  33. def showGameStartInfo(screen, imgGameStart):
  34.     font = pygame.font.Font("./font/msyh.ttc", fontSize)
  35.     screen.blit(imgGameStart, (0,0))
  36.     fontBuffer = font.render("按任意键开始游戏", True, colorRed)
  37.     screen.blit(fontBuffer, (250, 300))
  38.     fontBuffer = font.render("按q或ESC结束游戏", True, colorRed)
  39.     screen.blit(fontBuffer, (250, 300 + fontSize))      
  40.     pygame.display.update()

  41.     while True:
  42.         for event in pygame.event.get():
  43.             justiceGameOver(event)
  44.             if event.type == pygame.KEYDOWN:
  45.                 return
  46.       
  47. #退出游戏
  48. def terminate():
  49.     pygame.quit()
  50.     sys.exit()   

  51. #展示游戏结束信息
  52. def showGameOverInfo(screen, imgGameEnd, score):
  53.     font = pygame.font.Font("./font/msyh.ttc", fontSize)
  54.     screen.blit(imgGameEnd, (0,0))
  55.     fontBuffer = font.render("你的得分是%s" % score, True, colorRed)
  56.     screen.blit(fontBuffer, (250, 300 - fontSize))
  57.     fontBuffer = font.render("按r重新开始游戏", True, colorRed)
  58.     screen.blit(fontBuffer, (250, 300))
  59.     fontBuffer = font.render("按q或ESC结束游戏", True, colorRed)
  60.     screen.blit(fontBuffer, (250, 300 + fontSize))      
  61.     pygame.display.update()
  62.     while True:
  63.         for event in pygame.event.get():
  64.             justiceGameOver(event)
  65.             if event.type == pygame.KEYDOWN:
  66.                 if event.key == pygame.K_r:
  67.                     return

  68. #游戏运行主体
  69. def gameRunning(screen, snakeClock):
  70.     startxy = [random.randint(5, mpSize[0]-5), random.randint(5, mpSize[1]-5)]
  71.     snake = [
  72.         {'x':startxy[0], 'y':startxy[1]},
  73.         {'x':startxy[0]-1, 'y':startxy[1]},
  74.         {'x':startxy[0]-2, 'y':startxy[1]}
  75.     ]
  76.     direction = right
  77.     score = 0
  78.     food = CreateFood(screen)

  79.     while True:
  80.         if food not in snake:
  81.             del snake[-1]
  82.         else:
  83.             score += 1
  84.             food = CreateFood(screen)
  85.         for event in pygame.event.get():
  86.             justiceGameOver(event)
  87.             direction = justiceSnakeTurn(event, direction)
  88.         snakeMove(direction, snake)
  89.         if not isSnakeAlive(snake):
  90.             imgGameEnd = pygame.image.load('./img/gameEnd.jpg')
  91.             showGameOverInfo(screen, imgGameEnd, score)
  92.             return
  93.         screen.fill(colorBlack)
  94.         DrawFood(screen, food)
  95.         DrawSnake(screen, snake)
  96.         DrawScore(screen, score)
  97.         pygame.display.update()
  98.         
  99.         snakeClock.tick(snakeSpeed)

  100. #判断蛇是否活着 超出边界 吃到自己就是死
  101. def isSnakeAlive(snake):
  102.     if snake[0]['x'] == -1 or snake[0]['x'] == mpSize[0] or snake[0]['y'] == -1 or snake[0]['y'] == mpSize[1]:
  103.         return False
  104.     elif snake[0] in snake[1:]:
  105.         return False
  106.     return True

  107. #蛇移动
  108. def snakeMove(direction, snake):
  109.     if direction == left:
  110.         tmp = {'x':snake[0]['x']-1, 'y':snake[0]['y']}
  111.     elif direction == down:
  112.         tmp = {'x':snake[0]['x'], 'y':snake[0]['y']+1}
  113.     elif direction == up:
  114.         tmp = {'x':snake[0]['x'], 'y':snake[0]['y']-1}
  115.     elif direction == right:
  116.         tmp = {'x':snake[0]['x']+1, 'y':snake[0]['y']}

  117.     snake = snake.insert(0, tmp)
  118. #画出蛇
  119. def DrawSnake(screen, snake):
  120.     for i in snake:
  121.         x = i['x'] * cellSize
  122.         y = i['y'] * cellSize
  123.         tmp = (x, y, cellSize, cellSize)
  124.         pygame.draw.rect(screen, colorDarkBlue, tmp)
  125.         tmp = (x+3, y+3, cellSize-6, cellSize-6)
  126.         pygame.draw.rect(screen, colorBlue, tmp)


  127. #创造食物
  128. def CreateFood(screen):
  129.     xy = {'x':random.randint(0, mpSize[0]-1), 'y':random.randint(0, mpSize[1]-1)}
  130.     return xy
  131. #画出食物
  132. def DrawFood(screen, xy):
  133.     x = xy['x'] * cellSize
  134.     y = xy['y'] * cellSize
  135.     appleRect = (x, y, cellSize, cellSize)
  136.     pygame.draw.rect(screen, colorGreen, appleRect)
  137. #画出分数
  138. def DrawScore(screen, score):
  139.     font = pygame.font.Font("./font/msyh.ttc", fontSize)
  140.     fontBuffer = font.render("得分:%s" % score, True, colorRed)
  141.     screen.blit(fontBuffer, (600 ,0))

  142. #判断蛇转弯的方向
  143. def justiceSnakeTurn(event, direction):
  144.     if event.type == pygame.KEYDOWN:
  145.         if event.key in (pygame.K_LEFT, pygame.K_a) and direction != right:
  146.             direction = left
  147.         elif event.key in  (pygame.K_RIGHT, pygame.K_d) and direction != left:
  148.             direction = right
  149.         elif event.key in (pygame.K_UP, pygame.K_w) and direction != down:
  150.             direction = up
  151.         elif event.key in (pygame.K_DOWN, pygame.K_s) and direction != up:
  152.             direction = down

  153.     return direction

  154. #判断游戏是否应该结束
  155. def justiceGameOver(event):
  156.     if event.type == pygame.QUIT:
  157.         terminate()
  158.     elif event.type == pygame.KEYDOWN:
  159.         if event.key == pygame.K_q or event.key == pygame.K_ESCAPE:
  160.             terminate()
  161.         

  162. main()
复制代码

游戏中截图

游戏中截图

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-2-22 15:00:13 | 显示全部楼层
厉害
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-4-13 10:17:41 | 显示全部楼层
这么好的贴竟然沉了!
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-4-13 15:44:33 | 显示全部楼层
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-4-14 00:46:46 | 显示全部楼层
F:\Python\python.exe "F:/Program Files/untitled/3.py"
pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
  File "F:/Program Files/untitled/3.py", line 195, in <module>
    main()
  File "F:/Program Files/untitled/3.py", line 32, in main
    imgGameStart = pygame.image.load('./img/gameStart.jpg')
pygame.error: Couldn't open ./img/gameStart.jpg
这是什么错误啊
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-4-19 17:29:05 | 显示全部楼层
17851305596 发表于 2020-4-14 00:46
F:\Python\python.exe "F:/Program Files/untitled/3.py"
pygame 1.9.6
Hello from the pygame community ...

这个是无法打开那个图片。
因为我没有写异常处理,所以他会直接报错。
你去github里吧源码整个都下载下就可以了。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-30 14:19

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表