- 帖子
- 18
- 精华
- 0
- 积分
- 134
- 阅读权限
- 20
- 注册时间
- 2013-9-13
- 最后登录
- 2014-4-4
|
- # -*- coding: cp936 -*-
- from random import randint,choice
- def produce_password():
- pw=['1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
- ra=randint(0,9)
- password=''
- for i in range(0,ra):
- i=choice(pw)
- password+=i
- return password
- def the_guess_game(password,t_times,best_score,t_guess):
- print password
- guess=raw_input('请输入你所猜的密码,密码由小写字母和数字组成:')
- this_guess=0
- guess_result=''
- while guess!=password:
- if len(guess)==len(password):
- for i in range(0,len(guess)):
- if guess[i] in password:
- if guess[i]==password[i]:
- guess_result+='A'
- if guess[i]!=password[i]:
- guess_result+='B'
- if len(guess)<len(password):
- for i in range(0,len(guess)):
- if guess[i] in password[:len(guess)]:
- if guess[i]==password[i]:
- guess_result+='A'
- if guess[i]!=password[i]:
- guess_result+='B'
- if guess[i] in password[len(guess):]:
- guess_result+='B'
- if len(guess)>len(password):
- for i in range(0,len(password)):
- if guess[i] in password:
- if guess[i]==password[i]:
- guess_result+='A'
- if guess[i]!=password[i]:
- guess_result+='B'
- for i in range(len(password),len(guess)):
- if guess[i] in password:
- guess_result+='B'
- right_position=0
- wrong_position=0
- for j in guess_result:
- if j=='A':
- right_position+=1
- if j=='B':
- wrong_position+=1
- guess_result=str(right_position)+'A'+str(wrong_position)+'B'
- print '猜错了!'
- print '你所猜的密码有'+guess_result[0]+'位出现在了准确位置.'+'另外,有'+guess_result[2]+'位字符出现在了密码里,但是位置不准确。'
- t_guess+=1
- guess=raw_input('请再试一次:')
- guess_result=''
- this_guess+=1
- if guess==password:
- print '恭喜你,破解了密码!!!'
- t_guess+=1
- this_guess+=1
- t_times+=1
- raw_input('')
- if best_score==0:
- best_score=this_guess
- elif best_score!=0 and this_guess<best_score:
- best_score=this_guess
- return t_times,best_score,t_guess
- s=open('c:\Users\User\Desktop\python\codeguess\score.txt')
- score=s.readlines()
- s.close()
- dic={}
- f=[]
- for i in score:
- f.append(i[:-1])
- for j in f:
- p=j.split()
- dic[p[0]]=p[1:]
- name=raw_input('欢迎,这是一个猜密码游戏,请输出你的名字,以记录成绩:\n')
- score=dic.get(name)
- if score==None:
- score=[0,0,0]
- t_times=int(score[0])
- best_score=int(score[1])
- t_guess=int(score[2])
- if t_guess>0:
- print '%s,你一共玩了 %d 次游戏,最好的成绩是尝试 %d 次就破解了密码,你平均每次破解密码所用的次数是 %d 次'%(name,t_times,best_score,t_guess)
- if t_guess==0 and t_times==0 and best_score==0:
- print '欢迎第一次玩!'
- password=produce_password()
- a,b,c=the_guess_game(password,t_times,best_score,t_guess)
- dic[name]=[str(a),str(b),str(c)]
- result=''
- for k in dic:
- line = k +' '+ ' '.join(dic[k])+'\n'
- result+=line
- n=open('c:\Users\User\Desktop\python\codeguess\score.txt','w')
- n.write(result)
- n.close()
复制代码 之前做的不完善,没有随机生成密码,输入长度不对好像会有问题,也没有记录成绩。
这次重新改了哈,不过没有难度设置,学图形库再做个图形界面!! |
|