2013-08-02 89 views
-1

我想在python中創建一個文本冒險遊戲。我正在使用randint創建一個介於0和2之間的數字,當我使用if語句獲取隨機數並將生物羣變量分配給生物羣類型時,它將使用原始版本的變量並將其用作生物羣。我有問題重新分配python中的變量

#Defines game() 
print ('''You are in a %s biome.'''%(biome)) 
biome='placeholder' 
import random 
trees=random.randint(0,50) 
biomes=random.randint(0,2) 
animals=random.randint(0,3) 
wolves=random.randint(0,5) 
if biomes == "0": 
    biome='Forest' 

if biomes == "1": 
    biome='Taiga' 

if biomes == "2": 
    biome='Mountain' 

print ('''You are in a %s biome.'''%(biome)) 
+0

您的問題的答案是正確的,但是Python使[[隨機]更容易。](http://docs.python.org/2/library/random.html#random.choice):'biome = random.choice(['Forest','Taiga','Mountain'])' – kevingessner

+0

@ user2438758,[接受答案](http://stackoverflow.com/help/accepted-answer)。 – falsetru

回答

2

random.randint(...)返回一個整數。您在這裏將值與一個字符串進行比較。

>>> type(randint(0, 2)) 
<type 'int'> 

if聲明應被改寫爲 -

if biomes == 0: 
    biome='Forest' 
elif biomes == 1: 
    biome='Taiga' 
else: 
    biome='Mountain' 

PS - 你並不需要三個if語句,因爲,如果該值是0,但絕不能因此12,所以不需要檢查條件。您可以改用if-elif-else構造。

4

biomes是int值。 "0"是字符串值。

兩個值永遠不可能相等。

>>> 0 == "0" 
False 

使用int文字。

if biomes == 0: 
    biome = 'Forest' 
elif biomes == 1: 
    biome = 'Taiga' 
elif biomes == 2: # else 
    biome = 'Mountain' 

我建議您使用其他建議的random.choice。簡單,易於閱讀。

>>> random.choice(['Forest', 'Taiga', 'Mountain']) 
'Mountain' 
>>> random.choice(['Forest', 'Taiga', 'Mountain']) 
'Mountain' 
>>> random.choice(['Forest', 'Taiga', 'Mountain']) 
'Taiga' 
+1

這裏你不需要三個獨立的'if'條件。 :) –

+0

它甚至更好的字典。 。 。 biome_map = {0:'forest',1:'taiga',:'mountain'}然後它就是biome = biome_map.get(biomes) – GoingTharn

+0

@GoingTharn,'random.choice(..)'更像pythoic, 。 – falsetru

0

我想你應該在嘗試if語句生物羣落== 1,而不是生物羣落==「1」與同爲生物羣落== 2和生物羣落== 3

0

那是因爲你是將整數值與字符串進行比較(永遠不會相等)。這將工作:

import random 
trees=random.randint(0,50) 
biomes=random.randint(0,2) 
animals=random.randint(0,3) 
wolves=random.randint(0,5) 

# Compare biomes (which is an integer) to another integer 
if biomes == 0: 
    biome='Forest' 

# Use elif for multiple comparisons like that 
elif biomes == 1: 
    biome='Taiga' 

# Use an else here because the only other option is 2 
else: 
    biome='Mountain' 

print ('''You are in a %s biome.'''%(biome)) 

請注意我也刪除腳本的第一和第二行。第一個將被炸燬,因爲biome尚未定義,第二個什麼都不做。

1

這裏是一個更容易理解的方式:

from random import choice 
biomes = ['Forest', 'Tiaga', 'Mountain'] 
biome = choice(biomes) 

這時如果生物羣落的數量增加或減少時,您不必擔心更新範圍內的隨機數,不是很讓你if陳述的權利...

1

您需要在if biome == 0:

但是比較0而不是字符串值"0",這可以用01來簡化從列表中隨機選擇一個生物羣系。

biome = random.choice(['Forest', 'Taiga', 'Mountain']) 

並且完全消除您的if