怎么用Python Pygame实现赛车游戏
发表于:2026-11-03 作者:千家信息网编辑
千家信息网最后更新 2026年11月03日,今天小编给大家分享一下怎么用Python Pygame实现赛车游戏的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获
千家信息网最后更新 2026年11月03日怎么用Python Pygame实现赛车游戏
今天小编给大家分享一下怎么用Python Pygame实现赛车游戏的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。
一、环境安装
1)运行环境
文用到的运行环境:Python3.7、Pycharm社区版2021、Pygame游戏模块部分自带模块直 接导入不需要安装。
模块安装:pip install -i https://pypi.douban.com/simple/ +模块名
2)素材环境
音乐背景图片等:
二、代码展示
import pygame, random, sys ,os,timefrom pygame.locals import * WINDOWWIDTH = 800WINDOWHEIGHT = 600TEXTCOLOR = (255, 255, 255)BACKGROUNDCOLOR = (0, 0, 0)FPS = 40BADDIEMINSIZE = 10BADDIEMAXSIZE = 40BADDIEMINSPEED = 8BADDIEMAXSPEED = 8ADDNEWBADDIERATE = 6PLAYERMOVERATE = 5count=3 def terminate(): pygame.quit() sys.exit() def waitForPlayerToPressKey(): while True: for event in pygame.event.get(): if event.type == QUIT: terminate() if event.type == KEYDOWN: if event.key == K_ESCAPE: #escape quits terminate() return def playerHasHitBaddie(playerRect, baddies): for b in baddies: if playerRect.colliderect(b['rect']): return True return False def drawText(text, font, surface, x, y): textobj = font.render(text, 1, TEXTCOLOR) textrect = textobj.get_rect() textrect.topleft = (x, y) surface.blit(textobj, textrect) # set up pygame, the window, and the mouse cursorpygame.init()mainClock = pygame.time.Clock()windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))pygame.display.set_caption('car 赛车游戏')pygame.mouse.set_visible(False) # fontsfont = pygame.font.SysFont(None, 30) # soundsgameOverSound = pygame.mixer.Sound('music/crash.wav')pygame.mixer.music.load('music/car.wav')laugh = pygame.mixer.Sound('music/laugh.wav') # imagesplayerImage = pygame.image.load('image/car1.png')car3 = pygame.image.load('image/car3.png')car4 = pygame.image.load('image/car4.png')playerRect = playerImage.get_rect()baddieImage = pygame.image.load('image/car2.png')sample = [car3,car4,baddieImage]wallLeft = pygame.image.load('image/left.png')wallRight = pygame.image.load('image/right.png') # "Start" screendrawText('Press any key to start the game.', font, windowSurface, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 3))drawText('And Enjoy', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3)+30)pygame.display.update()waitForPlayerToPressKey()zero=0if not os.path.exists("data/save.dat"): f=open("data/save.dat",'w') f.write(str(zero)) f.close() v=open("data/save.dat",'r')topScore = int(v.readline())v.close()while (count>0): # start of the game baddies = [] score = 0 playerRect.topleft = (WINDOWWIDTH / 2, WINDOWHEIGHT - 50) moveLeft = moveRight = moveUp = moveDown = False reverseCheat = slowCheat = False baddieAddCounter = 0 pygame.mixer.music.play(-1, 0.0) while True: # the game loop score += 1 # increase score for event in pygame.event.get(): if event.type == QUIT: terminate() if event.type == KEYDOWN: if event.key == ord('z'): reverseCheat = True if event.key == ord('x'): slowCheat = True if event.key == K_LEFT or event.key == ord('a'): moveRight = False moveLeft = True if event.key == K_RIGHT or event.key == ord('d'): moveLeft = False moveRight = True if event.key == K_UP or event.key == ord('w'): moveDown = False moveUp = True if event.key == K_DOWN or event.key == ord('s'): moveUp = False moveDown = True if event.type == KEYUP: if event.key == ord('z'): reverseCheat = False score = 0 if event.key == ord('x'): slowCheat = False score = 0 if event.key == K_ESCAPE: terminate() if event.key == K_LEFT or event.key == ord('a'): moveLeft = False if event.key == K_RIGHT or event.key == ord('d'): moveRight = False if event.key == K_UP or event.key == ord('w'): moveUp = False if event.key == K_DOWN or event.key == ord('s'): moveDown = False # Add new baddies at the top of the screen if not reverseCheat and not slowCheat: baddieAddCounter += 1 if baddieAddCounter == ADDNEWBADDIERATE: baddieAddCounter = 0 baddieSize =30 newBaddie = {'rect': pygame.Rect(random.randint(140, 485), 0 - baddieSize, 23, 47), 'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED), 'surface':pygame.transform.scale(random.choice(sample), (23, 47)), } baddies.append(newBaddie) sideLeft= {'rect': pygame.Rect(0,0,126,600), 'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED), 'surface':pygame.transform.scale(wallLeft, (126, 599)), } baddies.append(sideLeft) sideRight= {'rect': pygame.Rect(497,0,303,600), 'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED), 'surface':pygame.transform.scale(wallRight, (303, 599)), } baddies.append(sideRight) # Move the player around. if moveLeft and playerRect.left > 0: playerRect.move_ip(-1 * PLAYERMOVERATE, 0) if moveRight and playerRect.right < WINDOWWIDTH: playerRect.move_ip(PLAYERMOVERATE, 0) if moveUp and playerRect.top > 0: playerRect.move_ip(0, -1 * PLAYERMOVERATE) if moveDown and playerRect.bottom < WINDOWHEIGHT: playerRect.move_ip(0, PLAYERMOVERATE) for b in baddies: if not reverseCheat and not slowCheat: b['rect'].move_ip(0, b['speed']) elif reverseCheat: b['rect'].move_ip(0, -5) elif slowCheat: b['rect'].move_ip(0, 1) for b in baddies[:]: if b['rect'].top > WINDOWHEIGHT: baddies.remove(b) # Draw the game world on the window. windowSurface.fill(BACKGROUNDCOLOR) # Draw the score and top score. drawText('Score: %s' % (score), font, windowSurface, 128, 0) drawText('Top Score: %s' % (topScore), font, windowSurface,128, 20) drawText('Rest Life: %s' % (count), font, windowSurface,128, 40) windowSurface.blit(playerImage, playerRect) for b in baddies: windowSurface.blit(b['surface'], b['rect']) pygame.display.update() # Check if any of the car have hit the player. if playerHasHitBaddie(playerRect, baddies): if score > topScore: g=open("data/save.dat",'w') g.write(str(score)) g.close() topScore = score break mainClock.tick(FPS) # "Game Over" screen. pygame.mixer.music.stop() count=count-1 gameOverSound.play() time.sleep(1) if (count==0): laugh.play() drawText('Game over', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3)) drawText('Press any key to play again.', font, windowSurface, (WINDOWWIDTH / 3) - 80, (WINDOWHEIGHT / 3) + 30) pygame.display.update() time.sleep(2) waitForPlayerToPressKey() count=3 gameOverSound.stop()三、效果展示
每个赛车游戏生命值三条消耗完即游戏结束。躲避相应的车子会加分。方向键左右即是移动键。
游戏开始——
游戏界面——
游戏结束——
以上就是"怎么用Python Pygame实现赛车游戏"这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注行业资讯频道。
赛车
模块
环境
知识
篇文章
内容
运行
不同
很大
代码
图片
大部分
就是
效果
方向
更多
游戏界面
生命
界面
知识点
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
山东特亿宝互联网科技有限公司
科技与互联网
合肥互联网科技公司
科技互联网公司logo
赫美联合互联网科技
镁科技互联网资讯平台
成都仁贤领冠互联网科技有限公司
老年人脱离互联网科技的作文
互联网科技博主是什么意思
栖莱科技互联网股份有限公司
恒生互联网科技指数跳水
互联网科技扶贫时间
亳州好赞互联网科技有限公司
互联网科技人工智能实验室
群盈汇互联网科技有限公司
山东有哪些互联网科技公司
元气玛特互联网科技公司是外包吗
广东工业互联网大赛深圳学泰科技
互联网科技接地气
互联网科技平台产品运营
天津市摩尔互联网科技
北京路客互联网科技有限公司
上海致骋互联网科技
广州紫鲸互联网科技
伍佰万互联网科技怎么赚钱
皮皮虾互联网科技有限公司
风投北京互联网科技
广东鹅鹅鹅互联网科技有限公司
亚光科技低轨卫星互联网
知域互联网科技有限公司官网