我目前正在用python编写2个程序,这些程序必须彼此对抗。一个程序选择一个介于1和100之间的数字。然后另一个程序尝试猜测该数字是多少。每次猜测者给出猜测时,选择者都会回答“太大”,“太小”或“得到”。根据答复是猜测者相应地调整其下一个猜测。

这是我选择的程序的代码:

    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)


这是给出猜测的程序代码:

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


我的主要问题是如何使这两个程序相互交互。我目前正在尝试使用一种使它们通过称为响应的文本文件进行通信的方法,但是肯定有更简单的方法吗?

我遇到的主要问题似乎是,当选择器尝试从猜测器中获取变量g时,它不能这样做,因为response.txt中当前没有响应,这意味着switch = int('')


  追溯(最近一次通话):文件
  第8行中的“ C:\ Users \ Jash \ Downloads \ guesser.py”
      switch = int(infile.readline())ValueError:int()以10为底的无效文字:''


是的,它们必须是2个单独的程序。而且必须在python中完成。

最佳答案

将两个播放器放在同一程序中会容易得多。

但是,如果您确实想使用2,则可以在unix或linux上像这样运行它们:

echo "" > somefile
tail -f somefile | program1 | program2 >> somefile


这将有效地将每个程序的输出传递到另一个程序的输入中。当然,您要查看的任何内容均应打印为标准错误。

关于python - 2个程序互相对战,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45393695/

10-13 09:37
查看更多