首页 > 解决方案 > 我无法让移动模块键工作,我无法选择它们

问题描述

我正在制作一个模块以使移动矩形更容易,但我无法让它的一部分工作,我希望能够命名它使用的键,但我似乎无法让它工作,这是我的代码:

import pygame

#this is where i would have i find out what keys the user want's to use
#The k1,k2,k3,k4s
def move(rect, vel, k1,k2,k3,k4):
    keys = pygame.key.get_pressed()
    if keys[pygame.K_k1]:
        rect.x -= vel
    if keys[pygame.K_k2]:
        rect.x += vel
    if keys[pygame.K_k3]:
        rect.y -= vel
    if keys[pygame.K_k4]:
        rect.y += vel

screen= pygame.display.set_mode([500,500])

running =  True
red = pygame.Rect(225,225,50,50)
clock = pygame.time.Clock()
while running:
    screen.fill([255,255,255])
    pygame.draw.rect(screen,[255,0,0],red)
    pygame.display.flip()
    move(red,10,"a","d","w","s")
    #ADWS being the keys i want to use to move
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            running = False

标签: pygame

解决方案


get_pressed()方法返回当前按下的键的 ascii 值数组。由于它是标准 ascii,用户可以输入左\右\上\下键,脚本可以使用该ord函数将它们转换为 ascii。

试试这个代码:

import pygame

keylst = input('Enter Keys to use (Left Right Up Down)').lower() # enter> a d w s

kLeft, kRight, kUp, kDown = (ord(k) for k in keylst.split())  # ascii codes, split on space

#this is where i would have i find out what keys the user want's to use
#The k1,k2,k3,k4s
def move(rect, vel):
    keys = pygame.key.get_pressed()
    if keys[kLeft]:
        rect.x -= vel
    if keys[kRight]:
        rect.x += vel
    if keys[kUp]:
        rect.y -= vel
    if keys[kDown]:
        rect.y += vel

screen= pygame.display.set_mode([500,500])

running =  True
red = pygame.Rect(225,225,50,50)
clock = pygame.time.Clock()
while running:
    screen.fill([255,255,255])
    pygame.draw.rect(screen,[255,0,0],red)
    pygame.display.flip()
    move(red,1)
    #ADWS being the keys i want to use to move
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            running = False

推荐阅读