如何在Pygame中获取键盘输入

发布于 2025-01-17 21:17:24 字数 614 浏览 0 评论 0原文

我正在尝试在程序上获取键盘输入,其中用户必须在屏幕上移动一个点。但是,当我运行该程序时,控制台没有出现。你能帮我解决这个错误吗?这是我的代码:

import pygame
import random
pygame.init()
x=0
y=0
xdir=5
ydir=5
r = random.randint(10,255)
g = random.randint(10,255)
b = random.randint(10,255)
screen = pygame.display.set_mode((500,300))
pygame.draw.circle(screen, (r, g, b), (x,y), 15, 0)
USI = pygame.key.get_pressed()
while True:
    pygame.draw.circle(screen, (r, g, b), (x,y), 15, 0)
    pygame.display.update()
    if USI[pygame.K_LEFT]:
        x -= 5
if USI[pygame.K_RIGHT]:
    x += 5
if USI[pygame.K_UP]:
    y -= 5
if USI[pygame.K_DOWN]:
    y += 5

I am trying to get keyboard input on a program where the user has to move a dot around the screen. However when I run the program, the console does not come up. Could you please help me fix this error? Here is my code:

import pygame
import random
pygame.init()
x=0
y=0
xdir=5
ydir=5
r = random.randint(10,255)
g = random.randint(10,255)
b = random.randint(10,255)
screen = pygame.display.set_mode((500,300))
pygame.draw.circle(screen, (r, g, b), (x,y), 15, 0)
USI = pygame.key.get_pressed()
while True:
    pygame.draw.circle(screen, (r, g, b), (x,y), 15, 0)
    pygame.display.update()
    if USI[pygame.K_LEFT]:
        x -= 5
if USI[pygame.K_RIGHT]:
    x += 5
if USI[pygame.K_UP]:
    y -= 5
if USI[pygame.K_DOWN]:
    y += 5

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

眸中客 2025-01-24 21:17:24

deteck键的示例循环,用pygame按下:

# creating a running loop
while True:
       
    # creating a loop to check events that
    # are occuring
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
         
        # checking if keydown event happened or not
        if event.type == pygame.KEYDOWN:
               
            # checking if key "A" was pressed
            if event.key == pygame.K_a:
                print("Key A has been pressed")
               
            # checking if key "J" was pressed
            if event.key == pygame.K_j:
                print("Key J has been pressed")
               
            # checking if key "P" was pressed
            if event.key == pygame.K_p:
                print("Key P has been pressed")
             
            # checking if key "M" was pressed
            if event.key == pygame.K_m:
                print("Key M has been pressed")

a sample loop to deteck key pressed with pygame:

# creating a running loop
while True:
       
    # creating a loop to check events that
    # are occuring
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
         
        # checking if keydown event happened or not
        if event.type == pygame.KEYDOWN:
               
            # checking if key "A" was pressed
            if event.key == pygame.K_a:
                print("Key A has been pressed")
               
            # checking if key "J" was pressed
            if event.key == pygame.K_j:
                print("Key J has been pressed")
               
            # checking if key "P" was pressed
            if event.key == pygame.K_p:
                print("Key P has been pressed")
             
            # checking if key "M" was pressed
            if event.key == pygame.K_m:
                print("Key M has been pressed")
蝶舞 2025-01-24 21:17:24
import pygame

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

rect = pygame.Rect(0, 0, 20, 20)
rect.center = window.get_rect().center
vel = 5

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN:
            print(pygame.key.name(event.key))

    keys = pygame.key.get_pressed()
    
    rect.x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel
    rect.y += (keys[pygame.K_DOWN] - keys[pygame.K_UP]) * vel
        
    rect.centerx = rect.centerx % window.get_width()
    rect.centery = rect.centery % window.get_height()

    window.fill(0)
    pygame.draw.rect(window, (255, 0, 0), rect)
    pygame.display.flip()

pygame.quit()
exit()

https://replit.com/@Rabbid76/PyGame-ContinouslyMovement#main.py< /a>

这应该可以帮助你弄清楚 pygame 中的移动。

import pygame

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

rect = pygame.Rect(0, 0, 20, 20)
rect.center = window.get_rect().center
vel = 5

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN:
            print(pygame.key.name(event.key))

    keys = pygame.key.get_pressed()
    
    rect.x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel
    rect.y += (keys[pygame.K_DOWN] - keys[pygame.K_UP]) * vel
        
    rect.centerx = rect.centerx % window.get_width()
    rect.centery = rect.centery % window.get_height()

    window.fill(0)
    pygame.draw.rect(window, (255, 0, 0), rect)
    pygame.display.flip()

pygame.quit()
exit()

https://replit.com/@Rabbid76/PyGame-ContinuousMovement#main.py

this should help you figure out movement in pygame.

栀子花开つ 2025-01-24 21:17:24

您可以从pygame获得事件,然后注意键盘事件,而不是查看get_pressed()返回的键那个框架)。
您的代码现在正在发生的事情是,如果您的游戏以30fps渲染,并且您将左箭头键持续半秒,则您将在15次更新位置。

events = pygame.event.get()
for event in events:
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT:
            location -= 1
        if event.key == pygame.K_RIGHT:
            location += 1

为了支持钥匙的持续移动,您必须建立某种限制,要么基于强制的游戏循环帧速率,要么是由您只允许您移动的每一个如此多的tick的计数器环形。

move_ticker = 0
keys=pygame.key.get_pressed()
if keys[K_LEFT]:
    if move_ticker == 0:
        move_ticker = 10
        location -= 1
        if location == -1:
            location = 0
if keys[K_RIGHT]:
    if move_ticker == 0:   
        move_ticker = 10     
        location+=1
        if location == 5:
            location = 4

然后,在游戏循环中的某个地方,您会做这样的事情:

if move_ticker > 0:
    move_ticker -= 1

这只会让您每10帧移动一次(因此,如果您移动,则记录器将设置为10帧,并且在10帧后,它将允许您再次移动)

You can get the events from pygame and then watch out for the KEYDOWN event, instead of looking at the keys returned by get_pressed()(which gives you keys that are currently pressed down, whereas the KEYDOWN event shows you which keys were pressed down on that frame).
What's happening with your code right now is that if your game is rendering at 30fps, and you hold down the left arrow key for half a second, you're updating the location 15 times.

events = pygame.event.get()
for event in events:
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT:
            location -= 1
        if event.key == pygame.K_RIGHT:
            location += 1

To support continuous movement while a key is being held down, you would have to establish some sort of limitation, either based on a forced maximum frame rate of the game loop or by a counter which only allows you to move every so many ticks of the loop.

move_ticker = 0
keys=pygame.key.get_pressed()
if keys[K_LEFT]:
    if move_ticker == 0:
        move_ticker = 10
        location -= 1
        if location == -1:
            location = 0
if keys[K_RIGHT]:
    if move_ticker == 0:   
        move_ticker = 10     
        location+=1
        if location == 5:
            location = 4

Then somewhere during the game loop you would do something like this:

if move_ticker > 0:
    move_ticker -= 1

This would only let you move once every 10 frames (so if you move, the ticker gets set to 10, and after 10 frames it will allow you to move again)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文