将代码转换为Python类

2024-09-29 09:23:55 发布

您现在位置:Python中文网/ 问答频道 /正文

在我发布我的问题之前,我想声明一下,我对Python还是非常陌生的,并且很难掌握类的窍门。我现在正在做一个程序,模拟一场篮球比赛,然后输出一个分数。程序运行得很好;但是,我意识到最好将代码放入一个类中,以避免将来代码变得难以编辑的问题。让我得出这个结论的第一个原因是我意识到,要考虑到加班时间,我基本上必须复制和粘贴我所有的代码。我意识到这将是非常低效的,所以决定寻找一个更好的方法来做这件事。我将尽可能具体地解释我要做的事情,以便你们能够提供帮助。你知道吗

首先,这是我的代码:

#Python NBA Sim Engine
#Started 6-8-2013, 10:59 PM
#Classes
import random
#Player Database
#Player = [Outside,Mid-Range,Inside,Passing,Ball Handling,Dunk,Perimeter,
#Post,Block,Steal,Speed,Strength,Height,Weight,Name]

#Miami Heat
Chris_Bosh = [67,78,87,44,41,78,34,77,81,31,60,64,'6.11',228,'Chris Bosh']
Udonis_Haslem = [24,78,81,32,39,60,44,80,59,30,57,84,'6.8',235,'Udonis Haslem']
Lebron_James = [76,72,97,97,84,97,96,88,80,88,97,90,'6.8',260,'Lebron James']
Dwayne_Wade = [66,69,90,64,78,82,80,51,42,77,89,70,'6.4',220,'Dwayne Wade']
Mario_Chalmers = [79,73,70,68,78,48,80,29,22,75,79,68,'6.2',190,'Mario Chalmers']
#San Antonio Spurs
Tim_Duncan = [31,64,94,60,33,70,30,98,80,22,33,88,'6.11',255,'Tim Duncan']
Tiago_Splitter = [4,21,75,30,17,70,39,74,60,21,35,71,'6.11',240,'Tiago Splitter']
Kawhi_Leonard = [74,75,75,66,66,84,89,52,60,78,77,60,'6.7',225,'Kawhi Leonard']
Manu_Ginobili = [80,77,80,80,75,29,64,20,11,55,70,41,'6.6',205,'Manu Ginobili']
Tony_Parker = [74,82,95,82,93,30,60,15,19,65,97,22,'6.2',185,'Tony Parker']
#Cleveland Cavaliers
Anderson_Varejao = [42,61,85,59,39,75,51,89,61,52,57,60,'6.11',240,'Anderson Varejao']
Tristan_Thompson = [20,44,80,39,32,82,44,77,77,29,59,73,'6.9',227,'Tristan Thompson']
Alonzo_Gee = [75,68,71,59,60,90,90,67,54,81,80,80,'6.6',219,'Alonzo Gee']
Dion_Waiters = [75,79,88,70,78,86,56,30,32,61,89,49,'6.4',215,'Dion Waiters']
Kyrie_Irving = [87,88,96,82,98,72,56,25,32,74,91,30,'6.3',191,'Kyrie Irving']

#Team Database
MIA = [Chris_Bosh,Udonis_Haslem,Lebron_James,Dwayne_Wade,Mario_Chalmers]
SAS = [Tim_Duncan,Tiago_Splitter,Kawhi_Leonard,Manu_Ginobili,Tony_Parker]
CLE = [Anderson_Varejao,Tristan_Thompson,Alonzo_Gee,Dion_Waiters,Kyrie_Irving]
#Engine
def engine():
    print ("1.Miami Heat\n2.San Antonio Spurs\n3.Cleveland Cavaliers")
#Variables
    Time = 2880
    FGA=0
    HTS=0
    ATS=0
#Team Names
    HTN=""
    ATN=""
