需要帮助在Python / Sage中编写算法

时间:2014-01-15 21:44:50

标签: python algorithm sage

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

首先,我将描述算法,然后我会尽力提出解决方案。

算法:

  

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

     

让我们说随机变量是20。玩家是   现在提示输入C范围内的数字。当玩家   已输入号码,我希望程序从中扣除该号码   S,所以如果玩家进入4(合法移动),则S为20-4 = 16。该   然后计算机计算mod(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时实现,然后打印:“你输了”。但是,如果你可以帮助我一路走下去,那就太棒了。

2 个答案:

答案 0 :(得分:1)

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

这是一个非常复杂的功能,基本上完全相同; - )

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()

答案 1 :(得分:0)

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

这涵盖了你所有的问题吗?还是我错过了一些?