- 帖子
- 2
- 精华
- 0
- 积分
- 13
- 阅读权限
- 10
- 注册时间
- 2017-9-28
- 最后登录
- 2022-6-20
|
本帖最后由 grass1996 于 2017-9-28 15:53 编辑
新手,学到40课,磕磕碰碰完善了一下猜数字游戏
本来只是想简单的完善下,没想到完善的代码比猜数字本身的代码多多了,中间也遇到很多问题,磕磕碰碰总算弄出来了有写的不好的地方或者可以精简代码做出来的,希望可以指点一下,谢谢。
有两个疑问:
\n 换行,为什么跑出来的效果是空了两行,不应该是只空一行吗?
另一个疑问是
chose == "Y" or chose == "Yes" 和 chose == "Y" or "yes" 的实现效果不一样,没太弄明白原理。- from random import randint
- f = open("game.txt","rt")
- score = f.read().split()
- f.close()
- game_times = int(score[0])
- min_times = int(score[1])
- total_times = int(score[2])
- print ("Do you want to play game? Y or N")
- i = 1
- while i == 1 :
- chose = input()
- print ("\n")
- if chose == "Y" or chose == "Yes":
- num = randint(1, 10) #Game start
- times = 0
- print ("Guess a number from 1 ~ 10")
- bingo = False
- while bingo == False:
- answer = input()
- if not answer.isdigit():
- print("please choose a number from 1 ~ 10 \n")
- continue
- else:
- answer = int(answer)
- times +=1
- if answer < num:
- print ("too small")
- if answer > num:
- print ("too big")
- if answer == num:
- print ("Bingo!")
- bingo = True
- #count times
- if game_times == 0 or times < min_times or min_times == 0:
- min_times = times
- total_times += times
- game_times += 1
- if game_times > 0:
- avg_times = float(total_times) / game_times
- else:
- avg_times = 0
- #save score
- result = "%d %d %d" %(game_times, min_times, total_times)
- f = open ("game.txt", "wt")
- f.write(result)
- f.close()
- print ("玩了%d次, 最少%d轮猜出答案, 平均%.2f猜出答案 \n" %(
- game_times, min_times, avg_times))
- #again Y/N
- print ("Once again? Yes or No")
- elif chose == "N" or chose == "No":
- break
- elif chose == "C" or chose == "n": #RESET
- for l in range(len(score)):
- score[l] = 0
- with open ("game.txt", "w") as f:
- for item in score:
- f.write("%s\t" %item)
- f.close()
- game_times = 0
- total_times = 0
- times = 0
- print ("RESET \n")
- print ("Do you want to play game? Y or N")
- continue
-
- else:
- print("please input Y or N \n")
- print ("Game over")
复制代码 |
|