-2

下面有很多代码,但您不必真正阅读任何代码,您只需要知道函数存在以及函数名称即可。我将首先描述我的问题。

我创建了一个完全基于函数和一些全局变量的程序程序,如下所示。我想将程序更改为面向对象的程序,但我遇到了麻烦,因为我以前从未做过这样的事情。

需要遵循的程序是: - 函数attack()需要放入名为attacker.py 的文件中 - 函数defence()、、updateVars()smartDefender()需要放入文件defender.py -main()函数和其余代码(大多数代码)将被放置在一个名为 manager.py 的文件中,该文件将成为主文件,并将所有内容放在一起。-我必须使用课程。

我尝试了一系列不同的事情,包括将函数的名称更改为__init__,然后导入并尝试在 manager.py 中使用它们。我还尝试保持函数名称相同,只是将函数放在类中并将攻击者.py 和防御者.py 导入 manager.py 但似乎没有任何工作......任何和所有帮助将不胜感激。

虽然我认为你并不需要对程序的功能进行描述,但如果你真的需要,我可以做一个简短的描述,或者你可以在这里查看。

任何和所有的帮助将不胜感激。

import random

HIGH= 3
MED= 2
LOW= 1

def attack(attackList):

    x= random.uniform(0,1)
    for attackLevel,probability in attackList:
        if x<probability:
            break
        x=x-probability
    return attackLevel





def defence(attackLevel,defendList):

    x= random.uniform(0,1)
    for defendLevel,probability in defendList:
        if x<probability:
            break
        x=x-probability
    return defendLevel





def updateVars(attackLevel,defendLevel,block,hit,run):

    if attackLevel==1:
        printAttackLevel='Low'
    if attackLevel==2:
        printAttackLevel='Medium'
    if attackLevel==3:
        printAttackLevel='High'
    if defendLevel==1:
        printDefendLevel='Low'
    if defendLevel==2:
        printDefendLevel='Medium'
    if defendLevel==3:
        printDefendLevel='High'



    if attackLevel==defendLevel:
        block=block+1
        hit=hit
        run=run+1
    else:
        block=block
        hit=hit+1
        run=run+1

    return block,hit,run,printAttackLevel,printDefendLevel





def smartDefender(defendLevel,attackLevel,smartList):

    for i in smartList:
        if (i==(i+1)==(i+2)):
            defendLevel= attackLevel
            return defendLevel
        else:
            return






def main():

    DEFAULT_PROBABILITY= 0.33
    run=0
    hit=0
    block=0
    smartList=[]


    rounds= int(input("\nPlease enter the number of rounds between 1 and 100:"))
    if rounds<=0 or rounds>100:
        print("\n")
        print("Invalid range. The number of rounds has been set to 10 by DEFAULT_PROBABILITY.")
        rounds=10


    lowAttackProb= float(input("\nPercentage of attacks aimed low(0-100):"))/100
    medAttackProb= float(input("Percentage of attacks aimed medium(0-100):"))/100
    highAttackProb= float(input("Percentage of attacks aimed high(0-100):"))/100
    if lowAttackProb+medAttackProb+highAttackProb !=1.00:
        print("\n")
        print("Invalid entry. The sum of the pecentages must equal 100%. The probability of each level has been set to 33.0% by DEFAULT_PROBABILITY.")
        lowAttackProb=DEFAULT_PROBABILITY
        medAttackProb=DEFAULT_PROBABILITY
        highAttackProb=DEFAULT_PROBABILITY


    print('\nLet The Fighting Begin')
    print('-'*22)


    while  run < rounds:

        lowDefProb= DEFAULT_PROBABILITY
        medDefProb= DEFAULT_PROBABILITY
        highDefProb= DEFAULT_PROBABILITY


        attackList= [(LOW,lowAttackProb),(MED,medAttackProb),(HIGH,highAttackProb)]
        attackLevel= attack(attackList)
        smartList.append(attackLevel)
        defendList=[(LOW,lowDefProb),(MED,medDefProb),(HIGH,highDefProb)]
        defendLevel=defence(attackLevel,defendList)
        block,hit,run,printAttackLevel,printDefendLevel= updateVars(attackLevel,defendLevel,block,hit,run)
        if run>(rounds/2):
            defendLevel=smartDefender(defendLevel,attackLevel,smartList)
            #implement smart mode

        print('%s%2s%s%3s%s%5s%s%3s'% ('\nRound',run,':\t','Attacker:',printAttackLevel,'\t','Defender:',printDefendLevel))


    print("%2s%2d%s%s%2d"% ('\nTotal Hits:',hit,'\t','Total Blocks:',block))
    print('Attacker Proportions:','','','Low:','','',lowAttackProb*100,'%','','','Medium:','','',medAttackProb*100,'%','','','High:','','',highAttackProb*100,'%')
    print('Defender Proportions:','','','Low:','','',lowDefProb*100,'%','','','Medium:','','',medDefProb*100,'%','','','High:','','',highDefProb*100,'%')
    print("\nThank you for using this program, Goodbye!")





main()

我的问题是,我怎样才能很容易(不一定有效地)将这些过程程序转换为使用类和多个文件的面向对象的程序。

我认为问题区域将包括调用函数的位置main(),如果这有助于解决问题的话..

4

2 回答 2

2

以防万一……我只是以这个基于类的脚本为例。

class Car():

    def __init__(self, mileage=0, mpg=10, tank_capacity=5):
        self.mileage = mileage
        self.mpg = mpg
        self.tank_capacity=tank_capacity
        self.tank_level = 0                

    def drive(self, miles):
        gallons_burned = float(miles) / self.mpg
        if self.tank_level < gallons_burned:
            miles_driven = float(self.tank_level) * self.mpg
            self.tank_level = 0
            self.mileage += miles_driven
            print "You ran out of gas after %s miles." % miles_driven
            return
        self.tank_level -= gallons_burned
        self.mileage += miles
        print "You made it to your destination after %s miles." % miles

    def pump_gas(self, gallons):
        self.tank_level += gallons
        if self.tank_level > self.tank_capacity:
            self.tank_level = self.tank_capacity
        print "You now have %s gallons in your tank" % self.tank_level

    def status(self):
        print "Mileage:", self.mileage
        print "Tank level: %s gallons" % self.tank_level

if __name__ == "__main__":
    my_car = Car(mileage=100, mpg=30, tank_capacity=3)
    my_car.pump_gas(4)
    my_car.status()
    my_car.drive(50)
    my_car.status()
    my_car.drive(60)
    my_car.status()

"""
You now have 3 gallons in your tank
Mileage: 100
Tank level: 3 gallons
You made it to your destination after 50 miles.
Mileage: 150
Tank level: 1.33333333333 gallons
You ran out of gas after 40.0 miles.
Mileage: 190.0
Tank level: 0 gallons
"""    
于 2012-12-07T16:18:48.803 回答
0

我现在没有足够的时间,但我在这里放了部分代码,应该对你有帮助,稍后我会添加更多

import random


class Attacker(object):
    def __init__(self, power):
    """In this method you can assign
        variables or perform actions which
        you want to perform on object create"""

        #for example on object create we want
        #to set strenght of attacker
        #so this variable will live and
        #availiable for object whole it's
        #life
        self.power = power

    def attack(self):
    """So attacker must can attack
        for example this method just
        return random int multiple on self.power 
        later we compare value of from defender's
        defend method and decide who is
        winner of round"""

        return random.randint(100) * self.power
于 2012-12-07T16:27:41.953 回答