2017-07-18 61 views
-1

我想要做的是讓Python生成一個介於1和6之間的數字,然後將6添加到該數字中,然後將其提供給我結果,但我似乎無法弄清楚是如何使可調用該值,因此可以在遊戲過程中有漲有跌,這裏是我到目前爲止有:在Python中隨機生成一個隨機生成的數字,可以隨時調用

import random 
import time 
Name = input("Before we get started lets get your character created, tell me what is your name?") 
print() 
print ("Welcome ",Name," to the adventure of a lifetime. The next thing you will need to do is sort out your character stats. This will require dice rolls which we will do within the game.") 
print() 

def skillroll(): 
    skillroll="" 

    while skillroll !="Y" and skillroll != "N": 
     skillroll = input("First we need to roll for your skill, would you like me to roll? Y/N") 

     if skillroll=="Y": 
      print("Rolling the dice..") 
      skill=random.randint(1,6) 
      time.sleep(2) 
      print("I rolled a", skill, " I will now add 6 to this so your skill is", skill+6) 
      skill=skill+6 
      print() 

    return skillroll 

skillroll() 

我只是不能看如何獲得最終答案,以便在遊戲中使用它。

我的一個朋友送我這個幫助 https://github.com/protocol7/python-koans/blob/master/python%202/koans/about_classes.py

但我只是不能看到這個關乎每一個答案,我就發現了#2是不同的語言。

+0

對於你的情況,定義和使用'skill'爲[全局變量](http://www.python-course.eu/global_vs_local_variables.php)應該足夠了。 – zwer

+0

我完全不明白。你想讓這個號碼在你的代碼中隨處可見嗎? –

+0

1.你不能有具有相同名稱的函數和變量,在python中,每個函數也是一個對象,所以你每次都覆蓋它 –

回答

1

只需使用:

import random 
random.randrange(1, 7) 

得到任何數字1和6

您的代碼就變成了:

import random 
import time 

def skillroll(): 
    skillroll="" 
    while skillroll !="Y" and skillroll != "N": 
     skillroll = input("First we need to roll for your skill, would you like me to roll? Y/N") 
     if skillroll=="Y": 
      print("Rolling the dice..") 
      skill = random.randrange(1, 7) 
      time.sleep(2) 
      print("I rolled a ", skill, ". I will now add 6 to this so your skill is", skill+6, "\n") 
      skill=skill+6 
      return skillroll # What if N?? 

Name = input("Before we get started lets get your character created, tell me 
what is your name?") 
print ("\nWelcome ",Name," to the adventure of a lifetime. The next thing you 
will need to do is sort out your character stats. This will require dice 
rolls which we will do within the game.\n") 
skillroll()