#Team Variable
    HT=0
    AT=0
    HTM=input("Select home team: ")
    if HTM=="1":
        HT=MIA
        HTN="Miami"
    if HTM=="2":
        HT=SAS
        HTN="San Antonio"
    if HTM=="3":
        HT=CLE
        HTN="Cleveland"
    ATM=input("Select away team: ")
    if ATM=="1":
        AT=MIA
        ATN="Miami"
    if ATM=="2":
        AT=SAS
        ATN="San Antonio"
    if ATM=="3":
        AT=CLE
        ATN="Cleveland"
#Shooting Formula
    num1HPG=(HT[4][0])-(AT[4][6]/2)
    num2HPG=(HT[4][1])-(AT[4][6]/2)
    num3HPG=(HT[4][2])-(AT[4][6]/2)
    num1APG=(AT[4][0])-(HT[4][6]/2)
    num2APG=(AT[4][1])-(HT[4][6]/2)
    num3APG=(AT[4][2])-(HT[4][6]/2)
###
    num1HSG=(HT[3][0])-(AT[3][6]/2)
    num2HSG=(HT[3][1])-(AT[3][6]/2)
    num3HSG=(HT[3][2])-(AT[3][6]/2)
    num1ASG=(AT[3][0])-(HT[3][6]/2)
    num2ASG=(AT[3][1])-(HT[3][6]/2)
    num3ASG=(AT[3][2])-(HT[3][6]/2)
###
    num1HSF=(HT[2][0])-(AT[2][6]/2)
    num2HSF=(HT[2][1])-(AT[2][6]/2)
    num3HSF=(HT[2][2])-(AT[2][6]/2)
    num1ASF=(AT[2][0])-(HT[2][6]/2)
    num2ASF=(AT[2][1])-(HT[2][6]/2)
    num3ASF=(AT[2][2])-(HT[2][6]/2)
###
    num1HPF=(HT[1][0])-(AT[1][6]/2)
    num2HPF=(HT[1][1])-(AT[1][6]/2)
    num3HPF=(HT[1][2])-(AT[1][7]/2)
    num1APF=(AT[1][0])-(HT[1][6]/2)
    num2APF=(AT[1][1])-(HT[1][6]/2)
    num3APF=(AT[1][2])-(HT[1][7]/2)
###
    num1HC=(HT[0][0])-(AT[0][6]/2)
    num2HC=(HT[0][1])-(AT[0][6]/2)
    num3HC=(HT[0][2])-(AT[0][7]/2)
    num1AC=(AT[0][0])-(HT[0][6]/2)
    num2AC=(AT[0][1])-(HT[0][6]/2)
    num3AC=(AT[0][2])-(HT[0][7]/2)
#Calculation:
    while Time > 0:
        pos=random.randint(0,4)
        Sub = random.randint(4,24)
