I am creating a Tetris game using Pygame. However, instead of calling a single shape, but code calls all the functions for the shapes randomly one after the other. I tried calling NewShape at different places, but nothings working. If it calls a single shape, then the keyboard control does not work.

x=50
y=50
def ShapeL(screen,x,y):
pygame.draw.rect(screen, Cyan, [x,y-50,50,150])
pygame.draw.line (screen,Cyan, [x, y], [x+50,y])
pygame.draw.line (screen,Cyan, [x, y+50], [x+50,y+50])
pygame.draw.line (screen,Cyan, [x, y+100], [x+50,y+100])
pygame.draw.rect(screen, Cyan, [x+50,y+50 ,50,50])

ShapeChosen=False
def NewShape(screen,x,y):
ListShapes=[ShapeS, ShapeT, ShapeL, ShapeI, ShapeSquare]
Shape=random.choice(ListShapes)(screen,x,y)#chooses random shape
ShapeChosen=True

def BasicGame(x,y):
Done=False
while not Done and y!=500 and ShapeChosen!=True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
Done=True
elif event.type == pygame.KEYDOWN:
if event.key ==pygame.K_LEFT:
x=x-50
elif event.key==pygame.K_RIGHT:
x=x+50
elif event.key==pygame.K_DOWN:
y=y+50
elif event.key==pygame.K_SPACE:
y=500
if x==0:#Borders so the shape doesn't leave the screen.
x=50
elif x==400:
x=350
if y==550:
y=500
screen.fill(White)
NewShape(screen,x,y)


I tried passing the parameter ShapeChosen to the function, however, it did not work as well. I tried passing global ShapeChosen, but it prevents the keyboard functions from working.

• Seems like an issue of accessing a global variable (ShapeChosen=True ) inside a function to me. Dec 28 '16 at 12:44
• Re: your edit. As far as I'm aware Python passes booleans by value, not reference. Hence a parameter solution won't work. Try global ShapeChosen inside your function instead? Dec 29 '16 at 23:42

You definitely want to modify your NewShape function so that it modifies the global variable ShapeChosen instead of creating a new global one.

ShapeChosen=False
def NewShape(screen,x,y):
global ShapeChosen
ListShapes=[ShapeS, ShapeT, ShapeL, ShapeI, ShapeSquare]
Shape=random.choice(ListShapes)(screen,x,y)#chooses random shape
ShapeChosen=True


Now, you mentioned that if you do so, the keyboard input stops working. I'm not really sure how you've planned your code to work here, but the line

while not Done and y!=500 and ShapeChosen!=True:


is obviously the issue, because the while-loop should stop as soon as ShapeChosen becomes true. I can't tell what your intention here is, but perhaps you would like to move the ShapeChosen-condition just above the call to NewShape? Something along the lines of

if not ShapeChosen:
NewShape(screen, x, y)