需要帮助用Python/Sage编写算法吗

需要帮助用Python/Sage编写算法吗,python,algorithm,sage,Python,Algorithm,Sage,我是python和sage的完全新手,所以我需要一些帮助和对所有步骤的澄清。这是一个关于博弈论的问题 首先,我将描述算法,然后我将尽我所能提出一个解决方案 算法: 我想用一个1-100的随机变量来启动程序。这 变量将被定义为“S”。我还想定义一组变量 每个回合都可以从S中扣除的“C”,这个集合是{1,2,3,4,5,6} (换句话说,用户和计算机可以扣除1、2、3、4、5或6。) 从S开始。如果变量S可被7整除(例如21),则打印:“I 如果没有,游戏就可以开始了 假设随机变量是20,玩家是 现

我是python和sage的完全新手,所以我需要一些帮助和对所有步骤的澄清。这是一个关于博弈论的问题

首先,我将描述算法,然后我将尽我所能提出一个解决方案

算法:

我想用一个1-100的随机变量来启动程序。这 变量将被定义为“S”。我还想定义一组变量 每个回合都可以从S中扣除的“C”,这个集合是{1,2,3,4,5,6} (换句话说,用户和计算机可以扣除1、2、3、4、5或6。) 从S开始。如果变量S可被7整除(例如21),则打印:“I 如果没有,游戏就可以开始了

假设随机变量是20,玩家是 现在提示输入C范围内的数字。当玩家 已经输入了号码,我希望程序从中扣除该号码 S、 因此,如果玩家输入4(合法移动),则S为20-4=16 然后计算机计算模(S,7),发现模16,7等于2 所以它从S中减去2,换句话说,16-2=14。 如果玩家输入的数字导致S可被7整除,例如6(20-6=14),那么计算机只需减去1,并尝试在下一轮再次获得该数字

游戏将继续进行,直到电脑最终以玩家的身份获胜 最终被排在7位,并且必须扣除计算机上显示的数字 可以完成(用户扣除6,计算机扣除最后一个) 打印:“我赢了”

正如我所说,我实际上没有python和sage方面的经验,所以我只能依靠我(有限的)java经验:

我会尝试用一些“ran”元素建立一个变量S(不知道它在python中叫什么)

if S%7=0 then print "I lose"

else

prompt "Pick a number between 1 and 6, those included".

Declare user input as variable U.

Do S-U=S

Now do S-S%7=S
现在我想让程序在
S=7
时实现,然后打印:“你输了”。不过,如果你能一直帮我,那就太好了

S=random.randint(1,100) #will pick a random number

user_input = int(raw_input("Enter a number:")) #will get an integer from the user

#subtraction and modulo work just like in any other language ...

if(condition):
    do_something() #is the format for if statements
这包括你所有的问题吗?还是我遗漏了一些

import random

def playgame():
    s = random.randint(1,100) #grabs a random integer between 1 and 100
    POSS = range(1,7) #range ignores the last number, so this is [1,2,3,4,5,6]
    if not s % 7: #if s%7 != 0
        print("I lose")
        return #exit the function
    while s > 0: #while s is still positive
        choice = 0 #set choice to 0 (this may as well have been "foo",
                   #                 I just needed it to not be in POSS)
        while choice not in POSS: #until the user picks a valid number
            choice = int(input("Select a number between 1 and 6: ")) #prompt for input
        s -= choice #subtract choice from s, then set the difference to s
        print("You subtracted {}, leaving {}".format(choice,s)) #print for the user
        comp_choice = s%7 #the computer's choice is always s%7
        s -= comp_choice #subtract the comp's choice from s, then set the diff to s
        print("I subtracted {}, leaving {}".format(comp_choice,s)) #print for user
    print("I win!") #since we know computer will always win, I don't have to do a check

playgame() #run the function
这里有一个非常复杂的函数,它基本上做着相同的事情;-)

