0

I'm trying to create a simple game, where a user moves an 'X' across the screen to try and get to an 'O'. It requires me to use the arrows (up, down, left, right) and I don't know how to program this. I've looked around online and seen various examples, such as curses, getch, sys, pygame, but either they're all too complicated or they don't work on my computer.

Could someone provide a full example and explanation of how to detect a keypress in Python, something like. Also need help with a game screen, specifically, printing something at a certain location, lie (0,0), kind of like how turtle starts drawing at (0,0):

userposy = 0 (y position of the 'X')
*print 'X' at (0, userposy)*
while True:
    char = *detect what key is pressed*
    if char == *down arrow*:
        userposy -= 1.
    *print 'X' at (0, userposy)*
  • Possible duplicate of [python keypress simple game](https://stackoverflow.com/questions/44002474/python-keypress-simple-game) – bendl Oct 18 '17 at 16:27
  • Detecting keypresses varies, depending on what OS you're using. That's why people normally do it using library code, so they don't need to worry about the messy details. – PM 2Ring Oct 18 '17 at 16:29

2 Answers2

1

Try using Pygame! It worries about all the nitty-gritty details and provides you with a simple interface for user input for games:

https://www.pygame.org/news

(What I'm saying is that this is probably the path of least resistance. I could be wrong though)

Austin A
  • 566
  • 2
  • 15
0

I believe this does what you describe using Python turtle:

from turtle import Turtle, Screen

FONT_SIZE = 24
FONT = ('Arial', FONT_SIZE, 'normal')

def tortoise_down(distance=1):
    screen.onkeypress(None, "Down Arrow")  # disable event hander in event hander
    tortoise.forward(distance)
    display.undo()  # erase previous distance
    display.write('X at {:.1f}'.format(tortoise.ycor()), align='center', font=FONT)
    screen.onkeypress(tortoise_down, "Down")  # (re)enable even handler

screen = Screen()
screen.setup(500, 500)

display = Turtle(visible=False)
display.speed('fastest')
display.penup()
display.goto(0, screen.window_height() / 2 - FONT_SIZE * 2)
display.write('', align='center', font=FONT)  # garbage for initial .undo()

tortoise = Turtle('turtle')
tortoise.speed('fastest')
tortoise.setheading(270)
tortoise.penup()

tortoise_down(0)  # initialize display and event handler

screen.listen()
screen.mainloop()

First click on the window to make it the listener. Then you can do individual down arrow presses or hold it down and (after a slight delay) it will repeat automatically.

enter image description here

cdlane
  • 40,441
  • 5
  • 32
  • 81