1
votes

I made a simple game with python using the Pygame library but when I finished I just noticed that I forgot something. LIMITS

I am pretty new at python and I tried with

if player_pos[1] <= 600:
  pygame.K_DOWN = None

*player_pos[1] is the y player's position *600 is the display's limit

But then, the "down" key just stopped working so I just erased that lines.

2
Is your limit upside-down? 600 is the bottom of the screen and 0 is the top. I think you want if player_pos[1] < 600: then move down, else: don't move. Y increases as you move down the screen. (it's reverse to a number plane). - Kingsley

2 Answers

4
votes

You can't (or shouldn't try at least) to turn the input into None. Just use a logical test to decide if you want to move further...

if key_pressed == 'K_RIGHT':  (or whatever syntax you use to catch keypress..)
    if player_pos[1] < limit:
        # update the player position
    else:
        pass
0
votes

@JeffH has already suggested the a way to fix your code. I just wanted to make sure you understood why what you did caused problems and to point out the convention for constants. Not understanding and using that naming convention will make it more difficult for you to understand other code, and will complicate others trying to read your code.

pygame.K_DOWN is intended to be a defined constant, it is not an input or a control variable. You should absolutely not change it.

Python does not have true constants that enforce not being able to change them, so it is handled by convention. Variables that are intended to be constants by convention use all uppercase names, like K_DOWN and you are just not supposed to change them. As you discovered things may break or behave weirdly if you do.

In your case 'the down key stopped working' because the constant used to check it no longer contained the right value anymore. Pygame will give you the keycode for the down arrow key (the number 274 when I print it on my system) but you have assigned None to the constant that you are supposed to compare that value with to determine if it is the down arrow key, so that comparison will now fail.

That is why it stopped things working.