2013-07-26 50 views
1

我對updateScore有問題,我的功能是如果用戶第一次玩遊戲。updateScore無法正常工作

它會創建一個名爲myFile.txt的文件來記錄分數,現在要做的代碼是(如果讀者那麼)看文件是否存在,如果不存在,它會去我的其他如果已經有一個文件,那麼我的內容應該有分數值,然後我可以用它來比較並獲得我的高分。

問題是我的內容總是返回nil價值,因此當你玩的時候總會得到的分數會取代應該是我的高分的分數,我不知道我做錯了什麼。

這裏是我的代碼

function updateScore() 

    local path = system.pathForFile("myfile.txt", system.DocumentsDirectory) 
    local reader = io.open(path, "r") 
    local file = io.open(path, "w") 

    if reader then 

     reader:close() 
     local reader1 = io.open(path, "r") 
     local contents = reader1:read("*n") 


     if (stopscore == false) then 
      score = score + 1 
      scoreText.text = "score: " .. score 
      scoreText:setReferencePoint(display.CenterLeftReferencePoint) 
      scoreText.x = 0 
      scoreText.y = 30 
     end 

     if (stopscore == true) then 

      if (contents == nil) then 
       local file = io.open(path, "w") 
       file:write(score) 
       file:flush() 
       file:close() 
       timer.pause(timer1) 
       director:changeScene("menu", "downFlip") 

      else 

       if (contents < score) then 
        file:write(score) 
        file:flush() 
        file:close() 
        timer.pause(timer1) 
        director:changeScene("menu", "downFlip") 
       else 
        file:write(contents) 
        file:flush() 
        file:close() 
        timer.pause(timer1) 
        director:changeScene("menu", "downFlip") 
       end 

      end 
     end 

    else 

     local file1 = io.open(path, "w") 
     local walaVal=0 
     file1:write(walaVal) 
     file1:close() 

     if (stopscore == false) then 
      score = score + 1 
      scoreText.text = "score: " .. score 
      scoreText:setReferencePoint(display.CenterLeftReferencePoint) 
      scoreText.x = 0 
      scoreText.y = 30 
      print(contents) 
     end 

     if (stopscore == true) then 
      local file = io.open(path, "w") 
      file:write(score) 
      file:flush() 
      file:close() 
      timer.pause(timer1) 
      director:changeScene("menu", "downFlip") 
     end 

    end 
end 

回答

0

內容返回nil,因爲這個代碼出現問題 local file = io.open(path, "w")當你調用這個它會刪除該文件的所有內容,以解決這個問題,你必須刪除當你調用本地文件如本地file = io.open(path)以及當你更新分數時,你應該再次使用模式「w」來進一步理解我在說什麼,我會寫和解釋代碼。

--first check the file if exist 
    local path = system.pathForFile("myfile.txt", system.DocumentsDirectory) 
    local file = io.open(path) 

-- if file exist check the content and read the score else create a file and write the score 

    if file then 
     local reader = io.open(path, "r") 
     local contents = reader:read("*n") 
-- if content is less than myScore Update the Score 
    if contents < myScore then 
    file = io.open(path,"w") 
    file:write(myScore) 
     file:flush() 
     file:close() 
    end 
else 
    file = io.open(path,"w") 
    file:write(myScore) 
    file:flush() 
    file:close() 
end 

希望我解釋它很好地爲您:)

+0

的感謝!它創造奇蹟 – user2596861