Sunday, May 28, 2017

hit and blow game coded by python

coding "hit and blow game" is a best way to get start studying new program language. I coded by python with my friends.

1. rules

- find out correct 3 digits.
- each digits used only at once, not like "555", "323"
- if digit "correct" and place "incorrect", counted as "blow".
- if digit "correct" and place "correct", counted as "hit".
% python hitandblow.py
Enter three digits >>123
0 hit 0 blow
Enter three digits >>456
0 hit 1 blow
Enter three digits >>857
1 hit 2 blow
Enter three digits >>875
3 hit 0 blow
congratulation!

2. code sample

import random
 
def judge(c, u):
h=0
b=0
 
for x in range(3):
for y in range(3):
if c[x] == u[y]:
if x == y:
h = h + 1
else:
b = b + 1
 
print("%s hit %s blow" %(h,b))
 
if h == 3:
print("congratulation!")
return True
else:
return False
 
if __name__ == '__main__':
 
com = []
while len(com)!=3:
rannum = random.randint(0,9)
if rannum not in com:
com.append(rannum)
 
while True:
usrnum=input("Enter three digits >>")
usr = (int(usrnum[0]),int(usrnum[1]),int(usrnum[2]))
 
if judge(com,usr) == True:
break