Search code examples
pythonserversocket

Python -- Client Waiting for Server Input (and vice versa)


I'm fairly new to Python and I'm very new to sockets and servers in Python, so please bear with me! Basically, I'm trying to set up a hangman game between a client and server to play a game. I know this system has a bunch of weaknesses (including having most of the code on the client side instead of the server side, which I'm working to fix, but anyway...)

In essence, my client launches the game, and gets an input from the server for the "word" of the hangman game. After the game finishes, it plays the init method again to restart the game. I want it to wait for input from the server again so it doesn't play the same input from the 1st time. Do you have any suggestions?

Here's my server code:

#!/usr/bin/env python
"""
Created on Tue Jul 26 09:32:18 2016

@author: Kevin Levine / Sam Chan
"""

# Echo server program
import socket
import time

HOST = '10.232.2.162'                 # Symbolic name meaning all available interfaces
PORT = 5007           # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr

def sendClient(message):
    conn.send(message)

data = "1"
while True:  # Whole game
    if data == "1":
        while True:
            print "Enter word to be guessed."
            message = raw_input("> ")
            if message.isalpha():
                sendClient(message)
            else:
                "Your word included some non-alphabetical characters."
    data = conn.recv(1024)
    if data == "2":
        break

# data = s.recv(1024)
# clientData = conn.recv(1024)
# print "Received", clientData, "from Client"

Here's my client code:

#!/usr/bin/python
"""
Created on Tue Jul 26 09:12:01 2016

@author: Kevin Levine / Sam Chan
"""

# Echo client program
import socket
import time

HOST = '10.232.5.58'    # The remote host
PORT = 5007        # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))

def sendServer(message):
    s.send(message)

class Hangman():
    def __init__(self):
        print "Welcome to 'Hangman', are you ready to play? "
        print "(1) Yup!\n(2) Nah"
        user_choice_1 = raw_input("> ")
        serverData = s.recv(1024)
        global the_word
        the_word = serverData
        if user_choice_1 == '1':

            print "Loading..."
            for t in range(3, -1, -1):
                print t, "..."
                time.sleep(1)
            self.start_game()
        elif user_choice_1 == '2':
            print "Bye bye now..."
            exit()
        else:
            print "I didn't understand you..."
            self.__init__()

    def start_game(self):
        print "Six fails, no more, no less. Try to guess the word by guessing letters!"
        self.core_game()

    def core_game(self):
        guesses = 0
        letters_used = ""
        progress = []
        for num in range(0, len(the_word)):
            progress.append("?")
        while guesses < 6:
            if "".join(progress) == the_word:
                print "Congrats! You guessed the word '%s'!" % the_word
                print "========================================"
                time.sleep(3)
                self.__init__()
            guessraw = raw_input("> ")
            guess = guessraw.lower()
            if (guess in the_word) and (guess not in letters_used):
                print "You guessed correctly!"
                letters_used += "," + guess
                self.hangman_graphic(guesses)
                print "Progress: " + self.progress_updater(guess, the_word, progress)
                print "Letter used: " + letters_used
            elif (guess not in "abcdefghijklmnopqrstuvwxyz"):
                print "Only guess letters!"
            elif (guess not in the_word) and (guess not in letters_used):
                guesses += 1
                print "That guess was wrong." 
                letters_used += "," + guess
                self.hangman_graphic(guesses)
                print "Progress: " + "".join(progress)
                print "Letter used: " + letters_used
            else:
                print "Only guess unique letters!"

    def hangman_graphic(self, guesses):
        if guesses == 0:
            print "________      "
            print "|      |      "
            print "|             "
            print "|             "
            print "|             "
            print "|             "
        elif guesses == 1:
            print "________      "
            print "|      |      "
            print "|      0      "
            print "|             "
            print "|             "
            print "|             "
        elif guesses == 2:
            print "________      "
            print "|      |      "
            print "|      0      "
            print "|     /       "
            print "|             "
            print "|             "
        elif guesses == 3:
            print "________      "
            print "|      |      "
            print "|      0      "
            print "|     /|      "
            print "|             "
            print "|             "
        elif guesses == 4:  
            print "________      "
            print "|      |      "
            print "|      0      "
            print "|     /|\     "
            print "|             "
            print "|             "
        elif guesses == 5:
            print "________      "
            print "|      |      "
            print "|      0      "
            print "|     /|\     "
            print "|     /       "
            print "|             "
        else:
            print "________      "
            print "|      |      "
            print "|      0      "
            print "|     /|\     "
            print "|     / \     "
            print "|             "
            print "GAME OVER, you lost! :("
            print "The word was ", the_word
            print "========================================"
            endmessage = 1
            sendServer(endmessage)
            self.__init__()

    def progress_updater(self, guess, the_word, progress):
        i = 0
        while i < len(the_word):
            if guess == the_word[i]:
                progress[i] = guess
                i += 1
            else:
                i += 1
        return "".join(progress)

game = Hangman()

Solution

  • Maybe you could make a loop instead of just creating only one Hangman instance, like this:

    while True:
        game = Hangman()
    

    instead of an infinite loop you can make an exit condition. For example in your class you may have a boolean variable that indicates if the game has ended or not.(for example lets say that the name of this variable is end)

    game = Hangman()
    while True:
        if not game.end:
            continue
        game = Hangman()