Python: 如何弹离屏幕的一侧

Python: how to bounce off the side of the screen

好的,我正在使用 inventwithpython 自学编码。我试图以我自己的方式重用代码来理解它是如何工作的,但这部分给我带来了麻烦:

Chapter 17中有一组动画代码,其中不同大小的盒子从屏幕的一侧弹开

for b in blocks:
    # move the block data structure
    if b['dir'] == DOWNLEFT:
        b['rect'].left -= MOVESPEED
        b['rect'].top += MOVESPEED
    if b['dir'] == DOWNRIGHT:
        b['rect'].left += MOVESPEED
        b['rect'].top += MOVESPEED
    if b['dir'] == UPLEFT:
        b['rect'].left -= MOVESPEED
        b['rect'].top -= MOVESPEED
    if b['dir'] == UPRIGHT:
        b['rect'].left += MOVESPEED
        b['rect'].top -= MOVESPEED

    # check if the block has move out of the window
    if b['rect'].top < 0:
        # block has moved past the top
        if b['dir'] == UPLEFT:
            b['dir'] = DOWNLEFT
        if b['dir'] == UPRIGHT:
            b['dir'] = DOWNRIGHT
    if b['rect'].bottom > WINDOWHEIGHT:
        # block has moved past the bottom
        if b['dir'] == DOWNLEFT:
            b['dir'] = UPLEFT
        if b['dir'] == DOWNRIGHT:
            b['dir'] = UPRIGHT
    if b['rect'].left < 0:
        # block has moved past the left side
        if b['dir'] == DOWNLEFT:
            b['dir'] = DOWNRIGHT
        if b['dir'] == UPLEFT:
            b['dir'] = UPRIGHT
    if b['rect'].right > WINDOWWIDTH:
        # block has moved past the right side
        if b['dir'] == DOWNRIGHT:
            b['dir'] = DOWNLEFT
        if b['dir'] == UPRIGHT:
            b['dir'] = UPLEFT

我想创建它,以便我的块左右移动并从屏幕的每一侧反弹。

但是,当我尝试自己更改此代码时,所发生的只是块飞出屏幕而没有弹跳。尝试了几种变体,结果完全相同。目前它看起来像这样: 编辑:更新完整代码

import pygame, sys, time
from pygame.locals import *

# set up pygame
pygame.init()

# set up the window
WINDOWWIDTH = 480
WINDOWHEIGHT = 800
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption('Jumper')

#Directions
LEFT = 4
RIGHT = 6
UP = 8
DOWN = 2

MOVESPEED = 4

# set up the colors
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)


b1 = {'rect':pygame.Rect(240, 700, 20, 20), 'color':GREEN, 'dir':LEFT}
blocks = [b1]

# run the game loop
while True:
# check for the QUIT event
for event in pygame.event.get():
    if event.type == QUIT:
        pygame.quit()
        sys.exit()

# draw the black background onto the surface
windowSurface.fill(BLACK)

for b in blocks:
    # move the block data structure
    if b['dir'] == LEFT:
        b['rect'].left -= MOVESPEED
    if b['dir'] == RIGHT:
        b['rect'].left += MOVESPEED

        if b['rect'].left < 0:
             b['dir'] = RIGHT


        if b['rect'].right > WINDOWWIDTH:
                b['dir'] = LEFT

             # draw the block onto the surface
    pygame.draw.rect(windowSurface, b['color'], b['rect'])

# draw the window onto the screen
pygame.display.update()
time.sleep(0.02)

您的代码中的问题只是混淆了缩进。如果您修复缩进,它可以正常工作:

import pygame, sys, time
from pygame.locals import *

# set up pygame
pygame.init()

# set up the window
WINDOWWIDTH = 480
WINDOWHEIGHT = 800
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption('Jumper')

#Directions
LEFT = 4
RIGHT = 6
UP = 8
DOWN = 2

MOVESPEED = 4

# set up the colors
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)


b1 = {'rect':pygame.Rect(240, 700, 20, 20), 'color':GREEN, 'dir':LEFT}
blocks = [b1]

# run the game loop
while True:
    # check for the QUIT event
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    # draw the black background onto the surface
    windowSurface.fill(BLACK)

    for b in blocks:
        # move the block data structure
        if b['dir'] == LEFT:
            b['rect'].left -= MOVESPEED
        if b['dir'] == RIGHT:
            b['rect'].left += MOVESPEED

        if b['rect'].left < 0:
             b['dir'] = RIGHT
        if b['rect'].right > WINDOWWIDTH:
                b['dir'] = LEFT

        # draw the block onto the surface
        pygame.draw.rect(windowSurface, b['color'], b['rect'])

    # draw the window onto the screen
    pygame.display.update()

time.sleep(0.02)

Python 使用缩进来说明什么嵌套在什么里面。在 C# 和其他使用大括号或其他块定界符的语言中,只要将大括号放在正确的位置,就可以避免错误的缩进。但在 Python 中,缩进很关键。 (在所有其他语言中,正确的缩进对于代码的可读性仍然至关重要,即使编译器不关心它。)

