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