0

I'm making 2048 in python, and I'm having no trouble with any part of the game except initializing that next random block after each of the users turns. Creating the function that does this is easy, and only requires randomly changing one entry in the array of entries for the blocks. The issue I'm having is that it is a random function, and it is in a (game) loop. This means that it keeps getting called, and keeps giving different output, which means it keeps changing the array when it should change it only once. The game loop itself is posted below, and should be pretty self-explanatory. The function I'm concerned about is the addTile() function. I've thought of tracking when it comes in and out of the if statements, or maybe storing the output of the random function somewhere, but that doesn't seem to work. How could I selectively call this function at the times I need it?

while not done:

screen.fill((0,0,0))
board()

for event in pygame.event.get():
    if event.type == pygame.QUIT:
        done = 1

pressed = pygame.key.get_pressed()

if pressed[pygame.K_UP]:
    state = 1
if pressed[pygame.K_DOWN]:
    state = 2
if pressed[pygame.K_LEFT]:
    state = 3
if pressed[pygame.K_RIGHT]:
    state = 4

if state == 0:
    tiles(positions)
elif state == 1:
    positions = addTile(positions)
    positions = up(positions)
    tiles(positions)
elif state == 2:
    positions = down(positions)
    tiles(positions)
elif state == 3:
    positions = left(positions)
    tiles(positions)
elif state == 4:
    positions = right(positions)
    tiles(positions)

pygame.display.flip()
clock.tick(60)
3
  • It seems that after you press "UP" your state remains 1, but you want to change it after you handled the event. Maybe just adding state = 0 at the end will fix your problem. Commented Feb 22, 2015 at 5:01
  • @syntonym: That should be in an answer, not a comment. Commented Feb 22, 2015 at 6:07
  • Please fix the indentation in your code. Commented Feb 22, 2015 at 6:09

1 Answer 1

1

Your state remains 1 even after you dealed with the keypress. You should set state back to 0 after dealing with keypresses.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.