Skip to main content
1 de 3

Limit input duration (help please)

I'm new in the programation and these days I've been trying to learn pygame, I'm trying to make some movility for the character and for that I want to make a jump, which I want to limit to two seconds and then the character falls, but I've been trying with diferent stuff and nothing works, it just goes up while "w" is pressed with no limit, it can go up infinitelly and only fall when it's no longer pressed, so i would appreciate some help from y'all. This is the code I currently have:

import pygame
from pygame import *
pygame.init()
Clock = pygame.time.Clock

#classes

class AllSprites(pygame.sprite.Sprite):
    def __init__(self, image, weight, height):
        self.image = image
        self.weight = weight
        self.height = height
    
    def place(self, x, y):
        self = pygame.Rect(x, y, 50, 50)  
class IsPressed():
    def __init__(self, ispressed):
        self.ispressed = ispressed     

#Colors

ColorRed = (255, 0, 0)
ColorBlack = (0, 0, 0)
ColorWhite = (255, 255, 255)
running = True

#objects

player = pygame.Rect(300, 200, 50, 50)
screen = pygame.display.set_mode((1000, 700))
knight = pygame.image.load("sprites/HollowKnightSprite.webp")
Knight = AllSprites(knight, 50, 50)
KnightRect = Knight.image.get_rect()
Floor = pygame.Rect(0, 650, 1000, 50)

#state variables

CanJump = True
W = IsPressed(False)
AirTime = 0
IsJumping = False
MaxJumpDuration = 2000

#main bucle

while running == True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            raise SystemExit
    screen.fill(ColorBlack) 
    pygame.draw.rect(screen, ColorWhite, Floor)
    pygame.draw.rect(screen, ColorBlack, KnightRect)
    screen.blit(knight, KnightRect)

    if pygame.key.get_pressed()[pygame.K_w] and CanJump == True:
        W.ispressed = True
        IsJumping = True
        AirTime = pygame.time.get_ticks()
    if pygame.key.get_pressed()[pygame.K_w] == False:
        W.ispressed = False
        if W.ispressed == False:
            CanJump = False
            IsJumping = False
    if IsJumping == True:
        if pygame.time.get_ticks() - AirTime < MaxJumpDuration:
            KnightRect.y += -2
            if pygame.time.get_ticks() - AirTime > MaxJumpDuration:
                IsJumping = False
   
    if pygame.key.get_pressed()[pygame.K_d]:
        KnightRect.x += 1
    if pygame.key.get_pressed()[pygame.K_a]:
        KnightRect.x += -1   
    KnightRect.y += 1    
    if pygame.Rect.colliderect(KnightRect, Floor):
        AirTime = 0
        KnightRect.y += -1 
        CanJump = True
    
    pygame.display.flip()