fork download
  1. #!/usr/bin/env python3
  2.  
  3. # ゲームの環境情報
  4. class World:
  5. def __init__(self, stones, player):
  6. self.stones = stones
  7. self.player = player
  8.  
  9. # メッセージ分離方式
  10. Messages = {"init" : "石の数 (10以上) :",
  11. "number-of-stones" : "石の数: {0}\n",
  12. "prompt" : "プレイヤー{0}の番です\n何個取る (1〜3個) ?",
  13. "winner" : "プレイヤー{0}の勝ち\n"}
  14.  
  15. # 入力の最小値と最大値
  16. Min, Max = 0, 4
  17.  
  18. # Eval
  19. def world_go(x, env):
  20. stones = env.stones - x
  21. player = 2 if env.player == 1 else 1
  22. return World(stones, player)
  23.  
  24. # Eval(短縮版)
  25. ##def world_go(x, env):
  26. ## return World(env.stones - x, 2 if env.player == 1 else 1)
  27.  
  28. # Read
  29. def read(env, prompt):
  30. while True:
  31. num = int(input(prompt.format(env.player)))
  32. if num > Min or num < Max:
  33. return num
  34.  
  35. # REPL 用補助関数
  36. # ゲーム終了判定
  37. def is_game_end(env):
  38. return env.stones < 2
  39.  
  40. # ゲーム勝者表示
  41. def winner(env):
  42. player = env.player
  43. if env.stones == 0:
  44. return player
  45. else:
  46. return 2 if player == 1 else 1
  47.  
  48. # 初期化
  49. def init():
  50. while True:
  51. try: num = int(input(Messages["init"]))
  52. except ValueError: continue
  53. if num > 9:
  54. return World(num, 1)
  55.  
  56. # ゲーム実行
  57.  
  58. if __name__ == "__main__":
  59. env = init()
  60. while True:
  61. print(Messages["number-of-stones"].format(env.stones))
  62. if is_game_end(env):
  63. print(Messages["winner"].format(winner(env)))
  64. break
  65. else:
  66. try: env = world_go(read(env, Messages["prompt"]), env)
  67. except ValueError: env
  68.  
Runtime error #stdin #stdout #stderr 0.16s 23376KB
stdin
15
stdout
石の数 (10以上) :石の数: 15

プレイヤー1の番です
何個取る (1〜3個) ?
stderr
Traceback (most recent call last):
  File "./prog.py", line 66, in <module>
  File "./prog.py", line 31, in read
EOFError: EOF when reading a line