Pygame - 在给定区域随机产生物体

时间:2018-01-12 02:20:28

标签: python python-3.x pygame

所以我目前正计划制作一个相对基本的游戏,让敌人朝着玩家的“基地”方向前进,这个游戏将直接位于屏幕的中心。我正在努力寻找一种方法,我可以从屏幕的四周产生这些敌人,但只能在边缘。下面是我为敌人精灵创建的基本类,以及我尝试在屏幕外部的位置生成它们的尝试。在大多数情况下它是有效的,除了它永远不会在我的屏幕的底部外部产生任何精灵,因为我不确定如何使Y坐标在0,80之间或600,680之间的随机数。此外,这似乎不是分配X和Y值的最有效方式。非常感谢任何建议或帮助。我使用的屏幕尺寸是800x680,谢谢。

class Enemy(pygame.sprite.Sprite):
def __init__(self,x,y):
    pygame.sprite.Sprite.__init__(self)
    self.image = pygame.Surface((15,15))
    self.image.fill(RED)
    self.rect = self.image.get_rect()
    self.rect.x = x
    self.rect.y = y

all_sprites = pygame.sprite.Group()
mobs = pygame.sprite.Group()
for i in range (10):
    x = random.randint(0,800)
    if x < 100 or x > 700:
        y = random.randint(0,680)
    else:
        y = random.randint(0,80)
    m = Enemy(x,y)
    all_sprites.add(m)
    mobs.add(m)

3 个答案:

答案 0 :(得分:1)

你可以创建一个边的列表(作为字符串),用random.choice选择一个,然后根据所选的边分配坐标。

sides = ['top', 'bottom', 'left', 'right']
while True:
side = random.choice(sides)

if side == 'top':
    y = 0
    x = random.randrange(screen_width-4)
# etc.

然而,存在问题,因为较短边缘的密度会更高。如果要沿所有边缘随机分布对象,可以使用random.choices(Python 3.6+中提供),根据权重进行选择。只需将边长作为weights参数传递即可。这是一个简短的例子(我只是画红色的):

import random
import pygame as pg

pg.init()
RED = pg.Color('red')
screen = pg.display.set_mode((800, 400))
width, height = screen.get_size()
clock = pg.time.Clock()
done = False

sides = ['top', 'bottom', 'left', 'right']
weights = [width, width, height, height]

while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True

    side = random.choices(sides, weights)[0]

    if side == 'top':
        y = 0
        x = random.randrange(width-4)
    elif side == 'bottom':
        y = height-4
        x = random.randrange(width-4)
    elif side == 'left':
        x = 0
        y = random.randrange(height-4)
    elif side == 'right':
        x = width-4
        y = random.randrange(height-4)

    pg.draw.rect(screen, RED, (x, y, 4, 4))
    pg.display.flip()
    clock.tick(30)

答案 1 :(得分:0)

你可以让randint决定是否将敌人置于顶部或底部:

for i in range (10):
   x = random.randint(0,800)
   if x < 100 or x > 700:
       y = random.randint(0,680)
   else:
       bot_top = random.randint(0,1)
       if(bot_top == 0):
          y = random.randint(0,80)
       else:
          y = random.randint(600,680)
   m = Enemy(x,y)
   all_sprites.add(m)
   mobs.add(m)

答案 2 :(得分:0)

但是当我结合我的代码执行该代码时,它永远不会停止更新,直到我停止移动鼠标

import pygame as py
import random as ra


py.init()

RED = py.Color(255,0,0)
sw = 800
sh = 400
Screen = py.display.set_mode((sw, sh))
width, height = Screen.get_size()
clock = py.time.Clock()
done = False

Sides = ["top","bottom","left","right"]
Weights = [width,width,height,height]

py.display.set_caption("Spaceship")
icon = py.image.load('battleship.png')
py.display.set_icon(icon)

playerX = 400
playerY = 200
playerx_Change = 0
playery_Change = 0

enemyimg = py.image.load("meteor.png")

def Player(x,y):
    Screen.blit(icon, (x, y))
def Enemy(x,y):
    Screen.blit(enemyimg, (x, y))


running = True
while running or not done:

    for event in py.event.get():


        if event.type == py.QUIT :
            running = False
            done = True

        side = ra.choices(Sides, Weights)[0]

        if side == "top":
            y = 0
            x = ra.randrange(width-4)
        elif side == "bottom":
            y = height -4
            x = ra.randrange(width-4)
        elif side == "left":
            y = 0
            x = ra.randrange(height-4)
        elif side == "right":
            y = width-4
            x = ra.randrange(height-4)


        if event.type == py.KEYDOWN:
            if event.key == py.K_UP:
                playery_Change = -1
            if event.key == py.K_DOWN:
                playery_Change = 1
            if event.key == py.K_LEFT:
                print("La tecla izquierda se ha activado")
                playerx_Change = -1
            if event.key == py.K_RIGHT:
                playerx_Change = 1
                print("La tecla derecha se ha accionado")
        if event.type == py.KEYUP:
            if event.key == py.K_LEFT or event.key == py.K_RIGHT:
                playerx_Change = 0
            if event.key == py.K_DOWN or event.key == py.K_UP:
                playery_Change = 0


    Screen.fill((40,40,50))

    playerX += playerx_Change
    playerY += playery_Change

    if playerX <=0:
        playerX = 0
    if playerX >= sw -30:
        playerX = sw -30
    if playerY <=0:
        playerY=0
    if playerY >= sh -30:
        playerY = sh - 30


    Player(playerX,playerY)

    py.draw.rect(Screen, RED, (x, y, 4, 4))
    py.display.flip()
    clock.tick(30)
    py.display.update()