Ste*_*rks 5 python pygame class
我想制作一个游戏,我的敌人来自屏幕的两侧。现在我有了它,以便敌人一次一个地在屏幕上滚动。我希望一次有更多的人来,慢慢地增加他们遇到的频率。这是我的代码
import pygame, sys, time, random
from pygame.locals import *
pygame.init()
winW = 1000
winH = 600
surface = pygame.display.set_mode ((winW, winH),0,32)
pygame.display.set_caption ('Moving Orc')
class Enemy:
    def __init__(self, char, startY, startX):
        self.char=char
        self.startY=startY
        self.startX=startX
        self.drawChar()
    def drawChar (self):
        self.space = pygame.image.load (self.char)
        self.spaceRect = self.space.get_rect ()
        self.spaceRect.topleft = (self.startX,self.startY)
        self.moveChar()
    def moveChar (self):
        if self.startX == 0:
            self.xMoveAmt = 5
        elif self.startX == 800:
            self.xMoveAmt = -5
        while True:
            surface.fill ((255,255,255))
            self.spaceRect.left += self.xMoveAmt
            surface.blit (self.space, self.spaceRect)
            pygame.display.update()
            time.sleep (0.02)
            if self.spaceRect.right >= winW:
                surface.fill ((255,255,255))
                break
            elif self.spaceRect.left <= 0:
                surface.fill ((255,255,255))
                break
#MAINLINE
while True:
    enemyList=[]
    leftOrRight = random.randint(0,1)
    if leftOrRight == 0:
        leftOrRight = 0
    elif leftOrRight == 1:
        leftOrRight = 800
    enemyList.append(Enemy(("orc.png"), random.randint(50, 500), leftOrRight))
    for i in range (0,len(enemyList)):
        enemyList[i].drawChar()
        break
我有它,所以每次你进入循环时,它都会重置它在我制作的课程中运行的列表。一个人会从左边或右边穿过屏幕。
我什至会从哪里开始?
为了拥有多个敌人,你需要解决一些问题。
简单的 pygame 程序结构是什么样的
init() 
While(True):
    draw()
    update()
    checkInput()
我看到你已经为敌人编写了绘制和移动函数,但他们没有做他们应该做的事情。
您的绘制方法加载图像,并调用移动函数。加载通常应该在__init__().
您的 move 函数会绘制并移动角色,但它有一个 While 循环,这会使其卡住,直到该角色离开屏幕。
解决方案示例:
def draw(self,surface):
    surface.blit (self.space, self.spaceRect)
def move(self):
    self.spaceRect.left += self.xMoveAmt
    if self.spaceRect.right >= winW:
        self.kill()
    elif self.spaceRect.left <= 0:
        self.kill()
杀死对象的一种可能方法是设置一个标志,并在 While 方法中检查是否可以将其从对象列表中删除。
现在您可以创建敌人列表,并调用绘制,并为每个敌人进行更新。在 for 循环中。
| 归档时间: | 
 | 
| 查看次数: | 6231 次 | 
| 最近记录: |