請原諒這個標題用詞不當(dāng)!對于我的計算機科學(xué) GCSE,我獲得了一個 20 小時的項目。其中大部分已完成且功能齊全,但我正在努力完成最后一步。我這樣做是為了讓用戶可以將他們的最終分數(shù)存儲到一個外部文件中,并且該文件的內(nèi)容會在游戲結(jié)束時打印出來。但是,我希望它僅打印前 5 名得分手,并將得分從最高到最低進行分類。每個位置旁邊都有一個數(shù)字來顯示他們在棋盤上的位置會很酷,但如果這很難做到,我可以跳過它。這是用于定義排行榜的代碼部分: def leaderboard(): print ("\n") print ("? Check out the leaderboard ?") #LEADERBOARD SECTION f = open('H_Highscore.txt', 'r') leaderboard = [line.replace('\n','') for line in f.readlines()] for i in leaderboard: print(i) f.close() time.sleep(10) sys.exit()這是寫入排行榜的代碼:user = str(input("Enter a name to save your highscore: ")) file = open ("H_Highscore.txt", "a") file.write("\n") file.write(user) file.write(",") file.write(str(score)) # (int(x)) can not be written file.write("pts") file.write("\n") file.close() time.sleep(0.5) leaderboard() sys.exit()
2 回答

九州編程
TA貢獻1785條經(jīng)驗 獲得超4個贊
指針,將問題分解為一系列步驟并繼續(xù)閱讀:
字符串操作函數(shù) split() 和子字符串,
python 數(shù)據(jù)構(gòu)造元組(一種將值保持在一起的方法)
想想也許:
以與您編寫的格式相同的格式逐行讀取您的高分文件
從相關(guān)行中獲取相關(guān)文本和數(shù)字
將每個(用戶名,分數(shù))作為元組附加到列表中
將列表反向排序
打印列表中的前 5 個項目
代碼片段:
scores.append((user_name,score)) #core is of type list
i = 0
while i < limit:
item = sorted_list[i]
print ("first item of tupple: {} second item:{}".format(item[0],item[1]))
i+=1
提示:不要忘記在排序之前將分數(shù)從 string 轉(zhuǎn)換為 int。
添加回答
舉報
0/150
提交
取消