#python #pygame
Вопрос:
Я понятия не имею, как это сделать, используя метод get_pressed() в Pygame. Я также повозился с нажатой клавишей события, но особого успеха не добился.
Вот основной план перехода get_pressed из технологии с Тимом, чтобы начать работу: https://www.ideone.com/ypS334
импорт pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
x = 50
y = 250
width = 40
height = 60
vel = 5
isJump = False
jumpCount = 10
run = True
while run:
pygame.time.delay(50)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and x > vel:
x -= vel
if keys[pygame.K_RIGHT] and x < 500 - vel - width:
x = vel
if not (isJump):
if keys[pygame.K_SPACE]:
isJump = True
else:
if jumpCount >= -10:
y -= (jumpCount * abs(jumpCount)) * 0.5
jumpCount -= 1
else:
jumpCount = 10
isJump = False
win.fill((0, 0, 0))
pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
pygame.display.update()
pygame.quit()
Как мы можем это сделать: А) настроить его так, чтобы А) определить, когда ключ отпущен, и Б) немедленно начать спуск, когда это произойдет. Также, вероятно, должно быть ограничение по высоте для того, как высоко он может прыгать. Большинство ресурсов, веб-сайтов и видео либо просто рассказывают, как заставить объект прыгать, либо переводят его на другой язык. Любая помощь приветствуется, спасибо!
Комментарии:
1. Вам нужно просмотреть документацию по пакету, чтобы ознакомиться с его возможностями. Все, что вам нужно для вашего приложения, — это отметить
time.time()
разницу между вводом и вводом.
Ответ №1:
Добавьте переменную jumpCountMax
вместо константы 10.
jumpCountMax = 10
jumpCount = jumpCountMax
Используйте KEYDONW
KEYUP
событие и вместо keys[pygame.K_SPACE]:
. Используйте pygame.time.get_ticks()
для измерения времени между KEYDONW
и KEYUP
. Установите jumpCountMax
в зависимости от времени и начните прыжок, когда SPACEон будет выпущен ( KEYUP
):
while run:
# [...]
for event in pygame.event.get():
# [...]
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and not isJump:
sp_start = pygame.time.get_ticks()
if event.type == pygame.KEYUP:
if event.key == pygame.K_SPACE and not isJump:
sp_time = pygame.time.get_ticks() - sp_start
jumpCountMax = min(12, sp_time // 40)
jumpCount = jumpCountMax
isJump = True
# [...]
Поиграйте с константами min(12, sp_time // 40)
, чтобы удовлетворить ваши потребности.
Полный пример:
import pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
clock = pygame.time.Clock()
x, y, width, height, vel = 50, 250,40, 60, 5
isJump = False
jumpCountMax = 10
jumpCount = jumpCountMax
run = True
while run:
clock.tick(20)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and not isJump:
sp_start = pygame.time.get_ticks()
if event.type == pygame.KEYUP:
if event.key == pygame.K_SPACE and not isJump:
sp_time = pygame.time.get_ticks() - sp_start
jumpCountMax = min(12, sp_time // 40)
jumpCount = jumpCountMax
isJump = True
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and x > vel:
x -= vel
if keys[pygame.K_RIGHT] and x < 500 - vel - width:
x = vel
if isJump:
if jumpCount >= -jumpCountMax:
y -= (jumpCount * abs(jumpCount)) * 0.5
jumpCount -= 1
else:
jumpCount = jumpCountMax
isJump = False
win.fill((0, 0, 0))
pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
pygame.display.update()
pygame.quit()