current position:Home>The game comprehensively "invades" life: Python releases the "cool run +" plan!

The game comprehensively "invades" life: Python releases the "cool run +" plan!

2022-02-01 16:38:22 Muzixue Python

Introduction

“ Run fast —— Enjoy the good times in life !” 

                                               —— Gu Muzi acridine

Heavy news ! Mumuzi will introduce a new game to you again today !

Look forward to it or not Let's first see what games make everyone so excited

《 Cool run every day 》 This game has a history of several years , It was really hot at the beginning , I still remember my first contact with this game was in the summer vacation after the college entrance examination , Because of that

It's a long holiday , I went to work in a clothing store , When I'm free, the people in the store are playing cool running every day , In order to have a conversation, I went into the pit , Later, it was found that there were still

Young students are also playing , And the score is much higher than yourself . Now it's about the past six or seven years , I have already given up running every day .

Maybe it's because everyday cool running is the first mobile game you come into contact with , Quite impressive —— Now it's not easy to download it and find that many rules have been changed , Over your face .jpg 

I can't operate at all . see ? Ready to make a Python Simple version 《 Parkour every day 》 Little games , By the way, go back to childhood !

Brief introduction :

《​ Cool run every day 》 Tencent mobile game platform is designed for massive wechat and mobile phones QQ A high-quality mobile game customized by users .

On the basis of following the traditional playing methods , In particular, the flash mount is added 、 A series of exciting designs such as cute pets , Bring players the most handy Parkour experience .

Communicate with wechat anytime, anywhere 、QQ Play with friends , Grab the leaderboard 、 Love keeps sending 、 Show off high scores ! Intimate interaction makes you close to your friends , Sharing and showing off makes you popular

Friends follow , Become a cool runner ! Tell your friends loudly : Parkour is different from now on !

​ Text

This article is about Pygame Made by game module 《 Parkour every day 》 Little games ~

One 、 In preparation

All right. ! We officially began to prepare the materials needed for the small game 、 Environment !

Picture material :

Environmental installation :

Python3.6、Pycharm2019( Most versions are runnable )、Pygame Some built-in modules .

 Module installation :pip install -i https://pypi.douban.com/simple/ + Module name 
 Copy code 

The rules of the game :

Press the space bar to jump 、 Press a short jump 、 Press the second long jump , There will be many obstacles in the middle , And the corresponding gold coins , After the game fails, press the space bar to restart .

Two 、 Game steps

1). Game initialization

  • utilize pygame Create a game window of a specific size .

  • Display the initial interface of the game , Prompt the user to start the game

  • Set the background picture in the game interface , And show people 、 Objects such as obstacles and gold coins .

2). Game control

  • The character automatically runs forward , Press the space bar to control the character to jump .

  • utilize addObstacle Function to create an obstacle .

  • utilize updateScreen Function constantly updates the display of objects in the interface .

3). collision detection

  • utilize ListenKeyBoard Function to monitor the user's keyboard input , And detect whether characters and obstacles collide .

  • People collide with obstacles : When the intersection of the position information of the person and the obstacle is detected , It is judged as collision , Reduce the character's HP by one , Obstacle Elimination .

  • Characters collide with gold coins : When a character hits a gold coin , Gold coin elimination , score +100.

  • When the character successfully avoids obstacles , score +10.

  • utilize judgeState Function to determine whether the game is over .

  • The final score is displayed at the end of the game , And prompt the user to press “Enter” Key to restart the game .

3、 ... and 、 Officially tap the code

import pygame,sys
import random

#  Game configuration 
width = 1200            # Window width 
height = 508            # Window height 
size = width, height   
score=None              # fraction 
myFont=myFont1=None     # typeface 
surObject=None          # Pictures of obstacles          
surGameOver=None        # End of game picture 
bg=None                 # Background object 
role=None               # People, objects 
object=None             # Obstacles, objects         
objectList=[]           # An array of obstacle objects 
clock=None              # The clock 
gameState=None          # Game status (0,1) Express ( In the game , Game over )



class Role: # figure 
    def __init__(self,surface=None,y=None):
        self.surface=surface
        self.y=y
        self.w=(surface.get_width())/12
        self.h=surface.get_height()/2
        self.currentFrame=-1
        self.state=0        #0 It's running ,1 It's a jump state ,2 It's for continuous jumps 
        self.g=1            # Acceleration of gravity 
        self.vy=0           #y Shaft speed        
        self.vy_start=-20   # Take off start speed 
    def getRect(self):
        return (0,self.y+12,self.w,self.h)


class Object:  # obstacle 
    def __init__(self,surface,x=0,y=0):
        self.surface=surface
        self.x=x
        self.y=y
        self.w=surface.get_width()
        self.h=surface.get_height()
        self.currentFrame=random.randint(0,6)
        self.w = 100
        self.h = 100
    def getRect(self):
        return (self.x,self.y,self.w,self.h)
    def collision(self,rect1,rect2):
        # collision detection 
        if (rect2[0]>=rect1[2]-20) or (rect1[0]+40>=rect2[2])or (rect1[1]+rect1[3]<rect2[1]+20) or (rect2[1]+rect2[3]<rect1[1]+20):
            return False
        return True
    
    
class Bg:   # background 
    def __init__(self,surface):
        self.surface=surface
        self.dx=-10
        self.w=surface.get_width()
        self.rect=surface.get_rect()
   
    
