如何让实例在玩家周围自动生成? [英] How to make instances spawn automatically around the player?

查看:23
本文介绍了如何让实例在玩家周围自动生成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想让僵尸在玩家周围生成(僵尸的数量应该随着时间的推移而增加).由于我不希望玩家立即死亡,因此我需要僵尸在远离玩家一定距离但除此之外的随机位置生成.

导入pygame进口龟导入时间导入数学随机导入导入系统导入操作系统pygame.init()白色 = (255,255,255)绿色 = (0,255,0)红色 = (255,0,0)蓝色 = (0,0,255)黑色 = (0,0,0)BGColor = (96,128,56)ZColor = (221,194,131)PColor = (0,0,255)移动 = 2.5大小 = (1200, 620)屏幕 = pygame.display.set_mode(size)pygame.display.set_caption("僵尸游戏")类字符(pygame.sprite.Sprite):def __init__(self, color, pos, radius, width):super().__init__()self.image = pygame.Surface([半径*2,半径*2])self.image.fill(白色)self.image.set_colorkey(白色)pygame.draw.circle(self.image,颜色,[半径,半径],半径,宽度)self.rect = self.image.get_rect()def moveRight(自我,像素):self.rect.x += 像素经过def moveLeft(自我,像素):self.rect.x -= 像素经过def moveUp(自我,像素):self.rect.y -= 像素经过def moveDown(自我,像素):self.rect.y += 像素经过类僵尸(pygame.sprite.Sprite):def __init__(self2, color, pos, radius, width):super().__init__()self2.image = pygame.Surface([半径*2,半径*2])self2.image.fill(白色)self2.image.set_colorkey(白色)pygame.draw.circle(self2.image,颜色,[半径,半径],半径,宽度)self2.rect = self2.image.get_rect()def moveRight(self2,像素):self2.rect.x += 像素经过def moveLeft(self2,像素):self2.rect.x -= 像素经过def moveUp(self2, 像素):self2.rect.y -= 像素经过def moveDown(self2,像素):self2.rect.y += 像素经过all_sprites_list = pygame.sprite.Group()playerChar = Char(PColor, [0, 0], 15, 0)playerChar = Char(PColor, [0, 0], 15, 0)playerChar.rect.x = 0playerChar.rect.y = 0all_sprites_list.add(playerChar)随身携带 = 真时钟 = pygame.time.Clock()随身携带:对于 pygame.event.get() 中的事件:如果 event.type==pygame.QUIT:携带=假elif event.type==pygame.KEYDOWN:如果 event.key==pygame.K_x:携带=假键 = pygame.key.get_pressed()如果键[pygame.K_a]:playerChar.moveLeft(移动)如果键[pygame.K_d]:playerChar.moveRight(MOVE)如果键[pygame.K_w]:playerChar.moveUp(MOVE)如果键[pygame.K_s]:playerChar.moveDown(MOVE)屏幕填充(BGColor)screen.blit(playerChar.image,playerChar.rect)pygame.display.flip()时钟滴答(60)pygame.quit()

我还不能尝试任何东西,因为我不知道如何开始.

解决方案

我需要僵尸在距离玩家一定距离处生成.

Zombie类的构造函数中,必须设置属性rect的中心位置:

class Zombie(pygame.sprite.Sprite):def __init__(self2, color, pos, radius, width):super().__init__()self2.image = pygame.Surface([半径*2,半径*2])self2.image.fill(白色)self2.image.set_colorkey(白色)pygame.draw.circle(self2.image,颜色,[半径,半径],半径,宽度)self2.rect = self2.image.get_rect()self2.rect.center = pos # <-------- 添加这个

定义一个包含僵尸的列表(zombie_list),僵尸的大小(半径)zombie_rad.还有一个范围 (zombie_dist) 用于僵尸的生成距离(最小和最大距离)和第一个僵尸出现时的时间跨度(next_zombie_time).

zombie_list = []僵尸_拉德 = 10僵尸距离 = (65, 150)next_zombie_time = pygame.time.get_ticks() + 3000 # 3 秒后第一个僵尸

使用

zombie_list = []僵尸_拉德 = 10僵尸距离 = (65, 150)next_zombie_time = 3000随身携带:对于 pygame.event.get() 中的事件:如果 event.type==pygame.QUIT:携带=假elif event.type==pygame.KEYDOWN:如果 event.key==pygame.K_x:携带=假键 = pygame.key.get_pressed()如果键[pygame.K_a]:playerChar.moveLeft(移动)如果键[pygame.K_d]:playerChar.moveRight(MOVE)如果键[pygame.K_w]:playerChar.moveUp(MOVE)如果键[pygame.K_s]:playerChar.moveDown(MOVE)current_time = pygame.time.get_ticks()如果 current_time >next_zombie_time:next_zombie_time = current_time + 1000 # 1 秒间隔到下一个僵尸on_screen_rect = pygame.Rect(zombie_rad,zombie_rad,大小[0]-2*zombie_rad,大小[1]-2*zombie_rad)zombi_pos = (-1, -1)而不是 on_screen_rect.collidepoint(zombi_pos):dist = random.randint(*zombie_dist)角度 = random.random() * math.pi * 2p_pos = (playerChar.rect.centerx, playerChar.rect.centery)zombi_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_zomby = 僵尸(红色,zombi_pos,zombi_rad,0)僵尸列表.追加(新僵尸)屏幕填充(BGColor)screen.blit(playerChar.image,playerChar.rect)对于zombie_list 中的僵尸:screen.blit(zombie.image,zombie.rect)pygame.display.flip()时钟滴答(60)

