程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python Basics: Lesson 012 - minimal program framework (code parsing)

編輯:Python

Reference resources :pygame Detailed tutorial
Reference cases : Game module
Pygame As an entry-level game development library , It's not hard to learn , Just master Python The knowledge of programming can be easily mastered .

Pygame Grammar is simple 、 clear , Hold on Python The consistent style of language . meanwhile , As a game development library , It has the basic characteristics of graphic programming , If you have never known anything about graphic programming , Even if you have Python Programming based , I feel a little confused . therefore , In the next study, I will introduce in detail Pygame Common modules of , And related concepts in graphic programming , Help you master Pygame Use .

Screen coordinate system

# Import the required modules
import pygame, sys
# Use pygame Must initialize before
pygame.init()
# Set main screen window
screen = pygame.display.set_mode((600,400))
# Set the title of the window , The name of the game
pygame.display.set_caption(" Small workshop ")
# Load image , Stored in ball variable ,ball Is an image object
ball = pygame.image.load('pygame/images/ball.gif')
# Get the... Of the display object rect Regional coordinates
ball_rect = ball.get_rect()
# Set the display object to center
ball_rect.center = (300, 200)
# Draw the prepared image to the main screen Screen On .
screen.blit(ball, ball_rect)
# Create a clock object
fclock = pygame.time.Clock()
# Fixed code snippets , Click the close button to exit the game , Almost all pygame Will use this code
while True :
# Loop to get events , Listen for event status
for event in pygame.event.get():
# Judge whether the user has clicked "X" close button , And implement if Code segment
if event.type == pygame.QUIT:
# Uninstall all modules
pygame.quit()
# To terminate the program , Make sure you exit the program
sys.exit()
ball_rect = ball_rect.move(speed,speed)
screen.fill((0,0,0))
screen.blit(ball,ball_rect)
# Update screen content
pygame.display.update()
fclock.tick(60)

12. Code parsing

Python:pygame How to use the package in detail

12.1 Game initialization and exit

# Use pygame Must initialize before
pygame.init()
  • To use pygame Before all the functions provided , Need to call init Method , Its function is to automatically detect Pygame Whether the software package is normally available , And check the hardware calling interface of the computer 、 Whether there is a problem with basic functions , Like audio 、 CD drive 、 Sound card driver and other equipment . meanwhile , It will complete Pygame Initialization of all modules in , such as display( Display module )、font( Font module )、mixer( Sound control module )、cursors( Cursor control module ) etc. .

  • Before the end of the game, you need to call quit Method

12.1.1 Method statement

pygame.init() Import and initialize all pygame modular , Before using other modules , Must call first iinit Method
pygame.quit() Uninstall all pygame modular , Call before the game ends

12.2 Surface object

12.2.1 Coordinate system

  • Origin in the upper left corner (0,0)
  • x Axis horizontal right , Gradually increase
  • y The axis goes down vertically , Gradually increase

Pictured :

  • In the game , All visible elements They are all described by rectangular areas
  • To describe a rectangular area, there are four elements : (x, y) (width, height)

(x,y) Is the coordinates of the object ,(width, height) Is the pixel size of the object

  • pygame A special class is provided pygame.Rect Used to describe a rectangular area

x, y
left,top,bottom,right
center,centerx,centery
size,width,height

12.2.2 How to create Surface object

So how do we create Surface What about objects? ?Pygame Provides a variety of creation Surface Object method , Here are the following methods .

The above example , Create a... Using the following method surface object :

# Also called screen object , It's essentially a Surface, size 400*400
screen = pygame.display.set_mode((400,400))

screen Is essentially a Surface object , It is the main window of the game , That is, the largest in the whole game “ paper ”, Any other Surface Objects need to be attached to the largest “ paper ” On , For example, create an image Surface object , Draw it on the home screen in the following way :

# Load image , Stored in ball variable ,ball Is an image object
ball = pygame.image.load('pygame/images/ball.gif')
# Get the... Of the display object rect Regional coordinates
ball_rect = ball.get_rect()
# Set the display object to center
ball_rect.center = (300, 200)
# Draw the prepared image to the main screen Screen On .
screen.blit(ball, ball_rect)

For example, create a that contains text Surface object , Draw it on the home screen in the following way :

