我正在通过书籍和互联网学习Python。我试图在一个单独的课程中保持游戏的分数。为了测试我的想法,我构建了一个简单的例子。由于某种原因,它看起来太复杂了。是否有更简单/更好/更Pythonic的方法来做到这一点?
我的代码如下:
import os
class FOO():
def __init__(self):
pass
def account(self, begin, change):
end = float(begin) + float(change)
return (change, end)
class GAME():
def __init_(self):
pass
def play(self, end, game_start):
os.system("clear")
self.foo = FOO()
print "What is the delta?"
change = raw_input('> ')
if game_start == 0:
print "What is the start?"
begin = raw_input('> ')
else:
begin = end
change, end = self.foo.account(begin, change)
print "change = %r" % change
print "end = %r" % end
print "Hit enter to continue."
raw_input('> ')
self.play_again(end, game_start)
def play_again(self, end, game_start):
print "Would you like to play again?"
a = raw_input('> ')
if a == 'yes':
game_start = 1
self.play(end, game_start)
else:
print "no"
exit(0)
game = GAME()
game.play(0, 0)
答案 0 :(得分:1)
以下是我如何格式化代码:
import os
class Game(object):
def play(self, end, game_start=None):
os.system("clear")
change = input('What is the delta? ')
# Shorthand for begin = game_start if game_start else end
begin = game_start or end
end = float(begin + change)
print "change = {}".format(change)
print "end = {}".format(end)
self.play_again(end, game_start)
def play_again(self, end, game_start):
raw_input('Hit enter to continue.')
if raw_input('Would you like to play again? ').lower() in ['yes', 'y']:
self.play(end, game_start)
else:
exit(0)
if __name__ == '__main__':
game = Game()
game.play(0, 0)
还有一些提示:
Game
类是一个例外,因为您可能会向其中添加更多代码。CamelCase
编写的。全局常量通常用UPPERCASE
。raw_input()
返回一个字符串。 input()
将评估的字符串返回给Python对象。答案 1 :(得分:0)
我问了一个更好的问题,得到了我在这里寻找的东西:
python: how do I call a function without changing an argument?