LoginSignup
2
1

More than 5 years have passed since last update.

ヒットアンドブローをPythonで書いてみる

Last updated at Posted at 2017-12-30

・Pythonの手始めに、ゲーム「ヒットアンドブロー」を書いてみる。
・対戦方式ではなく、コンピュータがランダムに生成する3桁の数値を当てるゲーム。
・3桁の数字を回答し、数字の位置と数値があっていればヒット。
・数字の位置は違うが、数値があっていればブロー。
・3ヒットになれば正解(クリアー)

HitAndBlow.py
import random
k = ["0","1","2","3","4","5","6","7","8","9"]
#print(k)
random.shuffle(k)
#print(k)
kotae = [k[0],k[1],k[2]]
#print(kotae)
hit = 0
count = 0
while hit != 3:
    count +=1
    q = input("? ")
    print(q[0]+q[1]+q[2])
    hit = 0
    blow = 0
    if(q[0] == k[0]):
        hit +=1
    if(q[1] == k[1]):
        hit +=1
    if(q[2] == k[2]):
        hit +=1
    print(str(hit)+" Hit")
    if(q[1] == k[0]):
        blow +=1
    if(q[2] == k[0]):
        blow +=1
    if(q[0] == k[1]):
        blow +=1
    if(q[2] == k[1]):
        blow +=1
    if(q[0] == k[2]):
        blow +=1
    if(q[1] == k[2]):
        blow +=1
    print(str(blow)+" Blow")
print('Clear! ' + str(count))

対話方式で、以下のように回答をする

============= RESTART: /Users/xxx/Desktop/Python1/HitAndBlow.py =============
? 345
345
0 Hit
1 Blow
? 678
678
0 Hit
1 Blow
? 129
129
1 Hit
0 Blow
? 156
156
0 Hit
1 Blow
? 527
527
3 Hit
0 Blow
Clear! 5
>>> 
2
1
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1