如何将两个代码/程序放在一起?

时间:2015-08-22 13:50:03

标签: python menu

我不确定如何将这两个代码与菜单放在一起,以便能够选择其中一个运行,就像这样的东西:

Welcome to (etc etc)
What would you like to play?
All computer generated OR You vs computer?
Selection 1 or 2? Please enter your selection:

或者那些东西。 我对编码很新,所以我不知道如何处理这个问题。非常感谢所有帮助:)

以下是两个代码,如果有帮助的话: 代码1(计算机生成);

import sys
import time
import random

#Build a list to convert move numbers to names
move_names = "rock Spock paper lizard scissors".split()

#Build a dict to convert move names to numbers
move_numbers = dict((name, num) for num, name in enumerate(move_names))

win_messages = [
    "Computer 2 and Computer 1 tie!",
    "Computer 1 wins!",
    "Computer 2 wins!",
]

def rpsls(name): 
    # convert Computer 1 name to player_number
    player_number = move_numbers[name]

    # generate random guess Computer 2
    comp_number = random.randrange(0, 5)

    # compute difference modulo five to determine winner
    difference = (player_number - comp_number) % 5

    print "\nComputer 2 chooses", name
    print "Computer 1 chooses", move_names[comp_number]
    #print "Score was:", difference # XXX

    #Convert difference to result number.
    #0: tie. 1: Computer 1 wins. 2:Computer 2 wins
    if difference == 0: 
        result = 0
    elif difference <= 2:
        result = 2
    else:
        result = 1

    return result


def main():
    banner = "! ".join([word.capitalize() for word in move_names]) + "!.\n"
    print "Welcome to..."
    for char in banner:
        sys.stdout.write(char)
        sys.stdout.flush()
        time.sleep(0.02)

    print "Rules!:"
    print """\nScissors cuts Paper
    Paper covers Rock
    Rock crushes Lizard
    Lizard poisons Spock
    Spock smashes Scissors
    Scissors decapitates Lizard
    Lizard eats Paper
    Paper disproves Spock
    Spock vaporizes Rock
    (and as it always has) Rock crushes scissors"""
    print "\n<Follow the enter key prompts!>"
    raw_input("\n\nPress the enter key to continue.")

    #A list of moves for Computer 1
    computer1_moves = [
        "rock",
        "Spock",
        "paper",
        "lizard",
        "scissors",
        "rock",
        "Spock",
        "paper",
        "lizard",
        "scissors",
    ]

    #Create a list to hold the scores
    scores = [0, 0, 0]

    for name in computer1_moves:
        result = rpsls(name)
        scores[result] += 1 
        print result, win_messages[result], scores
        raw_input("\n\nPress the enter key to continue.")

    print "\nFinal scores"
    print "Computer 1 wins:", scores[1]
    print "Computer 2 wins:", scores[2]
    print "Ties:", scores[0]

    raw_input("\n\nPress the enter key to exit")


if __name__ == "__main__":
    main()

代码2(你和电脑);

import random 

data = "rock", "spock", "paper", "lizard", "scissors"

print "Rules!:"
print """Scissors cuts Paper
Paper covers Rock
Rock crushes Lizard
Lizard poisons Spock
Spock smashes Scissors
Scissors decapitates Lizard
Lizard eats Paper
Paper disproves Spock
Spock vaporizes Rock
(and as it always has) Rock crushes scissors"""

def playgames():
  tally = dict(win=0, draw=0, loss=0)
  numberofgames = raw_input("How many games do you want to play? ")
  numberofgames = int(numberofgames)
  for _ in range(numberofgames):
    outcome = playgame()
    tally[outcome] += 1
  print """
  Wins: {win}
  Draws: {draw}
  Losses: {loss}
  """.format(**tally)

def playgame():
  choice = ""
  while (choice not in data):
    choice = raw_input("Enter choice (choose rock , paper , scissors , lizard, or spock):")
    choice = choice.lower()
  print "Player choice is:{}".format(choice)
  player_number = data.index(choice)
  computer_number = random.randrange(5)
  print "Computer choice is: {}".format(data[computer_number])
  difference = (player_number - computer_number) % 5
  if difference in [1, 2]:
    print "Player wins!"
    outcome = "win"
  elif difference == 0:
    print "Player and computer tie!"
    outcome = "draw"
  else:
    print "Computer wins!"
    outcome = "loss"
  return outcome

playgames()

raw_input("\n\nPress the enter key to exit.")

2 个答案:

答案 0 :(得分:0)

快速简单的黑客就是创建一个运行code1.py或code2.py的menu.py,具体取决于用户输入。

#menu.py

import os

print """
Welcome to (etc etc)
What would you like to play?
All computer generated OR You vs computer?
Selection 1 or 2? Please enter your selection:
"""

choice = raw_input()


if choice == '1':
    os.system('code1.py')
elif choice == '2':
    os.system('code2.py')
else:
    print 'invalid choice'

将menu.py,code1.py和code2.py全部放在同一目录中,然后运行menu.py。

答案 1 :(得分:0)

将您的第一个脚本命名为script1.py。现在将其添加到第二个脚本的顶部

import script1

以下代码片段位于第二个脚本的末尾:

print("Welcome! What would you like to play?")
print("All computer generated OR You vs computer?")
print("Selection 1 or 2? Please enter your selection:")

while True:
    choice = int(input())
    if choice == 1:
        script1.main()
    elif choice == 2:
        playgames()
    else:
        print("Enter either 1 or 2!\n")

(我使用了python 3语法,但将它们转换为python 2)应该没问题。