這是因爲你不打電話給ScoreBoard
,即使你這樣做,你已經讀了你的文件,當你做FileList = FileOpen.readlines()
,所以當你試圖做list(FileOpen)
時,你會得到一個空的列表。當然這是件好事,因爲FileList(item, 1)
和FileList(item, 2)
不會很好地工作。
一個很好的方法來檢查,如果你的代碼是做什麼的應該是通過使用記錄模塊的內容:
import logging
log = logging.basicConfig(level=logging.DEBUG)
current_1 = 0
current_2 = 0
current_3 = 0
current_4 = 0
current_5 = 0
FileOpen = open("playerScores.txt")
FileList = FileOpen.readlines()
def ScoreBoard ():
log.debug(">> ScoreBoard")
for item in list(FileOpen):
log.debug("Checking item %s", item)
CheckLevel = FileList(item,1)
CheckScore = Filelist(item,2)
if CheckLevel == 1:
if CheckScore > current_1:
current_1 = CheckScore
elif CheckLevel == 2:
if CheckScore > current_2:
current_2 = CheckScore
elif CheckLevel == 3:
if CheckScore > current_3:
current_3 = CheckScore
elif CheckLevel == 4:
if CheckScore > current_4:
current_4 = CheckScore
elif CheckLevel == 5:
if CheckScore > current_4:
current_5 = CheckScore
log.debug("Calling ScoreBoard")
ScoreBoard
log.debug("Done with ScoreBoard")
print(current_1,current_2,current_3,current_4,current_5)
但是,您可以大大提高你的程序的可讀性:
import logging
log = logging.basicConfig(level=logging.DEBUG)
current_1 = 0
current_2 = 0
current_3 = 0
current_4 = 0
current_5 = 0
def scoreboard():
log.debug('>> scoreboard')
with open("playerScores.txt") as f:
log.info('Reading scores...')
for line in f:
level, score = line.strip().split()
level = int(level)
score = int(score)
log.debug('level: %s score: %s', level, score)
if level == 1 and score > current_1:
log.debug('Level 1 high score: %s', score)h
current_1 = score
elif level == 2 and score > current_2:
log.debug('Level 2 high score: %s', score)
current_2 = score
elif level == 3 and score > current_3:
log.debug('Level 3 high score: %s', score)
current_3 = score
elif level == 4 and score > current_4:
log.debug('Level 4 high score: %s', score)
current_4 = score
elif level == 5 and score > current_5:
log.debug('Level 6 high score: %s', score)
current_5 = score
log.debug("<< scoreboard")
scoreboard()
print(current_1,current_2,current_3,current_4,current_5)
可能不會解決你的問題,但是如果你使用'&&'連接它們,每個'if checkLevel ...''如果checkScore ...'對可以合併爲1行。將每個級別的當前高分存儲在列表中以減少所有重複的代碼也可能是有利的。 – Carcigenicate 2015-04-01 11:02:37
謝謝:)我現在試試吧 – user3921501 2015-04-01 11:15:27