2020-04-12

之前跟著Crossin的編程教室上的教程學(xué)習(xí)了一點(diǎn)python的入門知識(shí)教程,下面是幾個(gè)總結(jié)了學(xué)習(xí)內(nèi)容的游戲代碼和其他小程序:

  1. 猜數(shù)字的小游戲:

    from random import randint
    num=randint(1,100)
    name=input('請(qǐng)輸入你的名字:')
    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 ('你已經(jīng)玩了%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()
    

    運(yùn)行該程序需要在.py文件所在子目錄創(chuàng)建一個(gè)名稱為game的txt的文件以儲(chǔ)存用戶數(shù)據(jù)。

  2. 點(diǎn)球大戰(zhàn):

    import random
    back=False
    while back==False:              #判斷是否再來(lái)一局游戲
        direct = ['左', '中', '右']
        score=[0,0]
        rest1=5
        rest2=5                      #rest用于判斷游戲是否需要中止
        def kick():                 #將踢球過(guò)程寫(xiě)成一個(gè)函數(shù)
            global rest1,rest2
            # 攻
            print('\n')
            print('=====輪到你踢球了=====')
            print('請(qǐng)選擇一個(gè)方向攻擊:')
            print('左,中,右')
            you = input()
            print('你選擇的攻擊方向?yàn)?s' % you)
            com = random.choice(direct)
            print('你的對(duì)手選擇防守方向?yàn)?s' % com)
            if com != you:
                print('====恭喜你,進(jìn)球成功!====')
                score[0] += 1
            else:
                print('====很遺憾,對(duì)方防守成功……====')
            print('\n')
            #判斷是否需要提前終止游戲
            if rest1>0:
                rest1-=1
                if score[0]<score[1] and score[0]+rest1<score[1]:
                    print('===對(duì)不起,你已經(jīng)無(wú)法力挽狂瀾===')
                    return True
                if score[1]<score[0] and score[1]+rest2<score[0]:
                    print('===守門員已經(jīng)無(wú)法阻擋你了!===')
                    return True
                #判斷邏輯為,rest儲(chǔ)存剩余局?jǐn)?shù),每局最多得一分。如果在某一局結(jié)束后,自己的得分小于電腦的得分,并且當(dāng)前得分
                #加上剩余的局?jǐn)?shù)仍小于電腦的得分,則比賽無(wú)需繼續(xù)進(jìn)行。之后定義一個(gè)end變量用于終止游戲,將返回值賦值給end
    
            # 守
            print('=====輪到你防守了=====')
            print('請(qǐng)選擇一個(gè)方向防守:')
            print('左,中,右')
            you = input()
            print('你選擇的防守方向?yàn)?s' % you)
            com = random.choice(direct)
            print('你的對(duì)手選擇攻擊方向?yàn)?s' % com)
            if com != you:
                print('====很遺憾,對(duì)方攻擊成功……====')
                score[1] += 1
            else:
                print('====恭喜你,防守成功!====')
            print('\n')
            # 判斷是否需要提前終止游戲
            if rest2 > 0:
                rest2-= 1
                if score[0] < score[1] and score[0] + rest1 < score[1]:
                    print('===對(duì)不起,你已經(jīng)無(wú)法力挽狂瀾===')
                    return True
                if score[1] < score[0] and score[1] + rest2 < score[0]:
                    print('===守門員已經(jīng)無(wú)法阻擋你了!===')
                    return True
                # 判斷邏輯為,rest儲(chǔ)存剩余局?jǐn)?shù),每局最多得一分。如果在某一局結(jié)束后,自己的得分小于電腦的得分,并且當(dāng)前得分
                # 加上剩余的局?jǐn)?shù)仍小于電腦的得分,則比賽無(wú)需繼續(xù)進(jìn)行。之后定義一個(gè)end變量用于終止游戲,將返回值賦值給end
    
            return False
        i=0                         #計(jì)比賽輪數(shù)
        end=False                   #與kick函數(shù)內(nèi)部結(jié)構(gòu)配合用于判斷是否終止游戲
        while i<5 and not end:      #游戲的主體
            print('\n')
            print('=====第%d輪比賽=====' % (i + 1))
            end=kick()
            i+=1
        # 比賽結(jié)束,計(jì)算得分
        print('\n')
        print('比賽結(jié)束,得分情況為%d :%d' % (score[0], score[1]))
        # 判斷輸贏
        if score[0] > score[1]:
            print('======你贏啦?。?=====')
        else:
            if score[0] < score[1]:
                print('======你輸了……======')
            else:
                print('======是平局喲======')
                #加時(shí)賽
                count = 1
                jiashi = True
                while jiashi == True:
                    print('\n')
                    print('=====加時(shí)賽%d=====' % count)
                    kick()
                    #加時(shí)賽判斷輸贏
                    if score[0] > score[1]:
                        print('五輪比賽及加時(shí)賽結(jié)束,得分情況為%d :%d' % (score[0], score[1]))
                        print('======你贏啦?。?=====')
                        jiashi = False
                    else:
                        if score[0] == score[1]:
                            print('======繼續(xù)加時(shí)賽======')
                            jiashi = True
                            count += 1
                        else:
                            print('五輪比賽及加時(shí)賽結(jié)束,得分情況為%d :%d' % (score[0], score[1]))
                            print('======你輸了……======')
                            jiashi=False
        print('想再來(lái)一局比賽嗎?(回答是或否)')
        answer = input()
        if answer == '是':
            back = False
        else:
            back = True
    
  3. 判斷坐標(biāo)所在象限:

    back=False
    while back==False:
        x=int(input('x='))
        y=int(input('y='))
        if x>0:
            if y>0:
                print('坐標(biāo)(%d,%d)位于第一象限'%(x,y))
            else:
                if y<0:
                    print('坐標(biāo)(%d,%d)位于第四象限'%(x,y))
                else:
                    print('坐標(biāo)(%d,%d)位于x軸上'%(x,y))
        else:
            if x<0:
                if y>0:
                    print('坐標(biāo)(%d,%d)位于第二象限'%(x,y))
                else:
                    if y<0:
                        print('坐標(biāo)(%d,%d)位于第三象限'%(x,y))
                    else:
                        print('坐標(biāo)(%d,%d)位于x軸上'%(x,y))
            else:
                if y!=0:
                    print('坐標(biāo)(%d,%d)位于y軸上'%(x,y))
                else:
                    print('坐標(biāo)(%d,%d)是原點(diǎn)O'%(x,y))
        print('你想再輸入一次嗎?(回答是或否)')
        answer=input()
        if answer=='是':
            back=False
        else:
            back=True
    
  4. 天氣查詢小程序:

    import requests
    try: #若try內(nèi)部的程序報(bào)錯(cuò),則執(zhí)行except語(yǔ)句
        while True:  
            city = input('請(qǐng)輸入要查詢的城市名:\n')
            if not city:
                break
            req = requests.get('http://wthrcdn.etouch.cn/weather_mini?city=%s' % city)
            dic_city = req.json()    #將從天氣查詢接口得到的json文件轉(zhuǎn)化為一個(gè)字典
            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. 面向?qū)ο蟮某绦蛟O(shè)計(jì):

    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)
    
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 基礎(chǔ)1.r''表示''內(nèi)部的字符串默認(rèn)不轉(zhuǎn)義2.'''...'''表示多行內(nèi)容3. 布爾值:True、False(...
    neo已經(jīng)被使用閱讀 1,887評(píng)論 0 5
  • 8月22日-----字符串相關(guān) 2-3 個(gè)性化消息: 將用戶的姓名存到一個(gè)變量中,并向該用戶顯示一條消息。顯示的消...
    future_d180閱讀 1,034評(píng)論 0 1
  • "use strict";function _classCallCheck(e,t){if(!(e instanc...
    久些閱讀 2,142評(píng)論 0 2
  • Cyber-dojo.org是編程操練者的樂(lè)園。下面是這個(gè)網(wǎng)站上的43個(gè)編程操練題目,供編程操練愛(ài)好者參考。 10...
    程序員吾真本閱讀 1,981評(píng)論 1 2
  • 這群女人是真的強(qiáng),比男人還厲害,我這每天過(guò)的心驚膽戰(zhàn)的 不敢有半點(diǎn)松弛,一天沒(méi)有狀態(tài) 就一直是倒數(shù),努力了好幾...
    阿飛Fineyoga閱讀 197評(píng)論 0 8

友情鏈接更多精彩內(nèi)容