脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python Pygame实战之赛车游戏的实现

Python Pygame实战之赛车游戏的实现

2022-10-21 11:21顾木子吖 Python

如今的游戏可谓是层出不穷,不过小编发现,赛车游戏也是深受大家欢迎啊,像跑跑卡丁车、QQ飞车,还有主机游戏极品飞车系列。本文将用Python中的Pygame模块制作一个简单的赛车游戏,感兴趣的可以了解一下

导语

小伙伴们大家好~

如今的游戏可谓是层出不穷,NBA 2K系列啊,FIFA系列啊更是经典中的经典,不过小编发现,赛车游戏也是深受大家欢迎啊,像跑跑卡丁车、QQ飞车,还有主机游戏极品飞车系列。

咳咳咳......小编那时候主要是最喜欢里面的人物颜值来的!

赛车游戏,通常以款式多样的车型、各式各样的赛道、身临其境的拟真度吸引了众多玩家,而玩家在游戏中需要驾驶各类赛车驰骋在世界各地的赛道上,享受肾上腺素飙升的快感。

那么接下来就给小编大家用代码编写一款《赛车CAR》小游戏吧,让我们一起来看看

一、环境安装

1)运行环境

文用到的运行环境:Python3.7、Pycharm社区版2021、Pygame游戏模块部分自带模块直 接导入不需要安装。

模块安装:pip install -i https://pypi.douban.com/simple/ +模块名

 

2)素材环境

音乐背景图片等:

Python Pygame实战之赛车游戏的实现

 

二、代码展示

​
import pygame, random, sys ,os,time
from pygame.locals import *
 
WINDOWWIDTH = 800
WINDOWHEIGHT = 600
TEXTCOLOR = (255, 255, 255)
BACKGROUNDCOLOR = (0, 0, 0)
FPS = 40
BADDIEMINSIZE = 10
BADDIEMAXSIZE = 40
BADDIEMINSPEED = 8
BADDIEMAXSPEED = 8
ADDNEWBADDIERATE = 6
PLAYERMOVERATE = 5
count=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 cursor
pygame.init()
mainClock = pygame.time.Clock()
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption("car 赛车游戏")
pygame.mouse.set_visible(False)
 
# fonts
font = pygame.font.SysFont(None, 30)
 
# sounds
gameOverSound = pygame.mixer.Sound("music/crash.wav")
pygame.mixer.music.load("music/car.wav")
laugh = pygame.mixer.Sound("music/laugh.wav")
 
 
# images
playerImage = 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" screen
drawText("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=0
if 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实战之赛车游戏的实现

 

游戏界面——

Python Pygame实战之赛车游戏的实现

 

游戏结束——

Python Pygame实战之赛车游戏的实现

到此这篇关于Python Pygame实战之赛车游戏的实现的文章就介绍到这了,更多相关Python Pygame赛车游戏内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文地址:https://blog.csdn.net/weixin_55822277/article/details/123002193

延伸 · 阅读

精彩推荐
  • PythonAppium+Python自动化测试之运行App程序示例

    Appium+Python自动化测试之运行App程序示例

    这篇文章主要介绍了Appium+Python自动化测试之运行App程序示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    zh17557880910642021-05-21
  • Pythonpython通过opencv实现图片裁剪原理解析

    python通过opencv实现图片裁剪原理解析

    这篇文章主要介绍了python通过opencv实现图片裁剪原理解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友...

    天子骄龙3932020-04-14
  • PythonPython基础详解之邮件处理

    Python基础详解之邮件处理

    这篇文章主要介绍了Python基础详解之邮件处理,文中有非常详细的代码示例,对正在学习python基础的小伙伴们有非常好的帮助,需要的朋友可以参考下...

    拿头来坚持9252021-10-22
  • Pythonpython实现栅栏加解密 支持密钥加密

    python实现栅栏加解密 支持密钥加密

    这篇文章主要为大家详细介绍了python实现栅栏加解密,支持密钥加密,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    OshynSong5182021-06-07
  • Python实现用python算法计算圆周率的小诀窍

    实现用python算法计算圆周率的小诀窍

    什么!你不会背圆周率(鄙夷的眼神) 3.1415926535 8979323846 26433... 但是,我会算啊,本文用一个简单的python代码,教你计算圆周率...

    不吃西红柿丶6092021-12-27
  • PythonPython如何生成随机高斯模糊图片详解

    Python如何生成随机高斯模糊图片详解

    这篇文章主要给大家介绍了关于高斯模糊的原理以及python实现的相关资料,Python使用opencv库生成模糊图像还是很方便的,需要的朋友可以参考下...

    Cloudox_8532021-11-05
  • PythonPython实现删除列表中满足一定条件的元素示例

    Python实现删除列表中满足一定条件的元素示例

    这篇文章主要介绍了Python实现删除列表中满足一定条件的元素,结合具体实例形式对比分析了Python针对列表元素的遍历、复制、删除等相关操作技巧,需要的...

    JoeBlackzqq3362020-11-17
  • PythonPython 设计模式行为型解释器模式

    Python 设计模式行为型解释器模式

    本文介绍了Python解释器模式,解释器模式即Interpreter Pattern,给定一个语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语...

    范桂飓4672022-09-29