gpt4 book ai didi

python - 敌人角色被游戏背景 overdraw

转载 作者:太空宇宙 更新时间:2023-11-04 04:10:56 25 4
gpt4 key购买 nike

我正在开发一款生成敌人的游戏。尽管一旦生成这些敌人,它们就会立即再次消失,因为背景是在它们之上绘制的。

有没有办法在 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()

最佳答案

我不明白 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 指出的那样,您需要在绘制背景的代码的同一部分中绘制敌人。

附言你不应该使用 Gameplay = threading.Thread(target=Gameplay) 因为这会覆盖你的函数。我在我的代码中为线程实现了一个不同的变量

关于python - 敌人角色被游戏背景 overdraw ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56280392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com