eliotz
eliotz

Reputation: 119

Pressing a key creates a loop until you press another key

I'm creating a Snake game in Python. After pressing a direction key the snake will move in that direction at a slow pace until the user presses another key. I was able to make the snake move after pressing a key, but I could not stop it by pressing another key: (I'm using a pygame)

if event.type == pygame.KEYDOWN:

    if event.key == pygame.K_LEFT:

        while i==False:
            time.sleep(0.2)
            X_had1=X_had1 - 1

            #Print operation

            if event.type == pygame.KEYDOWN:
                if event.key != pygame.K_LEFT:
                    i=True

Upvotes: 2

Views: 87

Answers (2)

eliotz
eliotz

Reputation: 119

This is what I did in the end-

    if event.type == pygame.KEYDOWN:
    x=event.key
    y=x
    print(x)

while b == False:


    if y1 != 275:
        if y == 276:

            hadX1=hadX1 -1
            IMAGEsnake=r"C:\תמונות פיתון\‏‏ראש הנחש קטן שמאלה.png"
            y1=y
            print(nums)
            b=True
    elif y1==275:
        if y == 276:
            y=275





    if y1 != 273:
        if y == 274:
            hadY1=hadY1 + 1
            IMAGEsnake=r"C:\תמונות פיתון\‏‏ראש הנחש קטן למטה.png"
            y1=y
            print(nums)
            b=True
    elif y1==273:
        if y == 274:
            y=273


    if y1 !=276:
        if y == 275:
            hadX1=hadX1 + 1
            IMAGEsnake=r"C:\תמונות פיתון\ראש הנחש קטן ימינה.png"
            y1=y
            print(nums)
            b=True
    elif y1==276:
        if y == 275:
            y=276



    if y1 != 274:
        if y == 273:
            hadY1=hadY1 - 1
            IMAGEsnake=r"C:\תמונות פיתון\‏‏ראש הנחש קטן למעלה.png"
            y1=y
            print(nums)
            b=True
    elif y1==274:
        if y == 273:
            y=274

Upvotes: 0

Rabbid76
Rabbid76

Reputation: 211277

No. Never try to control the application with an additional loop in the application loop. You have the application loop use it. Add a variable that controls direction and change the value of the variable when you press a key. Use the direction to change the position (X_had1, Y_had1):

direction = None
speed = 1

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                direction = (-1, 0)
            if event.key == pygame.K_RIGHT:
                direction = (1, 0)
            if event.key == pygame.K_UP:
                direction = (0, -1)
            if event.key == pygame.K_DOWN:
                direction = (0, 1)

    if direction:
        X_had1 += direction[0] * speed
        Y_had1 += direction[1] * speed

Upvotes: 2

Related Questions