这是我的代码
code
__author__ = 'Jared Reabow'
__name__ = 'Assignment 2 Dice game'
#Date created: 14/11/2014
#Date modified 17/11/2014
#Purpose: A game to get the highest score by rolling 5 virtual dice.
import random
#pre defined variables
NumberOfDice = 5 #this variable defined how many dice are to be rolled
def rollDice(NumberOfDice):
dice = [] #this is the creation of an unlimited array (list), it containes the values of the 5 rolled dice.
RunCount1 = 1 #This defines the number of times the first while loop has run
while RunCount1 <= NumberOfDice:
#print("this loop has run " , RunCount1 , " cycles.") #this is some debugging to make sure how many time the loop has run
TempArrayHolder = random.randint(1,6) #This holds the random digit one at a time for each of the dice in the dice Array.
dice.append(TempArrayHolder) #this takes the TempArrayHolder value and feeds it into the array called dice.
RunCount1 += 1 #this counts up each time the while loop is run.
return dice
rollDice(NumberOfDice)
dice = rollDice(NumberOfDice)
print(dice,"debug") #Debug to output dice array in order to confirm it is functioning
def countVals(dice,NumberOfDice):
totals = [0]*6 #this is the creation of a array(list) to count the number of times, number 1-6 are rolled
#print(dice, "debug CountVals function")
SubRunCount = 0
while SubRunCount < NumberOfDice:
totals[dice[SubRunCount -1] -1] += 1 #this is the key line for totals, it takes the dice value -1(to d eal with starting at 0) and uses it
#to define the array position in totals where 1 is then added.
#print(totals)
SubRunCount += 1
return totals
countVals(dice,NumberOfDice)
totals = countVals(dice,NumberOfDice)
print("totals = ",totals)
缩进可能有点不对,我是stackoverflow的新手。 标题中陈述的问题是,无论是否调用,两个函数都将运行,但如果调用它们将运行两次。
我在某处读取了删除括号的内容:
dice = rollDice(NumberOfDice)
这就是这个
dice = rollDice
会解决这个问题,并且在某种程度上它会做一些事情而不是我想要的事情。 如果我这样做,它会输出
<function rollDice at 0x00000000022ACBF8> debug
而不是运行该功能,所以我很难被卡住。
我很欣赏有关正在发生的事情的详细解释?
更新:我错误地调用了两次该函数。 我以为我需要先运行它才能使用它返回的输出,但是只要在代码中使用它就不会。
答案 0 :(得分:0)
你两次致电rollDice()
:
rollDice(NumberOfDice)
dice = rollDice(NumberOfDice)
第一次忽略返回值时,您可以删除该调用。
您对countVals
执行相同的操作:
countVals(dice,NumberOfDice)
totals = countVals(dice,NumberOfDice)
同样,那个两个调用,而不是一个,第一个忽略了返回值;只需删除这些行。