美文网首页
2020-04-12

2020-04-12

作者: Aspirinor | 来源:发表于2020-04-12 20:54 被阅读0次

之前跟着Crossin的编程教室上的教程学习了一点python的入门知识教程,下面是几个总结了学习内容的游戏代码和其他小程序:

  1. 猜数字的小游戏:

    from random import randint
    num=randint(1,100)
    name=input('请输入你的名字:')
    scores={}
    f=open('game.txt')
    oneuser=f.readlines()
    f.close()
    for el in oneuser:
        s=el.split()
        scores[s[0]]=s[1:]
    score=scores.get(name)
    if score==None:
        scores[name]=[0,0,0]
        score=scores.get(name)
    game_time=int(score[0])
    min_time=int(score[1])
    total_time=int(score[2])
    if game_time>0:
        avg_time=total_time/game_time
    else:
        avg_time=0
    print ('你已经玩了%d次,最少%d轮猜出答案,平均%.2f轮猜出答案' % (
        game_time, min_time, avg_time))
    print('Guess what I am thinking of?')
    answer=int(input())
    time=1
    while answer!=num:
        if answer<num:
            print('%d is too small!'%answer)
        else:
            print('%d is too big'%answer)
        print('Guess again')
        answer=int(input())
        time+=1
    print('bingo, %d is the right answer!'%num)
    if game_time==0 or time<min_time:
        min_time=time
    total_time+=time
    game_time+=1
    scores[name]=[str(game_time),str(min_time),str(total_time)]
    result=''
    for n in scores:
        line=n+' '+' '.join(scores[n])+'\n'
        result+=line
    f=open('game.txt','w')
    f.write(result)
    f.close()
    

    运行该程序需要在.py文件所在子目录创建一个名称为game的txt的文件以储存用户数据。

  2. 点球大战:

    import random
    back=False
    while back==False:              #判断是否再来一局游戏
        direct = ['左', '中', '右']
        score=[0,0]
        rest1=5
        rest2=5                      #rest用于判断游戏是否需要中止
        def kick():                 #将踢球过程写成一个函数
            global rest1,rest2
            # 攻
            print('\n')
            print('=====轮到你踢球了=====')
            print('请选择一个方向攻击:')
            print('左,中,右')
            you = input()
            print('你选择的攻击方向为%s' % you)
            com = random.choice(direct)
            print('你的对手选择防守方向为%s' % com)
            if com != you:
                print('====恭喜你,进球成功!====')
                score[0] += 1
            else:
                print('====很遗憾,对方防守成功……====')
            print('\n')
            #判断是否需要提前终止游戏
            if rest1>0:
                rest1-=1
                if score[0]<score[1] and score[0]+rest1<score[1]:
                    print('===对不起,你已经无法力挽狂澜===')
                    return True
                if score[1]<score[0] and score[1]+rest2<score[0]:
                    print('===守门员已经无法阻挡你了!===')
                    return True
                #判断逻辑为,rest储存剩余局数,每局最多得一分。如果在某一局结束后,自己的得分小于电脑的得分,并且当前得分
                #加上剩余的局数仍小于电脑的得分,则比赛无需继续进行。之后定义一个end变量用于终止游戏,将返回值赋值给end
    
            # 守
            print('=====轮到你防守了=====')
            print('请选择一个方向防守:')
            print('左,中,右')
            you = input()
            print('你选择的防守方向为%s' % you)
            com = random.choice(direct)
            print('你的对手选择攻击方向为%s' % com)
            if com != you:
                print('====很遗憾,对方攻击成功……====')
                score[1] += 1
            else:
                print('====恭喜你,防守成功!====')
            print('\n')
            # 判断是否需要提前终止游戏
            if rest2 > 0:
                rest2-= 1
                if score[0] < score[1] and score[0] + rest1 < score[1]:
                    print('===对不起,你已经无法力挽狂澜===')
                    return True
                if score[1] < score[0] and score[1] + rest2 < score[0]:
                    print('===守门员已经无法阻挡你了!===')
                    return True
                # 判断逻辑为,rest储存剩余局数,每局最多得一分。如果在某一局结束后,自己的得分小于电脑的得分,并且当前得分
                # 加上剩余的局数仍小于电脑的得分,则比赛无需继续进行。之后定义一个end变量用于终止游戏,将返回值赋值给end
    
            return False
        i=0                         #计比赛轮数
        end=False                   #与kick函数内部结构配合用于判断是否终止游戏
        while i<5 and not end:      #游戏的主体
            print('\n')
            print('=====第%d轮比赛=====' % (i + 1))
            end=kick()
            i+=1
        # 比赛结束,计算得分
        print('\n')
        print('比赛结束,得分情况为%d :%d' % (score[0], score[1]))
        # 判断输赢
        if score[0] > score[1]:
            print('======你赢啦!!======')
        else:
            if score[0] < score[1]:
                print('======你输了……======')
            else:
                print('======是平局哟======')
                #加时赛
                count = 1
                jiashi = True
                while jiashi == True:
                    print('\n')
                    print('=====加时赛%d=====' % count)
                    kick()
                    #加时赛判断输赢
                    if score[0] > score[1]:
                        print('五轮比赛及加时赛结束,得分情况为%d :%d' % (score[0], score[1]))
                        print('======你赢啦!!======')
                        jiashi = False
                    else:
                        if score[0] == score[1]:
                            print('======继续加时赛======')
                            jiashi = True
                            count += 1
                        else:
                            print('五轮比赛及加时赛结束,得分情况为%d :%d' % (score[0], score[1]))
                            print('======你输了……======')
                            jiashi=False
        print('想再来一局比赛吗?(回答是或否)')
        answer = input()
        if answer == '是':
            back = False
        else:
            back = True
    
  3. 判断坐标所在象限:

    back=False
    while back==False:
        x=int(input('x='))
        y=int(input('y='))
        if x>0:
            if y>0:
                print('坐标(%d,%d)位于第一象限'%(x,y))
            else:
                if y<0:
                    print('坐标(%d,%d)位于第四象限'%(x,y))
                else:
                    print('坐标(%d,%d)位于x轴上'%(x,y))
        else:
            if x<0:
                if y>0:
                    print('坐标(%d,%d)位于第二象限'%(x,y))
                else:
                    if y<0:
                        print('坐标(%d,%d)位于第三象限'%(x,y))
                    else:
                        print('坐标(%d,%d)位于x轴上'%(x,y))
            else:
                if y!=0:
                    print('坐标(%d,%d)位于y轴上'%(x,y))
                else:
                    print('坐标(%d,%d)是原点O'%(x,y))
        print('你想再输入一次吗?(回答是或否)')
        answer=input()
        if answer=='是':
            back=False
        else:
            back=True
    
  4. 天气查询小程序:

    import requests
    try: #若try内部的程序报错,则执行except语句
        while True:  
            city = input('请输入要查询的城市名:\n')
            if not city:
                break
            req = requests.get('http://wthrcdn.etouch.cn/weather_mini?city=%s' % city)
            dic_city = req.json()    #将从天气查询接口得到的json文件转化为一个字典
            city_data = dic_city.get('data')
            if city_data:
                forecast = city_data.get('forecast')[0]
                print(forecast.get('date'))
                print(forecast.get('type'))
                print(forecast.get('high'))
                print(forecast.get('low'))
            else:
                print('未获得')
    except:
        print('查询失败')
    
  5. 面向对象的程序设计:

    class Vehicle:
        def __init__(self, speed):
            self.speed = speed
            
        def drive(self, distance):
            print ('need %f hour(s)' % (distance / self.speed))
            
    class Bike(Vehicle):
        pass
        
    class Car(Vehicle):
        def __init__(self, speed, fuel):
            Vehicle.__init__(self, speed)
            self.fuel = fuel
            
        def drive(self, distance):
            Vehicle.drive(self, distance)
            print ('need %f fuels' % (distance * self.fuel))
    
    b = Bike(15.0)
    c = Car(80.0, 0.012)
    b.drive(100.0)
    c.drive(100.0)
    

