您的位置:首页 > 编程语言 > Python开发

python 版猜数字游戏

2014-05-03 14:52 471 查看
初学 python,写了一个小小的toy code 来练习,bug 肯定有,欢迎提出意见

#! /usr/bin/python

#This is guess number Game written in python

import random

running = True
maxTrial = 10
guessTimes = 0
answerlist = ['0', '0', '0', '0']
guessList = ['0', '0', '0', '0']

def hasCommonNumber(list):
for i in range(0, 4):
for j in range(i+1, 4):
if list[i] == list[j]:
return True
return False

# Check the guessNumber and give a hit for it
# A:right number in the right position
# B:right number in the wrong position
def isRightAnswer(guessNumber):
global running
global guessTimes

guessTimes += 1

flagA = 0
flagB = 0

guessList[0] = guessNumber / 1000
guessList[1] = (guessNumber % 1000) / 100
guessList[2] = ((guessNumber % 1000) % 100) / 10
guessList[3] = guessNumber % 10

#check the guess list
print(guessList)

for i in range(0, 4):
for j in range(0, 4):
if answerlist[i] == guessList[j]:
if i == j:
flagA += 1
else:
flagB += 1

if flagA == 4:
print 'You Got It, The Answer Is', answerlist
running = False
elif guessTimes >= maxTrial:
print 'Sorry,After ', guessTimes, 'times guessing you just can\'t get it'
running = False
else:
print flagA, 'A', flagB, 'B'

# generate the answer, and make sure there's no common numbers
while True:
for i in range(0, 4):
answerlist[i] = random.randrange(10)
if hasCommonNumber(answerlist) == False:
break

while running:

# check the seq
print(answerlist)

guessNumber = (int(raw_input("Make A Guess: ")))

isRightAnswer(guessNumber)

else:
print 'Game Exit!'
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python