mardi 29 mars 2016

Socket Programming Python While and If issues

I am trying to write a hangman game using python using a simple client and server. I have the server opening and listening on the socket and then I have the client connecting to the server and sending a message and the server responding with a secret word represented by _ * by the letter count of the secret word.

I have written a hangman game that doesn't use sockets so I have that but the issue is I cannot get the If statements to work. They either return nothing or they bring up syntax errors. Here is the server without the if statement

import socket
import random

#Characters and places from HHGTTG to make it a little more difficult

word_list = [ 'agrajag','altairians','android','apple','arthur','beeblebrox',
              'betelgeuse','colin','dent','dentrassis','dolphins','eddie','fenchurch',
              'ford','galaxy','gargravarr','garkbit','god','golgafrinchans','guide',
              'hactar','harmless','hello','hitchhikers','hooloovoo','hyperspace',
              'krikkiters','lallafa','laminate','lamuella','magrathea','marvin',
              'panic','paranoid','prefect','random','roosta','russell',
              'slartibartfast','sorcerer','thor','towel','trillian','vogon','willow',
              'zaphod','zarniwoop','zarquon','zem']

lowercase = ['q','w','e','r','t','y','u','i','o','p','l','k','j','h','g','f',
             'd','s','a','z','x','c','v','b','n','m']

secret_word = random.choice(word_list)

guesses=0
letters_guessed = []
word = []


#while testing i used this a lot and i have left it in in case you want to cheat as well
#print(secret_word)

for x in range(len(secret_word)):
    word.append('_ ')

arthur = ("\n %s"%''.join(word))

def Main():
    host = ''
    port = 4242

    s = socket.socket()
    s.bind((host,port))

    s.listen(1)
    c, addr = s.accept()
    print("Connection from: " + str(addr), secret_word)
    while True:
        data = c.recv(1024).decode('utf-8')
        if not data:
            break
        print("from connected user: " + data)
        data = data.upper()
        print("sending: " + arthur)
        c.send(arthur.encode('utf-8'))
    c.close()

if __name__ == '__main__':
    Main()

The if statement causing so much headache is this

while True:
        data = c.recv(1024).decode('utf-8')
        if len(data) == 1:
            print ("BlaBlaBla")
        else:
            print ("Bohoohooho")

Obviously that isn't the actually if and else statements i will be using in the game but it is my test and it isn't working. It keeps coming up with syntax errors which i check and then it

Aucun commentaire:

Enregistrer un commentaire