Pygame:随机方向?

2024-09-28 20:54:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一款游戏,它的特点是随机生成洞穴。它首先创建一个由16x16块组成的640x480字段。然后放置CaveMaker的3个实例,这些实例会破坏它们所接触的每个块,它们应该每隔几秒改变方向,以产生随机的洞穴状路径,但在我的代码中,它们会变成这样的垃圾:

Eeeewwww

我相信这是因为我写的那些非常即兴的代码会让它改变方向:

class CaveMaker(object):
    def __init__(self):
        self.active=1
        self.x=randrange(1,640)
        self.y=randrange(1,480)
        #Choose a X speed and Y speed
        self.direction=(choice([20,-20,1,-1,15,0,-15]),choice([20,-20,1,-1,15,0,-15]))
        self.rect=pygame.Rect(self.x,self.y,75,75)
        #Set amount of time to move this direction
        self.timeout=choice([30,50,70,90,110])
        self.destroytime=randrange(200,360)
    def Update(self):
        if self.active==1:
            #Move in a certain direction?
            self.x+=self.direction[0]
            self.y+=self.direction[1]
            self.timeout-=1
            if self.timeout==0:
                #Change direction?
                self.direction=   (choice([20,-20,1,-1,15,0,-15]),choice([20,-20,1,-1,15,0,-15]))
                self.timeout=choice([30,50,70,90,110])
            self.destroytime-=1
            if self.destroytime==0:
                self.active=0
            self.rect=pygame.Rect(self.x,self.y,60,60)

那么我如何告诉物体随机移动呢?在

以下是我的完整代码:

^{pr2}$

Tags: 实例代码rectselfifdeftimeoutactive
2条回答

一些伪/C代码:

// lets say we have 4 directions
// we generate random number for it    

int randomDirection = Random.Next(0, 4);

// 0:MoveUp()
// 1:MoveDown()
// 2:MoveLeft()
// 3:MoveRight()

// then we check what random direction number we got 
// and execute specific method for it

switch(randomDirection)
{
    case 0:
    player.MoveUp();
    break;

    case 1:
    player.MoveDown();
    break;

    case 3:
    player.MoveDown();
    break;

    case 4:
    player.MoveDown();
    break;
}

我刚刚发现Python中没有case/switch语句。检查这个question看看如何替换它。在

我不太明白你想要什么。你想要一系列相连的隧道吗?你想要一组不相连的被清除的圆圈吗?你想要用隧道连接的干净的圆圈吗?在

不过,这里有一些一般性的建议。在

首先,你的代码有太多的硬编码数字。您应该创建一个名为Board或类似的类,它将所有数字作为常量变量保存,然后使用这些数字:

class Board(object):
    def __init__(self, width, height, block_size):
        assert width % block_size == 0
        assert height % block_size == 0
        self.width = width
        self.height = height
        self.block_size = block_size
        self.w = width // self.block_size
        self.h = height // self.block_size

现在,一旦你有了以上这些,你就可以这样做:

^{pr2}$

我的建议是使用上面的代码来选择洞穴的位置,当你添加每个洞穴时,绘制一条隧道来连接它。不要画一堆随机的线,选择随机的洞穴,然后用线连接洞穴。让你的代码使用连接洞穴的直线来工作,如果你不喜欢直线,重新编写代码来绘制一些随机的线条。在

相关问题 更多 >