def initGame():
        
    global bg,role,clock,gameState,surObject,surGameOver,score,myFont,myFont1,objectList
    # Score initialization 
    score=0
    # initialization 
    objectList=[]
    # Load Fonts 
    myFont=pygame.font.Font("./freesansbold.ttf",32)
    myFont1=pygame.font.Font("./freesansbold.ttf",64)   
    #  Create a clock object  ( You can control the frequency of the game cycle )
    clock = pygame.time.Clock()
    # Initialize game state 
    gameState=0
    # Game background 
    surBg=pygame.image.load("image/bg.bmp").convert_alpha()
    bg=Bg(surBg)
    # End screen 
    surGameOver=pygame.image.load("image/gameover.bmp").convert_alpha()
    # Images of people 
    surRole=pygame.image.load("image/role.png").convert_alpha()  
    role=Role(surRole,508-85)
    # Pictures of obstacles 
    surObject=pygame.image.load("image/object.png").convert_alpha()  


def addObject():
    global surObject,object,objectList,object
    rate=4
    # Whether an obstacle is created 
    if not random.randint(0,300)<rate:
        return
    y=random.choice([height-100,height-200,height-300,height-400])
    object=Object(surObject,width+40,y)
    objectList.append(object)


def updateLogic():
    global gameState,score
    # Keyboard event handling 
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
             sys.exit()
        elif event.type==pygame.KEYDOWN:
            # The space bar jumps 
            if gameState==0:
                if event.key==pygame.K_SPACE:
                    if role.state==0:
                        role.state=1
                        role.vy=role.vy_start
                    elif role.state==1:
                        role.state=2
                        role.vy=role.vy_start
            elif gameState==1:
                if event.key==pygame.K_SPACE:
                    # Restart the game 
                    initGame()
                    
    if gameState==0:
        # The movement of the background    
        bg.dx+=10
        if bg.dx==1200:
            bg.dx=0 
            
        # The movement of characters   
        if role.state==0:    
            role.currentFrame+=1
            if role.currentFrame==12:
                role.currentFrame=0  
        else:
            role.y+=role.vy
            role.vy+=role.g 
            if role.y>=508-85:
                role.y=508-85
                role.state=0
        # The movement of obstacles 
        addObject()
        
        for object in objectList:
            object.x-=10     # Obstacles move 
            #  Obstacles beyond the screen , Remove obstacles 
            if object.x+object.w<=0:
                objectList.remove(object)
                score+=10    # Avoid obstacles , Add 10 branch 
                print(" Removed a target ")   
            # collision detection 
            if object.collision(role.getRect(),object.getRect()):
                if(object.currentFrame==6):
                    objectList.remove(object)
                    score+=100  # Gold and silver 100 branch 
                    print(score)
                    print(" I ate a gold coin ")
                else: 
                    gameState=1   # The game failed 
                    print(" There was a collision !")



  
    
       
def updateView(screen):
    # Background mapping 
    screen.blit(bg.surface,[-bg.dx,0])
    screen.blit(bg.surface,[1200-bg.dx,0])
    # Score mapping 
    textSur=myFont.render("score:%d"%score, True, (128, 128, 128))
    screen.blit(textSur, (500,20))
    del textSur
    # Character mapping 
    screen.blit(role.surface, [0, role.y], [int(role.currentFrame) * role.w, 0, role.w, role.h])   
    # Mapping of obstacles 
    for object in objectList:
        screen.blit(object.surface, [object.x, object.y], [int(object.currentFrame) * object.w, 0, object.w, object.h])   
         
     
def judgeState(screen):
    global gameState
    if gameState==0:
        updateView(screen)
        return
    elif gameState==1:
        screen.blit(surGameOver,[0,0])
        textSur = myFont1.render("GameOver Score:%d"%score, True, (255, 0, 0))
        screen.blit(textSur, (width/2-350, height/2+150))
                     
def main():
    
    pygame.init()
    screen = pygame.display.set_mode(size)
    pygame.display.set_caption(' Parkour every day ——CSDN: Gu Muzi acridine ')
    initGame()
    screen.blit(bg.surface,[0,0])
    while True:
        # Set the clock frequency 
        clock.tick(60)  
              
        judgeState(screen)
        updateLogic()  
        pygame.display.flip()

main()
 Copy code 

Four 、 Effect display

Screenshot display ——

Game begins :

jumping 、 obstacle :

​ Game over :

summary

After watching this game , Is it full of memories : While my parents are away , Secretly open the computer to play games

When I first bought a smartphone , Download one or two of the hottest games ……

Now it seems , Every game , Are the marks of time , What other games do you have to kill ? I've written many classic childhood games before. You can go and have a look !

Complete project source code : Private letter editor 06 Or click this line of blue font to get the source code for free !

Previous games are recommended ——

project 1.1 Mine clearance

Pygame actual combat : It is said that this is the most difficult minesweeping game in history , Not one of them. , You feel ......

project 1.2 Contra

Pygame actual combat : Many years later “ Contra ” Pixel wind returns Not just classics and feelings @ All members

project 1.3 Space mecha game

Pygame actual combat : cattle , Thousands of lines of code 《 Mecha adventure game 》, Too cattle ( Save it and learn it slowly )

project 1.4 Fruit ninja

【Pygame actual combat 】 An upgraded version of the fruit cutting game popular all over the world “ Fruit ninja ” Online , You dare to come PK Well ?

A summary of the article ——

project 1.0 Python—2021 | Summary of existing articles | Continuous updating , Just read this article directly

( More + The source code is summarized in the article !! Welcome to ~)

copyright notice
author[Muzixue Python],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202011638204232.html

Random recommended