#Home Team
        #Center
        if pos == 0:
            sht=random.randint(1,3)
            if sht==1:
                chance=random.randint(1,100)
                if chance <=num1HC:
                    print (HT[0][14],"hits a three!")
                    HTS = HTS + 3
                    FGA = FGA + 1
                    Time = Time - Sub
                else:
                    print (HT[0][14],"misses from deep.")
                    FGA = FGA + 1
                    Time = Time - Sub
            if sht==2:
                chance=random.randint(1,100)
                if chance <=num2HC:
                    print (HT[0][14],"nails the long two.")
                    Time = Time - Sub
                    HTS = HTS + 2
                    FGA = FGA + 1
                else:
                    print (HT[0][14],"comes up short from mid range.")
                    Time = Time - Sub
                    FGA = FGA + 1
            if sht==3:
                chance=random.randint(1,100)
                if chance <=num3HC:
                    print (HT[0][14],"backs down",AT[0][14],"and lays it in for two.")
                    Time = Time - Sub
                    HTS = HTS + 2
                    FGA = FGA + 1
                else:
                    print (HT[0][14],"misses from close range.")
                    Time = Time - Sub
                    FGA = FGA + 1
            #Power Forward
        if pos == 1:
            sht=random.randint(1,3)
            if sht==1:
                chance=random.randint(1,100)
                if chance <=num1HPF:
                    print (HT[1][14],"hits a three!")
                    Time = Time - Sub
                    HTS = HTS + 3
                    FGA = FGA + 1
                else:
                    print (HT[1][14],"misses from deep.")
                    Time = Time - Sub
                    FGA = FGA + 1
            if sht==2:
                chance=random.randint(1,100)
                if chance <=num2HPF:
                    print (HT[1][14],"nails the long two.")
                    Time = Time - Sub
                    HTS = HTS + 2
                    FGA = FGA + 1
                else:
                    print (HT[1][14],"comes up short from mid range.")
                    Time = Time - Sub
                    FGA = FGA + 1
            if sht==3:
                chance=random.randint(1,100)
                if chance <=num3HPF:
                    print (HT[1][14],"backs down",AT[1][14],"and lays it in for two.")
                    Time = Time - Sub
                    HTS = HTS + 2
                    FGA = FGA + 1
                else:
                    print (HT[1][14],"misses from close range.")
                    Time = Time - Sub
                    FGA = FGA + 1
            #Small Forward
        if pos == 2:
            sht=random.randint(1,3)
            if sht==1:
                chance=random.randint(1,100)
                if chance <=num1HSF:
                    print (HT[2][14],"hits a three!")
                    Time = Time - Sub
                    HTS = HTS + 3
                    FGA = FGA + 1
                else:
                    print (HT[2][14],"misses from deep.")
                    Time = Time - Sub
                    FGA = FGA + 1
            if sht==2:
                chance=random.randint(1,100)
                if chance <=num2HSF:
                    print (HT[2][14],"nails the long two.")
                    Time = Time - Sub
                    HTS = HTS + 2
                    FGA = FGA + 1
                else:
                    print (HT[2][14],"comes up short from mid range.")
                    Time = Time - Sub
                    FGA = FGA + 1
            if sht==3:
                chance=random.randint(1,100)
                if chance <=num3HSF:
                    print (HT[2][14],"drives to the basket and lays it for two.")
                    Time = Time - Sub
                    HTS = HTS + 2
                    FGA = FGA + 1
                else:
                    print (HT[2][14],"misses from close range.")
                    Time = Time - Sub
                    FGA = FGA + 1
            #Shooting Guard
        if pos == 3:
            sht=random.randint(1,3)
            if sht==1:
                chance=random.randint(1,100)
                if chance <=num1HSG:
                    print (HT[3][14],"hits a three!")
                    Time = Time - Sub
                    HTS = HTS + 3
                    FGA = FGA + 1
                else:
                    print (HT[3][14],"misses from deep.")
                    Time = Time - Sub
                    FGA = FGA + 1
            if sht==2:
                chance=random.randint(1,100)
                if chance <=num2HSG:
                    print (HT[3][14],"nails the long two.")
                    Time = Time - Sub
                    HTS = HTS + 2
                    FGA = FGA + 1
                else:
                    print (HT[3][14],"comes up short from mid range.")
                    Time = Time - Sub
                    FGA = FGA + 1
            if sht==3:
                chance=random.randint(1,100)
                if chance <=num3HSG:
                    print (HT[3][14],"drives to the basket and lays it for two.")
                    Time = Time - Sub
                    HTS = HTS + 2
                    FGA = FGA + 1
                else:
                    print (HT[3][14],"misses from close range.")
                    Time = Time - Sub
                    FGA = FGA + 1
            #Point Guard
        if pos == 4:
            sht=random.randint(1,3)
            if sht==1:
                num=(HT[4][0])-(AT[4][6]/2)-10
                chance=random.randint(1,100)
                if chance <=num1HPG:
                    print (HT[4][14],"hits a three!")
                    Time = Time - Sub
                    FGA = FGA + 1
                    HTS = HTS + 3
                else:
                    print (HT[4][14],"misses from deep.")
                    Time = Time - Sub
                    FGA = FGA + 1
            if sht==2:
                num=(HT[4][1])-(AT[4][6]/2)-5
                chance=random.randint(1,100)
                if chance <=num2HPG:
                    print (HT[4][14],"nails the long two.")
                    Time = Time - Sub
                    FGA = FGA + 1
                    HTS = HTS + 2
                else:
                    print (HT[4][14],"comes up short from mid range.")
                    Time = Time - Sub
                    FGA = FGA + 1
            if sht==3:
                chance=random.randint(1,100)
                if chance <=num3HPG:
                    print (HT[4][14],"drives to the basket and lays it for two.")
                    Time = Time - Sub
                    FGA = FGA + 1
                    HTS = HTS + 2
                else:
                    print (HT[4][14],"misses from close range.")
                    Time = Time - Sub
                    FGA = FGA + 1
        pos=random.randint(0,4)
        Sub = random.randint(4,24)
        #Away Team
            #Center
        if pos == 0:
            sht=random.randint(1,3)
            if sht==1:
                chance=random.randint(1,100)
                if chance <=num1AC:
                    print (AT[0][14],"hits a three!")
                    Time = Time - Sub
                    FGA = FGA + 1
                    ATS = ATS + 3
                else:
                    print (AT[0][14],"misses from deep.")
                    Time = Time - Sub
                    FGA = FGA + 1
            if sht==2:
                chance=random.randint(1,100)
                if chance <=num2AC:
                    print (AT[0][14],"nails the long two.")
                    Time = Time - Sub
                    FGA = FGA + 1
                    ATS = ATS + 2
                else:
                    print (AT[0][14],"comes up short from mid range.")
                    Time = Time - Sub
                    FGA = FGA + 1
            if sht==3:
                chance=random.randint(1,100)
                if chance <=num3AC:
                    print (AT[0][14],"backs down",HT[0][14],"and lays it in for two.")
                    Time = Time - Sub
                    FGA = FGA + 1
                    ATS = ATS + 2
                else:
                    print (AT[0][14],"misses from close range.")
                    Time = Time - Sub
                    FGA = FGA + 1
            #Power Forward
        if pos == 1:
            sht=random.randint(1,3)
            if sht==1:
                chance=random.randint(1,100)
                if chance <=num1APF:
                    print (AT[1][14],"hits a three!")
                    Time = Time - Sub
                    FGA = FGA + 1
                    ATS = ATS + 3
                else:
                    print (AT[1][14],"misses from deep.")
                    Time = Time - Sub
                    FGA = FGA + 1
            if sht==2:
                chance=random.randint(1,100)
                if chance <=num2APF:
                    print (AT[1][14],"nails the long two.")
                    Time = Time - Sub
                    FGA = FGA + 1
                    ATS = ATS + 2
                else:
                    print (AT[1][14],"comes up short from mid range.")
                    Time = Time - Sub
                    FGA = FGA + 1
            if sht==3:
                chance=random.randint(1,100)
                if chance <=num3APF:
                    print (AT[1][14],"backs down",HT[1][14],"and lays it in for two.")
                    Time = Time - Sub
                    FGA = FGA + 1
                    ATS = ATS + 2
                else:
                    print (AT[1][14],"misses from close range.")
                    Time = Time - Sub
                    FGA = FGA + 1
            #Small Forward
        if pos == 2:
            sht=random.randint(1,3)
            if sht==1:
                chance=random.randint(1,100)
                if chance <=num1ASF:
                    print (AT[2][14],"hits a three!")
                    Time = Time - Sub
                    FGA = FGA + 1
                    ATS = ATS + 3
                else:
                    print (AT[2][14],"misses from deep.")
                    Time = Time - Sub
                    FGA = FGA + 1
            if sht==2:
                chance=random.randint(1,100)
                if chance <=num2ASF:
                    print (AT[2][14],"nails the long two.")
                    Time = Time - Sub
                    FGA = FGA + 1
                    ATS = ATS + 2
                else:
                    print (AT[2][14],"comes up short from mid range.")
                    Time = Time - Sub
                    FGA = FGA + 1
            if sht==3:
                chance=random.randint(1,100)
                if chance <=num3ASF:
                    print (AT[2][14],"drives to the basket and lays it for two.")
                    Time = Time - Sub
                    FGA = FGA + 1
                    ATS = ATS + 2
                else:
                    print (AT[2][14],"misses from close range.")
                    Time = Time - Sub
                    FGA = FGA + 1
            #Shooting Guard
        if pos == 3:
            sht=random.randint(1,3)
            if sht==1:
                chance=random.randint(1,100)
                if chance <=num1ASG:
                    print (AT[3][14],"hits a three!")
                    Time = Time - Sub
                    FGA = FGA + 1
                    ATS = ATS + 3
                else:
                    print (AT[3][14],"misses from deep.")
                    Time = Time - Sub
                    FGA = FGA + 1
            if sht==2:
                chance=random.randint(1,100)
                if chance <=num2ASG:
                    print (AT[3][14],"nails the long two.")
                    Time = Time - Sub
                    FGA = FGA + 1
                else:
                    print (AT[3][14],"comes up short from mid range.")
                    Time = Time - Sub
                    FGA = FGA + 1
                    ATS = ATS + 2
            if sht==3:
                chance=random.randint(1,100)
                if chance <=num3ASG:
                    print (AT[3][14],"drives to the basket and lays it for two.")
                    Time = Time - Sub
                    FGA = FGA + 1
                    ATS = ATS + 2
                else:
                    print (AT[3][14],"misses from close range.")
                    Time = Time - Sub
                    FGA = FGA + 1
            #Point Guard
        if pos == 4:
            sht=random.randint(1,3)
            if sht==1:
                chance=random.randint(1,100)
                if chance <=num1APG:
                    print (AT[4][14],"hits a three!")
                    Time = Time - Sub
                    FGA = FGA + 1
                    ATS = ATS + 3
                else:
                    print (AT[4][14],"misses from deep.")
                    Time = Time - Sub
                    FGA = FGA + 1
            if sht==2:
                chance=random.randint(1,100)
                if chance <=num2APG:
                    print (AT[4][14],"nails the long two.")
                    Time = Time - Sub
                    FGA = FGA + 1
                    ATS = ATS + 2
                else:
                    print (AT[4][14],"comes up short from mid range.")
                    Time = Time - Sub
                    FGA = FGA + 1
            if sht==3:
                chance=random.randint(1,100)
                if chance <=num3APG:
                    print (AT[4][14],"drives to the basket and lays it for two.")
                    Time = Time - Sub
                    FGA = FGA + 1
                    ATS = ATS + 2
                else:
                    print (AT[4][14],"misses from close range.")
                    Time = Time - Sub
                    FGA = FGA + 1
    else:
        if HTS > ATS:
            print (HTN,HTS,"vs",ATN,ATS)
        elif ATS > HTS:
            print (ATN,ATS,"vs",HTN,HTS)
        elif HTS == ATS:

