【问题标题】:2 programs playing against eachother2个节目互相对战
【发布时间】:2017-07-29 20:21:59
【问题描述】:

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

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

The ma​​in 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(最近一次调用最后一次):文件 “C:\Users\Jash\Downloads\guesser.py”,第 8 行,在 switch = int (infile.readline()) ValueError: int() 以 10 为底的无效文字:''

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

【问题讨论】:

  • 你想单独启动你的脚本,还是如果你有一个为其他脚本创建子进程的主脚本可以吗?
  • 或者你可以使用套接字。
  • @michip96 他们是否单独开始都没有关系,这是针对我的一个班级的小组项目。我已经达到了我只是想尝试直到它起作用的地步哈哈任何帮助都非常感谢。

标签: python if-statement ipc


【解决方案1】:

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

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

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

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

【讨论】:

    【解决方案2】:

    您可以像这样从主脚本中打开子脚本:

    from subprocess import Popen, PIPE
    
    prog = Popen("child.py", shell=True, stdin=PIPE, stdout=PIPE)
    
    prog.stdin.write("Message to child.py maybe from another child?\n")
    print prog.stdout.read() #Response from child
    
    prog.wait() # Wait for script to finish run next script
    

    【讨论】:

      【解决方案3】:

      正如马特·蒂默曼斯所说: 如果不是绝对必要,将整个逻辑放到一个程序中:

      import random
      
      def createNum():
          return random.randint(1,101)
      
      lastGuess = 0
      randMin, randMax = 1, 101
      def guessNum(sigmoidAdjustmentInt):
          # sigmoidAdjustmentInt represents a number which is negative, equal to zero or positiv; e.g. [-1 / 0 / +1]
          #   0 == no information about to big or to small number
          #   -1 == number has to be smaller this time
          #   1 == number has to be bigger this time
          # guess somehow; e.g. with random again
          if sigmoidAdjustmentInt < 0:
              randMax = lastGuess-1
          elif 0 < sigmoidAdjustmentInt:
              randMin = lastGuess+1
          return random.randint(randMin,randMax)
      
      def main():
          secretNumber = createNum()
          guessedCorrectly = False
          triesCounter = 0
          sigmoidAdjustmentInt = 0 # set here for the first call
          while not guessedCorrectly:
              triesCounter = 0
              if guessNum(sigmoidAdjustmentInt) == secretNumber:
                  guessedCorrectly = True
                  break
              # print here if too high or low
          print("needed guesses: "+ triesCounter)
          # do something else
      

      请注意,createNum 和guessNum 的random.randint(...) 调用只是您首选实现的占位符。

      另请参阅:random.randint

      至于您的问题如何执行多个脚本。 假设你有 3 个文件:

      a.py
      b.py
      c.py
      

      你启动a.py,它会做一些事情,调用b.py,然后调用c.py 并得到结果。 你可以这样做:

      # in a.py
      import subprocess
      
      args = ( # rebuild the commandline call of the file here; the following stands for the comandline command: python b.py
          "python", # every whitespace in the cmd-command is a comma in this args-tuple
          "b.py"
      )
      popen = subprocess.Popen(args, stdout=subprocess.PIPE)
      popen.wait()
      resultsOfB, errorsOfB = popen.communicate()
      del popen
      
      args = ( # this represents: python c.py someStringValueContainedInResultFromB
          "python",
          "c.py",
          resultOfB # lets just say this var contains a string => if not convert it to one
      )
      popen = subprocess.Popen(args, stdout=subprocess.PIPE)
      popen.wait()
      resultsOfC, errorsOfC = popen.communicate()
      # do something with the results of c.py
      

      再次:如果您编写所有三个文件,请考虑将它们合二为一。如果您必须调用第三方软件或类似的东西,这种方法很好(例如:)

      【讨论】:

        【解决方案4】:

        创建第三个,裁判程序。取两个参数 - 选择器和猜测器程序的名称。让裁判程序打开两个程序的读/写管道,并使用subprocesspexpect 模块。

        【讨论】:

          猜你喜欢
          • 2012-07-28
          • 1970-01-01
          • 2020-12-22
          • 2020-09-18
          • 1970-01-01
          • 1970-01-01
          • 2020-04-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多