# Introduce font type
f = pygame.font.Font('C:/Windows/Fonts/simhei.ttf',50)
# Create a with text Surface object
# Generate text messages , The text content of the first parameter ; The second parameter , Is the font smooth ;
# The third parameter ,RGB The font color of the mode ; Fourth parameter ,RGB Mode font background color ;
text = f.render(" Small workshop ",True,(255,0,0),(0,0,0))
textRect =text.get_rect()
# adopt blit Method to draw it on the main screen , there textRect Position coordinates
screen.blit(text,textRect)
set_mode() Method

set_ mode( resolution=(0,0),flags=0, depth=0) -> Surface( Random names )

  • effect : Create a game display window
  • Parameters
    • resolution Specify the width and height of the screen , The window size created by default is consistent with the screen size
    • flags Parameter specifies additional options for the screen , For example, whether the screen is full or not , By default, there is no need to pass
    • depth The parameter represents the number of bits of the color , Default auto match
  • Return value :Surface object
    Surface Object is a screen data object in memory , It can be understood as the screen of the game , The elements of the game need to be drawn on the screen of the game
    1. At development time , Fixed values may be required , For example, the height of the screen is 700
    2. This is the time , It is not recommended to use fixed values directly , Instead, use constants
    3. When the experimental requirements change , Just change the value of the constant , There is no need to look for numerical changes one by one

How constants are named :

All letters are capitalized , Use underline connection between words

12.2.3 *Rect object

pygame.Rect It's a special class , It just encapsulates some digital calculations

example :

import pygame
hero = pygame.Rect(100,200,50,120)
print(" The hero's x,y The coordinates are %d, %d" % (hero.x, hero.y))
print(" The width and height of heroes are :%d,%d" % (hero.width, hero.height))
# Rect Medium size Property is a tuple ( wide , high )
print(" The width and height of heroes are :%d,%d" % hero.size))
# Rect Medium bottom Property represents the vertical coordinate of the bottom y+height,top Attribute represents the top ordinate of the element y
print(" The bottom of the hero y Coordinate for :%d, Top y Coordinate for :%d" % (hero.bottom, hero.top))
# Rect Of right Attribute represents the abscissa on the right side of the element x+width, left Represents the abscissa of the element x
print(" The rightmost side of the hero x Coordinate for %d, Leftmost x Coordinate for :%d" % (hero.right, hero.left))
# Rect Of center Property is a tuple (centerx,centery)
print(" The central coordinate of the hero is :%d,%d" % hero.center)

12.3 Image rendering

Then you need to display the picture in the created window according to the specified requirements , Three steps are required :

1. Use `pygame.image.load()` Load image data
2. Use game screen objects , call `blit` Method to draw the image to the specified location
3. call `pygame.display.update()` Method to update the display of the entire screen
****load-File image file blit-image Image object +tuple Location update-screen update

notes : If you don't call pygame.display.update() Method , The picture will not be displayed after running the program , After all images are drawn, they can be uniformly updated at the end

12.4 Event monitoring

game , In our daily life, we often come into contact with , Whether it's mobile games 、 Or computer games , Has become the information society , An integral part of .

Generally speaking, the game is composed of animation and human-computer interaction experience , The animation consists of a series of continuous still pictures , After a certain frequency of refresh , This frequency is called FPS, If the frequency value is larger, the picture will be smoother ; If the frequency value is smaller, the screen will feel stuck , The lowest acceptable level in the game FPS about 30Hz, If you want a smooth picture FPS Be greater than 60 Hz.

FPS The higher the , The better the details , The better the experience , But the higher the file capacity

Animation ensures the player's visual experience , Human computer interaction is the experience of operation . By moving and clicking the mouse 、 Press the skill key on the keyboard , Or sliding the mobile phone screen to realize human-computer interaction , These operations that interact with the game program are called events (Event).

