2014-11-01 54 views
0
function saveScore() 
    local path = system.pathForFile("scoredata001.txt", system.DocumentsDirectory) 
    local file = io.open(path, "w") 

    if file then 
     local score=get_score() --The get_score() returns the value of current score which is saved in 'score'. 
     local newScore = compareScore() 
     local contents = tostring(newScore) 
     file:write(contents) 
     io.close(file) 
     return true 
    else 
     print("Error: could not write Score") 
     return false 
    end 
end 

function loadScore() 
    local path = system.pathForFile("scoredata001.txt", system.DocumentsDirectory) 

    local contents = "" 
    local file = io.open(path, "r") 
     if file then 
      local contents = file:read("*a") 
      local score = tonumber(contents); 
      io.close(file) 
      return score 
     end 
    print("Could not read scores from scoredata.txt") 
    return nil 
end 

function return_highScore() 
    local highscore=loadScore() 
     if highscore==nil then 
      highscore=0 
     end 
    return highscore 
end 

function compareScore() 
    local highscore=return_highScore() 
    if highscore then 
     local currscore=get_score() 
      if highscore==0 then 
       return highscore 
      elseif currscore>highscore then 
       return currscore 
      end 
    end 
    return true 
end 

function disp_permScore() 
    local display_score=return_highScore() 
    text_display2= display.newText("GAME OVER!\n BEST: " ..display_score, 0, 0, "Helvetica", 80) 
    text_display2.x = centerX 
    text_display2.y = centerY 
    text_display2.alpha=1 

function gameOver() 
    mainScreen() 
    saveScore() 
    disp_permScore() 
end 

(這是refernce以前的問題Permission issues in lua與盧阿節省高分問題

基本上我試圖建立在Lua遊戲(這是我的第一次比賽) 但是,我無法將高分保存到文件。如果它被保存,那麼我無法檢索它們。 (總之,我在執行代碼時總會出現一些或其他錯誤/問題

請看看上面的代碼我想同時顯示高分和當前分數當前分數正在顯示完美。是我昨天晚上試過的東西,但是現在,高分並沒有被保存在文件中(也就是說,最好總是顯示0)另外,cmd表示「無法從scoredata.txt讀取分數)我無法找到哪裏我去錯了。

請幫助呢? 請告訴我在哪裏去了? 另外,如果可能的話,提供(或編輯)正確的代碼嗎?

+0

+1關於縮進。因爲它的代碼甚至沒有語法上的有效性(末尾有一個「末端」丟失)。適當的縮進會使這一點變得明顯。對於嘗試閱讀和理解代碼的人來說,這也是一個禮節性的問題... – siffiejoe 2014-11-01 10:51:26

回答

1

似乎有成爲這條線上的問題

if highscore==0 
then 
return highscore 

這意味着你檢查高分是否爲0,如果是,那麼你返回它而不是實際的高分。

此外,我不知道你的代碼是否只是粘貼錯誤,但沒有縮進你的代碼,它變得很難閱讀。試着再看一遍,我記下它,現在錯誤變得很容易發現。

+0

非常感謝您縮進代碼。 當我運行代碼時,電暈模擬器輸出顯示「無法從scoredata.txt讀取分數」表示此錯誤從loadScore()函數閃爍。我添加了斷言函數,並且錯誤閃爍了「權限被拒絕」。該怎麼辦? – Ozitrick 2014-11-01 11:00:04

+0

這可能是一些問題。你有沒有檢查過該文件?否則,我最好的建議是將您的代碼更改爲使用JSON。通過這種方式,您可以創建一個可變的值,並像這樣使用它:「highscores.currentScore」和「highscore.highestScore」。閱讀本文http://stackoverflow.com/questions/24810358/simple-way-to-keep-track-of-a-high-score-with-corona-sdk/24810753#24810753 - 還請記住接受有問題的答案通過點擊答案旁邊的小「v」或批准標記。 – 2014-11-01 11:10:44

+1

非常感謝@Frozire在您的代碼上花費您的時間和精力。我成功地在沒有JSON的情況下成功保存了高分。感謝您的幫助 :) – Ozitrick 2014-11-02 05:48:41