pygame не может порождать врагов - PullRequest
0 голосов
/ 02 августа 2020

Я пытаюсь создать простую игру, в которой вам нужно уворачиваться от врагов (астероидов) с помощью pygame, но теперь у меня проблемы с их созданием, и я не знаю, следует ли мне использовать списки или другие вещи, или класса врага (asteroidClass) достаточно. Интервал между их появлением довольно прост, я просто не знаю, как разобраться с частью спавна (занимаясь этим в течение 3 дней).

import pygame
import random

pygame.init()
#images 
background = pygame.image.load('#path')
asteroid = pygame.image.load('#path')

display = pygame.display.set_mode((300,500))
FPS = 50

display.blit(background,(0,0))
#player everything is fine

#asteroid
class asteroidClass:
    def __init__(self,asteroidX,asteroidY,asteroidVel):
        self.x = asteroidX
        self.y = asteroidY
        self.vel = asteroidVel
    def asteroid_advancing(self):
        self.y += self.vel
        display.blit(asteroid, (self.x, self.y))

def update():
    pygame.display.update()
    pygame.time.Clock().tick(FPS)

#variables
asteroidX = random.randint(0,250)
asteroidY, asteroidVel = 0, 2
asteroidOutClass = asteroidClass(asteroidX,asteroidY,asteroidVel)



#main loop
run = True
while run:
    #should spawn multiple I don't know with what logic
    #spawning in the same x
    #saw in web they're using lists, maybe i should too?
    #when i print i it just do 0123456 like it should, then restart to 0123456, is it wrong? kinda 100%
    for i in range(7):
        asteroidOutClass.asteroid_advancing() #everytime it's called should spawn and asteroid in random x?

    update()
    display.blit(background, (0, 0))

1 Ответ

0 голосов
/ 02 августа 2020

Несколько вещей:

  • Создайте астероиды перед основным l oop
  • Используйте метод инициализации для случайной установки положения и скорости астероида
  • Be обязательно вызовите метод события в главном l oop, чтобы предотвратить зависание

Вот обновленный код. Я удалил фоновые вызовы и использовал круг для астероида.

import pygame
import random

pygame.init()
#images pygame.load() not in here

display = pygame.display.set_mode((300,500))
FPS = 50

#display.blit(background,(0,0))
#player everything is fine

#asteroid
class asteroidClass:
    def __init__(self):
        self.x = random.randrange(0, 300)
        self.y = 0 # always top
        self.velx = random.randrange(1,15)/3
        self.vely = random.randrange(1,15)/3
    def asteroid_advancing(self):
        self.y += self.vely
        self.x += self.velx
        # wrap around screen
        if self.x < 0: self.x=300
        if self.x > 300: self.x=0
        if self.y < 0: self.y=500
        if self.y > 500: self.y=0
        pygame.draw.circle(display, (200, 0, 0), (int(self.x), int(self.y)), 20) # draw asteroid

def update():
    pygame.display.update()
    pygame.time.Clock().tick(FPS)

#variables
# create list of 5 asteroids
roidlist = [asteroidClass() for x in range(7)]

#main loop
run = True
while run:
    for event in pygame.event.get(): # required for OS events
      if event.type == pygame.QUIT:
         pygame.quit()
    display.fill((0,0,0))
    #should spawn multiple I don't know with what logic
    #spawning in the same x
    #saw in web they're using lists, maybe i should too?
    #when i print i it just do 0123456 like it should, then restart to 0123456, is it wrong? kinda 100%
    for r in roidlist:
        r.asteroid_advancing() #everytime it's called should spawn and asteroid in random x?

    update()
#    display.blit(background, (0, 0))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...