2014-01-15 42 views
0

我是python和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".

所以就像我說的,我有蟒蛇和鼠尾草字面上沒有經驗,所以我只能通過我的(有限)的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,然後打印意識到:「你輸」。如果你能一路幫助我,那會很棒。

回答

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

這看起來不錯,但我得到一個錯誤:文件「main.py」 12行 選擇= int(input(「Select a number between 1 and 6:」)) ^ IndentationError:unindent不匹配任何外部縮進級別 我試圖在http://www.compileonline.com/上運行它execute_python_online.php I'd li可以在我開始搞亂之前看到它運行。 – user3200098

+0

當我沒有提示進行復制時,看起來像PythonWin混合了空格和空格。我現在改變了它。 –

+0

雖然如果您嘗試在線運行它,但當它提示用戶輸入時幾乎肯定會失敗。當我通過鏈接的實用程序運行它時,當腳本詢問用戶輸入時,它給了我一個EOFError。 –

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 

這是否涵蓋了所有問題?還是我錯過了一些?