- 帖子
- 1
- 精华
- 0
- 积分
- 6
- 阅读权限
- 10
- 注册时间
- 2017-8-7
- 最后登录
- 2017-8-8
|
当时看了先生的课,就想到了这个游戏,想着把记录成绩结合进来,感觉写的有点冗长,希望先生指点。
PS:生成随机数那边就想了好久,最后写了2个生成方法,都没舍得删- from random import randint
- def generate_1():
- a = [0, 0, 0, 0]
- i = 0
- while i <= 3:
- a[i] = randint(0,9)
- if i >=1:
- for j in range(0,i):
- if a[i] == a[j]:
- i -= 1
- break
- i += 1
- return a
- def generate_2():
- k = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
- a = [0, 0, 0, 0]
- for i in range(4):
- n = randint(0, 9-i)
- a[i] = k[n]
- del k[n]
- return a
-
- def compare(a, b):
- num_a = 0
- num_b = 0
- for i in range(4):
- for j in range(4):
- if int(a[i]) == b[j]:
- if i == j:
- num_a += 1
- break
- else:
- num_b += 1
- break
- return [num_a, num_b]
-
-
- print '====****====guess number game====****====\n'
- print 'Rules:\nThe answer is 4 different numbers\n\
- A means number and position are all \
- correct\nB means only number is right\n'
- scores = {}
- name = raw_input('Input you name:\n')
- try:
- f = file('scores.txt')
- lines = f.readlines()
- for l in lines:
- s = l.split()
- scores[s[0]] = s[1:]
- except:
- print 'You are the first player!'
-
- score = scores.get(name)
- if score is None:
- score = [0, 0]
- game_time = score[0]
- s_turn = score[1]
- again = 'y'
- while again == 'y':
- game_time += 1
- num = generate_2()
- #print num
- answer = [0, 0]
- guess_turn = 0
- print 'Guess the numbers:\n'
- while answer[0] != 4:
- guess_turn += 1
- print 'turn %d:' %guess_turn
- guess = raw_input()
- trans = guess.split(' ')
- #print trans
- answer = compare(trans, num)
- #print reflect
- if answer[0] != 4:
- print '===>>>%dA%dB<<<===' %(answer[0],answer[1])
- else:
- break
- if s_turn == 0 or s_turn > guess_turn:
- s_turn = guess_turn
- print 'Congratulations! %d %d %d %d is correct!\n' %(num[0], num[1], num[2], num[3])
- print 'Player: %s\tGame time: %d\tCurrent \
- turns: %d\tShortest turns: %d' %(name, game_time, guess_turn, s_turn)
- scores[name] = [str(game_time), str(s_turn)]
- result = ''
- for n in scores:
- str_result = n + ' ' + ' '.join(scores[n]) + '\n'
- result += str_result
- o = file('scores.txt','w')
- o.write(result)
- o.close()
- print 'Do you want to play it again? (y/n)'
- again = raw_input()
复制代码 |
|