Pygame As a game development library , It also has the function of setting and monitoring events . It provides a event Event module , This module contains all the common game events . The following is a code example for exiting the game ( Other types of events , I'll introduce it later ):

# Loop to get events , Listen for event status , Use get() Get events
for event in pygame.event.get():
# Judge event type , Whether the user clicked "X" close button
# pygame.QUIT It refers to clicking on the window in the upper right corner "X" Number
if event.type == pygame.QUIT:
# After clicking , Uninstall all pygame modular
pygame.quit()

12.5 Game cycle

When playing our game, it may trigger various events in the game , Like mouse events 、 Keyboard key events 、 Camera shooting events, etc , Therefore, the game program needs to continuously monitor the player's operation , Only when the user clicks on the game “ close ” Button , Monitoring will end . If you want to achieve “ Loop monitoring ” Purpose , At this point, you need to set up a game cycle (Game Loop) Also known as the main loop of the game , Only in this way can we ensure the experience of human-computer interaction . The code example is as follows :

# The main cycle of the game ( Game cycle )
while True:
# Loop to get events , Monitoring events
for event in pygame.event.get():
# Judge whether the user clicked the close button
if event.type == pygame.QUIT:
# When the user closes the game window, do the following
# Here you have to call quit() Method , Quit the game
pygame.quit()
# Terminate the system
sys.exit()
# Update and draw screen content
pygame.display.flip()

The main loop of the game is each Pygame An essential part of the game program , It mainly undertakes the following three important tasks :

  • Handling game events
  • Update game status
  • Draw the updated game status on the screen


chart 2: Main cycle diagram

The game screen and game operation status will change due to the animation effect and the player's operation , Therefore, it is necessary to update the main screen in real time in a circular way (screen) Display content of . Put the following code into the main game loop to update and draw the screen content in real time , As shown below :

# Refresh the interface display
pygame.display.flip()

In addition to the above methods ,Pygame There is another way . As shown below :

pygame.display.update()

The main difference between the two methods is : The latter can update part of the content according to the selected area , The former is to update the entire content to be displayed . If the latter does not provide the area location parameter , Its function and display.flip() identical .

12.6 About the principle of animation

It is similar to the principle of film , Animation effects in the game , It is essentially a quick way to draw images on the screen , A movie is a series of still motion picture films 、 Fast playback , Produce a coherent visual effect !

Generally, it is drawn every second on the computer 60 Time , It can achieve very continuous and high-quality animation effects , The result of each painting is called a frame Frame

On each call pygame.display.update() Method produces a result of one frame , That is, you need to call every second 60 Time pygame.display.update() Method , You can achieve high-quality animation effects

How to achieve every second 60 frame ?
pygame A special class is provided pygame.time.Clock It is very convenient to set the screen drawing speed - - Refresh frame rate

Two steps are required to use the clock object :

  1. Create a clock object during game initialization
  2. In the game loop, let the clock object call tick( Frame rate ) Method ,tick The method will be based on . Last called time , Automatically set the delay in the game cycle

Implementation method :

# Create a clock object
clock = pygame.time.Clock()
while True:
# Call... Inside the game loop tick Method , Pass in the desired number of frames
​ clock.tick(60)

Animation implementation cases : The plane is flying upwards
example :

 import pygame
pygame.init()
# Create game window
screen = pygame.display.set_mode((480,700))
# Load the images needed in the game
background = pygame.image.load("./pygame/images/xx.jpg")
plane = pygame.image.load("./pygame/images/xxx.jpg)
# Display the image to the position where the game is initialized
screen.blit(background, (0, 0))
screen.blit(plane, (120, 500))
# Define the rectangular area of the aircraft display
plane_Rect = pygame.Rect(120, 500, 120, 90)
# Create a clock object
clock = pygame.time.Clock()
while True:
# Define per second 60 frame
clock.tick(60)
# Move the aircraft to show the position of the rectangular area
plane_Rect.y = plane_Rect.y -5
# Redraw the background image , Avoid residual shadows
screen.blit(background, (0, 0))
# Redraw the image
screen.blit(plane, place_Rect)
# Update screen
pygame.display.update()
pygame.quit()

12.7 There are two ways to capture keyboard keys

● The first way to judge event.type == pygame.KEYDOWN

Implementation code :

if event.type == pygame. KEYDOWN and event.key == pygame.K RIGHT:
print(" To the right ...")

● The second way ( Press and hold the arrow key to move continuously )

  1. use first pygame. key.get_ pressed() Returns all key tuples
  2. Through the keyboard constant , Determine whether a key in the tuple is pressed —— If pressed , The corresponding value is 1

Implementation code :

 Variable = pygame.key.get_pressed()
if Variable [pygame.K_RIGHT]:
print(" To the right ")

● The difference between the two ways

The first way event.type The user must lift the key to count as a key event ( The list can also be used to continuously move in a certain direction , Specific view )
The second way The user can hold the key , It can continuously move in a certain direction

*12.8 pygame Advanced class sprites and Sprite groups provided in

Image loading 、 Position change 、 Drawing images requires programmers to write code to process them separately , To simplify the code , Avoid too much similar duplicate code ,pygame Provides sprites and Sprite group classes

Experience : Its essence is , Plan multiple elements that need to be created to perform the same action together through the wizard class , Then, the action of each element is performed by the wizard group and drawn on the screen , Reduce repeated code to a single code .

  • pygame.sprite.Sprite —— Store image data image And location rect The object of
  • pygame.sprite.Group

notes : At development time , If the parent of a subclass is not Object class , You have to go through super(),__init__() To call the initialization method of the parent class , Because the initialization method in the parent class encapsulates many properties , After inheriting the parent class, you can only manually call the initialization method of the parent class , To use the attributes encapsulated by the parent class initialization method in the initialization method of the child class

● spirit
. Encapsulate images image、 Location rect
. Provide update() Method , According to the needs of the game , Update location rect

 # Define the properties of an object
self.image = pygame.image.load(image)
# Get the coordinates and width and height pixels of the picture
self.rect = self.image.get_rect()

● Spirit group
. Contains multiple sprite objects
.update Method , Let all sprites in the sprite group call update Method to update the location
.draw( Game window objects ) Method , Draw all the sprites in the sprite group on the game window

example :

# ccsprite planeSprites:
import pygame
class planeSprites(pygame.sprite.Sprite):
def __init__(self, image, speed=1):
# Call the initialization method of the parent class
super().__init__()
# Define the properties of an object
self.image = pygame.image.load(image)
# Get the coordinates and width and height pixels of the picture
self.rect = self.image.get_rect()
# Define the running speed of the picture
self.speed = speed
def update(self, *args):
# Make the plane fly sideways
self.rect.x += self.speed
self.rect.y += self.speed
# Kill the elves , To save memory
self.kill()

In the main program :

import pygame
from plane_sprites import planeSprites
pygame.init()
# Create enemy aircraft 1, Enemy planes flying in and out 2
enemy1 = planeSprites("./ Aircraft battle material / Enemy planes flying in and out .png")
enemy2 = planeSprites("./ Aircraft battle material / Enemy planes flying in and out .png")
# Add enemy aircraft to the spirit group 1
enemy_group = pygame.sprite.Group(enemy1, enemy2)
while True:
# Call the wizard group's update Method
enemy_group.update()
# Draw the enemy aircraft in the spirit group onto the screen
enemy_group.draw(screen)
# *** Be sure to update the view , Otherwise, no image will be displayed
pygame.display.update()
pygame.quit()

12.9 pygame Two sprite collision detection methods provided in


pygame.sprite.groupcolide()
groupcollide(group1, group2, dokill1, dokill2, collided = None) -> Sprite_ dict

group1 and group2 They are all a group of elves
dokill1 and dokill2 All Boolean types

When put dokill1 Set to True after , Spirit group 1 And the elves 2 When colliding, the sprite group 1 Automatically destroyed
When put dokill2 Set to True after , Spirit group 1 And the elves 2 When colliding, the sprite group 2 Automatically destroyed

pygame.sprite.spritecollide()
● Determine the collision between a sprite and the sprite in the specified sprite group

spritecollide(sprite, group, dokill, collided = None) -> Sprite_ list

● If you will dokill Set to True, The sprites that collide in the specified sprite group will be automatically removed

● collided Parameter is the callback function used to calculate the hammer
. If not specified , Then each elf must have one rect attribute

● Returns the list of sprites in the sprite group that collide with the sprites

notes : Here is to return a list

Code implementation :

 enemies = pygame.sprite.spritecollide(self.hero, self.enemyGroup, True)
if len(enemies) > 0:
print(" Game over , The plane was damaged ")
pygame.quit()
exit()

12.10 The background scrolls alternately

Commonly known as treadmill mode

In the aircraft war, the game background changes constantly to produce the visual effect of upward flight

Realization principle :

In fact, two background pictures of the same size as the screen move down , As soon as the first picture is removed from the screen, change the coordinates and move to the second picture

Code implementation :
ccsprite

import pygame
from plane_main import SCREEN_RECT
class planeSprites(pygame.sprite.Sprite):
def __init__(self, image, speed=1):
# Call the initialization method of the parent class
super().__init__()
# Define the properties of an object
self.image = pygame.image.load(image)
# Get the coordinates and width and height pixels of the picture
self.rect = self.image.get_rect()
# Define the running speed of the picture
self.speed = speed
def update(self, *args):
# Make the spirit move down
self.rect.y += self.speed
# Be a parent update If the update method cannot meet the conditions of a sprite class, you can create the experience sprite subclass
class background(planeSprites):
def __init__(self, is_single=False):
super().__init__("./ Aircraft battle material / Game background .jpg")
if is_single:
# Put the second picture on top of the first picture
self.rect.y = - self.rect.height
def update(self, *args):
# Call the parent class update method
super().update()
if self.rect.y == SCREEN_RECT.height:
self.rect.y = - self.rect.height

Main method :

import pygame
from plane_sprites import *
pygame.init()
SCREEN_RECT = pygame.Rect(0, 0, 480, 700)
class main(object):
def __init__(self):
# Game creation screen
self.screen = pygame.display.set_mode(SCREEN_RECT.size)
# Create a game clock
self.clock = pygame.time.Clock()
# Create a game sprite group
self.__create_spirits()
# Sprite creation
def __create_spirits(self):
bg1 = background()
bg2 = background(True)
self.backGroup = pygame.sprite.Group(bg1, bg2)
# Wizard update processing
def __update_spirits(self):
self.backGroup.update()
self.backGroup.draw(self.screen)

12.11 Timer

● stay pygame Can be used in pygame.time.set.timer() To add a timer

● The so-called timer , It's every once in a while , Go do something

set_timer(eventid, milliseconds) -> None

●set_timer You can create an event
● This event can be captured in the event listening method of the game loop

● The first 1 Parameter event codes need to be based on constants pygame. USEREVENT To specify the

USEREVENT It's an integer , Additional events can use USEREVENT + 1 Appoint , By analogy …

● The first 2 The first parameter is the millisecond value of the event trigger interval

Listening for timer events
● adopt pygame.event.get() You can get the list of all events at the current time
● Traverse the list and determine event.type Is it equal to eventid, If equal , Indicates that a timer event has occurred

Implementation method :

# Create timer for enemy aircraft , every other 1000ms Send out an event
pygame.time.set_timer(pygameUSEREVENT, 3000)
# Event monitoring
for event in pygame.event.get():
if event.type == pygameUSEREVENT:
pass

example ( The enemy aircraft flew into the screen at random ):

ccsprite

import random
import pygame
# Specify the screen format size
SCREEN_RECT = pygame.Rect(0, 0, 480, 700)
CREATE_EVVENTID = pygame.USEREVENT
class planeSprites(pygame.sprite.Sprite):
def __init__(self, image, speed=1):
# Call the initialization method of the parent class
super().__init__()
# Define the properties of an object
self.image = pygame.image.load(image)
# Get the coordinates and width and height pixels of the picture
self.rect = self.image.get_rect()
# Define the running speed of the picture
self.speed = speed
# Create timer for enemy aircraft , every other 1000ms Send out an event
pygame.time.set_timer(CREATE_EVVENTID, 3000)
class enemy(planeSprites):
""" Enemy spirit """
def __init__(self):
super().__init__("./ Aircraft battle material / Enemy planes flying in and out .png")
self.rect.bottom = 0
# The speed of the plane changes from 1—3 Take whatever you like
self.speed = random.randint(1, 3)
max_x = SCREEN_RECT.width - self.rect.width
# The position of the aircraft is from 0- On the right side of the screen, you can select any
self.rect.x = random.randint(0, max_x)
def update(self, *args):
super().update()
# Kill the elves after they fly out of the screen
if self.rect.y >= SCREEN_RECT.height:
self.kill()

Main method :

import pygame
from plane_sprites import *
pygame.init()
# Sprite creation
def __create_spirits(self):
self.enemyGroup = pygame.sprite.Group()
# Event monitoring processing
def __event_handler(self):
for event in pygame.event.get():
# Determine whether the event type is given by the timer
if event.type == CREATE_EVVENTID:
# New sprites
oneEnemy = enemy()
# Add sprites to the sprite group
self.enemyGroup.add(oneEnemy)
# Wizard update processing
def __update_spirits(self):
self.enemyGroup.update()
self.enemyGroup.draw(self.screen)

12.12 Music introduction

# Import music
pygame.mixer.init()
def background_music_load():
global hero_fire_music # Import function external variables
pygame.mixer.music.load("./music/PlaneWarsBackgroundMusic.mp3")# Game background music
pygame.mixer.music.set_volume(0.3)# set volume (0-1)
pygame.mixer.music.play(-1)# Loop Playback
hero_fire_music = pygame.mixer.Sound("./music/hero_fire.wav")# Aircraft fire music
hero_fire_music.set_volume(0.2)# set volume (0-1)


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved