python 贪吃蛇小游戏代码

x33g5p2x  于2021-12-06 转载在 Python  
字(5.6k)|赞(0)|评价(0)|浏览(398)
  1. #!/usr/bin/python import randomimport pygameimport sysfrom pygame.locals import * Snakespeed = 17Window_Width = 800Window_Height = 500Cell_Size = 20
  2. # Width and height of the cells
  3. # Ensuring that the cells fit perfectly in the window. eg if cell size was
  4. # 10 and window width or windowheight were 15 only 1.5 cells would# fit.assert Window_Width % Cell_Size == 0, "Window width must be a multiple of cell size."
  5. # Ensuring that only whole integer number of cells fit perfectly in the window.assert Window_Height % Cell_Size == 0, "Window height must be a multiple of cell size."Cell_W = int(Window_Width / Cell_Size)
  6. # Cell WidthCell_H = int(Window_Height / Cell_Size)
  7. # Cellc Height White = (255, 255, 255)
  8. Black = (0, 0, 0)
  9. Red = (255, 0, 0)
  10. # Defining element colors for the program.Green = (0, 255, 0)
  11. DARKGreen = (0, 155, 0)
  12. DARKGRAY = (40, 40, 40)
  13. YELLOW = (255, 255, 0)
  14. Red_DARK = (150, 0, 0)
  15. BLUE = (0, 0, 255)
  16. BLUE_DARK = (0, 0, 150)
  17. BGCOLOR = Black
  18. # Background color UP = 'up'DOWN = 'down'
  19. # Defining keyboard keys.LEFT = 'left'RIGHT = 'right' HEAD = 0
  20. # Syntactic sugar: index of the snake's head def main():
  21. global SnakespeedCLOCK, DISPLAYSURF, BASICFONT
  22. pygame.init()
  23. SnakespeedCLOCK = pygame.time.Clock()
  24. DISPLAYSURF = pygame.display.set_mode((Window_Width, Window_Height))
  25. BASICFONT = pygame.font.Font('freesansbold.ttf', 18)
  26. pygame.display.set_caption('Snake')
  27. showStartScreen()
  28. while True:
  29. runGame()
  30. showGameOverScreen() def runGame():
  31. # Set a random start point.
  32. startx = random.randint(5, Cell_W - 6)
  33. starty = random.randint(5, Cell_H - 6)
  34. wormCoords = [{'x': startx, 'y': starty},
  35. {'x': startx - 1, 'y': starty},
  36. {'x': startx - 2, 'y': starty}]
  37. direction = RIGHT
  38. # Start the apple in a random place.
  39. apple = getRandomLocation()
  40. while True: # main game loop
  41. for event in pygame.event.get():
  42. # event handling loop
  43. if event.type == QUIT:
  44. terminate()
  45. elif event.type == KEYDOWN:
  46. if (event.key == K_LEFT) and direction != RIGHT:
  47. direction = LEFT
  48. elif (event.key == K_RIGHT) and direction != LEFT:
  49. direction = RIGHT
  50. elif (event.key == K_UP) and direction != DOWN:
  51. direction = UP
  52. elif (event.key == K_DOWN) and direction != UP:
  53. direction = DOWN
  54. elif event.key == K_ESCAPE:
  55. terminate()
  56. # check if the Snake has hit itself or the edge
  57. if wormCoords[HEAD]['x'] == -1 or wormCoords[HEAD]['x'] == Cell_W or wormCoords[HEAD]['y'] == -1 or wormCoords[HEAD]['y'] == Cell_H:
  58. return
  59. # game over
  60. for wormBody in wormCoords[1:]:
  61. if wormBody['x'] == wormCoords[HEAD]['x'] and wormBody['y'] == wormCoords[HEAD]['y']:
  62. return # game over
  63. # check if Snake has eaten an apply
  64. if wormCoords[HEAD]['x'] == apple['x'] and wormCoords[HEAD]['y'] == apple['y']:
  65. # don't remove worm's tail segment
  66. apple = getRandomLocation()
  67. # set a new apple somewhere
  68. else:
  69. del wormCoords[-1]
  70. # remove worm's tail segment
  71. # move the worm by adding a segment in the direction it is moving
  72. if direction == UP:
  73. newHead = {'x': wormCoords[HEAD]['x'],
  74. 'y': wormCoords[HEAD]['y'] - 1}
  75. elif direction == DOWN:
  76. newHead = {'x': wormCoords[HEAD]['x'],
  77. 'y': wormCoords[HEAD]['y'] + 1}
  78. elif direction == LEFT:
  79. newHead = {'x': wormCoords[HEAD][ 'x'] - 1, 'y': wormCoords[HEAD]['y']}
  80. elif direction == RIGHT:
  81. newHead = {'x': wormCoords[HEAD][ 'x'] + 1, 'y': wormCoords[HEAD]['y']}
  82. wormCoords.insert(0, newHead)
  83. DISPLAYSURF.fill(BGCOLOR)
  84. drawGrid()
  85. drawWorm(wormCoords)
  86. drawApple(apple)
  87. drawScore(len(wormCoords) - 3)
  88. pygame.display.update()
  89. SnakespeedCLOCK.tick(Snakespeed)
  90. def drawPressKeyMsg():
  91. pressKeySurf = BASICFONT.render('Press a key to play.', True, White)
  92. pressKeyRect = pressKeySurf.get_rect()
  93. pressKeyRect.topleft = (Window_Width - 200, Window_Height - 30)
  94. DISPLAYSURF.blit(pressKeySurf, pressKeyRect)
  95. def checkForKeyPress():
  96. if len(pygame.event.get(QUIT)) > 0:
  97. terminate()
  98. keyUpEvents = pygame.event.get(KEYUP)
  99. if len(keyUpEvents) == 0:
  100. return None
  101. if keyUpEvents[0].key == K_ESCAPE:
  102. terminate()
  103. return keyUpEvents[0].key def showStartScreen():
  104. titleFont = pygame.font.Font('freesansbold.ttf', 100)
  105. titleSurf1 = titleFont.render('Snake!', True, White, DARKGreen)
  106. degrees1 = 0
  107. degrees2 = 0 while True:
  108. DISPLAYSURF.fill(BGCOLOR)
  109. rotatedSurf1 = pygame.transform.rotate(titleSurf1, degrees1)
  110. rotatedRect1 = rotatedSurf1.get_rect()
  111. rotatedRect1.center = (Window_Width / 2, Window_Height / 2)
  112. DISPLAYSURF.blit(rotatedSurf1, rotatedRect1)
  113. drawPressKeyMsg()
  114. if checkForKeyPress():
  115. pygame.event.get()
  116. # clear event queue
  117. return
  118. pygame.display.update()
  119. SnakespeedCLOCK.tick(Snakespeed)
  120. degrees1 += 3
  121. # rotate by 3 degrees each frame
  122. degrees2 += 7
  123. # rotate by 7 degrees each frame def terminate():
  124. pygame.quit()
  125. sys.exit() def getRandomLocation():
  126. return {'x': random.randint(0, Cell_W - 1), 'y': random.randint(0, Cell_H - 1)}
  127. def showGameOverScreen():
  128. gameOverFont = pygame.font.Font('freesansbold.ttf', 100)
  129. gameSurf = gameOverFont.render('Game', True, White)
  130. overSurf = gameOverFont.render('Over', True, White)
  131. gameRect = gameSurf.get_rect() overRect = overSurf.get_rect()
  132. gameRect.midtop = (Window_Width / 2, 10)
  133. overRect.midtop = (Window_Width / 2, gameRect.height + 10 + 25)
  134. DISPLAYSURF.blit(gameSurf, gameRect)
  135. DISPLAYSURF.blit(overSurf, overRect)
  136. drawPressKeyMsg()
  137. pygame.display.update()
  138. pygame.time.wait(500)
  139. checkForKeyPress()
  140. # clear out any key presses in the event queue
  141. while True:
  142. if checkForKeyPress():
  143. pygame.event.get()
  144. # clear event queue
  145. return def drawScore(score):
  146. scoreSurf = BASICFONT.render('Score: %s' % (score), True, White)
  147. scoreRect = scoreSurf.get_rect()
  148. scoreRect.topleft = (Window_Width - 120, 10)
  149. DISPLAYSURF.blit(scoreSurf, scoreRect)
  150. def drawWorm(wormCoords):
  151. for coord in wormCoords:
  152. x = coord['x'] * Cell_Size
  153. y = coord['y'] * Cell_Size
  154. wormSegmentRect = pygame.Rect(x, y, Cell_Size, Cell_Size)
  155. pygame.draw.rect(DISPLAYSURF, DARKGreen, wormSegmentRect)
  156. wormInnerSegmentRect = pygame.Rect( x + 4, y + 4, Cell_Size - 8, Cell_Size - 8)
  157. pygame.draw.rect(DISPLAYSURF, Green, wormInnerSegmentRect)
  158. def drawApple(coord):
  159. x = coord['x'] * Cell_Size
  160. y = coord['y'] * Cell_Size
  161. appleRect = pygame.Rect(x, y, Cell_Size, Cell_Size)
  162. pygame.draw.rect(DISPLAYSURF, Red, appleRect)
  163. def drawGrid():
  164. for x in range(0, Window_Width, Cell_Size):
  165. # draw vertical lines
  166. pygame.draw.line(DISPLAYSURF, DARKGRAY, (x, 0), (x, Window_Height))
  167. for y in range(0, Window_Height, Cell_Size):
  168. # draw horizontal lines
  169. pygame.draw.line(DISPLAYSURF, DARKGRAY, (0, y),
  170. (Window_Width, y)) if __name__ == '__main__': try:
  171. main()
  172. except SystemExit:
  173. pass

start

game over

相关文章