zoukankan      html  css  js  c++  java
  • python学习——计算游戏

    逻辑:

    从1-9之间随机选取2个数,从+、-中随机选取一个运算符,等待一个算式。我们根据算式给出答案,如果对则显示答对了,并且得分+1,如果同一道题3次都答错了就告诉正确答案,结束游戏的时候告知你得分。

    实现代码:

     1 from operator import add, sub
     2 from random import randint, choice
     3 
     4 #定义全局变量:操作符字典、得分、答题机会
     5 ops = {'+': add, '-': sub}
     6 MAXTRIRES = 2
     7 COUNT = 0
     8 
     9 def example():
    10     #未加global则为局部变量
    11     global  COUNT
    12     op = choice('+-')
    13     nums = [randint(1,10) for i in range(2)]
    14     #把2个数字排序
    15     nums.sort(reverse=True)
    16     ans=ops[op](*nums)
    17     oops=0
    18     #字符串格式化 %s %d %f %c,2个字符串同时引用%(1,2)
    19     equales = '%s %s %s = ' % (nums[0], op, nums[1])
    20     while True:
    21             if(int(input(equales)) == ans):
    22                 print("correct")
    23                 COUNT = COUNT + 1
    24                 break
    25             elif(oops == MAXTRIRES):
    26                 print("Anwser is %d" %ans)
    27                 break
    28             else:
    29                 oops += 1
    30                 print("you are wrong")
    31 
    32 def main():
    33     while True:
    34         example()
    35         try:
    36             opt = input("Do you want to play again?").lower()
    37             if(opt == 'n'):
    38                 print("You get %d score" %COUNT)
    39                 break
    40         except (KeyboardInterrupt, EOFError):
    41             break
    42 
    43 #如果单独调用这个程序则只需这下面的内容
    44 if __name__=='__main__':
    45     main()
  • 相关阅读:
    PHP创建socket服务
    linux配置PS1
    几个常用的linux命令
    MongoDB的分片集群搭建
    django-admin 配置
    django使用mysql数据库
    Django知识
    docker 监控之 cadvisor
    shell 拾遗
    shell 基数数值方法
  • 原文地址:https://www.cnblogs.com/gforce/p/5983883.html
Copyright © 2011-2022 走看看