Skip to content
Advertisement

How to make fighting game command inputs in PyGame

I am currently making a fighting game and was wondering how command inputs could be added. I understand it is kind of irrelevant and many substitutes are possible, but it would be nice to use familiar fighting game inputs.

I currently have something like this:

        keys = pygame.key.get_pressed()
        if keys[pygame.K_DOWN]:
            commandcount +=1
            if commandcount > 0 and commandcount < 30 and keys[pygame.K_RIGHT] and keys[pygame.K_z]:               
                player1.projectile = True

The “commandcount” helps keep the window of action available until a certain amount of time.

The main problem with this is that you could still press the inputs in whatever order and the projectile would still come out.

Thanks

Advertisement

Answer

Try using the pygame.KEYDOWN events instead of pygame.key.get_pressed() so the order can be observed. Use a list to keep track of the order of these KEYDOWN events. When the order matches a specific combo then execute the move and reset the list. The list also gets reset after a certain amount of time with a combo. I made an example program with the combo down, right, z activating a fireball.

import pygame

# pygame setup
pygame.init()

# Open a window on the screen
width, height = 600, 600
screen = pygame.display.set_mode((width, height))


def main():
    clock = pygame.time.Clock()
    black = (0, 0, 0)
    move_combo = []
    frames_without_combo = 0

    while True:
        clock.tick(30)  # number of loops per second
        frames_without_combo += 1

        if frames_without_combo > 30 or len(move_combo) > 2:
            print("COMBO RESET")
            frames_without_combo = 0
            move_combo = []

        screen.fill(black)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            if event.type == pygame.KEYDOWN:
                move_combo.append(event.key)  # Only keys for combos should be added

        if move_combo == [pygame.K_DOWN, pygame.K_RIGHT, pygame.K_z]:
            print("FIRE BALL")
            frames_without_combo = 0
        print(move_combo)
        pygame.display.update()


main()
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement