如何阻止 pygame 中的角色离开屏幕边缘? [英] How can I stop a character in pygame from leaving the edge of the screen?

查看:109
本文介绍了如何阻止 pygame 中的角色离开屏幕边缘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 pygame 中创建了一个小程序,其中玩家控制一个在屏幕上移动的蓝色方块,但我想阻止玩家越过屏幕边缘.这是我到目前为止的代码,我该怎么做?

I have created a small program in pygame where the player controls a blue square moving around the screen, but I want to stop the player from moving past the edge of the screen. Here is the code I have so far, how can I do this?

import pygame

pygame.init()
screen = pygame.display.set_mode((800, 600))
done = False
x = 30
y = 30

clock = pygame.time.Clock()

while not done:
        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                        done = True
                if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                        is_blue = not is_blue


    pressed = pygame.key.get_pressed()
    if pressed[pygame.K_UP]: y -= 5
    if pressed[pygame.K_DOWN]: y += 5
    if pressed[pygame.K_LEFT]: x -= 5
    if pressed[pygame.K_RIGHT]: x += 5

    screen.fill((0, 0, 0))
    color = (0, 128, 255)
    pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60))

    pygame.display.flip()
    clock.tick(60)

推荐答案

这应该可行

if pressed[pygame.K_UP] and y > 0: y -= 5
if pressed[pygame.K_DOWN] and y < 600 - 60: y += 5
if pressed[pygame.K_LEFT] and x > 0: x -= 5
if pressed[pygame.K_RIGHT] and x < 800 - 60: x += 5

其中 600 和 800 是屏幕尺寸,60 是矩形的尺寸

Where 600 and 800 is the screen size and 60 the size of your rectangle

这篇关于如何阻止 pygame 中的角色离开屏幕边缘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