我正在研究会产生敌人的游戏。尽管一旦生成这些敌人,它们就会立即消失,因为背景被绘制在它们之上。
在Pygame中是否可以使用图层系统?
重新创建问题的代码:
import pygame
import threading
from random import randint
from time import sleep
pygame.init()
window = pygame.display.set_mode((900, 900))
bg=pygame.image.load("Background.png").convert()
def Gameplay():
while True:
window.blit(bg, [0,0])
pygame.display.update()
def spawn_enemy():
enemyW = 50
enemyH = 50
enemyX = 420
enemyY = 850
pygame.draw.rect(window, (93,124,249),(enemyX,enemyY,enemyW, enemyH))
print("an enemy has been spawned")
return True # would be "return enemy" after you create your enemy entity
def EnemySpawn():
enemy_list = [] # to maintain records of all enemies made
while True: # make enemies forever
sleep(randint(1,5))
enemy_list.append(spawn_enemy()) # call our function we made above which spawns enemies
Gameplay = threading.Thread(target=Gameplay)
Gameplay.start()
EnemySpawn = threading.Thread(target=EnemySpawn)
EnemySpawn.start()
答案 0 :(得分:1)
我不理解pygame
,由于某种原因,它在我运行此命令时通常会变得无响应,但是它确实会产生敌人并显示出人们将如何实现一个类来存储其变量(也许是pygame
专家可以对其进行编辑以变得敏感,也可以评论我的代码在做什么,从而使窗口“冻结”:
import pygame
import threading
from random import randint
from time import sleep
import random
pygame.init()
window = pygame.display.set_mode((900, 900))
bg = pygame.image.load("Background.png").convert()
class Enemy:
def __init__(self):
self.W = random.randint(30, 50)
self.H = random.randint(30, 50)
self.X = random.randint(0, 900)
self.Y = random.randint(0, 900)
def Gameplay():
global enemy_list
while True:
window.blit(bg, [0, 0])
for enemy in enemy_list:
pygame.draw.rect(window, (93, 124, 249), (enemy.X, enemy.Y, enemy.W, enemy.H))
pygame.display.update()
def EnemySpawn():
global enemy_list
while True: # make enemies forever
sleep(randint(1, 5))
print("Spawned an enemy")
enemy_list.append(Enemy()) # make an instance of our class
enemy_list = [] # to maintain records of all enemies made
game_thread = threading.Thread(target=Gameplay)
game_thread.start()
enemy_spawner_thread = threading.Thread(target=EnemySpawn)
enemy_spawner_thread.start()
要注意的关键点是在全局空间中使用enemy_list
,然后使用global enemy_list
将其调用为函数,以便它们访问相同的列表对象。该类基本上执行您在函数中所做的相同的操作,但是为敌人提供随机的生成点。正如@Rabbid指出的那样,您需要在绘制背景的代码的同一部分绘制敌人。
P.S。您不应该使用Gameplay = threading.Thread(target=Gameplay)
,因为这会覆盖您的函数。我在代码中为线程实现了另一个变量