Input for a snake in Python

2

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)
    
asked by Sagrel 20.12.2017 в 20:14
source

1 answer

0

The problem is that the input() function is blocking, what you need is a non-blocking routine. In windows you can use the msvcrt module and the functions msvcrt.kbhit() to know if there is a pending key in the queue and msvcrt.getch() to read it

import msvcrt
import time

ch = b""

while True:

    ts = time.time()
    print("{0} {1} (use 'q' para salir)".format(ts, "ultima tecla presionada {0}".format(ch.decode()) if ch != b"" else ""))

    if msvcrt.kbhit():
        ch = msvcrt.getch()
        if ch == b"q":
          break
    
answered by 22.12.2017 в 15:02