【发布时间】:2021-09-20 01:41:07
【问题描述】:
我正在尝试使用 Python 编写游戏,但它一直显示错误“TypeError: update() 需要 1 个位置参数,但给出了 2 个”。我已经检查了多个论坛,包括 stackoverflow 多次,但他们都说当我们忘记“自我”参数时会发生错误。但是,这不是我的情况。
下面,你可以看到我的tiles.py 文件。它显示了Tile 类。
import pygame
class Tile(pygame.sprite.Sprite):
def __init__(self,pos,size):
super().__init__()
self.image = pygame.Surface((size,size))
self.image.fill('grey')
self.rect = self.image.get_rect(topleft = pos)
def update(self,x_shift):
self.rect.x += x_shift
如您所见,__init__() 和 update() 函数都有 self 参数。当我在level.py 中运行更新部分时:
import pygame
from tiles import Tile
from settings import tile_size
from player import Player
class Level:
def __init__(self,level_data,surface):
self.display_surface = surface
self.setup_level(level_data)
self.world_shift = 0
def setup_level(self,layout):
self.tiles = pygame.sprite.Group()
self.player = pygame.sprite.GroupSingle()
for row_index,row in enumerate(layout):
for col_index,cell in enumerate(row):
x = col_index * tile_size
y = row_index * tile_size
if cell == 'X':
tile = Tile((x,y),tile_size)
self.tiles.add(tile)
if cell == 'P':
player_sprite = Player((x,y))
self.tiles.add(player_sprite)
def run(self):
#level tiles
self.tiles.update(self.world_shift)
self.tiles.draw(self.display_surface)
#player
self.player.update()
self.player.draw(self.display_surface)
run 函数的self.tiles.update(self.world_shift),如您所见,其中也有一个参数,即x_shift 参数。但是,当我在 main.py 文件中运行 run 函数时:
import pygame, sys
from settings import *
from level import Level
#Setup
pygame.init()
screen = pygame.display.set_mode((screen_width,screen_height))
clock = pygame.time.Clock()
level = Level(level_map,screen)
pygame.display.set_caption('Pirates Run')
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill('black')
level.run()
pygame.display.update()
clock.tick(60)
当我运行代码时,我得到的唯一输出是一个黑屏,它出现了不到一秒钟然后关闭,然后出现如下错误:
Traceback (most recent call last):
File "c:\Users\User\OneDrive\Desktop\Blazel\Pirates Run\code\main.py", line 19, in <module>
level.run()
File "c:\Users\User\OneDrive\Desktop\Blazel\Pirates Run\code\level.py", line 26, in run
self.tiles.update(self.world_shift)
File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-
packages\pygame\sprite.py", line 531, in update
sprite.update(*args, **kwargs)
TypeError: update() takes 1 positional argument but 2 were given
请帮我解决这个问题!谢谢!
【问题讨论】:
-
self.tiles是pygame.sprite.Group(),而不是Tile的实例。 -
那么我应该在我的代码中做什么/编辑以使其工作? @martineau
-
@Rabbid76:我知道这个问题比我提到的要多。即将注销并且没有时间写出像您这样的正确答案 - 所以只是想至少给 OP 一个提示。