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

标签 python algorithm sage

我是 python 和 sage 的新手,所以我需要一些帮助和对整个步骤的说明。这是一个关于博弈论的问题。

首先我会描述算法,然后我会尽可能地提出一个解决方案。

算法:

I want to start the program with a random variable from 1-100. This variable will be defined 'S'. I also want to define a set of variables 'C' which can be deducted from S every turn, this set is {1,2,3,4,5,6} (in other words the user and computer can deduct 1, 2, 3, 4, 5 or 6 from S. If variable S is divisible by 7 (e.g. 21), then print: "I lose". If not, the game can begin.

Let's say that the random variable turns out to be 20. The player is now prompted to enter a number within the range of C. When the player has entered the number, I want the program to deduct that number from S, so if the player enters 4 (a legal move), S is then 20-4=16. The computer then calculates mod(S,7) and finds out that modulo 16,7 is 2 so it deducts 2 from S, in other words, 16-2=14. If the player enters a number which results in S being divisible by 7, such as 6 (20-6=14) then the computer simply deducts 1 and attempts to get to such a number again next round.

The game continues until the computer eventually wins as the player is eventually placed at 7 and has to deduct a number which the computer can finish with (user deducts 6, computer deducts the last one and wins). Print: "I win".

所以就像我说的,我几乎没有 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 时实现,然后打印:“你输了”。不过,如果你能帮助我一路走下去,那就太好了。

最佳答案

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

关于python - 需要帮助在 Python/Sage 中编写算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21148885/

相关文章:

python argparse - 在没有参数的情况下向子解析器添加操作?

python - 如何在 Windows 上运行 SageTeX?

python - 将 Sage 提供的 Scipy 与自己的 python 结合使用

performance - RSA、ManagedRijndael 和 Managed AES 在 C# 中的性能差异比较

python - 如何更改 Sage 集成的 R 版本?

Python:没有变量的类实例化的意义是什么

python - re.sub 上的非贪婪运算符

python - 列表中 Python 中的无序对(对集)

python - 找到最少的删除次数以获得每个字母的唯一计数

c# - 三位数字的递归排列