Ask coding questions

← Back to all posts
how to make a timed readchar()
AlexanderTarn (231)

I'm trying to make a snake game, but I need a timed readchar() to check if the snake is supposed to change direction or not.

Commentshotnewtop
Geocube101 (566)

I've never used "readchar" so i'm assuming it's a synchronous (blocking) function
If this is the case, you can make it asynchronous by using the "threading" module and using a loop to store the value of readchar() to a global variable

from threading import Thread
from readchar import *
from time import sleep

def getChar(): #Create a function to infinity get the character
  global char
  while True:
    char = readchar()
    sleep(0.1) #This is optional

read_char_loop = Thread(target=getChar) #Use the function to create a new thread
read_char_loop.start() #Start the thread

#The variable "char" should now be accessible globally

[Note]: If the "readchar()" function blocks the console like the "input()" function, then this will not work

AlexanderTarn (231)

@Geocube101 Sorry, but this solution does not work, the error that is given is that a thread can only be started once. FYI I am on windows.

Geocube101 (566)

@AlexanderTarn Why are you starting the thread more than once
Start the thread once at the beginning of your code and then that's it

from threading import Thread
from readchar import readchar
from time import sleep

def getChar(): #Create a function to infinitly get the character
	global char
	char = ''
	while True:
		char = readchar()
		sleep(0.1)

read_char_loop = Thread(target=getChar) #Use the function to create a new thread
read_char_loop.start() #Start the thread

#Loop
while True:
	if char != '': #Do something if char is not empty
		print('\r' + char)
		char = ''
	sleep(1)

#The variable "char" should now be accessible globally
AlexanderTarn (231)

@Geocube101 This solution works, the snake will now move according to the user's orders, but now the terminal looks weird, do you have any idea why?

Geocube101 (566)

@AlexanderTarn On line 72 change print(x) to print('\r' + x)

Vandesm14 (2218)

What do you mean by a timed readchar()? Can you explain more?

AlexanderTarn (231)

@Vandesm14 Every 0.5 seconds the snake should move, if the readchar() gets an input during this time the direction of the snake changes. This is just like any other game.