0

因此,我按照 StackOverflow 上另一个问题的答案进行了回答,但似乎我错过了一些东西。阅读完答案后,我继续复制代码并将其调整为我的变量和类名。

以下是 Idle 给我的错误代码:

Traceback (most recent call last):
  File "D:\Programme (x86)\Python\Games\Zombie Game\Zombie Game_Test1.py", line 133, in <module>
  Zombie.move_towards_Char(Char)
TypeError: move_towards_Char() missing 1 required positional argument: 'Char'

这是我看的地方: 如何让敌人在pygame中跟随玩家?

import pygame
import turtle
import time
import math
import random
import sys
import os
pygame.init()

WHITE = (255,255,255)
GREEN = (0,255,0)
RED = (255,0,0)
BLUE = (0,0,255)
BLACK = (0,0,0)

BGColor = (96,128,56)
ZColor = (225,0,0)
PColor = (0,0,255)

MOVE = 2.5

size = (1920, 1080)

screen = pygame.display.set_mode(size)
pygame.display.set_caption("Zombie Game")

class Char(pygame.sprite.Sprite):
    def __init__(self, color, pos, radius, width):
        super().__init__()
        self.image = pygame.Surface([radius*2, radius*2])
        self.image.fill(WHITE)
        self.image.set_colorkey(WHITE)
        pygame.draw.circle(self.image, color, [radius, radius], radius, width)
        self.rect = self.image.get_rect()

    def moveRightP(self, pixels):
        self.rect.x += pixels
        pass

    def moveLeftP(self, pixels):
        self.rect.x -= pixels
        pass

    def moveUpP(self, pixels):
        self.rect.y -= pixels
        pass

    def moveDownP(self, pixels):
        self.rect.y += pixels
        pass


class Zombie(pygame.sprite.Sprite):
    def __init__(self2, color, pos, radius, width):
        super().__init__()
        self2.image = pygame.Surface([radius*2, radius*2])
        self2.image.fill(WHITE)
        self2.image.set_colorkey(WHITE)
        pygame.draw.circle(self2.image, color, [radius, radius], radius, width)
        self2.rect = self2.image.get_rect()
        self2.rect.center = pos

    def move_towards_Char(self2, Char):
        dx, dy = self2.rect.x - Char.rect.x, self2.rect.y - Char.rect.y
        dist = math.hypot(dx, dy)
        dx, dy = dx / dist, dy / dist
        self2.rect.x += dx * self2.speed
        self2.rect.y += dy * self2.speed


    def moveRightZ(self2, pixels):
        self2.rect.x += pixels
        pass

    def moveLeftZ(self2, pixels):
        self2.rect.x -= pixels
        pass

    def moveUpZ(self2, pixels):
        self2.rect.y -= pixels
        pass

    def moveDownZ(self2, pixels):
        self2.rect.y += pixels
        pass


all_sprites_list = pygame.sprite.Group()

playerChar = Char(PColor, [0, 0], 15, 0)
playerChar.rect.x = 960
playerChar.rect.y = 505

all_sprites_list.add(playerChar)

carryOn = True
clock = pygame.time.Clock()

zombie_list = []
zombie_rad = 15   
zombie_dist = (200, 900)
next_zombie_time = pygame.time.get_ticks() + 10000

zombie_list = []
zombie_rad = 15   
zombie_dist = (200, 900)
next_zombie_time = 10000

while carryOn:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            carryOn=False
        elif event.type==pygame.KEYDOWN:
            if event.key==pygame.K_x:
                carryOn=False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_a]:
        playerChar.moveLeftP(MOVE)
    if keys[pygame.K_d]:
        playerChar.moveRightP(MOVE)
    if keys[pygame.K_w]:
        playerChar.moveUpP(MOVE)
    if keys[pygame.K_s]:
        playerChar.moveDownP(MOVE)

    current_time = pygame.time.get_ticks()
    if current_time > next_zombie_time:
        next_zombie_time = current_time + 2000

        on_screen_rect = pygame.Rect(zombie_rad, zombie_rad, size[0]-2*zombie_rad, size[1]-2*zombie_rad)
        zombie_pos = (-1, -1)
        while not on_screen_rect.collidepoint(zombie_pos):
            dist  = random.randint(*zombie_dist)
            angle = random.random() * math.pi * 2 
            p_pos = (playerChar.rect.centerx, playerChar.rect.centery)
            zombie_pos = (p_pos[0] + dist * math.sin(angle), p_pos[1] + dist * math.cos(angle))

        new_pos = (random.randrange(0, size[0]), random.randrange(0, size[1]))
        new_zombie = Zombie(RED, zombie_pos, zombie_rad, 0)
        zombie_list.append(new_zombie)

    screen.fill(BGColor)    
    screen.blit(playerChar.image,playerChar.rect)   
    for zombie in zombie_list:
        screen.blit(zombie.image,zombie.rect)      

    pygame.display.flip()    
    clock.tick(60)    
