pygame制作飞机大战2——pygame基础知识

如果使用过scratch的话,相信对于pygame制作游戏的内在逻辑就很容易理解了。

pygame是一个python3自带的库,能够帮我们非常简便的制作各类2D游戏或者3D(嗯哼),它包含了游戏化涉及到的基本操作,例如:键盘控制、鼠标控制、窗口设置、图像移动、帧......

而要制作一个简单的游戏,就需要知道pygame实现一个游戏的最简程序,python的最简程序包括以下部分:

(1)导入函数

(2)参数初始化

  • 背景图
  • 被控制的控件图

(3)加载并转化图像

(4)窗口参数设定

(5)初始化pygame

(6)游戏主循环

 

下面分别说下几个部分:

(1)导入函数

import pygame
from pygame.locals import *
from sys import exit
  • 导入pygame模块
  • pygame.local,python中常用的常量
  • exit,退出python程序

(2)参数初始化

background_image_filename = 'sea.jpg'
mouse_image_filename = 'nemo.png'

初始化需要用到的背景图片、操作的控件图片

(3)加载并转化图像/(4)创建窗口及标题

#加载并转换图像
background = pygame.image.load(background_image_filename)
mouse_cursor = pygame.image.load(mouse_image_filename)

#创建窗口及标题
screen = pygame.display.set_mode((500, 375), 0, 32)
pygame.display.set_caption("hello world")

和第五步不冲突,建好窗口,加载好后续需要的图片资源,功能参数具体设定参考文末附页

(5)初始化pygame

pygame.init()

为硬件使用作准备

(6)游戏主循环

#游戏主循环
while True:
    # 检测退出事件,判断是否执行退出
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()

    #将背景画上去
    screen.blit(background, (0, 0))

    #获取按键状态
    press = pygame.key.get_pressed()

    if press[K_LEFT] == True:
        x1 = x1 - 2
    elif press[K_RIGHT] == True:
        x1 = x1 + 2
    elif press[K_UP] == True:
        y1 = y1 - 2
    elif press[K_DOWN] == True:
        y1 = y1 + 2
    # 获取鼠标位置
    #x, y = pygame.mouse.get_pos()
    #计算光标在左上角的位置
    #x -= mouse_cursor.get_width() / 2
    #y -= mouse_cursor.get_height() / 2

    #将光标画上去
    screen.blit(mouse_cursor, (x1, y1))
    # 在新的位置上画图
    pygame.display.update()

包括:

  1. 检测退出事件:例如:当关闭窗口时,event.type关键字变为QUIT,此时退出程序
  2. 将加载好的背景图画到窗口中去
  3. 获取按键状态,并根据每按一次对应的键,控件(nemo)移动两步(PS:这里也可以改成鼠标控制,替换成下面的注释内容即可)
  4. 将更新后的光标位置画到指定的坐标(以此实现不断更新控件位置)
  5. 承接上一步,将绘制的东西画到屏幕(窗口)上

完整代码:

#参数初始化
background_image_filename = 'sea.jpg'
mouse_image_filename = 'nemo.png'
x1 = 0
y1 = 0

#导入函数
import pygame
from pygame.locals import *
from sys import exit

#加载并转换图像
background = pygame.image.load(background_image_filename)
mouse_cursor = pygame.image.load(mouse_image_filename)

#创建窗口及标题
screen = pygame.display.set_mode((500, 375), 0, 32)
pygame.display.set_caption("hello world")

#初始化pygame,为硬件使用作准备
pygame.init()

#游戏主循环
while True:
    # 检测退出事件,判断是否执行退出
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()

    #将背景画上去
    screen.blit(background, (0, 0))

    #获取按键状态
    press = pygame.key.get_pressed()

    if press[K_LEFT] == True:
        x1 = x1 - 2
    elif press[K_RIGHT] == True:
        x1 = x1 + 2
    elif press[K_UP] == True:
        y1 = y1 - 2
    elif press[K_DOWN] == True:
        y1 = y1 + 2
    # 获取鼠标位置
    #x, y = pygame.mouse.get_pos()
    #计算光标在左上角的位置
    #x -= mouse_cursor.get_width() / 2
    #y -= mouse_cursor.get_height() / 2

    #将光标画上去
    screen.blit(mouse_cursor, (x1, y1))
    # 在新的位置上画图
    pygame.display.update()

附页(相关功能):

pygame.display:https://blog.csdn.net/qq_41556318/article/details/85952413

pygame.key:https://blog.csdn.net/qq_41556318/article/details/86304649

pygame.mouse:https://blog.csdn.net/qq_41556318/article/details/86304810

