Draw lines with time delay pygame - python-2.7

I want to draw multiple lines with a time delay. I'm using for loop to for the x and y coordinates.I'm searching for a solution to draw those lines with a time delay between them(eg 1 second). Here is my code:
import pygame,sys
pygame.init()
screen = pygame.display.set_mode((1600, 900))
RED = (230, 30, 30)
background_image = pygame.image.load("image.jpg")
background_image = pygame.transform.scale(background_image, (1600,900))
clock = pygame.time.Clock()
# Main loop
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Fill the background
screen.blit(background_image, [0, 0])
x= [60,70,80]
y= [500,600,700]
for x,y in zip(x,y):
pygame.draw.line(background_image, RED,(x,y),(900,1280), 10)
pygame.display.update()
pygame.time.delay(10)
# Update the screen
pygame.display.flip()
`

You have to draw the lines on the screen instead of the background_image. 500 milliseconds are a half second (10 ms is a bit fast). Also, don't use the same variable names for the lists and the coords.
import sys
import pygame
pygame.init()
screen = pygame.display.set_mode((1024, 768))
RED = (150, 30, 30)
# Replaced the image with a Surface to test the code.
background_image = pygame.Surface((1024, 768))
background_image.fill((50, 90, 140))
clock = pygame.time.Clock()
xs = [60, 70, 80, 90]
ys = [500, 600, 700, 800]
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.blit(background_image, [0, 0])
for x, y in zip(xs, ys):
# Draw the lines on the screen not the background.
pygame.draw.line(screen, RED, (x, y), (400, 480), 10)
pygame.display.update()
pygame.time.delay(500)
pygame.display.flip()
clock.tick(30)
This version is still problematic, because you stop the execution of the rest of the main
loop when the for loop runs. That means you can't quit or handle other events during that time.
I've got a more complex example for you with a timer variable. You subtract the delta time (the time that passed since the last tick) from it and when it's below 0 you add another coordinate to a list which you use for the drawing.
import sys
import pygame
pygame.init()
screen = pygame.display.set_mode((1024, 768))
RED = (120, 30, 30)
background_image = pygame.Surface((1024, 768))
background_image.fill((50, 90, 140))
clock = pygame.time.Clock()
xs = [60, 70, 80, 90]
ys = [400, 500, 600, 700]
xys = zip(xs, ys)
startpoints = [] # This holds the current startpoints.
dt = 0
timer = 500 # A countdown timer.
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
timer -= dt # Decrease timer.
if timer <= 0: # If timer < 0 append the next xy coords.
try:
# `next` just gives you the next item in the xys zip iterator.
startpoints.append(next(xys))
# When the zip iterator is exhausted, clear the
# startpoints list and create a new zip iterator.
except StopIteration:
startpoints.clear()
xys = zip(xs, ys)
timer = 500 # Reset the timer.
screen.blit(background_image, [0, 0])
for x, y in startpoints: # Loop over the available startpoints.
pygame.draw.line(screen, RED, (x, y), (400, 480), 10)
pygame.display.flip()
dt = clock.tick(30)
Or you could do kind of the same with a custom event and pygame.time.set_timer:
add_coord_event = pygame.USEREVENT + 1
pygame.time.set_timer(add_coord_event, 500)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == add_coord_event:
try:
startpoints.append(next(xys))
# When the zip iterator is exhausted, clear the
# startpoints list and create a new zip iterator.
except StopIteration:
startpoints.clear()
xys = zip(xs, ys)
Edit: Or better just create the startpoint list before the while loop and use i to slice it. Then you don't have to move the items from the iterator to the list.
xs = [60, 70, 80, 90]
ys = [400, 500, 600, 700]
startpoints = list(zip(xs, ys))
i = 0 # Current index, used to slice startpoints.
clock = pygame.time.Clock()
increase_index_event = pygame.USEREVENT + 1
pygame.time.set_timer(increase_index_event, 500)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == increase_index_event:
i += 1
i %= len(startpoints) + 1 # Keep i in the correct range.
screen.blit(background_image, [0, 0])
for x, y in startpoints[:i]:
pygame.draw.line(screen, RED, (x, y), (500, 580), 10)
pygame.display.flip()
clock.tick(30)

You could either use time.wait() but that will just freeze your program for a bit or you could have a variable that holds what time the line should be draw. Basically when you draw the first line have nextLine = time.clock()+1 and have an if in your loop saying if time.clock > nextLine: then draw the next line.

Related

Using pygame.time.set_timer() within a while loop

I am currently trying to make a game animation based off the game plant versus zombies. When the zombie moves across the screen and contacts the plant, the plant sprite gets saved in a list called plants_eaten_list. The zombie also stops moving to the left. After a 1 second delay (when the plants_eaten_event is triggered), the plant loses 10 health points. When the plant's health reaches 0, the plant sprite dies through the plant.kill() command.
The code for setting up the timer (pygame.time.set_timer(plants_eaten_event, 1000) needs to be inside the main while loop in order to constantly check for a plant within the plants_eaten_list. However, my problem is that for every refresh of the while loop, the timer for the plants_eaten_event gets reset back to 1 second, so the plants_eaten_event never occurs.
Is there any way I can structure the logic of this program to alleviate this issue?
I do not own copyright to any of these images, and the images are intended only for private use.
The zombie image is downloaded from http://plantsvszombies.wikia.com/wiki/Zombie/Gallery?file=Regular_Zombie.png
The plant image is downloaded from http://plantsvszombies.wikia.com/wiki/File:Peashooter.png
Here is my code:
import pygame
import random
BLACK = (0,0,0)
WHITE = (255,255,255)
RED = (255,0,0)
BLUE = (0,0,255)
GREEN = (0,255,0)
pygame.init()
borders_sound = pygame.mixer.Sound("bump.wav")
class Zombie(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("Regular_Zombie.png").convert()
self.image.set_colorkey(WHITE)
# Make our top-left corner the passed-in location.
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
# -- Attributes
# Set speed vector
self.change_x = -1
self.change_y = 0
def changespeed(self, x, y):
""" Change the speed of the player"""
self.change_x += x
self.change_y += y
def move(self):
""" Find a new position for the player"""
#self.change_x = -1
self.rect.x += self.change_x
#print(self.rect.x)
#times = 0
if self.rect.x < 0:
self.rect.x = 0
def eatplant(self,plant):
pygame.time.set_timer(plants_eaten_event,6000)
self.change_x = 0
plant.health = plant.health - 10
class Plant(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("Peashooter.png").convert()
self.image.set_colorkey(BLUE)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.alive = True
self.health = 60
screen_width = 700
screen_height = 400
screen = pygame.display.set_mode([screen_width, screen_height])
all_sprites_list = pygame.sprite.Group()
plants_list = pygame.sprite.Group()
zombies_list = pygame.sprite.Group()
zombie1 = Zombie(690, 15)
plant1 = Plant(300,15)
all_sprites_list.add(zombie1)
all_sprites_list.add(plant1)
plants_list.add(plant1)
zombies_list.add(zombie1)
done = False
clock = pygame.time.Clock()
plants_eaten_event = pygame.USEREVENT + 1
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# If plant.health = 0 at the end of the timer, the plant is eaten.
# If plant.health != 0 at the end of the timer, the entire event
# must happen again in the while loop until the health = 0
elif event.type == plants_eaten_event:
print("Zombie 1 ate plant 1")
zombie1.eatplant(plant)
# Set timer equal to 0 until another plant gets eaten or zombie continues eating current plant
pygame.time.set_timer(plants_eaten_event, 0)
if plant.health == 0:
plant.alive = False
plant.kill()
zombie1.change_x = -1
zombie1.move()
elif event.type == zombie_eaten_plant_event:
zombie1.change_x = -1
zombie1.move()
print("Zombie 1 is eating plant")
pygame.time.set_timer(zombie_eaten_plant_event, 0)
screen.fill(WHITE)
zombie1.move()
if times == 0 and zombie1.rect.x <= 0:
times = times + 1
borders_sound.play()
all_sprites_list.draw(screen)
all_sprites_list.update()
# I set the do kill command in spritecollide command to False because I
# needed to delay the plants that were eaten before they were removed. They
# will be removed after six seconds(symbolize zombies eating plants). Aftera
# a period of time, then I will create a loop that will loop through all plants
# in the plants_eaten_list and use .kill() . I will need to create a separate
# collision function that will stall the zombies until the plants are killed.
plants_eaten_list = pygame.sprite.spritecollide(zombie1,plants_list,False)
# I changed the delay to 6 seconds, and plant 1 still died instantly. The zombie
# stayed frozen in place for 6 seconds before teh 2nd plant was instantly destroyed
for plant in plants_eaten_list:
# If I remove this, plant1 is not killed, even though
# there is the same code within the plants_eaten_event function.
if plant1.health == 0:
plant1.kill()
# The while loop loops so fast that the timer doesnot have a chance to
# finish its countdown before it restarts again. Will I need some kind of a threading
# module to prevent the timers from restarting until they end?
pygame.time.set_timer(plants_eaten_event, 1000)
for plant_eaten in plants_eaten_list:
borders_sound.play()
clock.tick(60)
pygame.display.flip()
pygame.quit()
my problem is that for every refresh of the while loop, the timer for the plants_eaten_event gets reset back to 1 second, so the plants_eaten_event never occurs.
That happens because the rect of the zombie still collides with the rect of the plant in the next frame, spritecollide returns the list with the colliding plant and the for plant in plants_eaten_list: loop where you call set_timer gets executed again each frame.
The first thing you need to do is to set the zombie.rect.left position to plant.rect.right after the first collision, so that the sprites don't collide anymore in the next frame:
for plant in plants_eaten_list:
zombie1.change_x = 0 # Stop the zombie.
# Move the rect so that it doesn't touch the plant's rect anymore.
zombie1.rect.left = plant.rect.right
if plant1.health <= 0:
plant1.kill()
pygame.time.set_timer(plants_eaten_event, 1000)
borders_sound.play()
However, once you start adding more zombies, the code will break because you use the zombie1 and the plant variable (which depends on the for plant in plants_eaten_list: loop) in the event loop, so it will work only for this zombie and the last collided plant. Unfortunately, it's not possible to send more information than the event type with pygame.time.set_timer, otherwise you could attach the specific zombie and plant to the event in order to handle them in the event loop.
An alternative solution would be to give each zombie an own timer attribute (just a number) which you can update in their update methods.
So when the zombie touches a plant, I start the timer by setting it to 1 (second) and then decrement it by the delta time (the time needed for the last frame) each frame. I also stop the zombie self.change_x = 0, move the rect back self.rect.left = plant.rect.right and store a reference to the plant because we need it to reduce its health when the timer is finished.
Once the timer is <= 0 the zombie starts to move again, takes a bite of the plant, the sprites touch again and the timer is started anew.
import pygame
WHITE = (255,255,255)
BLUE = (0,0,255)
GREEN = (0,255,0)
class Zombie(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((30, 50))
self.image.fill(BLUE)
self.rect = self.image.get_rect(topleft=(x, y))
self.change_x = -1
self.timer = 0 # Timer for the attacks.
self.plant = None # Currently attacked target.
def update(self, dt):
"""Update the zombie."""
if self.timer != 0:
self.timer -= dt
if self.timer <= 0: # Move if the timer is inactive.
self.change_x = -1
# Check if a plant is touching and eat it.
if self.plant is not None:
self.plant.health -= 10
print('Health', self.plant.health)
if self.plant.health <= 0:
print('Eaten')
self.plant.kill()
self.plant = None
self.timer = 0
self.rect.x += self.change_x
if self.rect.x < 0:
self.rect.x = 0
def eatplant(self, plants):
print('Play sound')
self.change_x = 0 # Stop the zombie.
self.timer = 1 # Start the timer.
for plant in plants:
self.plant = plant # Store a reference to the plant.
# Move the zombie back, so that the sprites
# don't collide anymore.
self.rect.left = plant.rect.right
class Plant(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((30, 50))
self.image.fill(GREEN)
self.rect = self.image.get_rect(topleft=(x, y))
self.health = 30
pygame.init()
screen = pygame.display.set_mode([700, 400])
# No need to assign the sprites to variables.
plants = pygame.sprite.Group(Plant(500, 15), Plant(350, 115))
zombies = pygame.sprite.Group(Zombie(690, 15), Zombie(690, 115))
all_sprites = pygame.sprite.Group(plants, zombies)
clock = pygame.time.Clock()
dt = 0
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# Pass the delta time to the update methods of the sprites.
all_sprites.update(dt)
# groupcollide returns a dictionary of the collided zombies and plants.
plants_eaten = pygame.sprite.groupcollide(zombies, plants, False, False)
for zombie, collided_plants in plants_eaten.items():
zombie.eatplant(collided_plants)
screen.fill(WHITE)
all_sprites.draw(screen)
dt = clock.tick(60) / 1000 # Time in seconds since last tick.
pygame.display.flip()
pygame.quit()

How do i create multiple shapes that are an equal distance apart using pygame?

Under #Trees i had written a for loop. The first loop works fine, x = 0.
The second loop, however, although x = 300, the shape doesn't move from its original spot.
What this is supposed to do is change the x coordinates of my shape after the 2nd "for loop" is finished creating the leaves on my tree.
import pygame
from pygame.locals import *
pygame.init()
window = pygame.display.set_mode([640,600])
# color reference
white = (255,245,238)
blue = (65,105,225)
green = (154,205,50)
grey = (105,105,105)
lightblue = (176,196,222)
brown = (93, 64, 55)
darkgreen = (0, 121, 107)
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
# Sky
window.fill((135,206,250))
# Pond
pygame.draw.rect (window, (blue), Rect((0,510),(640,100)))
# House base
pygame.draw.rect (window, (white), Rect((100,310),(200,190)))
# Grass
pygame.draw.rect (window, (green), Rect((0,500),(440,100)))
# Windowsill
pygame.draw.rect (window, (grey), Rect((200,420),(80,10)))
# Window/Door
pygame.draw.rect (window, (lightblue), Rect((206,360),(70,60)))
pygame.draw.rect (window, (lightblue), Rect((115,410),(70,90)))
# Doorknob
pygame.draw.circle(window, (grey), (125, 459), 5, 0)
# Roof
pygame.draw.polygon (window, (grey), ((100,310),(203,260),(299,310)))
# Trees
for trees in range(3):
y = 0
x = 0
pygame.draw.rect (window, (brown), Rect((40 + x,470),(20,30)))
for leaves in range(3):
pygame.draw.polygon (window, (darkgreen), ((10 + x,470 - y),(50 + x,410 - y),(90 + x,470 - y)))
y = y + 40
if leaves == 2:
x = x + 300
pygame.display.flip()
My goal is to have a tree on both sides of the house, using a for loop.
A little help would be tremendously appreciated.
This seemed to work
# Trees
y = 0
x = 0
for trees in range(2):
pygame.draw.rect (window, (brown), Rect((40 + x,470),(20,30)))
for leaves in range(3):
pygame.draw.polygon (window, (darkgreen), ((10 + x,470 - y),(50 + x,410 - y),(90 + x,470 - y)))
y = y + 40
if leaves == 2:
x = x + 300
y = y - 120
The for loop kept changing the x and y values back to zero, so i set the range of the leaves back to 3 and moved the x and y accumulator variables above the loop.
You actually don't need the y and x variables above the for loops, since you can pass an optional "step" argument to range. So for example list(range(0, 81, 40)) gives you [0, 40, 80].
for x in range(0, 301, 300):
pygame.draw.rect (window, (brown), Rect((40 + x,470),(20,30)))
for y in range(0, 81, 40):
pygame.draw.polygon(
window, darkgreen,
((10+x, 470-y), (50+x, 410-y), (90+x, 470-y)))

pygame constant movement with if statement

i am trying to make a simple game but movement doesn't work properly
i want it to constantly move while the buttons are pressed but respect the borders of the screen currently the buttons will work overall but it causes the rectangle to stutter, here is my code,
import pygame
pygame.init()
SD = pygame.display.set_mode((640,480))
x = 16
y = 16
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
if y > 0:
y -= 8
if keys[pygame.K_a]:
if x > 0:
x -= 8
if keys[pygame.K_s]:
if y < 448:
y += 8
if keys[pygame.K_d]:
if x < 608:
x += 8
SD.fill((255,255,255))
pygame.draw.rect(SD, (255,0,0), (x,y, 30, 30))
pygame.display.update()
pygame.event.get() will only return an event if a hardware event happened like pressing a key. So your if keys[...] won't be evaluated when nothing happens (a pressed key event won't get repeated)
Move your ifs one level up and it will work without stuttering but you'll have to slow down the movement of your box afterwards (a sleep(0.1) will do for the example but you probably want to move to something more advanced since you don't want to sleep in you drawing loop)
The way key presses are handled in pygame (and most other game engines) is that you only get an event when a key is pressed or released. The reason your character movement is looking so jumpy, is because the key press is being handled like holding a key down in a text editor. If you hold the key down, a letter will show up and after a short while you'll get lots of the letter repeating.
What you really want to do is to have a boolean for each key that you set to True when you get a key press event, and False when you get a key release event (take a very careful look at the process_events function).
I've modified your code to do just that (along with some other changes that I'll explain afterwards):
import pygame
class Game(object):
def __init__(self):
"""
Initialize our game.
"""
# The initial position.
self.x = 16
self.y = 16
# The keyboard state.
self.keys = {
pygame.K_w: False,
pygame.K_a: False,
pygame.K_s: False,
pygame.K_d: False,
}
# Create the screen.
self.SD = pygame.display.set_mode((640,480))
def move_character(self):
"""
Move the character according to the current keyboard state.
"""
# Process vertical movement.
if self.keys[pygame.K_w] and self.y > 0:
self.y -= 1
if self.keys[pygame.K_s] and self.y < 448:
self.y += 1
# Process horizontal movement.
if self.keys[pygame.K_a] and self.x > 0:
self.x -= 1
if self.keys[pygame.K_d] and self.x < 608:
self.x += 1
def process_events(self):
"""
Go through the pending events and process them.
"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
# If the event is a key press or release event, then register it
# with our keyboard state.
elif event.type == pygame.KEYDOWN:
self.keys[event.key] = True
elif event.type == pygame.KEYUP:
self.keys[event.key] = False
def draw(self):
"""
Draw the game character.
"""
self.SD.fill((255,255,255))
pygame.draw.rect(self.SD, (255,0,0), (self.x, self.y, 30, 30))
pygame.display.update()
def run(self):
while True:
self.process_events()
self.move_character()
self.draw()
def main():
pygame.init()
game = Game()
game.run()
# This just means that the main function is called when we call this file
# with python.
if __name__ == '__main__':
main()
The biggest change I've made is to move your game into a class to give you better access to variables from your functions. It also lets you partition your code into different functions that make it easier to read.

Pygame independent moving images on the screen

I am new to Python and Pygame. I want to have a screen in pygame with multiple copies of the same images moving around independently. I have tried to write it as a class and then call instances of it inside the while loop, but it doesn't work. Could someone show how can i basically do such a thing using a class?
I've tried to keep everything simple
Example:
import pygame
pygame.init()
WHITE = (255,255,255)
BLUE = (0,0,255)
window_size = (400,400)
screen = pygame.display.set_mode(window_size)
clock = pygame.time.Clock()
class Image():
def __init__(self,x,y,xd,yd):
self.image = pygame.Surface((40,40))
self.image.fill(BLUE)
self.x = x
self.y = y
self.x_delta = xd
self.y_delta = yd
def update(self):
if 0 <= self.x + self.x_delta <= 360:
self.x += self.x_delta
else:
self.x_delta *= -1
if 0 <= self.y + self.y_delta <= 360:
self.y += self.y_delta
else:
self.y_delta *= -1
screen.blit(self.image,(self.x,self.y))
list_of_images = []
list_of_images.append(Image(40,80,2,0))
list_of_images.append(Image(160,240,0,-2))
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
screen.fill(WHITE)
for image in list_of_images:
image.update()
pygame.display.update()
clock.tick(30)
pygame.quit()
Each image can be called individually from the list and moved by simply changing Image.x/y to whatever you want

Pygame Key events only detects a limited amount of keys being held down

Hi I have used pygame (the modules for python) for a while. Now I have written a RPG game that has multiple keys been held down at once. It seem that only 2 or 3 keys are detected whiles been held down. If anyone knows how to fix this problem it would be great. Try out my code below for python 2.7 and see if you have the same problem. Thanks
import pygame
def main():
# Initialise screen
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((150, 50))
pygame.display.set_caption('Basic Pygame program')
# Fill background
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((250, 250, 250))
# Display some text
font = pygame.font.Font(None, 36)
text = font.render("Hello There", 1, (10, 10, 10))
textpos = text.get_rect()
textpos.centerx = background.get_rect().centerx
background.blit(text, textpos)
# Blit everything to the screen
screen.blit(background, (0, 0))
pygame.display.flip()
q=0
w=0
e=0
r=0
#Event loop
while True:
for event in pygame.event.get():
if event.type == QUIT:
return
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q :
q = 1
if event.key == pygame.K_w :
w = 1
if event.key == pygame.K_e :
e = 1
if event.key == pygame.K_r :
r = 1
if event.type == pygame.KEYUP:
if event.key == pygame.K_q :
q = 0
if event.key == pygame.K_w :
w = 0
if event.key == pygame.K_e :
e = 0
if event.key == pygame.K_r :
r = 0
count = q+w+e+r
print("Total: "+str(count)+" q: "+str(q) + " w: "+str(w)+ " e: "+str(e)+ " r: "+str(r))
clock.tick(30)
screen.blit(background, (0, 0))
pygame.display.flip()
if __name__ == '__main__': main()
Here I have tryed with pygame.key.get_pressed() but it still does not seem to work with more than 3 keys being held down. )-:
from pygame.locals import *
import pygame
def main():
# Initialise screen
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((150, 50))
pygame.display.set_caption('Basic Pygame program')
# Fill background
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((250, 250, 250))
# Display some text
font = pygame.font.Font(None, 36)
text = font.render("Hello There", 1, (10, 10, 10))
textpos = text.get_rect()
textpos.centerx = background.get_rect().centerx
background.blit(text, textpos)
# Blit everything to the screen
screen.blit(background, (0, 0))
pygame.display.flip()
#Event loop
while True:
for event in pygame.event.get():
if event.type == QUIT:
return
q=0
w=0
e=0
r=0
keys=pygame.key.get_pressed()
if keys[K_q] :
q = 1
if keys[K_w] :
w = 1
if keys[K_e] :
e = 1
if keys[K_r] :
r = 1
count = q+w+e+r
print("Total: "+str(count)+" q: "+str(q) + " w: "+str(w)+ " e: "+str(e)+ " r: "+str(r))
clock.tick(30)
screen.blit(background, (0, 0))
pygame.display.flip()
if __name__ == '__main__': main(
)
It is quite likely this is a hardware issue with your keyboard, not something you can address in your game's software. Most keyboards have a limit on the number of keys they can read as being pressed simultaneously (though common modifier keys like Shift and Control are usually handled separately). It's not at all uncommon on laptop or lower-end desktop keyboards for only two ordinary (non modifier) key presses to be supported at a time. Gaming keyboards (and higher-end keyboards in general) will support more, but there's often still some limit. If you press more keys than the keyboard can handle, it will either ignore the later presses (known as "jamming") or cause the keyboard to report extra key presses for other keys (known as "ghosting").
If you're designing a game yourself, this is probably an important thing to be aware of, since it will affect your players, not just you! You probably want to make sure you don't design your game's interface in such a way that users of low-end keyboards can't play effectively. If your UI cannot possibly work without multiple keys being pressed at once, you might want to move some of the key assignments to modifier keys like Shift and Control, which have a better chance of being supported when being pressed at the same time as other keys. With the prevalence of first-person shooter games, the WASD keys may also get special handling on some keyboards.
You can used 'get_pressed' which will give you a bool value for every key on the keyboard.
http://www.pygame.org/docs/ref/key.html#pygame.key.get_pressed
keys = pygame.key.get_pressed()
if keys[K_LEFT]:
go_left()