pygame.quit()
4

2 回答 2

1

主要问题是,您使用整数数据类型进行僵尸移动计算。如果僵尸的移动是 1 个像素并且移动是对角线,那么移动的 x 和 y 分量小于 1。使用整数数据类型,这可能会导致 0 移动,因为截断为int。注意 的成员pygame.Rect是整数值。

您必须切换到浮点值才能解决问题。用于pygame.math.Vector2进行计算。

pos将类型的成员添加到存储僵尸浮点位置的Vector2类中:Zombie

class Zombie(pygame.sprite.Sprite):

    def __init__(self2, color, pos, radius, width):
        super().__init__()
        self2.image = pygame.Surface([radius*2, radius*2])
        self2.image.fill(WHITE)
        self2.image.set_colorkey(WHITE)
        pygame.draw.circle(self2.image, color, [radius, radius], radius, width)
        self2.rect = self2.image.get_rect() 
        self2.speed = 1
        self2.pos = pygame.Vector2(pos[0], pos[1])

    # [...]

draw向该类添加一个新方法,该方法在该位置Zombie绘制 ( blit) 一个僵尸pos

class Zombie(pygame.sprite.Sprite):

    # [...]

    def draw(self2):
        self2.rect.center = (int(round(self2.pos.x)), int(round(self2.pos.y)))
        screen.blit(self2.image, self2.rect)  

根据 计算僵尸的运动Vector2。确保玩家与僵尸之间的距离大于 0,并且僵尸不会跨过玩家的位置(min(len, self2.speed)):

class Zombie(pygame.sprite.Sprite):

    # [...]

    def move_towards_Char(self2, Char):
        deltaVec = pygame.Vector2(Char.rect.center) - self2.pos
        len = deltaVec.length()
        if len > 0:
            self2.pos += deltaVec/len * min(len, self2.speed)

在应用程序的主循环中为每个僵尸调用方法move_towards_Char和:draw

while carryOn:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            carryOn=False
        elif event.type==pygame.KEYDOWN:
            if event.key==pygame.K_x:
                carryOn=False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_a]:
        playerChar.moveLeftP(MOVE)
    if keys[pygame.K_d]:
        playerChar.moveRightP(MOVE)
    if keys[pygame.K_w]:
        playerChar.moveUpP(MOVE)
    if keys[pygame.K_s]:
        playerChar.moveDownP(MOVE)

    current_time = pygame.time.get_ticks()
    if current_time > next_zombie_time:
        next_zombie_time = current_time + 2000

        on_screen_rect = pygame.Rect(zombie_rad, zombie_rad, size[0]-2*zombie_rad, size[1]-2*zombie_rad)
        zombie_pos = (-1, -1)
        while not on_screen_rect.collidepoint(zombie_pos):
            dist  = random.randint(*zombie_dist)
            angle = random.random() * math.pi * 2 
            p_pos = (playerChar.rect.centerx, playerChar.rect.centery)
            zombie_pos = (p_pos[0] + dist * math.sin(angle), p_pos[1] + dist * math.cos(angle))

        new_pos = (random.randrange(0, size[0]), random.randrange(0, size[1]))
        new_zombie = Zombie(RED, zombie_pos, zombie_rad, 0)
        zombie_list.append(new_zombie)

    # update all the positions of the zombies
    for zombie in zombie_list:
        zombie.move_towards_Char(playerChar)

    screen.fill(BGColor)
    screen.blit(playerChar.image,playerChar.rect)

    # draw all the zombies
    for zombie in zombie_list:
        zombie.draw()

    pygame.display.flip()
    clock.tick(60)

于 2019-02-22T20:02:06.800 回答
1

L{Zombie.move_towards_Char} 是一个自我方法。您需要创建 Zombie 类的对象,并传递 L{Zombie. 初始化}。

如下所示:

zm = Zombie(color=<color>, pos=<pos>, radius=<radius>, width=<width>)
zm.move_towards_Char(Char)
于 2019-02-17T18:01:29.337 回答