engine()

我想尝试使用这段代码作为一个类的主要原因是能够考虑像超时这样的情况。到现在为止,我有一个“时间”变量,用随机数减去每一次占有。但是,如果我可以使用一个类来确定模拟运行的“时间”长度,那么我就可以考虑规则和任何超时,并让超时时间贡献给总分(“HTS”和“ATS”变量)。你知道吗

我的课程设想是这样开始的:

级别引擎(自身,时间):

然而,老实说,从这一点上我觉得完全失去了我应该去哪里下一步。我一直在尝试一些东西,但是我很难理解课程是如何在最基本的层次之外工作的,我只是觉得这有点超出了我的理解范围。我意识到这个问题可能很混乱,但我希望有人能理解,至少能给我指出正确的方向,我应该从这里走到哪里。你知道吗

列出我困惑的事情:

  • 我不知道该从哪里开始上课。有一次,我试图将类分解为多个方法。一个是用户界面部分,另一个是实际模拟。然而,我无法得到任何接近工作。

  • 变量在类中的工作方式也让我困惑。我不确定a类变量在什么情况下被视为全局变量或局部变量,这使得我很难知道是否需要更改定义HTS和ATS变量的位置,以跟踪分数。

  • 除了这两件事,我真的不是100%确定我是困惑或误解,因为我是一个非常新的OOP。基本上,我希望有人能帮我把这些代码移到一个类中;但是,如果有明显的事情你看到我误解了,你可以指出给我看,那也没关系。

