我该如何使我的桔子的randomizefall pthon?

问题描述

所以我一直在尝试使橙子随机落在100-650宽度和-200高度之间,但是我放置的代码无法正常工作,我尝试正确的代码使橙子只保持随机状态我要使其随机随机化,而不仅仅是随机https://gyazo.com/928b117fb01d9050ac2c50cb1d2f269f

我的随机

run = True
while run:
# [...]


    for Platform in platforms:
        if orange1.rect.colliderect(Platform.rect):
            orange1.speed += 1
            orange1.x = random.randint(Orange.rect.x,Orange.rect.x + Orange.rect.width)
            orange1.y = random.randrange(0,1 + 12)

我的完整代码

https://pastebin.com/aiWMQ5b5

解决方法

这是因为要在orange_rect矩形而不是对象的位置self.rect上绘制位图。稍后在更改中,self.rect会移动橙色,但这不会影响Orange.orange位图的.get_rect()返回的矩形。问题的根源在于,当只需要一个Rect时就有两个Rect。

class Orange:
    # [...]

    def draw(self):
        self.rect.topleft =(self.x,self.y)                             # <--here
        pygame.draw.rect(window,self.color,self.rect)
 
        orange_rect = self.orange.get_rect(center = self.rect.center)  # <<--HERE
        orange_rect.centerx -= 2
        orange_rect.centery += 2
        window.blit(self.orange,orange_rect)                           # <--HERE

我将对此进行重新处理以仅使用单个矩形:

WINDOW_WIDTH=500
WINDOW_HEIGHT=700

class Orange:
    def __init__(self,x,y,width,height,color):
        self.width = width
        self.height = height
        self.color = color
        self.speed = 6
        self.orange = pygame.image.load("Orange_1.png")
        self.orange = pygame.transform.scale(self.orange,(self.orange.get_width()//25,self.orange.get_height()//25))

        self.rect = self.orange.get_rect()   # get the rect,and set the position
        self.rect.x = x
        self.rect.y = y

    def draw( self ):
        pygame.draw.rect( window,self.rect)
        window.blit( self.orange,self.rect )

    def fall( self,amount ):
        self.rect.y += amount
        if ( self.rect.y > WINDOW_HEIGHT ):
            self.randomReset()  # restart at the top

    def randomReset( self ):
        """ Reposition the fruit somewhat randomly """
        self.speed += 1
        self.x = random.randint( self.rect.x,self.rect.x + self.rect.width)
        self.y = -self.rect.height   # start just off-screen
        # keep on-screen
        if ( self.x < 0 or self.x > WINDOW_WIDTH ):
            screen_eighth = WINDOW_WIDTH // 8
            self.x = random.randint( screen_eighth,WINDOW_WIDTH-screen_eighth )

在编写面向对象的代码时,主要思想之一就是代码中包含的数据是对象的“属性”,并且外部代码不应触及诸如Orange.x之类的事物。考虑到这一点,我创建了一些函数来支持Orange类上的必要操作。

所以不要打电话:

for Orange in oranges:
    Orange.y += playerman.speed

for Platform in platforms:
    if orange1.rect.colliderect(Platform.rect):
        orange1.speed += 1
        orange1.x = random.randint(Orange.rect.x,Orange.rect.x + Orange.rect.width)
        orange1.y = random.randrange(0,1 + 12)

我们要求Orange类对其自身进行更改,并调用成员函数:

for Orange in oranges:
    Orange.fall( playerman.speed )

for Platform in platforms:
    if orange1.rect.colliderect( Platform.rect ):
        orange1.randomReset()

这将所有Orange功能保留在类中。这有助于防止副作用错误。