Python - 等待服务器输入的客户端(反之亦然)

时间:2016-07-26 19:21:29

标签: python serversocket

我对Python很新,我对Python中的套接字和服务器都很陌生,所以请耐心等待!基本上,我正在尝试在客户端和服务器之间建立一个刽子手游戏来玩游戏。我知道这个系统有一堆弱点(包括客户端而不是服务器端的大部分代码,我正在努力修复,但无论如何......)

本质上,我的客户启动游戏,并从服务器获取刽子手游戏“单词”的输入。游戏结束后,它再次播放init方法,以重启游戏。我希望它再次等待来自服务器的输入,因此它不会从第一次播放相同的输入。你有什么建议吗?

这是我的服务器代码:

#!/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"

这是我的客户代码:

#!/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()

1 个答案:

答案 0 :(得分:1)

也许你可以创建一个循环,而不是只创建一个Hangman实例,如下所示:

while True:
    game = Hangman()

而不是无限循环,你可以做出退出条件。例如,在你的类中你可能有一个布尔变量来指示游戏是否已经结束。(例如,假设这个变量的名称已经结束)

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