相关文章

  • 佛陀的证悟

    佛陀的证悟 三圣阳明文化书院 关注 6.959 · 字数 1634 · 阅读 594 2020-04-12 21:...

  • 读物-呼啸山庄

    书名:呼啸山庄 作者:艾米莉·勃朗特 阅读时长:2020-04-03 至 ~2020-04-12 一:打卡记录: ...

  • 怎么老是那么纠结——“三个我”

    2020-04-12 课上,Z君肚子饿了。 本我说:“你想饿死我吗?快去给我找吃的!” 超我说:”现在在上课,怎么...

  • 坚持打卡2020-04-11

    2020-04-11周六 学习-2-打卡-redis 运动-2-打卡-20min室内运动 2020-04-12周日

  • 【周总结】第八期第14周07号-醒

    2020-04-12 【本周计划/总结】 一、职业发展 本周好好学习,没有太多的简单事情,最近亲戚经常在家里,自己...

  • 《贫穷的本质》3

    Day27 2020-04-12 《简七:只需3赵,打造你的“万能财富池”》 【字数】 以前的社会求温饱,渐渐地奔...

  • 如果是去见你 我一定是跑着去的/跟同桌小聚

    2020-04-12 今天是休假。7:40几分也正常醒来了。起床的话,把自己的昨晚的衣服还有我的枕套都给洗了。 准...

  • 遇见NO.148

    2020-04-12 星期日 晴 遇见NO.148 前几天,在爱播者朗诵时,听到日记星球的一位同学朗读的内...

  • 2020-04-12

    2020-04-12 2020年4月12星期六【子湘妈读经典感恩日记第644篇】晴 读经方法:育心147累积法 读...

  • 父女关于“屁”的对话--宝贝成长记录11

    2020-04-12 lucky3岁4个月27天,很快就到3岁半啦 宝贝日常记录: 父女对话: 听到爸爸和女儿的对...

网友评论

      本文标题:2020-04-12

      本文链接:https://www.haomeiwen.com/subject/kbtimhtx.html