《十九、绘制出病毒并向左移动》练习题答案

这篇博客介绍了一个使用Pygame库编写的简单游戏,玩家需要在医院背景中抗击不断生成的病毒。病毒每0.5秒随机出现在屏幕一侧,并以不同速度向另一侧移动。游戏包含不同类型的病毒图片和 boss 级别的敌人,玩家通过射击来消除病毒。当病毒触碰边界或医生时,游戏结束。博客内容涉及Python编程、游戏设计和图像处理。
摘要由CSDN通过智能技术生成
让病毒0.5秒生成一个。
import pygame
from random import randint,choice
from time import sleep,time
from os import system,remove
from os.path import exists
from pygame.locals import *

pygame.init()   
canvas = pygame.display.set_mode((980,700))
canvas.fill((255,255,255))
pygame.display.set_caption('抗击病毒')

bg = pygame.image.load('images/hospital.jpg')
doctor = pygame.image.load('images/doctor.png')
virus1 = pygame.image.load('images/virus.png')
virus2 = pygame.image.load('images/virus.jpg')
virus3 = pygame.image.load('images/virus.jpeg')
boss1 = pygame.image.load('images/boss1.png')
boss2 = pygame.image.load('images/boss2.png')
lose = pygame.image.load('images/lose.jpg')
bullet = pygame.image.load('images/bullet.png')
win = pygame.image.load('images/win.jpg')
bag1 = pygame.image.load('images/bag.png')

def isActionTime(lastTime,interval):
    if lastTime == 0:
        return True
    currentTime = time()
    return currentTime - lastTime >= interval

def conPaint():
    canvas.blit(bg,(0,0))
    
    for virus in Game.virus:
        virus.paint()

def event():
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            exit()

def conEnter():
    if not isActionTime(Game.lastTime,Game.interval):
        return
    Game.lastTime = time()
    Game.virus.append(Virus())

def conStep():
    for virus in Game.virus:
        virus.step()

def control():
    conPaint()
    event()
    conEnter()
    conStep()
    pygame.display.update()

class Virus():
    def __init__(self):
        self.width = 33  #图片的宽
        self.height = 33 #图片的高
        self.img = choice(Game.virus_imgs) #随机使用病毒的图片
        self.x = 1000 - self.width #X坐标
        self.y = randint(0,700 - self.height) #随机的Y坐标
        self.speed = randint(1,10) #向左飞行的速度
    def paint(self): #绘制
        canvas.blit(self.img,(self.x,self.y))
    def step(self): #移动
        self.x -= self.speed


class Game():
    virus_imgs = [virus1,virus2,virus3]
    virus = []
    lastTime = time()
    interval = 0.5
    
while True:
    control()
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值