再次说明:一个编程问题会有很多种解法,我给的只是其中一种,而且未必是最好的一种。所以,你尽可去想自己的方法,然后实现它。
我们的点球游戏已经快完成了,现在要做的就是增加比赛提前结束的机制,让它更真实。(关于这个小游戏的前几课内容参见第 26 27 28 课)
我的思路是这样:比赛提前结束,就是落后一方的得分,加上他在5轮中剩下的轮数,仍然低于领先方现在的得分。虽然可以根据当前的轮数计算剩下的机会,但由于先踢和后踢的情况不同,这样计算会有些复杂,容易搞错。
所以我决定再增加一个list,里面记录双方剩余的轮数,初始均为5。
每踢一球,就把对应那一方的计数减1。
每踢一球,就判断输的那一方是否还有机会。
于是需要增加的代码就是:
在最开始
rest = [5, 5]
以玩家为例,每踢完一球的判断
if rest[0] > 0:
rest[0] -= 1
if score[0] < score[1] and score[0] + rest[0] < score[1]:
return True
if score[1] < score[0] and score[1] + rest[1] < score[0]:
return True
由于提前结束仅限于5轮内,所以要判断rest[0]>0。return可以让kick函数提前结束。电脑的判断与这个类似,只是要换成rest[1]。
因为需要有个方法提前结束循环,所以我让kick函数返回一个bool值,正常情况返回False,一旦提前结束就返回True。
之前的for循环也改成while,以便于提前结束循环。
i = 0
end = False
while(i < 5 and not end)
print '==== Round %d ====' % (i+1)
end = kick()
i += 1
完整代码如下,改动之处用颜色标出,注意点参考图片上的注释:
from random import choice
score = [0, 0]
rest = [5, 5]
direction = ['left', 'center', 'right']
def kick():
print '==== You Kick! ===='
print 'Choose one side to shoot:'
print 'left, center, right'
you = raw_input()
print 'You kicked ' + you
com = choice(direction)
print 'Computer saved ' + com
if you != com:
print 'Goal!'
score[0] += 1
else:
print 'Oops...'
print 'Score: %d(you) - %d(com)\n' % (score[0], score[1])
if rest[0] > 0:
rest[0] -= 1
if score[0] < score[1] and score[0] + rest[0] < score[1]:
return True
if score[1] < score[0] and score[1] + rest[1] < score[0]:
return True
print '==== You Save! ===='
print 'Choose one side to save:'
print 'left, center, right'
you = raw_input()
print 'You saved ' + you
com = choice(direction)
print 'Computer kicked ' + com
if you == com:
print 'Saved!'
else:
print 'Oops...'
score[1] += 1
print 'Score: %d(you) - %d(com)\n' % (score[0], score[1])
if rest[1] > 0:
rest[1] -= 1
if score[0] < score[1] and score[0] + rest[0] < score[1]:
return True
if score[1] < score[0] and score[1] + rest[1] < score[0]:
return True
return False
i = 0
end = False
while(i < 5 and not end):
print '==== Round %d ====' % (i+1)
end = kick()
i += 1
while(score[0] == score[1]):
print '==== Round %d ====' % (i+1)
kick()
i += 1
if score[0] > score[1]:
print 'You Win!'
else:
print 'You Lose.'
这次的程序比我们之前写过的都要长,结构也更复杂,需要耐心去分析。你可以按照自己的理解,去一步步完善这个游戏。
#==== Crossin的编程教室 ====#
面向零基础初学者的编程课
每天5分钟,轻松学编程
回复『 p 』查看课程目录
回复『 t 』查看习题列表