pygame - 我无法让移动模块键工作,我无法选择它们
问题描述
我正在制作一个模块以使移动矩形更容易,但我无法让它的一部分工作,我希望能够命名它使用的键,但我似乎无法让它工作,这是我的代码:
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
解决方案
该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
推荐阅读
- angular - 我们如何在 Angular 的延迟加载模块中获取路由参数
- database - 修复 Cassandra 数据库
- arrays - VBA 比较 2 个数组并返回缺失的行,包括重复项
- sql-server - SQL Server 2019 :: 功能是否适用于以前的兼容性级别?
- php - json rpc 2.0 在 laravel api 中的添加请求错误
- sql - 如何使用外键对模型进行单元测试?
- php - 注册用户时检查记录是否存在
- azure - 从应用服务计划创建托管时,Azure 函数应用不显示密钥
- nlp - 手套导入错误 - 语料库 - 无法导入
- java - jvm byte[] 实例字符集是什么