再次,我意识到这可能是一个非常混乱的职位,所以我理解如果你不能帮助我,但如果这里有人理解我的问题(s),我会非常感谢你的帮助!你知道吗


Tags: fromiftimerandomelseathtprint
2条回答

将过程代码转换为OO的基本方法是基于真实世界的对象对类进行建模。例如,为了创建一个Player类:

  • 将玩家的特征和状态转化为属性
  • 将玩家的行为转化为方法

例如:

>>> class Player(object):
    def __init__(self, name, outside, mid_range, inside, passing, 
        ball_handling, dunk, perimeter, post, block, steal, speed, 
        strength, height, weight):
        self.name = name
        self.outside = outside
        self.mid_range = mid_range
        self.inside = inside
        self.passing = passing
        self.ball_handling = ball_handling
        self.dunk = dunk
        self.perimeter = perimeter
        self.post = post
        self.block = block
        self.steal = steal
        self.speed = speed
        self.strength = strength
        self.height = height
        self.weight = weight
    def shoot(self, from_distance)
        # calculate chance here, for example...
        result = roll_dice(self, from_distance)
        if result == "scored":
            do_something()
            return
        if result == "fault":
            do_something_else()
            return
        do_default_action() # missed?

>>> chris_bosh = Player('Chris Bosh', 67, 78, 87, 44, 41, 78, 34, 
        77, 81, 31, 60, 64, 6.11, 228)