将您的代码版本与上面的代码进行比较,您将看到需要修复缩进的地方。

现在讨论一个更大的问题。来自 Inventing With Python 网站的示例代码是......说得好听一点,不太好。

暂时假装您对编程一无所知,然后看一下您开始使用的原始代码。是不是好像有很多重复的地方?

而且非常棘手的重复。查看它设法使用 DOWNLEFTDOWNRIGHTUPLEFTUPRIGHT 的所有不同方式,以及代码如何必须如此小心才能每次都正确.

任何时候你想写这种棘手的代码,停下来,坐下来问问自己,"Isn't there a simpler way to do this?"

事实上,您绝对是在正确的轨道上剥离了一堆复杂的代码并为您的实验做了一些更简单的事情。

但是为了好玩,让我们回到他们的代码,看看我们如何能够简化它,但仍然做它所做的一切。

从这四个名字开始,DOWNLEFT等等。为什么每个名字都有自己的名字?他们真的不是基本上都是一样的吗?都是对角线,只是不同方向的对角线。

顾名思义,对角线实际上是垂直和水平两个方向的组合。

现在,我们如何指定 screen/window 上的位置?我们不会给每个可能的位置命名,我们给它一个带有 xy 值的坐标。最左边、最上面的像素是 x=0, y=0,我们从那里开始,向右或向下加一,向左或向上减一。

因此,我们不要为四个对角线方向编 names,而是使用实际数字!我们将 DOWNRIGHT 表示为 x=1, y=1UPLEFT 表示为 x=-1, y=-1,等等

现在发生了一件美妙的事情。考虑检查左边缘反弹的代码 (if b['rect'].left < 0)。我们不必特意将 DOWNLEFT 更改为 DOWNRIGHT 或将 UPLEFT 更改为 UPRIGHT,我们可以忽略 y 方向,只需将 x=-1 更改为 x=1.

除了我们将 x=1 更改为 x=-1 之外,从右边缘弹起也是如此。事实上,您可以通过将 x 乘以 -1.

来处理这两种情况

所以我们可以做到这一点:如果我们撞到左边缘或右边缘,我们将 x 方向乘以 -1。顶部或底部边缘以及 y 方向也是如此。

这是对原始代码的修订,它执行此操作并进行了一些其他简化:

import pygame, sys, time
from pygame.locals import *

class Block( object ):
    def __init__( self, rect, color, dir ):
        self.rect = rect
        self.color = color
        self.dir = dir
    def move( self ):
        # reverse direction if the block will move out of the window
        if self.rect.left < SPEED or self.rect.right > WIN_WIDTH - SPEED:
            self.dir.x *= -1
        if self.rect.top < SPEED or self.rect.bottom > WIN_HEIGHT - SPEED:
            self.dir.y *= -1
        # move the block
        self.rect.left += self.dir.x * SPEED
        self.rect.top += self.dir.y * SPEED
    def draw( self ):
        pygame.draw.rect( windowSurface, self.color, self.rect )

class Direction( object ):
    def __init__( self, x, y ):
        self.x = x
        self.y = y

# set up pygame
pygame.init()

# set up the window
WIN_WIDTH = 400
WIN_HEIGHT = 400
windowSurface = pygame.display.set_mode( ( WIN_WIDTH, WIN_HEIGHT ), 0, 32 )
pygame.display.set_caption( 'Animation' )

# set up the movement speed
SPEED = 4

# set up the colors
BLACK = ( 0, 0, 0 )
RED = ( 255, 0, 0 )
GREEN = ( 0, 255, 0 )
BLUE = ( 0, 0, 255 )

# set up the block objects
blocks = [
    Block( pygame.Rect( 300, 80, 50, 100 ), RED, Direction( -1, 1 ) ),
    Block( pygame.Rect( 200, 200, 20, 20 ), GREEN, Direction( -1, -1 ) ),
    Block( pygame.Rect( 100, 150, 60, 60 ), BLUE, Direction( 1, -1 ) ),
]

# run the game loop
while True:
    # check for the QUIT event
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    # draw the black background onto the surface
    windowSurface.fill( BLACK )

    # move and draw each block
    for block in blocks:
        block.move()
        block.draw()

    # draw the window onto the screen
    pygame.display.update()
    time.sleep( 0.02 )

我还为块和方向创建了 类,而不是使用内联代码完成所有这些。请注意,"move and draw" 主循环现在只有三行代码,而不是原始代码中的巨大复杂混乱。

类 如果您有 C# 背景,您应该很熟悉。 Python 中的表示法有点不同 - 例如,__init__() 是构造函数 - 但概念非常相似。如果代码中有任何不清楚的地方,请告诉我。

还有一个小错误修复:原始代码让方块在反转之前经过屏幕边缘,所以我调整了边缘测试以在它反转之前反转越过边缘。这就是为什么它说 if self.rect.left < SPEED 而不是 if self.rect.left < 0.