Make the rectangle keep moving towards the direction i give to him
<p>I'm making a snake game but I'm using rectangle not snake actually, I can't make the rectangle keep moving towards the direction i give to him it just move one when i press it ,So i want to make it keep moving how to do it .</p>

<p>that is the code :</p>

<pre><code>def keys ():

    pressed = pygame.key.get_pressed()
    for i in range(2):
        if pressed[pygame.K_UP]:
            # rect.move_ip(0,-3)
            rect2.move_ip(0, -3)
        if pressed[pygame.K_DOWN]:
            # rect.move_ip(0,3)
            rect2.move_ip(0, 3)
        if pressed[pygame.K_LEFT]:
            # rect.move_ip(-3,0)
            rect2.move_ip(-3, 0)
        if pressed[pygame.K_RIGHT]:
            # rect.move_ip(3,0)
            rect2.move_ip(3, 0)
</code></pre>

<p>If you want the rectangle to continue moving, even when no button is pressed, I would recommend a <code>speed</code> variable.  Two, actually, you will need an <code>x_speed</code> and a <code>y_speed</code>.</p>

<pre><code>x_speed = y_speed = 0
x_location = y_location = 0

def keys():
    global x_speed
    global y_speed
    pressed = pygame.key.get_pressed()
    for i in range(2):
        if pressed[pygame.K_UP]:
            y_speed = 3
        if pressed[pygame.K_DOWN]:
            y_speed = -3
        if pressed[pygame.K_LEFT]:
            x_speed = -3
        if pressed[pygame.K_RIGHT]:
            x_speed = 3

while True:
    keys()
    x_location += x_speed
    y_location += y_speed
    pygame.draw.rect(SCREEN, COLOR, (x_location, y_location, WIDTH, HEIGHT))
</code></pre>

<p>By using <code>x_speed</code> and <code>y_speed</code>, the main loop will "remember" that it's moving, and only stop or change when it recognizes input.  The main loop simply adds <code>*_speed</code> to <code>*_location</code> every iteration, then calculates the speed for the next iteration.</p>

python python-2.7 pygame