如何制作边界,以使DVD徽标不会脱离屏幕?
我试图建立一个边界,但它不起作用,所以我删除了它,但是现在它不想工作。它是带有图像的代码,并使用键将其移动。我是编码的初学者,所以我不知道太多,因此我很感谢我应该做些什么编辑或建议。
这是我的代码:
#Imports Pygame module
import pygame
#Initializing/ Starting Pygame module
pygame.init()
#Setting the background and starting location of logo
dvdLogoSpeed = [1, 1]
backgroundColor = 0, 0, 0
#Screen size display variable
screen = pygame.display.set_mode(600, 600)
#Variable for logo and made rectangle for logo
dvdLogo = pygame.image.load("dvd-logo-white.png")
dvdLogoRect = dvdLogo.get_rect()
#Variables
x = 200
y = 200
vel = 10
width = 20
height = 20
def dvdwKeys ():
run = True
while run == True:
pygame.time.delay(10)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
screen.fill (backgroundColor)
screen.blit(dvdLogo, dvdLogoRect)
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and x>0:
dvdLogoRect.x -= vel
if keys[pygame.K_RIGHT] and x<600-width:
dvdLogoRect.x += vel
if keys[pygame.K_UP] and y>0:
dvdLogoRect.y -= vel
if keys[pygame.K_DOWN] and y<600-height:
dvdLogoRect.y += vel
pygame.display.flip()
dvdwKeys()
I tried to make a boundary and it didn't work so I deleted it however now it just doesn't want to work. It is a code with an image and uses keys to move it. I am a beginner at coding so I don't know much so I would appreciate some edits or recommendations on what I should do.
This is my code:
#Imports Pygame module
import pygame
#Initializing/ Starting Pygame module
pygame.init()
#Setting the background and starting location of logo
dvdLogoSpeed = [1, 1]
backgroundColor = 0, 0, 0
#Screen size display variable
screen = pygame.display.set_mode(600, 600)
#Variable for logo and made rectangle for logo
dvdLogo = pygame.image.load("dvd-logo-white.png")
dvdLogoRect = dvdLogo.get_rect()
#Variables
x = 200
y = 200
vel = 10
width = 20
height = 20
def dvdwKeys ():
run = True
while run == True:
pygame.time.delay(10)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
screen.fill (backgroundColor)
screen.blit(dvdLogo, dvdLogoRect)
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and x>0:
dvdLogoRect.x -= vel
if keys[pygame.K_RIGHT] and x<600-width:
dvdLogoRect.x += vel
if keys[pygame.K_UP] and y>0:
dvdLogoRect.y -= vel
if keys[pygame.K_DOWN] and y<600-height:
dvdLogoRect.y += vel
pygame.display.flip()
dvdwKeys()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要测试
dvdlogorect.x
和dvdlogorect.y
而不是x
和y
:但是,您可以简化带有
pygame.Rect.clamp_ip.clamp_ip
:另请参阅我的精灵的边界和当钥匙按住时,我该如何进行精灵移动和
You need to test
dvdLogoRect.x
anddvdLogoRect.y
instead ofx
andy
:However, you can simplify the code with
pygame.Rect.clamp_ip
:See also Setting up an invisible boundary for my sprite and How can I make a sprite move when key is held down and