鱼C论坛

 找回密码
 立即注册
查看: 1822|回复: 6

[已解决]我的贪吃蛇运行没问题,但做成exe就闪退,怎么回事?

[复制链接]
发表于 2020-8-28 19:21:49 | 显示全部楼层 |阅读模式

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

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

x

  1. import random
  2. import pygame
  3. import sys
  4. from pygame.locals import *

  5. Snakespeed = 6
  6. Window_Width = 800
  7. Window_Height = 500
  8. Cell_Size = 20  # Width and height of the cells
  9. # Ensuring that the cells fit perfectly in the window. eg if cell size was
  10. # 10     and window width or windowheight were 15 only 1.5 cells would
  11. # fit.
  12. assert Window_Width % Cell_Size == 0, "Window width must be a multiple of cell size."
  13. # Ensuring that only whole integer number of cells fit perfectly in the window.
  14. assert Window_Height % Cell_Size == 0, "Window height must be a multiple of cell size."
  15. Cell_W = int(Window_Width / Cell_Size)  # Cell Width
  16. Cell_H = int(Window_Height / Cell_Size)  # Cellc Height


  17. White = (255, 255, 255)
  18. Black = (0, 0, 0)
  19. Red = (255, 0, 0)  # Defining element colors for the program.
  20. Green = (0, 255, 0)
  21. DARKGreen = (0, 155, 0)
  22. DARKGRAY = (40, 40, 40)
  23. YELLOW = (255, 255, 0)
  24. Red_DARK = (150, 0, 0)
  25. BLUE = (0, 0, 255)
  26. BLUE_DARK = (0, 0, 150)


  27. BGCOLOR = Black  # Background color


  28. UP = 'up'
  29. DOWN = 'down'      # Defining keyboard keys.
  30. LEFT = 'left'
  31. RIGHT = 'right'

  32. HEAD = 0  # Syntactic sugar: index of the snake's head


  33. def main():
  34.     global SnakespeedCLOCK, DISPLAYSURF, BASICFONT

  35.     pygame.init()
  36.     SnakespeedCLOCK = pygame.time.Clock()
  37.     DISPLAYSURF = pygame.display.set_mode((Window_Width, Window_Height))
  38.     BASICFONT = pygame.font.Font('freesansbold.ttf', 18)
  39.     pygame.display.set_caption('Snake')

  40.     showStartScreen()
  41.     while True:
  42.         runGame()
  43.         showGameOverScreen()


  44. def runGame():
  45.     # Set a random start point.
  46.     startx = random.randint(5, Cell_W - 6)
  47.     starty = random.randint(5, Cell_H - 6)
  48.     wormCoords = [{'x': startx, 'y': starty},
  49.                   {'x': startx - 1, 'y': starty},
  50.                   {'x': startx - 2, 'y': starty}]
  51.     direction = RIGHT

  52.     # Start the apple in a random place.
  53.     apple = getRandomLocation()

  54.     while True:  # main game loop
  55.         for event in pygame.event.get():  # event handling loop
  56.             if event.type == QUIT:
  57.                 terminate()
  58.             elif event.type == KEYDOWN:
  59.                 if (event.key == K_LEFT) and direction != RIGHT:
  60.                     direction = LEFT
  61.                 elif (event.key == K_RIGHT) and direction != LEFT:
  62.                     direction = RIGHT
  63.                 elif (event.key == K_UP) and direction != DOWN:
  64.                     direction = UP
  65.                 elif (event.key == K_DOWN) and direction != UP:
  66.                     direction = DOWN
  67.                 elif event.key == K_ESCAPE:
  68.                     terminate()

  69.         # check if the Snake has hit itself or the edge
  70.         if wormCoords[HEAD]['x'] == -1 or wormCoords[HEAD]['x'] == Cell_W or wormCoords[HEAD]['y'] == -1 or wormCoords[HEAD]['y'] == Cell_H:
  71.             return  # game over
  72.         for wormBody in wormCoords[1:]:
  73.             if wormBody['x'] == wormCoords[HEAD]['x'] and wormBody['y'] == wormCoords[HEAD]['y']:
  74.                 return  # game over

  75.         # check if Snake has eaten an apply
  76.         if wormCoords[HEAD]['x'] == apple['x'] and wormCoords[HEAD]['y'] == apple['y']:
  77.             # don't remove worm's tail segment
  78.             apple = getRandomLocation()  # set a new apple somewhere
  79.         else:
  80.             del wormCoords[-1]  # remove worm's tail segment

  81.         # move the worm by adding a segment in the direction it is moving
  82.         if direction == UP:
  83.             newHead = {'x': wormCoords[HEAD]['x'],
  84.                        'y': wormCoords[HEAD]['y'] - 1}
  85.         elif direction == DOWN:
  86.             newHead = {'x': wormCoords[HEAD]['x'],
  87.                        'y': wormCoords[HEAD]['y'] + 1}
  88.         elif direction == LEFT:
  89.             newHead = {'x': wormCoords[HEAD][
  90.                 'x'] - 1, 'y': wormCoords[HEAD]['y']}
  91.         elif direction == RIGHT:
  92.             newHead = {'x': wormCoords[HEAD][
  93.                 'x'] + 1, 'y': wormCoords[HEAD]['y']}
  94.         wormCoords.insert(0, newHead)
  95.         DISPLAYSURF.fill(BGCOLOR)
  96.         drawGrid()
  97.         drawWorm(wormCoords)
  98.         drawApple(apple)
  99.         drawScore(len(wormCoords) - 3)
  100.         pygame.display.update()
  101.         SnakespeedCLOCK.tick(Snakespeed)


  102. def drawPressKeyMsg():
  103.     pressKeySurf = BASICFONT.render('Press a key to play.', True, White)
  104.     pressKeyRect = pressKeySurf.get_rect()
  105.     pressKeyRect.topleft = (Window_Width - 200, Window_Height - 30)
  106.     DISPLAYSURF.blit(pressKeySurf, pressKeyRect)


  107. def checkForKeyPress():
  108.     if len(pygame.event.get(QUIT)) > 0:
  109.         terminate()
  110.     keyUpEvents = pygame.event.get(KEYUP)
  111.     if len(keyUpEvents) == 0:
  112.         return None
  113.     if keyUpEvents[0].key == K_ESCAPE:
  114.         terminate()
  115.     return keyUpEvents[0].key


  116. def showStartScreen():
  117.     titleFont = pygame.font.Font('freesansbold.ttf', 100)
  118.     titleSurf1 = titleFont.render('Snake!', True, White, DARKGreen)
  119.     degrees1 = 0
  120.     degrees2 = 0
  121.     while True:
  122.         DISPLAYSURF.fill(BGCOLOR)
  123.         rotatedSurf1 = pygame.transform.rotate(titleSurf1, degrees1)
  124.         rotatedRect1 = rotatedSurf1.get_rect()
  125.         rotatedRect1.center = (Window_Width / 2, Window_Height / 2)
  126.         DISPLAYSURF.blit(rotatedSurf1, rotatedRect1)

  127.         drawPressKeyMsg()

  128.         if checkForKeyPress():
  129.             pygame.event.get()  # clear event queue
  130.             return
  131.         pygame.display.update()
  132.         SnakespeedCLOCK.tick(Snakespeed)
  133.         degrees1 += 3  # rotate by 3 degrees each frame
  134.         degrees2 += 7  # rotate by 7 degrees each frame


  135. def terminate():
  136.     pygame.quit()
  137.     sys.exit()


  138. def getRandomLocation():
  139.     return {'x': random.randint(0, Cell_W - 1), 'y': random.randint(0, Cell_H - 1)}


  140. def showGameOverScreen():
  141.     gameOverFont = pygame.font.Font('freesansbold.ttf', 100)
  142.     gameSurf = gameOverFont.render('Game', True, White)
  143.     overSurf = gameOverFont.render('Over', True, White)
  144.     gameRect = gameSurf.get_rect()
  145.     overRect = overSurf.get_rect()
  146.     gameRect.midtop = (Window_Width / 2, 10)
  147.     overRect.midtop = (Window_Width / 2, gameRect.height + 10 + 25)

  148.     DISPLAYSURF.blit(gameSurf, gameRect)
  149.     DISPLAYSURF.blit(overSurf, overRect)
  150.     drawPressKeyMsg()
  151.     pygame.display.update()
  152.     pygame.time.wait(500)
  153.     checkForKeyPress()  # clear out any key presses in the event queue

  154.     while True:
  155.         if checkForKeyPress():
  156.             pygame.event.get()  # clear event queue
  157.             return


  158. def drawScore(score):
  159.     scoreSurf = BASICFONT.render('Score: %s' % (score), True, White)
  160.     scoreRect = scoreSurf.get_rect()
  161.     scoreRect.topleft = (Window_Width - 120, 10)
  162.     DISPLAYSURF.blit(scoreSurf, scoreRect)


  163. def drawWorm(wormCoords):
  164.     for coord in wormCoords:
  165.         x = coord['x'] * Cell_Size
  166.         y = coord['y'] * Cell_Size
  167.         wormSegmentRect = pygame.Rect(x, y, Cell_Size, Cell_Size)
  168.         pygame.draw.rect(DISPLAYSURF, DARKGreen, wormSegmentRect)
  169.         wormInnerSegmentRect = pygame.Rect(
  170.             x + 4, y + 4, Cell_Size - 8, Cell_Size - 8)
  171.         pygame.draw.rect(DISPLAYSURF, Green, wormInnerSegmentRect)


  172. def drawApple(coord):
  173.     x = coord['x'] * Cell_Size
  174.     y = coord['y'] * Cell_Size
  175.     appleRect = pygame.Rect(x, y, Cell_Size, Cell_Size)
  176.     pygame.draw.rect(DISPLAYSURF, Red, appleRect)


  177. def drawGrid():
  178.     for x in range(0, Window_Width, Cell_Size):  # draw vertical lines
  179.         pygame.draw.line(DISPLAYSURF, DARKGRAY, (x, 0), (x, Window_Height))
  180.     for y in range(0, Window_Height, Cell_Size):  # draw horizontal lines
  181.         pygame.draw.line(DISPLAYSURF, DARKGRAY, (0, y), (Window_Width, y))


  182. if __name__ == '__main__':
  183.     try:
  184.         main()
  185.     except SystemExit:


  186.         pass
