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】
“ 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 !
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>=rect1-20) or (rect1+40>=rect2)or (rect1+rect1<rect2+20) or (rect2+rect2<rect1+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 ：
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 ！
Previous games are recommended ——
project 1.1 Mine clearance
project 1.2 Contra
project 1.3 Space mecha game
project 1.4 Fruit ninja
A summary of the article ——
（ More + The source code is summarized in the article ！！ Welcome to ~）
author[Muzixue Python],Please bring the original link to reprint, thank you.
The sidebar is recommended
- Python learning notes - the fifth bullet * class & object oriented
- Python learning notes - the fourth bullet IO operation
- Python crawler actual combat: crawl all the pictures in the answer
- Quick reference manual of common regular expressions, necessary for Python text processing
- [Python] the characteristics of dictionaries and collections and the hash table behind them
- Python crawler - fund information storage
- Python crawler actual combat, pyteseract module, python realizes the visualization of boos direct employment & hook post data
- Pit filling summary: Python memory leak troubleshooting tips
- Python code reading (Chapter 61): delaying function calls
- Through the for loop, compare the differences between Python and Ruby Programming ideas
guess what you like
leetcode 1606. Find Servers That Handled Most Number of Requests（python）
leetcode 1611. Minimum One Bit Operations to Make Integers Zero（python）
06python learning notes - reading external text data
[Python] functions, higher-order functions, anonymous functions and function attributes
Python Networkx practice social network visualization
Data analysis starts from scratch, and pandas reads and writes CSV data
Python review (format string)
[pandas learning notes 01] powerful tool set for analyzing structured data
leetcode 147. Insertion Sort List（python）
apache2. 4 + windows deployment Django (multi site)
- Python data analysis - linear regression selection fund
- How to make a python SDK and upload and download private servers
- Python from 0 to 1 (day 20) - basic concepts of Python dictionary
- Django -- closure decorator regular expression
- Implementation of home page and back end of Vue + Django tourism network project
- Easy to use scaffold in Python
- [Python actual combat sharing] I wrote a GIF generation tool, which is really TM simple (Douluo continent, did you see it?)
- [Python] function decorators and common decorators
- Explain the python streamlit framework in detail, which is used to build a beautiful data visualization web app, and practice making a garbage classification app
- Construction of the first Django project
- Python crawler actual combat, pyecharts module, python realizes the visualization of river review data
- Python series -- web crawler
- Plotly + pandas + sklearn: shoot the first shot of kaggle
- How to learn Python systematically?
- Analysis on several implementations of Python crawler data De duplication
- leetcode 1616. Split Two Strings to Make Palindrome （python）
- Python Matplotlib drawing violin diagram
- Python crawls a large number of beautiful pictures with 10 lines of code
- [tool] integrated use of firebase push function in Python project
- How to use Python to statistically analyze access logs?
- How IOS developers learn Python Programming 22 - Supplement 1
- Python can meet any API you need
- Python 3 process control statement
- The 20th of 120 Python crawlers, 1637. All the way business opportunity network joined in data collection
- Datetime of pandas time series preamble
- How to send payslips in Python
- [Python] closure and scope
- Application of Python Matplotlib color
- leetcode 1627. Graph Connectivity With Threshold （python）
- Python thread 08 uses queues to transform the transfer scenario
- Python: simple single player strange game (text)
- Daily python, chapter 27, Django template
- TCP / UDP communication based on Python socket
- Use of pandas timestamp index
- leetcode 148. Sort List（python）
- Confucius old book network data collection, take one anti three learning crawler, python crawler 120 cases, the 21st case
- [HTB] cap (datagram analysis, setuid capability: Python)
- How IOS developers learn Python Programming 23 - Supplement 2
- How to automatically identify n + 1 queries in Django applications (2)?
- Data analysis starts from scratch. Pandas reads HTML pages + data processing and analysis