Python编写的贪吃蛇游戏含完整源代码源程序
程序运行截图:
1 import pygame as pg 2 3 from random import randint 4 5 import sys 6 7 from pygame.locals import * 8 9 10 11 FPS = 6 # 画面帧数,代表蛇的移动速率 12 13 window_width = 600 14 15 window_height = 500 16 17 cellsize = 20 18 19 cell_width = int(window_width / cellsize) 20 21 cell_height = int(window_height / cellsize) 22 23 BGcolor = (0, 0, 0) 24 25 BLUE = (0, 0, 255) 26 27 RED = (255, 0, 0) 28 29 apple_color = (255, 0, 0) 30 31 snake_color = (0, 150, 0) 32 33 GREEN = (0, 255, 0) 34 35 WHITE = (255, 255, 255) 36 37 DARKGRAY = (40, 40, 40) 38 39 40 41 UP = "up" 42 43 DOWN = "down" 44 45 LEFT = "left" 46 47 RIGHT = "right" 48 49 HEAD = 0 50 51 52 53 54 55 def main(): # 有函数 56 57 global FPSclock, window, BASICFONT 58 59 pg.init() 60 61 FPSclock = pg.time.Clock() 62 63 window = pg.display.set_mode((window_width, window_height)) 64 65 BASICFONT = pg.font.Font("freesansbold.ttf", 18) 66 67 pg.display.set_caption("贪吃蛇") 68 69 showStartScreen() 70 71 while True: 72 73 runGame() 74 75 showGameOverScreen() 76 77 78 79 80 81 def runGame(): # 运行游戏函数 82 83 startx = randint(5, cell_width - 6) 84 85 starty = randint(5, cell_height - 6) 86 87 snakeCoords = [{"x": startx, "y": starty}, {"x": startx - 1, "y": starty}, {"x": startx - 2, "y": starty}] 88 89 direction = RIGHT 90 91 apple = getRandomLocation() 92 93 while True: 94 95 for event in pg.event.get(): 96 97 if event.type == QUIT: 98 99 terminate() 100 101 elif event.type == KEYDOWN: 102 103 if event.key == K_LEFT and direction != RIGHT: 104 105 direction = LEFT 106 107 elif event.key == K_RIGHT and direction != LEFT: 108 109 direction = RIGHT 110 111 elif event.key == K_UP and direction != DOWN: 112 113 direction = UP 114 115 elif event.key == K_DOWN and direction != UP: 116 117 direction = DOWN 118 119 elif event.key == K_ESCAPE: 120 121 terminate() 122 123 if snakeCoords[HEAD]["x"] == -1 or snakeCoords[HEAD]["x"] == cell_width or snakeCoords[HEAD]["y"] == -1 or \ 124 125 snakeCoords[HEAD]["y"] == cell_height: 126 127 return 128 129 for snakeBody in snakeCoords[1:]: 130 131 if snakeBody["x"] == snakeCoords[HEAD]["x"] and snakeBody["y"] == snakeCoords[HEAD]["y"]: 132 133 return 134 135 if snakeCoords[HEAD]["x"] == apple["x"] and snakeCoords[HEAD]["y"] == apple["y"]: 136 137 apple = getRandomLocation() 138 139 else: 140 141 del snakeCoords[-1] 142 143 if direction == UP: 144 145 newHead = {"x": snakeCoords[HEAD]["x"], "y": snakeCoords[HEAD]["y"] - 1} 146 147 elif direction == DOWN: 148 149 newHead = {"x": snakeCoords[HEAD]["x"], "y": snakeCoords[HEAD]["y"] + 1} 150 151 elif direction == LEFT: 152 153 newHead = {"x": snakeCoords[HEAD]["x"] - 1, "y": snakeCoords[HEAD]["y"]} 154 155 elif direction == RIGHT: 156 157 newHead = {"x": snakeCoords[HEAD]["x"] + 1, "y": snakeCoords[HEAD]["y"]} 158 159 160 161 snakeCoords.insert(0, newHead) 162 163 window.fill(BGcolor) 164 165 drawGrid() 166 167 drawSnake(snakeCoords) 168 169 drawApple(apple) 170 171 172 173 drawScore(len(snakeCoords) - 3) 174 175 176 177 pg.display.update() 178 179 FPSclock.tick(FPS) 180 181 182 183 184 185 def drawPressKeyMsg(): # 游戏开始提示信息 186 187 pressKeySurf = BASICFONT.render("press a key to play", True, BLUE) 188 189 pressKeyRect = pressKeySurf.get_rect() 190 191 pressKeyRect.topleft = (window_width - 200, window_height - 30) 192 193 window.blit(pressKeySurf, pressKeyRect) 194 195 196 197 198 199 def checkForKeyPress(): # 检查是否触发按键 200 201 if len(pg.event.get(QUIT)) > 0: 202 203 terminate() 204 205 keyUpEvents = pg.event.get(KEYUP) 206 207 if len(keyUpEvents) == 0: 208 209 return None 210 211 if keyUpEvents[0].key == K_ESCAPE: 212 213 terminate() 214 215 return keyUpEvents[0].key 216 217 218 219 220 221 def showStartScreen(): # 开始画面 222 223 window.fill(BGcolor) 224 225 titleFont = pg.font.Font("freesansbold.ttf", 100) 226 227 titleSurf = titleFont.render("snake!", True, RED) 228 229 titleRect = titleSurf.get_rect() 230 231 titleRect.center = (window_width / 2, window_height / 2) 232 233 window.blit(titleSurf, titleRect) 234 235 drawPressKeyMsg() 236 237 pg.display.update() 238 239 while True: 240 241 if checkForKeyPress(): 242 243 pg.event.get() 244 245 return 246 247 248 249 250 251 def terminate(): # 退出 252 253 pg.quit() 254 255 sys.exit() 256 257 258 259 260 261 def getRandomLocation(): # 出现位置 262 263 return {"x": randint(0, cell_width - 1), "y": randint(0, cell_height - 1)} 264 265 266 267 268 269 def showGameOverScreen(): # 游戏结束 270 271 gameOverFont = pg.font.Font("freesansbold.tff", 150) 272 273 gameSurf = gameOverFont.render("Game", True, WHITE) 274 275 overSurf = gameOverFont.render("over", True, WHITE) 276 277 gameRect = gameSurf.get_rect() 278 279 overRect = overSurf.get_rect() 280 281 gameRect.midtop = (window_width / 2, 10) 282 283 overRect.midtop = (window_width / 2, gameRect.height10 + 25) 284 285 window.blit(gameSurf, gameRect) 286 287 window.blit(overSurf, overRect) 288 289 290 291 drawPressKeyMsg() 292 293 pg.display.update() 294 295 pg.time.wait(500) 296 297 checkForKeyPress() 298 299 while True: 300 301 if checkForKeyPress(): 302 303 pg.event.get() 304 305 return 306 307 308 309 310 311 def drawScore(score): # 显示分数 312 313 scoreSurf = BASICFONT.render("Score:%s" % (score), True, WHITE) 314 315 scoreRect = scoreSurf.get_rect() 316 317 scoreRect.topleft = (window_width - 120, 10) 318 319 window.blit(scoreSurf, scoreRect) 320 321 322 323 324 325 def drawSnake(snakeCoords): # 画蛇 326 327 for coord in snakeCoords: 328 329 x = coord["x"] * cellsize 330 331 y = coord["y"] * cellsize 332 333 snakeSegmentRect = pg.Rect(x, y, cellsize, cellsize) 334 335 pg.draw.rect(window, snake_color, snakeSegmentRect) 336 337 snakeInnerSegmentRect = pg.Rect(x + 4, y + 4, cellsize - 8, cellsize - 8) 338 339 pg.draw.rect(window, GREEN, snakeInnerSegmentRect) 340 341 342 343 344 345 def drawApple(coord): 346 347 x = coord["x"] * cellsize 348 349 y = coord["y"] * cellsize 350 351 appleRect = pg.Rect(x, y, cellsize, cellsize) 352 353 pg.draw.rect(window, apple_color, appleRect) 354 355 356 357 358 359 def drawGrid(): # 画方格 360 361 for x in range(0, window_width, cellsize): 362 363 pg.draw.line(window, DARKGRAY, (x, 0), (x, window_height)) 364 365 for y in range(0, window_height, cellsize): 366 367 pg.draw.line(window, DARKGRAY, (0, y), (window_width, y)) 368 369 370 371 372 373 if __name__ == "__main__": 374 375 main()
更多Python小游戏源代码,请微信关注:Python代码大全