Write the childhood game fourth play, suddenly thought of a very interesting game played before, called fat bird fly, is a bird, through the constant click to adjust the position, through the steel pipe game, today we will write this game ~
Python game development :(fly fat bird)
We use the third party library PyGame and Basic Python syntax to develop the game with no more than 100 lines of code, even beginners can easily understand. Most importantly, developing the game not only solidifies python fundamentals, but also brings boring code to life, like cooking, eating.
** Install pyGame: ** install pygame; (If you have a compiler, you can import it in setting.)
Step 1: Understand the basic framework of the game;
The game is formed by constantly refreshing the running interface, and an endless loop is exactly this function. Inside the loop is the main module of the game;
Import pygame,time from pygame.locals import *# import pygame.image.load(' url')# def GameOver(): Pygame.quit ()# def main(): Pygame.display. Set_mode ([480,640])# game window interface pygame.display. Set_caption (' game name ')# game title Pygame.display.update ()# Game interface refresh while True: "" game body module ''' ''' event response" "for event in pygame.event.get(): if event.type==QUIT: Fill (pyGame.color (R,G,B))# form background Color fill, The default is black pygame.display.update()# Refresh the game interface time.sleep(' sleep time ')# generally 0.05-0.09 if __name__=='__main__': main()# main functionCopy the code
Result :(form with black background and size 480*640)
Step 2: Draw a simple image and realize a simple key response;
First we need to understand what is the concept of object-oriented, and through the appropriate way to construct the class we need to facilitate our subsequent operations;
For those who don’t know, you can learn related knowledge here: blog.csdn.net/weixin_4463…
BirdColor =pygame.Color(255,255,0)# birdColor= 1# birdscore =0# birdscoreCopy the code
After defining the class we can use this template to instantiate a fat bird object: bird= bird ();
Then we construct our own Draw method to achieve simple graph drawing; (PyGame provides Draw to draw simple images. Here we draw a simple rectangle.)
Python functions: blog.csdn.net/weixin_4463…
image
def DrawRect(windowsSize,bird): Pygame. The draw. The rect (windowsSize, bird birdColor, the rect (bird) position [0], bird. The position [1], 30, 30))Copy the code
Results :(a yellow rectangle appears on the screen, our fat bird, we will make it more vivid later)
So the question is, how do you get this fat little bird to move by button response? Pygame provides a Type attribute to determine the state of the key and a key attribute to determine which key is fired, responding to different events depending on the situation.
For event in Pygame.event.get (): if event.type == QUIT: GameOver() # game exit elif event.type==KEYDOWN:# key response if event.key==K_SPACE: Bird. Position [1]=bird. Position [1]-bird. Speed *50*level # According to the rank fat bird up or down flag=1 if flag==0:# detection bit bird.position[1]=bird.position[1]+bird.speed*10*level flag=0Copy the code
Does this start to feel like a game, our little fat bird can go up or down according to how often we press the space (ha ha);
Step 3: making and moving obstacles;
As with birds, we similarly construct a pipe class;
Pipe_y =[]# pipeColor= pygame.color (115,190,44)# pipeColor= pygame.color (115,190,44)# pipeColor=pygameCopy the code
Before using the pipe, we need to initialize it. According to the ordinate calculation, we set aside four empty positions for the fat bird, and mark these empty positions in the initialization, so that we can draw the pipe obstacles in the later stage. Here’s the PipeInit method we constructed;
Def PipeInit(pipe):# start = random. Randint (0, 10) * 30 pipe.pipe_y.append(start) pipe.pipe_y.append(start + 30) pipe.pipe_y.append(start + 60) pipe.pipe_y.append(start + 90)Copy the code
Fat bird is moving up and down through the blank space key, and the movement of the pipe is not controlled by the user and the direction for the horizontal movement in turn from right to left, here we have adopted with the moving of the loop will pipe in horizontal position minus 1 way to realize the relative motion of the birds and pipeline, which can be drawn at the same time of the pipeline and the operation. Let’s construct the method to draw the pipe:
Def pipeline (windowSize,pipeList,bird): Pipe_x =pipe. pipe_x-10 for I in range(0,20): pipe.pipe_x=pipe. pipe_x-10 for I in range(0,20): If I * 30 not in pipe. Pipe_y: # not realize the void space in pygame. The draw. The rect (windowSize, pygame. Color (0145, 0), the rect (pipe pipe_x, I * 30, 60. Bird.g_score = bird.g_score + 1# Pipe. pipe_x=480 pipe.pipe_y=[] PipeInit(PIPE) pipelist.pop ()# Pop the pipelist.append (pipe)# add the new pipe to the pipe listCopy the code
The fourth step: the judgment of the outcome of the game;
So far, we have basically realized all the functions of the game, but every game will end. So far, our game only realizes the map and Sprite movement, and there is no function to end the game. Here we use a Check method to judge the game;
Def CheckGame(bird,pipe):# if bird. Position [1]<0 or bird. Position [1]>570: Pipe_x and bird.position[0]<pipe[0]. Pipe_x +60: If bird.position[1]<pipe[0]. Pipe_y [0] or bird.position[1]+20>pipe[0]. Pipe_y [3]: PyGame.quit ()#Copy the code
This brings me to the end of my last major feature, and let’s take a look at how the game has changed and become substantially more playable (if you’re a little excited, let’s run our simple demo).
Step 5: optimize the game interface and import pictures;
Does it work, and is it similar to what we expect from fat birds? But if that’s a bit monotonous, let’s start making the whole interface a little bit more lively. The windowsize.fill () method we mentioned earlier is filled with black by default. We can change the background color to the desired color by changing the RGB color value of the filled background.
The plump yellow bird (which is really square) can be transformed by importing an image of a fat bird and changing the rectangle accordingly.
FlappyBird = Pygame.image.load (” bird.png “)#
image
For game score prompts, you can use pyGame’s own font to set the font size and add it to the screen (here we only give the code for score prompts, you can also fill in other prompts as needed).
Pygame.font.SysFont(‘宋体’, 24); text = font.render(“Game Score:” + str(bird.g_score), True, (255, 255, 255)); windowsSize.blit(text, Rect(360, 10, 200, 120)); #text = Rent(x,y,len,width)
FINALLY FINALLY (MayBe I will add new feature modules) :
Complete game code:
Import PyGame,random,sys,time from PyGame.locals import *# flappyBird = Pygame.image.load (" bird.png ")# Level =1# game level class Brid:# bird position = [10,200]# initial position speed=1# move speed g_score = 0 # game score Pipe_x =300 pipe_y=[] pipeColor= pygame.color (115,190,44) def # pipeColor= pygame.color (115,190,44) def # pipeColor=pygame GameOver(): pygame.quit()# Leveling up (count) # Leveling up (count) # Leveling up (count) Blit (flappyBird,Rect(brid. Position [0], return count/10 def GameInit(windowSize,brid): Position [1], 30, 30)) pygame.display.update() def PipeInit(pipe):# start = random. Randint (0, 0) 10) * 30 pipe.pipe_y.append(start) pipe.pipe_y.append(start + 30) pipe.pipe_y.append(start + 60) Pipe.pipe_y. Append (start + 90) def pipeline (windowSize,pipeList,bird): Pipe_x =pipe. pipe_x-10 for I in range(0,20): if I *30 not in pipe.pipe_y: pipe.pipe_x=pipe. pipe_x-10 for I in range(0,20): if I *30 not in pipe.pipe_y: Pygame.draw. rect(windowSize, pygame.color (0,145,0), rect(pipe.pipe_x, I *30, 60, 30)) if pipe.pipe_x<=-40: bird.g_score = bird.g_score + 1 pipe.pipe_x=480 pipe.pipe_y=[] PipeInit(pipe) pipeList.pop() pipeList.append(pipe) def CheckGame(bird,pipe):# check if bird.position[1]<0 or bird.position[1]>570: Pipe_x and bird.position[0]<pipe[0]. Pipe_x +60: If bird. Position [1]<pipe[0].pipe_y[0] or bird. Position [1]+20>pipe[0].pipe_y[3]: WindowsSize = Pygame.display.set_mode ([480,600])# Set window size Pygame.display. Set_caption ('FlappyBrid') Bird = 24) Brid () # create instances pipeList bird = [] # PipeLine list pipe1 = PipeLine pipe2 = PipeLine () () PipeInit (pipe1) pipe2 = pipe1 # copying the value of the objects Pipe2. Pipe_x = pipe2. Pipe_x + 80 pipeList. Append (pipe1) pipeList. Append (pipe2) windowsSize. The fill (pygame. Color (113197205)) GameInit initialization (windowsSize, bird) # game DrawPipeLine (windowsSize pipeList, bird) while True: # game subject level = Leveling (bird. G_score) text = font.render("Game Score:" + str(bird.g_score), True, (255, 255, 255)) text1 = font.render("Level:" + str(level), True, (255, 255, 255)) for event in pygame.event.get(): If event.type== QUIT: GameOver() # game exit elif event.type==KEYDOWN:# Key response if event.key==K_SPACE: Bird. position[1]=bird.position[1]-bird.speed*50*level Flag =1 if Flag ==0:# detect bit Bird. The position [1] = bird. The position [1] + bird. The speed level * 10 * flag = 0 windowsSize. The fill (pygame. Color (113197205)) CheckGame (bird, pipeList) DrawPipeLine(windowsSize,pipeList,bird) windowsSize.blit(text, Rect(360, 10, 200, 120)) windowsSize.blit(text1, Rect(360, 40, 200, Sleep (0.1-level/100) if __name__=='__main__': main()# main functionCopy the code
Game running screenshot:
conclusion
The above is fat bird fly source process, we can write to play a play
I am in vain, a young man who likes learning and programming
Please click “1” in the comments section if you need to study materials.
Learning exchange group has free learning materials, you can come together to exchange