类实体(对象):
“”“不应单独实例化的基类--”
存在要从中继承的。请改用Player()和Computer()
def uuu init uuuu(self,name=None):
如果名称为“无”:
name=输入(“你叫什么名字?”)
self.name=名称
self.myturn=False
定义(自我):
#这个神奇的函数意味着调用str(self)返回str(self.name)
#包括,以便我可以打印(播放器)
返回self.name
def makemove(自我,选择):
“”“查找全局s并从中减去给定的选项,
将选择和结果打印给用户。”“”
全球s
s-=选择
打印(“{}选择{},留下{}”。格式(self,choice,s))
返回选择
def激活(自):
self.myturn=True
回归自我
def停用(自我):
“”“完全执行self.myturn=False”“”
self.myturn=False
职业玩家(实体):
“”“玩家控制的实体”“”
def getchoice(自我选择):
“”“提示用户进行选择,确保其介于1和6之间,然后
以该参数“”调用实体的makemove()
选择=无
当选择不在范围(1,7)内时:
choice=int(输入(“选择一个介于1和6之间的数字:”)
return super().makemove(选项)
类计算机(实体):
定义初始化(自):
super()。\uuuu init\uuuuu(name=“计算机播放器”)
#覆盖以确保每个计算机对象都具有名称Computer Player
def getchoice(自我选择):
“”“为计算机获取一个号码,并进行移动”“”
全球s
选择=s%7
如果选择==0:#边缘情况下,计算机首先在s上运行,其中s%7==0
choice=random.randint(1,6)
return super().makemove(选项)
班级游戏(对象):
“”“定义游戏实例的类
功能:

Game.start()这看起来不错,但我得到一个错误:文件“main.py”,第12行choice=int(输入(“选择一个介于1和6之间的数字:”)^IndentationError:unindent与任何外部缩进级别都不匹配我正在尝试运行它。我希望在开始处理它之前看到它运行。在没有提示的情况下复制时,它看起来像是PythonWin混合了带空格的选项卡。我现在已经更改了它。但是如果您尝试联机运行它,当它提示用户输入时,这几乎肯定会失败。当我通过你链接的实用程序运行它时,当脚本请求用户输入时,它给了我一个EOFError。它现在工作得很好!我将分析代码并从中学习。非常感谢!@user320098我对描述每一行的代码进行了注释。我将为你写一些东西如果您想了解更多关于Python的知识,请稍微复杂一点。
class Entity(object):
    """Base class that should not be instantiated on its own -- only
       exists to be inherited from. Use Player() and Computer() instead"""
    def __init__(self,name=None):
        if name is None:
            name = input("What's your name? ")
        self.name = name
        self.myturn = False
    def __str__(self):
        # this magic function means calling str(self) returns str(self.name)
        # included so I can do print(player)
        return self.name

    def makemove(self,choice):
        """finds the global s and subtracts a given choice from it,
           printing the choice and the result to the user."""
        global s
        s -= choice
        print("{} chooses {}, leaving {}".format(self,choice,s))
        return choice
    def activate(self):
        self.myturn = True
        return self
    def deactivate(self):
        """does exactly self.myturn = False"""
        self.myturn = False

class Player(Entity):
    """A player-controlled Entity"""
    def getchoice(self):
        """Prompts the user for a choice, ensuring it's between 1 and 6, then
           calls Entity's makemove() with that as an argument"""
        choice = None
        while choice not in range(1,7):
            choice = int(input("Pick a number between 1 and 6: "))
        return super().makemove(choice)

class Computer(Entity):
    def __init__(self):
        super().__init__(name="Computer Player")
        #overrides to ensure every Computer object has the name Computer Player

    def getchoice(self):
        """grabs a number for the computer, and makes its move"""
        global s
        choice = s%7
        if choice == 0: #edge case where computer goes first on an s where s%7==0
            choice = random.randint(1,6)
        return super().makemove(choice)

class Game(object):
    """Class defining an instance of the Game

FUNCTIONS:
 Game.start() <-- use this to start the game"""

    def __init__(self,playerArray=[]):
        """defines s as a global, ensures the players array is built
           correctly, and gives s a random int value between 1-100"""
        global s
        if type(playerArray) is Player:
            playerArray = [playerArray]
        while len(playerArray) < 2:
            playerArray.append(Computer())
        self.players = playerArray
        s = random.randint(1,100)

    def start(self):
        """Let's play!"""

        global s
        print ("""
====================================
 THE GAME BEGINS NOW!!!
 We will begin with a value of: {:3}
====================================""".format(s).lstrip())
        turn = random.randint(1,len(self.players))-1

        while True:
            try:active_player = self.players[turn].activate()
            except IndexError: print(turn)
            choice = active_player.getchoice()
            if s <= 0: break
            active_player.deactivate() # is active_player.myturn = False
            turn += 1
            if turn == len(self.players): turn = 0 #wrap the list
        for player in self.players:
            #this will execute the turn s becomes zero
            if player.myturn:
                winner = player
                break
        print("Winner: {}".format(winner))

import random

game = Game()
game.start()