Двойной прыжок спрайта Pygame

Итак, я относительно новичок в pygame и начал отходить от базового руководства. Я хочу, чтобы спрайт мог совершать двойной прыжок, и я попытался добавить переменную и т. Д., Чтобы я мог изменить его на тройной прыжок, если они в конечном итоге получат усиление или что-то в этом роде, и я могу легко это изменить, но я столкнувшийся с трудностями. P.S: Некоторые комментарии могут не иметь смысла, поскольку некоторый код был удален, но они все еще полезны для меня.

x = 200
y = 450
width = 64
height = 66
vel = 5
screenwidth = 500
isjump = True #whether our character is jumping or not
jumpcount = 10
maxjump = 2 #double jump
maxjumpcount = 0

#we must keep track of direction, are they moving and how many steps for frames

left = False
right = False
walkcount = 0


def redrawGameWindow():
    global walkcount

    window.blit(background,(0,0)) #loads bg at 0,0

    if  walkcount +1 >= 15: #15 as we have 5 sprites, which will be displayed 3 times per second
        walkcount = 0

    if left:
        window.blit(walkleft[walkcount//3],(x,y))#excludes remainders
        walkcount+=1
    elif right:
        window.blit(walkright[walkcount//3],(x,y))
        walkcount+=1
    elif isjump:
        window.blit(jumpp,(x,y))
        walkcount+=1
    else:
        window.blit(char,(x,y))

    pygame.display.update()


#now to write main loop which checks for collisions, mouse events etc
run = True
while run: #as soon as we exit this, the game ends
    #main loop, gonna check for collision

    clock.tick(15) #frame rate, how many pics per second, games r just a ton of pictures running very quickly
    #now we check for events

    for event in pygame.event.get(): #gets a list of all events that happened
        print(event)
                                    #can go through these events& check if they've happened
        if event.type == pygame.QUIT: #if we try to exit the window
            run = False

   through the use of events. If a key has been pressed, we change the x & y of our shape
    #if we want it to continuely move, we need to get a list



    keys = pygame.key.get_pressed() #if these are pressed or held down, execute whatever is under these.


    if keys[pygame.K_LEFT] and x > vel-vel: #if pressed we move our character by the velocity in whatever direction via grid which works from the TOP LEFT of screen
        #0,0 is top left           #vel-vel to equal 0, makes border better
        x -= vel
        left = True
        right = False
    elif keys[pygame.K_RIGHT] and x < screenwidth - width: #as the square co ord is top left of it
        x+= vel
        right = True
        left = False
    else:
        right = False
        left = False
        walkcount = 0

   #JUMP CODE
    if not(isjump): # still lets them move left and right
        if keys[pygame.K_SPACE]:
            isjump = True #quadratic function for jump
            right = False
            left = False
            walkcount = 0
            maxjumpcount+=1
            if maxjumpcount > 2:
                isjump = False
    else:
        while jumpcount >= -10 and maxjumpcount < 2: #moving slower, then faster, hang, then go down
            pygame.time.delay(12)
            y -= (jumpcount*abs(jumpcount)) / 2#1.35? #squared, 10 ^2, /2, jumpcount = jump height
            jumpcount -= 1


        else: #jump has concluded if it reaches here
            isjump = False
            jumpcount = 10
            maxjumpcount = 0 #double jump resets once jump ends

    redrawGameWindow()

Извиняюсь за довольно жалкую попытку. Мы будем очень благодарны за любые другие предложения, так как мне еще так много предстоит узнать. Спасибо.

См. также:  Графическая диаграмма не отображается в блокноте Jupyter

idownvotedbecau.se/unclearquestion — в чем именно проблема? Вы получаете сообщение об ошибке / исключении? Если не то, что происходит, а что вы хотите / ожидаете?   —  person Mattt720    schedule 05.02.2020

Код перехода, который я использовал, не совсем соответствовал моим намерениям. Я решил это, используя переменную, которая ограничивает пользователя тем, сколько раз он может нажимать пробел и прыгать, пока снова не коснется пола, и мне пришлось полностью заново выполнить функцию прыжка. Однако спасибо, я поработаю над своей ясностью в следующем посте.   —  person Mattt720    schedule 07.02.2020

Понравилась статья? Поделиться с друзьями:
IT Шеф
Комментарии: 1
  1. Mattt720

    У вас есть игровой цикл, используйте его. Дополнительной петли для прыжка не требуется. Для решения проблемы используйте выделение (if) вместо внутреннего цикла while:

    run = True
    while run: #as soon as we exit this, the game ends
        # [...]
    
        if not(isjump): # still lets them move left and right
            if keys[pygame.K_SPACE]:
                # [...]
        else:
    
            # instead of: while jumpcount >= -10 and maxjumpcount < 2: 
            if jumpcount >= -10 and maxjumpcount < 2: # <---------------
    
                y -= (jumpcount*abs(jumpcount)) / 2
                jumpcount -= 1
    

    Обратите внимание, что этот блок кода постоянно вызывается в основном цикле приложения.

    Спасибо, что заметили это, изменили. person Mattt720; 07.02.2020

Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: