gpt4 book ai didi

python - 2个程序互相对抗

转载 作者:太空宇宙 更新时间:2023-11-03 14:57:43 26 4
gpt4 key购买 nike

我目前正在用 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 (' ')

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: ''

是的,它们必须是两个独立的程序。而且必须用Python来完成。

最佳答案

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

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

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

这将有效地将每个程序的输出通过管道传输到另一个程序的输入中。当然,您想看到的任何内容都应该打印到标准错误。

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com