最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python Pygame實戰(zhàn)之賽車游戲的實現(xiàn)

 更新時間:2022年03月04日 08:31:46   作者:顧木子吖  
如今的游戲可謂是層出不窮,不過小編發(fā)現(xiàn),賽車游戲也是深受大家歡迎啊,像跑跑卡丁車、QQ飛車,還有主機游戲極品飛車系列。本文將用Python中的Pygame模塊制作一個簡單的賽車游戲,感興趣的可以了解一下

導(dǎo)語

小伙伴們大家好~

如今的游戲可謂是層出不窮,NBA 2K系列啊,F(xiàn)IFA系列啊更是經(jīng)典中的經(jīng)典,不過小編發(fā)現(xiàn),賽車游戲也是深受大家歡迎啊,像跑跑卡丁車、QQ飛車,還有主機游戲極品飛車系列。

咳咳咳......小編那時候主要是最喜歡里面的人物顏值來的!

賽車游戲,通常以款式多樣的車型、各式各樣的賽道、身臨其境的擬真度吸引了眾多玩家,而玩家在游戲中需要駕駛各類賽車馳騁在世界各地的賽道上,享受腎上腺素飆升的快感。

那么接下來就給小編大家用代碼編寫一款《賽車CAR》小游戲吧,讓我們一起來看看

一、環(huán)境安裝

1)運行環(huán)境

文用到的運行環(huán)境:Python3.7、Pycharm社區(qū)版2021、Pygame游戲模塊部分自帶模塊直 接導(dǎo)入不需要安裝。

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

2)素材環(huán)境

音樂背景圖片等:

二、代碼展示

?
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()

三、效果展示

每個賽車游戲生命值三條消耗完即游戲結(jié)束。躲避相應(yīng)的車子會加分。方向鍵左右即是移動鍵。

游戲開始——

游戲界面——

游戲結(jié)束——

到此這篇關(guān)于Python Pygame實戰(zhàn)之賽車游戲的實現(xiàn)的文章就介紹到這了,更多相關(guān)Python Pygame賽車游戲內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • python3.5繪制隨機漫步圖

    python3.5繪制隨機漫步圖

    這篇文章主要為大家詳細介紹了python3.5繪制隨機漫步圖,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-08-08
  • Python實現(xiàn)TCP探測目標服務(wù)路由軌跡的原理與方法詳解

    Python實現(xiàn)TCP探測目標服務(wù)路由軌跡的原理與方法詳解

    這篇文章主要介紹了Python實現(xiàn)TCP探測目標服務(wù)路由軌跡的原理與方法,結(jié)合實例形式分析了Python TCP探測目標服務(wù)路由軌跡的原理、實現(xiàn)方法及相關(guān)操作注意事項,需要的朋友可以參考下
    2019-09-09
  • 如何用C代碼給Python寫擴展庫(Cython)

    如何用C代碼給Python寫擴展庫(Cython)

    這篇文章主要介紹了如何用C代碼給Python寫擴展庫(Cython),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-05-05
  • python scipy.misc.imsave()函數(shù)的用法說明

    python scipy.misc.imsave()函數(shù)的用法說明

    這篇文章主要介紹了python scipy.misc.imsave()函數(shù)的用法說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-05-05
  • 解決ImportError:cannot import name ‘Flatten‘ from ‘torch.nn‘問題

    解決ImportError:cannot import name ‘Flatten‘&nb

    這篇文章主要介紹了解決ImportError:cannot import name ‘Flatten‘ from ‘torch.nn‘問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-06-06
  • 純Python開發(fā)的nosql數(shù)據(jù)庫CodernityDB介紹和使用實例

    純Python開發(fā)的nosql數(shù)據(jù)庫CodernityDB介紹和使用實例

    這篇文章主要介紹了純Python開發(fā)的nosql數(shù)據(jù)庫CodernityDB介紹和使用實例,本文實例包含數(shù)據(jù)插入、數(shù)據(jù)更新、數(shù)據(jù)刪除、數(shù)據(jù)查詢等,需要的朋友可以參考下
    2014-10-10
  • Linux下為不同版本python安裝第三方庫

    Linux下為不同版本python安裝第三方庫

    本文給大家分享了下作者是如何在linux下為python2.x以及python3.x安裝第三方庫的方法,十分的實用,有需要的小伙伴可以參考下
    2016-08-08
  • python分分鐘繪制精美地圖海報

    python分分鐘繪制精美地圖海報

    基于Python中諸如matplotlib等功能豐富、自由度極高的繪圖庫,我們可以完成各種極富藝術(shù)感的可視化作品,關(guān)于這一點我在系列文章在模仿中精進數(shù)據(jù)可視化中已經(jīng)帶大家學(xué)習過很多案例了
    2022-02-02
  • caffe的python接口生成solver文件詳解學(xué)習

    caffe的python接口生成solver文件詳解學(xué)習

    這篇文章主要為大家介紹了caffe的python接口生成solver文件詳解學(xué)習示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-06-06
  • Python基礎(chǔ)教程之tcp socket編程詳解及簡單實例

    Python基礎(chǔ)教程之tcp socket編程詳解及簡單實例

    這篇文章主要介紹了Python基礎(chǔ)教程之tcp socket編程詳解及簡單實例的相關(guān)資料,需要的朋友可以參考下
    2017-02-02

最新評論

大埔县| 泸溪县| 余姚市| 电白县| 汉沽区| 图木舒克市| 涪陵区| 韶山市| 丹巴县| 湖州市| 易门县| 山阴县| 平远县| 宜州市| 峨眉山市| 招远市| 姚安县| 珲春市| 咸丰县| 甘洛县| 宁陕县| 石嘴山市| 蒙阴县| 昌图县| 固安县| 礼泉县| 永登县| 兖州市| 庄河市| 板桥市| 河池市| 江都市| 吉林省| 沙河市| 洱源县| 遂昌县| 阳原县| 宣城市| 荃湾区| 五莲县| 冷水江市|