3

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!

FerdinandoPH
  • 113
  • 1
  • 8
  • this answer might help if you're on windows https://stackoverflow.com/a/25144106/5666087 – jkr May 01 '22 at 20:12
  • another potential solution is https://stackoverflow.com/a/12113391/5666087. by the way i searched google for "python stop thread that is waiting for user input" – jkr May 01 '22 at 20:14
  • Thank you for your help, but the problem is that I need to stop the thread when a message is received through socket (not after a certain amount of seconds) – FerdinandoPH May 01 '22 at 21:45

1 Answers1

0

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")
FerdinandoPH
  • 113
  • 1
  • 8