samedi 29 juillet 2017

2 programs playing against eachother

I'm currently writing 2 programs in python that must play a number game against each other. One program picks a number between 1 and 100. Then the other attempts to guess what that number is. Each time the guesser gives it's guess, the chooser then replies with 'too big', 'too small', or 'you got it'. According to what the reply is the guesser adjusts its next guess accordingly.

Here's my code for the program that chooses:

    import random
from guesser import g

guessCount = 0

number = random.randint(1, 100)
print("I'm thinking of a number between 1 and 100.")

outfile = open ('response.txt', 'w')
guess = 50
print (guess)
if guess < number:
    print('Your guess is too low.') 
    switch = '1'
    outfile.write (switch + '\n')

elif guess > number:
    print('Your guess is too high.')
    switch = '2'
    outfile.write (switch + '\n')
else:
    print('Correct, You guessed the number in', guessCount, 'guesses.')
    switch = '3'
    outfile.write (switch + '\n')



while guessCount < 8:
    guess = g
    print (guess)
    guessCount += 1

    if guess < number:
        print('Your guess is too low.') 
        switch = '1'
        outfile.write (switch + '\n')

    elif guess > number:
        print('Your guess is too high.')
        switch = '2'
        outfile.write (switch + '\n')
    else:
        print('Correct, You guessed the number in', guessCount, 'guesses.')
        switch = '3'
        outfile.write (switch + '\n')
        break

outfile.close()
print('The number was',number)

And here's the code for the program that gives the guesses:

low = 1
high = 100
guess = 0


guessCounter = 0

infile = open ('response.txt', 'r')  
switch = int (infile.readline())

def g (switch):

    while switch != 3 and guessCounter < 8:
        guess = (low+high)//2
        guessCounter += 1

        if switch == 1:
            high = guess

        elif switch == 2:
            low = guess + 1

        return guess    

My main question is how to get the 2 programs to interact with eachother. I'm currently trying to use a method of having them communicate through a text file called response, but surely there's an easier way?

The main problem I'm having it seems is that when chooser tries to get the variable g from guesser it can't because there's no response currently in response.txt meaning switch = int ('')

Traceback (most recent call last): File "C:\Users\Jash\Downloads\guesser.py", line 8, in switch = int (infile.readline()) ValueError: invalid literal for int() with base 10: ''

And yes, they must be 2 separate programs. And it must be done in python.

Aucun commentaire:

Enregistrer un commentaire