gpt4 book ai didi

python - 如何限制 Racket 运动?

转载 作者:太空宇宙 更新时间:2023-11-04 10:36:43 25 4
gpt4 key购买 nike

我想让这个乒乓球游戏中的 Racket 不会越过游戏窗口的两侧。 (不要向右或向左移动太远)。我已经尝试编写一个解决方案,但桨板无法完全移出屏幕,但大约只有不到一半的桨板仍然能够移出屏幕。

如何修改我的代码,使 Racket 完全不会离开屏幕?游戏窗口设置为 600 x 600。我正在使用 update_paddle 移动桨。

这是我的桨类/方法:

import pygame

class Paddle:
def __init__(self, x, y, c, w, h):
self.x = x
self.y = y
self.color = c
self.width = w
self.height = h

def draw_paddle(self, screen):
pygame.draw.rect(screen, self.color,
pygame.Rect(self.x, self.y, self.width, self.height), 0)

def update_paddle(self, dir, dx):
if (dir == 'left') and (self.x >= 0):
self.x = self.x - dx
elif (dir == 'right') and (self.x + self.width <= 600):
self.x += dx

def get_left(self):
if (self.x < 300):
return self.x

def get_right(self):
if (self.x >= 300):
return self.x

最佳答案

我们想说的是桨的位置,(它的左上角,因为应该放置在桨永远不会离开屏幕的位置,或者更准确地说:

  • 桨的左侧不得向左移动到屏幕的左边缘之外,并且
  • Racket 的右侧不得向右移动超过屏幕的右边缘。

所以,让我们看看左右调整桨位置的方法。这只是 update_paddle(),它有单独的左右移动路径。让我们看看你的有什么问题,从左边开始:

if (dir == 'left') and (self.x >= 0):
self.x = self.x - dx

x 恰好为零时,所有测试都会通过,因此允许桨向左移动得更远,它可能会稍微移出屏幕;我们不想要那样,我们想让它完全不离开屏幕。更好的做法是让它一直到左边缘,然后保持在屏幕上:

if dir == 'left':
self.x = max(self.x - dx, 0)

同样的问题发生在右移上:

else:  # LEM: dir == 'right':
self.x = min(self.x + dx, 600 - self.width)

关于python - 如何限制 Racket 运动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22902640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com