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

Aircraft battle (Python)

編輯:Python

Configuration class

import pygame
# Constant of screen background image 
SCREEN_RECT = pygame.Rect(0,0,480,700)
# Create timer constant for enemy aircraft 
CREATE_ENEMY_EVENT = pygame.USEREVENT
# The hero fired bullets 
HERO_FIRE_EVENT = pygame.USEREVENT +1
class Settings():
""" Store all the settings classes """
def __init__(self):
self.caption = " Aircraft battle "

Main program class :

import pygame
from plane_sprites import *
import Settings
import sys
from hero import Hero
class PlaneGame():
""" Aircraft war main program """
def __init__(self):
self.screen = pygame.display.set_mode(Settings.SCREEN_RECT.size)
self.clock = pygame.time.Clock()
# Set the timer 
pygame.time.set_timer(Settings.CREATE_ENEMY_EVENT,1000)
pygame.time.set_timer(Settings.HERO_FIRE_EVENT, 500)
def __create_sprits(self):
# Create spirit and spirit group of enemy aircraft 
self.plane_group = pygame.sprite.Group()
# Create a hero's spirit and spirit group 
self.hero = Hero()
self.hero_group = pygame.sprite.Group(self.hero)
def start_game(self):
pygame.init()
pygame.display.set_caption(Settings.Settings().caption)
bg = pygame.image.load("./images/background.png")
bg_rect1 = pygame.Rect(0, 0, 480, 700)
bg_rect2 = pygame.Rect(0, -700, 480, 700)
self.screen.blit(bg, bg_rect1) # Display the loaded image on the screen , The second parameter specifies the location 
self.screen.blit(bg, bg_rect2)
# Create elves 
self.__create_sprits()
# Draw player plane 
# The main cycle of the game 
while True:
self.clock.tick(60)
# The movement of the background picture 
# Draw the background image first to avoid residual shadows 
self.__background_scrool(bg, bg_rect1, bg_rect2)
# Monitor keyboard and mouse events 
self.__event_handler()
# collision detection 
self.__check_collide()
# Call the sprite group 
self.__update_sprites()
# Make the most recently drawn screen visible 
pygame.display.flip()
def __background_scrool(self, bg, bg_rect1, bg_rect2):
""" Background image movement """
bg_rect1.y += 1
bg_rect2.y += 1
if bg_rect1.y >= 700:
bg_rect1.y = -700
elif bg_rect2.y >= 700:
bg_rect2.y = -700
self.screen.blit(bg, bg_rect1)
self.screen.blit(bg, bg_rect2)
def __event_handler(self):
""" Monitor keyboard and mouse events """
for event in pygame.event.get():
if event:
print(event)
# Determine whether the event type is an exit event 
if event.type == pygame.QUIT:
PlaneGame.__game_over()
elif event.type == Settings.CREATE_ENEMY_EVENT:
print(" Enemy planes flying in and out ---")
plane_path = "./images/enemy1.png"
plane = [GameSprites(plane_path) for i in range(10)]
self.plane_group.add(plane)
elif event.type == Settings.HERO_FIRE_EVENT:
self.hero.fire()
# elif event.type ==pygame.KEYDOWN and event.key == pygame.K_RIGHT:
# self.hero.speed = 2
# elif event.type ==pygame.KEYDOWN and event.key == pygame.K_LEFT:
# self.hero.speed = -2
# Use what the keyboard provides to get key tuples ( It can continuously move to the right )( recommend )
keys_press = pygame.key.get_pressed()
# Determine the index value of the corresponding key in the tuple 
if keys_press[pygame.K_RIGHT] :
self.hero.speed = 2
elif keys_press[pygame.K_LEFT]:
self.hero.speed = -2
else:
self.hero.speed =0
def __check_collide(self):
""" collision detection """
pygame.sprite.groupcollide(self.hero.bullets,self.plane_group,True,True)
enemies = pygame.sprite.spritecollide(self.hero, self.plane_group, True)
# Determine whether there is content in the list 
if enemies:
# Let the hero die 
self.hero.kill()
self.__game_over()
def __update_sprites(self, ):
""" Modify the sprite group """
self.plane_group.update()
self.plane_group.draw(self.screen)
self.hero_group.update()
self.hero_group.draw(self.screen)
self.hero.bullets.update()
self.hero.bullets.draw(self.screen)
@staticmethod
def __game_over():
""" How to end the game """
pygame.quit()
sys.exit()
# Test module 
if __name__ == '__main__':
PlaneGame().start_game()
# print(map(lambda x:x+1,[1,2,3]))

Enemy aircraft elves

