What I want is to create a snake and I would like to be able to detect which keys the user clicks on. I have a version made in C ++ in which the keystrokes are detected by a loop that is in another thread as I show here:
vec2 dir(0,0);
int main()
{
thread Input(input);
// Más codigo que mueve la serpiente
}
void input()
{
while (true)
{
char letra = _getch();
switch (letra)
{
case 's':
dir.x = 0; dir.y = 1; break;
case 'w':
dir.x = 0; dir.y = -1; break;
case 'a':
dir.x = -1; dir.y = 0; break;
case 'd':
dir.x = 1; dir.y = 0; break;
case 27:
dir.x = -2; break;
default:
break;
}
}
}
I wonder if there is any way to get the same result in python (I'm starting and I do not know much). I have tried with the module "import threading" and an identical code that the C ++ but still the program is waiting for the input instead of acting as a background. I'm doing something wrong or I just can not. This is the code I have:
import os
import random
import threading
import msvcrt as m
def clean():
os.system("cls")
class vec2:
// Una clase para controlar la posición
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
def run(self):
input()
class parte:
// Una clase con la información de las partes de la serpiente
dir = vec2()
serpiente = [parte(vec2(), "O")]
comida = parte(vec2(random.randint(0, 20), random.randint(0, 20)), "+")
print(comida.pos)
thread = myThread(1, "Thread-1", 1)
thread.start()
thread.run()
while dir != vec2(-1, -1):
// Muevo la serpiente
thread.join()
def imput():
while True:
x = m.getch()
if x == "w":
dir = vec2(1, 0)
elif x == "s":
dir = vec2(-1, 0)
elif x == "a":
dir = vec2(0, -1)
elif x == "d":
dir = vec2(0, 1)
elif x == "x":
dir = vec2(-1, -1)