Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use Python Pygame to realize Racing Games

Shulou Source: shulou.com Published: 2022-06-01 09:02:03 09月29日 Update

Today, I would like to share with you how to use Python Pygame to achieve racing games related knowledge points, detailed content, clear logic, I believe that most people still know too much about this knowledge, so share this article for your reference, I hope you can learn something after reading this article, let's learn about it.

1. Environment installation 1) running environment

The running environment used in the article: Python3.7, Pycharm Community Edition 2021, Pygame game module part of the built-in module direct import does not need to be installed.

Module installation: pip install-I https://pypi.douban.com/simple/ + module name

2) material environment

Music background pictures, etc.:

Code display 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 Racing Game') 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) 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 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 (0126600) 'speed': random.randint (BADDIEMINSPEED, BADDIEMAXSPEED), 'surface':pygame.transform.scale (wallLeft, (126,599)),} baddies.append (sideLeft) sideRight= {' rect': pygame.Rect (497, 0303600), 'speed': random.randint (BADDIEMINSPEED, BADDIEMAXSPEED) 'surface':pygame.transform.scale (wallRight, (303599)),} 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 () 3. Effect display

The life value of each racing game is worth three, that is, the end of the game. Avoiding the corresponding car will give you extra points. Key around is the mobile key.

The game begins--

Game interface--

Game over--

These are all the contents of the article "how to use Python Pygame to realize Racing Games". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Tags: Racing car module environment knowledge article content run different big code picture most that is effect direction more game interface life interface knowledge point Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn Docker Apple Huawei Shulou Tech Info