复制代码
最佳答案
2020-8-28 20:02:09
本帖最后由 sunrise085 于 2020-8-28 20:03 编辑

应该就是楼上所说的这个问题。
我帮你截屏了一下错误界面,就是你说一闪而过的那个界面
搜狗截图20200828195256.png
我看了一下,第50行就是字体的那一行
  1. BASICFONT = pygame.font.Font('freesansbold.ttf', 18)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-8-28 19:45:20 | 显示全部楼层
本帖最后由 疾风怪盗 于 2020-8-28 19:46 编辑

要查看错误提示,而不是窗口一闪而过,可以在地址栏输入cmd,然后运行你的exe文件,就会看到错误提示NotImplementedError: Can’t perform this operation for unregistered loader type
然后度娘一下,https://blog.csdn.net/u010098760/article/details/102966717,发现是字体问题,按照提示更改三处字体
  1. rp(relative_path):
  2.     """ Get absolute path to resource, works for dev and for PyInstaller """
  3.     try:
  4.         # PyInstaller creates a temp folder and stores path in _MEIPASS
  5.         base_path = sys._MEIPASS
  6.     except Exception:
  7.         base_path = os.path.abspath(".")

  8.     return os.path.join(base_path, relative_path)
复制代码
  1. BASICFONT = pygame.font.Font(rp('C:\Windows\Fonts\simsun.ttc'), 18)
  2. titleFont = pygame.font.Font(rp('C:\Windows\Fonts\simsun.ttc'), 100)
  3. gameOverFont = pygame.font.Font(rp('freesansbold.ttf'), 100)
复制代码

上面三个字体分别在你程序的三个地方,在添加那个rp代码后修改一下,要注意第三个,那个字体是不在系统内的,需要下载了放在py文件一起运行,然后再打包就能运行了
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-8-28 19:46:02 | 显示全部楼层
我没做过pygame,就是按照你的代码,打包,找错误提示,度娘解决方案,然后再打包一步一步试出来的
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-8-28 20:02:09 | 显示全部楼层    本楼为最佳答案   
本帖最后由 sunrise085 于 2020-8-28 20:03 编辑

应该就是楼上所说的这个问题。
我帮你截屏了一下错误界面,就是你说一闪而过的那个界面
搜狗截图20200828195256.png
我看了一下,第50行就是字体的那一行
  1. BASICFONT = pygame.font.Font('freesansbold.ttf', 18)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

发表于 2020-8-28 20:35:17 | 显示全部楼层
楼主学了多长时间啊?都会编游戏也太厉害了吧
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-8-31 16:49:57 | 显示全部楼层
枫宇 发表于 2020-8-28 20:35
楼主学了多长时间啊?都会编游戏也太厉害了吧

我就是照别人的,不是自己写的。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-9-5 12:46:03 | 显示全部楼层
那也挺厉害的!
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-6-26 17:49

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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