[pygame] How do i check if i hold a key?

[pygame] How do i check if i hold a key?

Postby dannyxy » Sat May 11, 2013 2:05 pm

When i hold a key the object moves only once?
dannyxy
 
Posts: 18
Joined: Fri Mar 29, 2013 11:26 am

Re: [pygame] How do i check if i hold a key?

Postby Mekire » Sat May 11, 2013 2:18 pm

Use:
Code: Select all
keys = pygame.key.get_pressed()
and then for example:
Code: Select all
if keys[pygame.K_UP]:


For instance, the following induces seizures if you hold the up arrow key:
Code: Select all
import pygame as pg
import sys,random

pg.init()
screen = pg.display.set_mode((500,500))
clock = pg.time.Clock()

color = (255,255,255)
while 1:
    keys = pg.key.get_pressed()
    for event in pg.event.get():
        if event.type == pg.QUIT or keys[pg.K_ESCAPE]:
            pg.quit();sys.exit()
    if keys[pg.K_UP]:
        color = [random.randint(0,255) for i in range(3)]
        print("pressing up")
    screen.fill(color)
    pg.display.update()
    clock.tick(60)

-Mek
User avatar
Mekire
 
Posts: 1025
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan

Re: [pygame] How do i check if i hold a key?

Postby hansn » Sat May 11, 2013 2:25 pm

That's the second time today I don't get to submit my post because you beat me to the punch, Mekire.

See this page for a list of the different key codes: http://thepythongamebook.com/en:glossar ... e:keycodes
hansn
 
Posts: 87
Joined: Thu Feb 21, 2013 8:46 pm

Re: [pygame] How do i check if i hold a key?

Postby Mekire » Sat May 11, 2013 2:32 pm

hansn wrote:That's the second time today I don't get to submit my post because you beat me to the punch, Mekire.

Haha, my dearest apologies.

I should mention that other than using pygame.keys.get_pressed() it is also very common, and at times more desirable, to simply set a flag to True when the pertinent key is pressed and then set it to False when the key is released. All depends on context.

-Mek
User avatar
Mekire
 
Posts: 1025
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan


Return to Game Development

Who is online

Users browsing this forum: No registered users and 1 guest