Сделайте несколько классов врагов одинаковыми, но в разных позициях - PullRequest
0 голосов
/ 30 ноября 2018
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,700)) #(length,height)
screen_rect=screen.get_rect()
background = pygame.Surface(screen.get_size())
background.fill((255,255,255))     # fill the background white 
background = pygame.image.load('stage.png').convert()
Black=(0,0,0)

class Player(pygame.sprite.Sprite):
x = 20
y = 615
def __init__(self):
    super().__init__()   # calls the parent class allowing sprite to initalize
    self.image = pygame.Surface((50,25))   # this is used to create a blank image with the size inputted 
    self.image.fill((0,0,128))    # fills the blank image with colour

    self.rect = self.image.get_rect(topleft =(20,615))   # This place the player at the given position   

    self.dist = 10

def update(self): # code to make the character move when the arrow keys are pressed
    if self.rect.right > 100:   # These are to make the player so move constantly
         self.rect.y += 1
         self.rect.x += 2
    if self.rect.bottom == 700:
         pygame.quit() 

    keys = pygame.key.get_pressed()
    if keys[K_LEFT]:
        self.rect.move_ip(-1,0)
    elif keys[K_RIGHT]:
        self.rect.move_ip(0.5,0)
    elif keys[K_UP]:
        self.rect.move_ip(0,-0.5)
    elif keys[K_DOWN]:
        self.rect.move_ip(0,1)
    self.rect.clamp_ip(screen_rect)
    #while self.rect == (20,615):
    if keys [K_SPACE]:
        self.rect = self.image.get_rect(topleft =(100,100))

class Enemy(pygame.sprite.Sprite): # the enemy class which works fine
def __init__(self):
    super().__init__()
    #y = random.randint(300,1200)
    x = random.randint(50,450)
    self.image = pygame.Surface((50,25))
    self.image.fill((128,0,0))
    self.rect = self.image.get_rect(topleft=(300, 50))

def update(self):
    if self.rect.bottom <= 400:
        self.rect.y += 1
    if self.rect.bottom >= 400:
         self.rect.y -= 300

В этой части я получил так, что класс противника движется вниз, а когда он достигает 400, он телепортируется на 300 вверх, но я хотел, чтобы он постоянно двигался вверх, а затем снова вниз.

Я думалчто я либо отменяю движение вниз, когда оно достигает позиции, но я не думаю, что вы можете сделать это.

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

enemy = Enemy()


enemy_list = pygame.sprite.Group(enemy)
#enemy_list.add(enemy)
sprites = pygame.sprite.Group(player, enemy)


def main():  #my main loop 
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    sprites.update()
    screen.blit(background, (0, 0))
    sprites.draw(screen)
    clock.tick(100)  # Limit the frame rate to 60 FPS.
    pygame.display.flip()   #updates the whole screen



#Collison check
    player_hit_list = pygame.sprite.spritecollide(player, enemy_list, True)

    for enemy in player_hit_list:
        pygame.quit()

if __name__ == '__main__': 
main()

1 Ответ

0 голосов
/ 30 ноября 2018

Класс Enemy нуждается в дополнительном атрибуте, который отслеживает направление его движения: вверх или вниз.

Поэтому простое решение может выглядеть следующим образом:

class Enemy(pygame.sprite.Sprite): # the enemy class which works fine
    def __init__(self):
        super().__init__()
        x = random.randint(50,450)
        self.image = pygame.Surface((50,25))
        self.image.fill((128,0,0))
        self.rect = self.image.get_rect(topleft=(300, 50))
        self.direction = 'DOWN'

    def update(self):
        self.rect.y += 1 if self.direction == 'DOWN' else -1  

        if self.rect.bottom >= 400:
            self.direction = 'UP'
        if self.rect.top <= 50:
            self.direction = 'DOWN'
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...