Hit and Blowは有名な数字当てゲームです。
出題者は0から9までの数字を重複しないように決められた桁数選びます。
解答者は何度でも回答できます。外れた場合は、
Hit(当たっている数)
Blow(数字は当たっているが桁が違う)
それぞれの数を教えてもらえます。
例.
正解 = "146"
回答(1) = "241" 1 Hit, 1 Blow
これをヒントに正解を目指すというゲームです。
import random
def hitblow(command, ans):
hit = 0
blow = 0
for i in range(len(command)):
if command[i] == ans[i]:
hit += 1
else:
if command[i] in ans:
blow += 1
return [hit, blow]
def generatoroff(length): # not used
ans = []
while len(ans) < length:
rand = random.randint(0, 9)
if rand in ans:
pass
else:
ans += [rand]
return ans
def generator(length): # Another solution
dummy=[0,1,2,3,4,5,6,7,8,9]
random.shuffle(dummy)
ans=[]
i=0
while i < length:
ans += [dummy[i]]
i +=1
return ans
print("Hit & Blow Game")
digit = input("Please, enter the number of digits you want to play: ")
ans = generator(int(digit))
cont = True
count = 0
print("Game Start!")
while cont:
count += 1
command = input("enter the {} digits number > ".format(digit))
your_ans = [int(command[i]) for i in range(len(command))]
[hit, blow] = hitblow(your_ans, ans)
print("{}: {} Hit, {} Blow".format(command, hit, blow))
if hit == len(ans):
print("Congratulations!!! You took {} steps.".format(count))
cont = False
=== RESTART: C:/python/Hit AndBlow02.py ===============
Hit & Blow Game
Please, enter the number of digits you want to play: 2
Game Start!
enter the 2 digits number > 01
01: 0 Hit, 0 Blow
enter the 2 digits number > 23
23: 1 Hit, 0 Blow
enter the 2 digits number > 24
24: 1 Hit, 0 Blow
enter the 2 digits number > 25
25: 2 Hit, 0 Blow
Congratulations!!! You took 4 steps.
>>>
コメント
コメントを投稿