import pygame
pygame.init()
width, height = 1000, 700
window = pygame.display.set_mode((width, height))
class Player:
def __init__(self, x, y):
self.pos_x = x
self.pos_y = y
self.width, height = 1000, 700
self.window = pygame.display.set_mode((width, height))
def player_init(self):
sprite = pygame.image.load("Character Sprite.png")
self.window.blit(sprite, (self.pos_x, self.pos_y))
while 1:
Player.player_init(500-38, 350-49)
我一直在四处寻找,但我似乎无法找到解决这种类型错误的原因
每当我创建一个类时,TypeError:必须使用
player_init()
实例作为第一个参数调用未绑定方法Player
(而不是int
实例)
就会一直弹出。
答案 0 :(得分:0)
您需要执行Player(x, y).player_init()
因为player_init
还需要self
参数,该参数也使用__init__
中指定的变量。您还使用2个参数调用player_init
,但它只接受一个。
答案 1 :(得分:0)
首先(在while
之前)创建具有预期参数的类Player
的实例
player = Player(500-38, 350-49)
以后再使用它(但没有参数)
player.player_init()
但对我来说,你的代码看起来应该是这样的
import pygame
# --- constants --- (UPPER_CASE names)
WIDTH = 1000
HEIGHT = 700
# --- classes --- (CamelCase names)
class Player:
# <- empty line to make code more readable
def __init__(self, x, y):
self.image = pygame.image.load("Character Sprite.png")
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
def draw(self, surface):
surface.blit(self.image, self.rect)
# --- functions --- (lower_case names)
# empty
# --- main ---
# - init -
pygame.init()
window = pygame.display.set_mode((WIDTH, HEIGHT))
# - objects -
player = Player(500-38, 350-49)
# - mainloop -
while True:
# other code
player.draw(window)
self.rect
对于设置位置非常有用,即。 self.rect.center
它具有检查冲突的功能。 player.rect.collidrect(enemy.rect)
或player.rect.collidpoint(mouse_pos)
有用的课程pygame.spripte.Group()
期望self.rect
和self.image
自动绘制所有精灵。
答案 2 :(得分:0)
import pygame
# --- constants --- (UPPER_CASE names)
WIDTH = 1000
HEIGHT = 700
# --- classes --- (CamelCase names)
class Player:
def __init__(self, x, y):
self.image = pygame.image.load("Character Sprite.png")
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
def draw(self, surface):
surface.blit(self.image, self.rect)
# --- functions --- (lower_case names)
# empty
# --- main ---
# - init -
pygame.init()
# - objects -
player = Player(500-38, 350-49)
player.draw(pygame.display.set_mode((WIDTH, HEIGHT)))
# - mainloop -
while True:
# other code
pygame.display.flip() # add to out image from display