如何使敌人出现?

时间:2018-11-13 12:42:31

标签: python pygame

当游戏第一次开始时,玩家和敌人都会出现,但是当玩家移动时,敌人就会消失。

import pygame
import os 
import random 
from pygame.locals import * # Constants
import math
import sys
import random

pygame.init()  

screen=pygame.display.set_mode((1280,720)) #(length,height)
screen_rect=screen.get_rect()
background = pygame.Surface(screen.get_size())
background.fill((255,255,255))     # fill the background white 
White = (255,255,255)

screen.blit(background, (0, 0))

class Player(pygame.sprite.Sprite):

def __init__(self):

    self.rect = pygame.draw.rect(screen, (0,0,128), (50,560,50,25)) #(colour)(x-position,y-position,width,height)
    self.dist = 100

def draw_rect(self,x,y):    # This is my code which should make the player move
    screen.blit(background, (0, 0)) #If this isn't included then when the rectangle moves it's old positon will still be on the screen
    self.rect = self.rect.move(x*self.dist, y*self.dist); pygame.draw.rect(screen, (0, 0, 128), self.rect)
    pygame.display.update()

def handle_keys(self): # code to make the character move when the arrow keys are pressed
    keys = pygame.key.get_pressed()
    if keys[K_LEFT]:
        self.draw_rect(-0.05,0)
    elif keys[K_RIGHT]:
        self.draw_rect(0.05,0)
    elif keys[K_UP]:
        self.draw_rect(0,-0.05)
    elif keys[K_DOWN]:
        self.draw_rect(0,0.05)
    elif keys[K_SPACE]:
        self.draw_rect(0.4,-0.9)
    if self.rect.right > 1280:   # These are to stop the player from going out of the boundary
        self.rect.right = 1280
    if self.rect.left < 0:
        self.rect.left = 0
    if self.rect.bottom > 720:
        self.rect.bottom = 720
    if self.rect.top < 0:
        self.rect.top = 0

播放器的运动非常正常。

class Enemy(pygame.sprite.Sprite): # the enemy class which works fine
def __init__(self):
    x = random.randint(50,450)
    self.rect = pygame.draw.rect(screen, (128,0,0), (300,x,50,25))

敌人只是在一个随机的地方生成,并且在玩家四处移动时仍会出现。我试图做点事,但是没用。

clock = pygame.time.Clock()  # A clock to limit the frame rate.
player = Player()
enemy = Enemy()

def main():  #my main loop 
    running = True
    while running:
        player.handle_keys()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
        clock.tick(60)  # Limit the frame rate to 60 FPS.
        pygame.display.flip()   #updates the whole screen

    if __name__ == '__main__': main()

1 个答案:

答案 0 :(得分:1)

这是因为您只绘制了一次敌人Rect:在__init__的{​​{1}}函数中。另外,您需要在Enemy类的不同位置进行大量绘制,例如清除屏幕。停止这样做。

您已经继承了Sprite的子类,因此请按预期使用此类。精灵有一个Playerimage来定义它们的外观和位置,然后将它们添加到Group中,以调用其rect函数并进行绘制它们显示在屏幕上。

您的代码应如下所示:

update