So I want to have the Zombies spawn around the player (the number of Zombies should increase as time passes). Since I don't want the player to die instantly I need the Zombies to spawn away from the player at a certain distance but other than that a random location.

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 = (221,194,131)    
PColor = (0,0,255)    

MOVE = 2.5    

size = (1200, 620)    
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 moveRight(self, pixels):    
        self.rect.x += pixels    
        pass    

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

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

    def moveDown(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()    

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

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

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

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


all_sprites_list = pygame.sprite.Group()    

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

all_sprites_list.add(playerChar)    

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

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.moveLeft(MOVE)    
    if keys[pygame.K_d]:    
        playerChar.moveRight(MOVE)    
    if keys[pygame.K_w]:    
        playerChar.moveUp(MOVE)    
    if keys[pygame.K_s]:    
        playerChar.moveDown(MOVE)    

    screen.fill(BGColor)    
    screen.blit(playerChar.image,playerChar.rect)    
    pygame.display.flip()    
    clock.tick(60)    
pygame.quit()    

I couldn't yet try anything because I had no idea how to start.

解决方案

I need the Zombies to spawn away from the player at a certain distance.

In the constructor of the class Zombie the center position of the attribute rect has to be set:

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 # <-------- add this

Define a list which contains the zombies (zombie_list), a size (radius) zombie_rad of the zombie. Further a range (zombie_dist) for spawn distance of the zombies (minimum and maximum distance) and a time span in milliseconds when the first zombie appears (next_zombie_time).

zombie_list = []
zombie_rad = 10   
zombie_dist = (65, 150)
next_zombie_time = pygame.time.get_ticks() + 3000 # first zombie after 3 seconds

Use pygame.time.get_ticks() to get the number of milliseconds since to program start. If the time exceeds next_zombie_time the span a zombie and set the time for the next zombie to spawn:

current_time = pygame.time.get_ticks()
if current_time > next_zombie_time:
    next_zombie_time = current_time + 1000 # 1 second interval to the next zombie

    # [...] spawn the zombie

Create the outer limit rectangle for the zombie position. This rectangle is the screen rectangle reduced by the radius of a zombie on each side. Each position inside this rectangle is a valid center position of a zombie, so that the zombie is completely on in the bounds of the screen.
Use pygame.Rect.collidepoint to check if a position is inside the rectangle. Repeat creating random position until a position inside the rectangle is found:

on_screen_rect = pygame.Rect(zombie_rad, zombie_rad, size[0]-2*zombie_rad, size[1]-2*zombie_rad)
    zombi_pos = (-1, -1)
    while not on_screen_rect.collidepoint(zombi_pos):

        # [...] create random zombie pos 

To get a random position around the player, get an random distance to the player by random.randint(a,b) and a random angle around the player in radiant by random.random() * math.pi * 2:

dist  = random.randint(*zombie_dist)
angle = random.random() * math.pi * 2

Finally calculate the position by converting the Polar coordinate (dist, angle) to a Cartesian coordinate:

p_pos = (playerChar.rect.centerx, playerChar.rect.centery)
zombi_pos = (p_pos[0] + dist * math.sin(angle), p_pos[1] + dist * math.cos(angle))

See the changes to the main loop of the program:

zombie_list = []
zombie_rad = 10   
zombie_dist = (65, 150)
next_zombie_time = 3000

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.moveLeft(MOVE)
    if keys[pygame.K_d]:
        playerChar.moveRight(MOVE)
    if keys[pygame.K_w]:
        playerChar.moveUp(MOVE)
    if keys[pygame.K_s]:
        playerChar.moveDown(MOVE)

    current_time = pygame.time.get_ticks()
    if current_time > next_zombie_time:
        next_zombie_time = current_time + 1000 # 1 second interval to the next zombie

        on_screen_rect = pygame.Rect(zombie_rad, zombie_rad, size[0]-2*zombie_rad, size[1]-2*zombie_rad)
        zombi_pos = (-1, -1)
        while not on_screen_rect.collidepoint(zombi_pos):
            dist  = random.randint(*zombie_dist)
            angle = random.random() * math.pi * 2 
            p_pos = (playerChar.rect.centerx, playerChar.rect.centery)
            zombi_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_zomby = Zombie(RED, zombi_pos, zombie_rad, 0)
        zombie_list.append(new_zomby)

    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)    

这篇关于如何让实例在玩家周围自动生成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