import pygame
import random
class GameSprites(pygame.sprite.Sprite):
""" Aircraft war game wizard """
def __init__(self, image_path, speed=1):
""" Initialization method :param image_path: Picture path :param speed: Movement speed """
super().__init__()
self.speed = random.randint(1,3)
self.image = pygame.image.load(image_path)
# x,y Will be set to 0,size Is the size of the image 
self.rect = self.image.get_rect()
self.rect.x = random.randint(0,400)
self.rect.y = random.randint(-500,-self.rect.height)
# Destroy enemy aircraft objects 
def __del__(self):
print(" The enemy plane hung up ")
# You can remove sprites from all sprite groups 
self.kill()
def update(self):
""" rewrite update Method """
self.rect.y += self.speed
if self.rect.y >= 700:
print("del enemy")
self.__del__()

Heroes

import pygame
import random
from bullet import Bullet
class Hero(pygame.sprite.Sprite):
""" Aircraft war heroes """
def __init__(self, speed=0):
""" Initialization method :param speed: Movement speed """
super().__init__()
self.speed = speed
self.image = pygame.image.load("./images/me1.png")
# x,y Will be set to 0,size Is the size of the image 
self.rect = self.image.get_rect()
self.rect.centerx = 480 * 0.5
self.rect.bottom = 700 - 120
# Create the sprite group of bullets 
self.bullets = pygame.sprite.Group()
# Destroy enemy aircraft objects 
def __del__(self):
print(" The hero is dead ")
# You can remove sprites from all sprite groups 
self.kill()
def update(self):
""" rewrite update Method """
self.rect.x += self.speed
if self.rect.x >= 380:
self.rect.x = 380
elif self.rect.x <= 0:
self.rect.x = 0
# bullets 
def fire(self):
print(" bullets ...")
for i in range(3):
# Create bullet wizard 
bullet = Bullet()
# Set the wizard position 
bullet.rect.bottom = self.rect.y -i*20
bullet.rect.centerx = self.rect.centerx
self.bullets.add(bullet)

Bullets

import pygame
class Bullet(pygame.sprite.Sprite):
""" Aircraft vs bullets """
def __init__(self, speed=-2):
""" Initialization method :param speed: Movement speed """
super().__init__()
self.speed = speed
self.image = pygame.image.load("./images/bullet2.png")
# x,y Will be set to 0,size Is the size of the image 
self.rect = self.image.get_rect()
def update(self):
""" rewrite update Method """
self.rect.y += self.speed
# Determine whether the bullet flew off the screen 
if self.rect.bottom <0:
self.__del__()
def __del__(self):
print(" The bullet was destroyed ")
self.kill()

The operation effect is as follows :

Understanding of key points :

  1. pygame Technical secondary school provides a class to describe rectangular areas Rect(x,y,weight,height)->Rect object . This object has many properties Rect.size Return a tuple (weight,height)
  2. pygame A module is specially provided pygame.display Used to create 、 Manage game windows .pygame.display.setmode() Initialize the game display window ( Variables must be used to record the returned results , Because all subsequent image rendering is based on this return result )
    pygame.display.update() Refresh the screen content display
  3. Understand image and realize image rendering :
    use first pygame.image.load() Load image data ; Use game screen objects , call blit Method , Draw the image to the specified position ; call pygame.diaplay.update() To update the display of the entire screen notes : Can be in screen Object to complete all bilt After method , Unified call update Method .
    png The image format supports transparent images
  4. The principle of animation in the game : In essence, it is to draw images on the screen quickly , Each image drawn is called a frame , Generally, the computer draws every second 60 Time
  5. Game clock :pygame The technical secondary school provides a clock class ,pygame.time.clock, It is convenient to set the drawing speed of the screen
    To use the game clock : First, create a clock object in the game initialization , Next, call in the game loop tick( Frame rate ) Method .tick According to the last time it was called , Automatically set the delay in the game cycle .
  6. Listen for events in the game loop :py.event.get() You can get a list of all the events
  7. Understand the role of elves and elves :pygame.sprite.Sprite() Record stored images (image) And location (rect);
    pygame.sprite.Group() Yes add、update( Change location , Let all the sprites in the sprite group call update Method to update the location ) and draw(screen): stay sceen Draw all the sprites in the sprite group on
  8. Timer :pygame.time.set_timer(eventid,mill) The first parameter eventid Constant needs to be specified pygame.USEREVENT To specify the , And increase at one time ; Make the timer happen by listening to events
  9. pygame There are two ways to capture keyboard keys in : First , Judge event.typepygame.KEYDOWN and event.keypygame.k_RIGHT
    The second way is : Get all key tuples pygame.key.get_press() If pressed , Values for 1

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