>>> print chris_bosh.height
6.11
>>> print chris_bosh.outside
67

您应该学习的一条非常重要的规则是,复制和粘贴代码是个坏主意,尤其是大量的代码,复制了很多次,每次只做很小的更改。你知道吗

在每个if语句中重复的两行:

Time = Time - Sub
FGA = FGA + 1

是一个例子,但一般来说,这段代码一次又一次地执行相同的逻辑。一个更具说明性的例子是,处理主队的整个代码可以使用以下行相同地完成:

pos=random.randint(0,4)
Sub = random.randint(4,24)

chances = [[num1HC, num2HC, num3HC],
           [num1HPF, num2HPF, num3HPF],
           [num1HSF, num2HSF, num2HSF],
           [num1HSG, num2HSG, num3HSG],
           [num1HPG, num2HPG, num3HPG]]

messages = [["hits a three!", "misses from deep."]
            ["nails the long two.", "comes up short from mid range."],
            [["backs down " + AT[pos][14] + "and lays it in for two.",
              "misses from close range."]]
points = [3, 2, 2]

sht=random.randint(1,3)
chance=random.randint(1,100)

if chance <= chances[pos][sht]:
    print HT[pos][14], messages[sht][0]
    HTS = HTS + points[sht]
else:
    print HT[pos][14], messages[sht][1]

这就把代码从180行减少到了20行:将代码缩小了9倍。请注意,它需要所有始终相同的行,例如“某某命中3!”,使它们只发生一次。你知道吗

那代码只是个开始。您可能想再次复制并粘贴它,将HT的每个用法更改为AT,从而创建客场团队逻辑。但是不要!相反,你可以做:

teams = [HT, AT]
team_scores = [HTS, ATS]

然后用teams[t]替换HT,用team_scores[t]替换HTS。这样,无论是主队还是客队都可以使用相同的逻辑:只需使用不同的t值运行两次:

for t in range(2):
    # all your logic here

把它放在Team类和Player类中将是重要的下一步,但对您来说,开始保存逻辑更为重要。你知道吗

相关问题 更多 >