Created
September 13, 2017 14:44
-
-
Save iamn3/4ed363dbf3f37618685436b9d11d40ec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# じゃんけんゲーム | |
import random | |
# 入力値が0 or 1 or 2か判定 | |
def validate_hands(hand): | |
try: | |
#数値で0,1,2なら正しい入力値とする(Trueを返す) | |
hand_num = int(hand) | |
return hand_num == 0 or hand_num == 1 or hand_num == 2 | |
except: | |
return False | |
# じゃんけんの勝敗を判定 | |
# result = (0:プレイヤーの勝ち、1:CPUの勝ち、2:あいこ) | |
def janken(player_hand, cpu_hand): | |
result = 1 | |
player_hand_num = int(player_hand) | |
cpu_hand_num = cpu_hand | |
if (player_hand_num == 0 and cpu_hand_num == 1) or (player_hand_num == 1 and cpu_hand_num == 2) or (player_hand_num == 2 and cpu_hand_num == 0): | |
result = 0 | |
elif player_hand_num == cpu_hand_num: | |
result = 2 | |
return result | |
# 0 or 1 or 2 をそれぞれ"ぐー"、"ちょき"、"ぱー"に変換する | |
def get_hand(hand): | |
if hand == 0: | |
return "ぐー" | |
elif hand == 1: | |
return "ちょき" | |
elif hand == 2: | |
return "ぱー" | |
else: | |
return "不明???" | |
# ゲームのメイン関数 | |
def start_repl(n): | |
i = 1 | |
player_win_count = 0 | |
cpu_win_count = 0 | |
print("じゃんけんをしよう!") | |
print(str(n) + "回勝負だよ。") | |
while i <= n: | |
print("最初はぐー、じゃんけん...(手を選んでね)") | |
print("ぐー:0、ちょき:1、ぱー:2") | |
print("> ",end="") | |
hand = input() | |
cpu_hand = random.randint(0,2) | |
if validate_hands(hand): | |
i += 1 | |
result = janken(hand,cpu_hand) | |
result_string = "あいこ" | |
if result == 0: | |
player_win_count += 1 | |
result_string = "あなたの勝ち!" | |
elif result == 1: | |
cpu_win_count += 1 | |
result_string = "CPUの勝ち!" | |
print("ぽん!") | |
print("あなた: {}".format(get_hand(int(hand)))) | |
print("CPU: {}\n".format(get_hand(cpu_hand))) | |
print("結果: {}\n".format(result_string)) | |
else: | |
print("やり直し") | |
print("{}回勝負の結果:".format(n)) | |
if player_win_count > cpu_win_count: | |
print(" あなたの勝ち") | |
elif cpu_win_count > player_win_count: | |
print(" CPUの勝ち") | |
else: | |
print(" 引き分け") | |
if __name__ == "__main__": | |
start_repl(3) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment