我目前正在使用pygame编写游戏代码,但我遇到了将对象作为参数的问题。所以,1)我有一个对象类,2)一个函数,它接受一个对象和一个整数,并将该对象追加到一个X次数,其中X等于整数,然后该函数返回该数组,3)运行初始化对象的函数。
这些部分中的每一个都在不同的文件中。他们每个都导入pygame和3)导入1)和2)
1)文件:对象
import pygame
class Obstacle(pygame.sprite.Sprite):
def __init__(self, screen, settings):
# Initialize the lander
#make the lander a sprite
pygame.sprite.Sprite.__init__(self)
#Keep local copy of screen
self.screen = screen
self.image = pygame.image.load('lander.png')
self.imageCopy = self.image.copy()
self.rect = self.image.get_rect()
#Start with each new lander at the top of the screen
self.rect.centerx = random.randint(50, settings.screen_width - 50)
self.rect.centery = 0
2)文件:GameMethods
import pygame
def random_array(number_needed, object):
#Takes in the number of objects to be created in an array
#and returns that new array
#Use: to make an array that holds randomly located objects
number_assigned = 0
array = []
while number_assigned < number_needed:
array.append(object)
number_assigned += 1
return array
3)文件:主要
from Objects import Obstacles
import GameMethods as gm
def run_game():
"""Main function to start game and run top-level loop"""
# Initialize pygame, settings and screen object.
pygame.init()
....
some unrelated code
....
number_of_fixed_Obstacles_needed = 5
fixed_Obstacles_array = gm.random_array(number_of_fixed_Obstacles_needed, fixedObstacle(screen, settings)
3)当我调用gm.random_array时出现问题。我不是100%肯定,但当我将fixedObstacle作为参数调用时,它将获取对象的实例或内存引用并附加相同的障碍5次。我试图让它为数组附加5个不同的障碍物。
如果我把它放在run函数中,它可以正常工作
number_of_Obstacles_assigned = 0
Obstacles_array = []
while number_of_Obstacles_assigned < number_of_Obstacles_needed:
Obstacles_array.append(fixedObstacle(screen, settings)
number_of_Obstacles_assigned += 1
PS。我正在尝试创建一个函数,因为我有许多Object类要附加到不同的数组,所以调用gm.random_array(number,object)要比调用while循环快得多,它也使代码更多面向对象的。
答案 0 :(得分:0)
[REWRITED]最后了解你的问题。您需要使用不同的类名创建不同的对象。因此,将创建者作为函数参数之一传递:
import pygame
def random_array(number_needed, Creator, screen, settings):
#Takes in the number of objects to be created in an array
#and returns that new array
#Use: to make an array that holds randomly located objects
number_assigned = 0
array = []
while number_assigned < number_needed:
array.append(Creator(screen, settings))
number_assigned += 1
return array
然后在Main
:
fixed_obstacles1_array = gm.random_array(number_obstacles1, Obstacle1, screen, settings)
fixed_obstacles2_array = gm.random_array(number_obstacles2, Obstacle2, screen, settings)
...
最后,如果你想
,你可以连接这些数组all_obstacles = fixed_obstacles1_array + fixed_obstacles2_array
甚至更加面向对象的方式:
all_obstacles = []
disered_obstacles = [Obstacle1, Obstacle2, ObstacleN]
numbers_needed = [42, 3, 17]
for obstacle, number in zip(disered_obstacles, numbers_needed):
all_obstacles += gm.random_array(number, obstacle, screen, settings)
现在你有一个很好的阵列,有各种障碍。