参考网站:

pygame官网:https://www.pygame.org/docs/

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这里是一个简单的Pygame飞机大战游戏示例: ```python import pygame import random # 初始化 Pygame pygame.init() # 创建游戏窗口 screen_width = 480 screen_height = 700 screen = pygame.display.set_mode((screen_width, screen_height)) # 设置游戏标题 pygame.display.set_caption("飞机大战") # 加载背景图片 background = pygame.image.load("images/background.png").convert() # 加载游戏音效 pygame.mixer.music.load("sound/game_music.ogg") pygame.mixer.music.set_volume(0.2) pygame.mixer.music.play(-1) bullet_sound = pygame.mixer.Sound("sound/bullet.wav") bullet_sound.set_volume(0.2) enemy_down_sound = pygame.mixer.Sound("sound/enemy_down.wav") enemy_down_sound.set_volume(0.2) game_over_sound = pygame.mixer.Sound("sound/game_over.wav") game_over_sound.set_volume(0.2) # 加载玩家飞机图片 player_image = pygame.image.load("images/player.png").convert_alpha() # 加载子弹图片 bullet_image = pygame.image.load("images/bullet.png").convert_alpha() # 加载敌机图片 enemy_images = [ pygame.image.load("images/enemy1.png").convert_alpha(), pygame.image.load("images/enemy2.png").convert_alpha(), pygame.image.load("images/enemy3.png").convert_alpha(), ] # 定义玩家飞机类 class Player(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = player_image self.rect = self.image.get_rect() self.rect.midbottom = (screen_width // 2, screen_height - 30) self.speed = 8 self.bullets = pygame.sprite.Group() def update(self, keys): if keys[pygame.K_LEFT] and self.rect.left > 0: self.rect.x -= self.speed if keys[pygame.K_RIGHT] and self.rect.right < screen_width: self.rect.x += self.speed def shoot(self): bullet = Bullet(self.rect.centerx, self.rect.top) self.bullets.add(bullet) bullet_sound.play() # 定义子弹类 class Bullet(pygame.sprite.Sprite): def __init__(self, x, y): super().__init__() self.image = bullet_image self.rect = self.image.get_rect() self.rect.centerx = x self.rect.bottom = y self.speed = -10 def update(self): self.rect.y += self.speed if self.rect.bottom < 0: self.kill() # 定义敌机类 class Enemy(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = random.choice(enemy_images) self.rect = self.image.get_rect() self.rect.x = random.randint(0, screen_width - self.rect.width) self.rect.y = random.randint(-200, -50) self.speed = random.randint(1, 4) self.health = 1 def update(self): self.rect.y += self.speed if self.rect.top > screen_height: self.kill() # 创建游戏对象 player = Player() enemies = pygame.sprite.Group() all_sprites = pygame.sprite.Group() all_sprites.add(player) # 设置游戏主循环 clock = pygame.time.Clock() score = 0 game_over = False while not game_over: clock.tick(60) # 处理事件 for event in pygame.event.get(): if event.type == pygame.QUIT: game_over = True # 检测玩家按键 keys = pygame.key.get_pressed() if keys[pygame.K_SPACE]: player.shoot() # 更新玩家和子弹 player.update(keys) player.bullets.update() # 检测子弹和敌机碰撞 for bullet in player.bullets: enemies_hit = pygame.sprite.spritecollide(bullet, enemies, True) for enemy in enemies_hit: enemy_down_sound.play() score += 100 bullet.kill() # 更新敌机 if random.randint(1, 30) == 1: enemy = Enemy() enemies.add(enemy) all_sprites.add(enemy) enemies.update() # 检测玩家与敌机碰撞 if pygame.sprite.spritecollide(player, enemies, True): game_over_sound.play() game_over = True # 绘制游戏界面 screen.blit(background, (0, 0)) all_sprites.draw(screen) # 显示得分 font = pygame.font.SysFont(None, 36) score_text = font.render("得分: {}".format(score), True, (255, 255, 255)) screen.blit(score_text, (10, 10)) # 更新屏幕 pygame.display.update() # 游戏结束 pygame.quit() ``` 你可以在代码中看到,程序使用了 Pygame 绘图模块来创建游戏窗口、加载图片和播放音效。游戏中有三个主要的类:Player、Bullet和Enemy。其中,Player类表示玩家飞机,Bullet类表示子弹,Enemy类表示敌机。游戏主循环中,程序不断更新玩家和子弹位置,检测子弹和敌机碰撞,更新敌机位置,检测玩家与敌机碰撞,绘制游戏界面,并在游戏结束时退出 Pygame
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值