2015-12-14 35 views
1

我们正在做计算机科学课的一项活动,而且我很难理解几行代码的含义。这些代码行是做什么的? (运动模拟)

这里是最初的代码(对于任何你可能需要的背景信息)。

class SportsMatch(object): 
    def __init__(self, teamA="Team A", teamB="TeamB"): 
      self.teamA = teamA 
      self.scoreA = 0 
      self.teamAScorePoints = 1 

      self.teamB = teamB 
      self.scoreB = 0 
      self.teamBScorePoints = 1 

    def setScorePoints(self, teamAScorePoints=1, teamBScorePoints=1): 
      self.teamAScorePoints = teamAScorePoints 
      self.teamBScorePoints = teamBScorePoints 

    def whoWins(self): 
      if (self.scoreA < self.scoreB): 
       print(self.teamB+" win the game!") 
      elif (self.scoreA > self.scoreB): 
       print(self.teamA+" win the game!") 
      else: 
       print("Tie score") 

    def teamAScores(self): 
      self.scoreA = self.scoreA + self.teamAScorePoints 

    def teamBScores(self): 
      self.scoreB = self.scoreB + self.teamBScorePoints 

然后,我们应该考虑下面的代码,弄清每一行代码的作用:

s = SportsMatch("Chargers", "Raiders") 
s.setScorePoints(1, 2) 
s.teamAScores() 
s.teamBScores() 
s.teamAScores() 
s.teamBScores() 
s.whoWins() 

我有一种大致的了解,但我的老师要我们更具体。我也明白第二行是用参数1和2调用的,但我不确定这些数字是如何影响其余代码的。如果有人能帮我解释这几行代码,那将不胜感激!

+0

是体育*刺激*还是*模拟*? :P –

回答

3

设置初始变量:

self.teamX = teamX  # setting name 
self.scoreX = 0   # initial score 
self.teamAXcorePoints = 1 # score increment 

这两个都是分数增量:

self.teamAScorePoints = 1 
self.teamBScorePoints = 1 

这里用于增加各队的得分:

def teamAScores(self): 
    self.scoreA = self.scoreA + self.teamAScorePoints 
def teamBScores(self): 
    self.scoreB = self.scoreB + self.teamBScorePoints 

现在流量:

s = SportsMatch("Chargers", "Raiders") # defining the match 
s.setScorePoints(1, 2)     # setting initial score increments 
s.teamAScores()      # team A scores 1 point 
s.teamBScores()      # team B scores 2 points 
s.teamAScores()      # team A scores another 1 point 
s.teamBScores()      # team B scores another 2 points 
s.whoWins()       # prints winner 
+1

不会's.setScorePoints()'设置*增量*这会影响他们每次得分吗?换句话说,它不会设置初始分数,它会设置每次团队分数时添加的金额。 –

+0

鲍勃是正确的'setScorePoints'设置增量不是初始分数。 – NendoTaka

+0

我的坏人。抱歉。已更新答案 –

2

代码的一般说明:

s = SportsMatch("Chargers", "Raiders") 

这行代码调用从SportsMatch类的__init__方法,并传递方法“充电器”和“攻略”。然后这些被保存为运动队的名字。

s.setScorePoints(1, 2) 

这行调用从类的setScorePoints方法,并传递它12。这些值会保存为每个球队得分后得分增加的数量。

s.teamAScores() 
s.teamBScores() 
s.teamAScores() 
s.teamBScores() 

这些行调用teamAScoresteamBScores方法。这些方法取决于调用哪种方法来增加团队的分数。

s.whoWins() 

这将调用类,比较球队的比分和打印冠军球队的whoWins方法。

胜出的队伍将被称为Raiders。 B队得分为4,A队得分为2