I am trying to make an online game using socket and threading. It is a competitive hangman game, where the fastest one to complete the word wins. I want that, when one of the players wins/runs out of lives, the other player gets kicked out of its game and is told that they have won/lost. However, I have run into a problem.
1: If I use "threading", there is no way to close the thread (since the program needs to read user input, I need to use the input() function, which means that the player's thread can't be terminated until they insert a character).
2: If I use "multiprocessing" (which has a terminate() function), I can't use input() (multiprocessing doesn't allow it).
I am in a stalemate, what should I do?
P.D: This is my first stackoverflow post ever, please tell me if I made a mistake at writing the post!
Ok, I got it, it is an ugly and complicated solution, but it works. I created a program that emulates the "input" command, without being the input command itself (so it doesn't stop the processes). Here it is:
import pynput.keyboard
global string
string=""
c=0
global oldprinted
oldprinted=""
def GetInput():
import pynput
def on_press(key):
global oldprinted
global string
if key==pynput.keyboard.Key.enter:
listener.stop()
else:
prompt="Introduce your input: "
try:
if key==pynput.keyboard.Key.backspace and len(string)>0:
string=string[:-1]
else:
string+=str(key.char)
prompt+=(string)
print(" "*len(oldprinted),end="\r")
print(prompt,end="\r")
oldprinted=prompt
except:
pass
print("Introduce your input: ",end="\r")
with pynput.keyboard.Listener(suppress=True,on_press=on_press) as listener:
listener.join()
return string
data=GetInput()
print("\n")