I am using twitter API to post highscores and it seems to be collecting the score variable correctly however, its not getting the highscore value on the turn that they played.
example: I start the game for first time and my highscore is 0. I get 20 on game over and want to tweet it but my tweet displays 0. on next play through it shows 20.
So its basically behind by 1 turn each time and displays the previous highscore. I have a feeling its a basic error but i can't see, to get around it.
I have two files that save my scores for leaderboards etc.
local scoring = require("helpers.scoring")
local utils = require("helpers.globals")
function scene:createScene( event )
local group = self.view
utils.loadHighscoreInfo()
-- Gameover --
if miles > utils.highscore then
utils.highscore = miles
utils.saveHighscoreInfo()
scoring.setHighScore( utils.highscore, utils.leaderboard )
end
-- Twitter set up --
local options = {
message = " I scored " .. utils.highscore .. " Miles ",
listener = tweetCallback
}
function tweetCallback( event )
if ( event.action == "cancelled" ) then
print( "User cancelled" )
else
native.showPopup( "twitter", options )
print( "Thanks for the tweet!" )
end
end
Update the options message before handling the tweet.
local options = {
message = " I scored " .. utils.highscore .. " Miles ",
listener = tweetCallback
}
This doesn't update dynamically as utils.highscore changes, it takes a snapshot of the value at the time you declare it (first run through each game). So you simply have to update it when the game is over using
options.message = "I scored" .. utils.highscore .. " Miles "
Related
Ive been racking brains all day tryna fix this and i am new with lua and cant come up with a solution to this problem even though im rather close.
SO
I have a drift leader board in my server. The problem is the script doesnt check for the players [id] in the table. So if player A has a score of 10 and Player B has a score of 5. Player A can take the 2nd position on the leaderboard (table) by getting a score of any int between. so lets say 7.
LEADERBOARD_CLEAR_TIME = 15 -- THIS IS IN MINUTES
local Players = {}
local Leaderboards = {}
RegisterCommand('cleardriftscores', function(source)
if IsPlayerAceAllowed(source, 'drift') then --Ace permissions
clearLeaderboard()
end
end)
RegisterNetEvent("SaveScore")
AddEventHandler("SaveScore", function(client, data)
local identifier = (GetPlayerIdentifier(source, 0))
local playerName = GetPlayerName(source)
if Players[identifier] ~= nil then
if Players[identifier].pb < data.curScore then
-- Personal Best Beat
local oldScore = Players[identifier].pb
Players[identifier] = { pb = data.curScore }
chatMessage(source, string.format("Congrats! You have just beaten your personal best drift chain score of ^2%s^0 with ^2%s^0!", oldScore, data.curScore))
end
else
Players[identifier] = { pb = data.curScore }
end
if #Leaderboards == 0 then
table.insert(Leaderboards, {score = data.curScore, name = playerName, id = identifier})
chatMessage(-1, string.format("^2%s^0 has started off the leaderboard with a score of ^2%s^0!", playerName, data.curScore))
end
for k, v in ipairs(Leaderboards) do
if v.score < data.curScore and checkLeaderboard(identifier) then
-- Outpassed Someone
table.insert(Leaderboards, { score = data.curScore, name = playerName, id = identifier } )
chatMessage(-1, string.format("^2%s^0 has beaten ^2%s's^0 score of ^2%s^0 with ^2%s^0! They are in ^2%s^0 place", playerName, v.name, v.score, data.curScore, GetPlacement(k)))
break
end
end
table.sort(Leaderboards, compare) --Currently bugged, when player 1 is in first and player 2 is in second. Player 1 can take second by getting a score inbetween table entry 1 & 2
end)
function chatMessage(target, msg)
TriggerClientEvent('chat:addMessage', target or -1, {
color = { 255, 0, 0},
multiline = true,
args = {"[Drift] ", msg}
})
end
function checkLeaderboard(identifier)
for k, v in ipairs(Leaderboards) do
if v.id == identifier then
Leaderboards[k] = nil
end
end
return true
end
function compare(a, b) --actual compare funtion. Need to check for player id's somehow...
if a ~= nil and b ~= nil then
return a.score > b.score --I tried adding another compare here but that didnt work.
end
end
function GetPlacement(number) --This doesnt work very well. (12nd place??)
lastDigit = number % 10
local placement = 'th'
if lastDigit == 1 then
placement = 'st'
elseif lastDigit == 2 then
placement = 'nd'
elseif lastDigit == 3 then
placement = 'rd'
end
return number .. placement
end
function clearLeaderboard()
Leaderboards = {}
chatMessage(-1, "The Drift leaderboard has been cleared!")
end
Citizen.CreateThread(function() --Code for timer to reset leaderboard
while true do
while #Leaderboards == 0 do
Citizen.Wait(0)
end
Citizen.Wait((LEADERBOARD_CLEAR_TIME * 1000 * 60) - (60 * 1000 * 5))
chatMessage(-1, "The Drift Leaderboard is clearing in 5 minutes!")
Citizen.Wait(1000 * 60 * 3)
chatMessage(-1, "The Drift Leaderboard is clearing in 2 minutes!")
Citizen.Wait(1000 * 60 * 1)
chatMessage(-1, "The Drift Leaderboard is clearing in 1 minute!")
Citizen.Wait(1000 * 60 * 1)
clearLeaderboard()
end
end)
The problem here is the code that adds to the leaderboards.
If a player is only allowed to be on a leaderboard once, you should check for that!
Here's how I'd do it:
If the player has beaten his/her personal best then attempt to add his new score to the leaderboards.
Start from the lowest score on the leaderboard. For each score:
If the score owner is equal to the player, delete this score (it's outdated).
If the personal best is smaller than the currently inspected score, insert the personal best one below the current inspected score.
Doing so there won't be any duplicates.
Btw, compare function is just fine ;)
But, just a friendly reminder:
a ~= nil and b ~= nil
--This is simpler and faster!
a and b
Remember that nil in Lua evaluates to false. Therefore, if you need to check if something holds value just:
if a then --This checks if a isn't false or nil
--your code goes here
end
And also that line is not really useful in your comparing function.
Hope that helps!
How do I get damage value and school of incoming damage magic using api World Of WarCraft 1.13 in lua language? Damage caused to me by another player or mob.
This is necessary so that I can use
print("You received " .. damageValue .. " " .. damageSchool .. " damage")
So that I can get in the chat:
You received 100 Fire damage
You received 50 Physical damage
etc.
Classic combat log should be almost the same as retail
See https://wow.gamepedia.com/COMBAT_LOG_EVENT
local playerGUID = UnitGUID("player")
local MSG_PLAYER_DAMAGE = "You received %d %s damage"
local damageEvents = {
SWING_DAMAGE = true,
SPELL_DAMAGE = true,
}
local f = CreateFrame("Frame")
f:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED")
f:SetScript("OnEvent", function(self, event)
self:OnEvent(event, CombatLogGetCurrentEventInfo())
end)
function f:OnEvent(event, ...)
local timestamp, subevent, _, sourceGUID, sourceName, sourceFlags, sourceRaidFlags, destGUID, destName, destFlags, destRaidFlags = ...
local spellId, spellName, spellSchool
local amount, overkill, school, resisted, blocked, absorbed, critical, glancing, crushing, isOffHand
if subevent == "SWING_DAMAGE" then
amount = select(12, ...)
elseif subevent == "SPELL_DAMAGE" then
spellId, spellName, spellSchool, amount = select(12, ...)
end
if damageEvents[subevent] and destGUID == playerGUID then
print(MSG_PLAYER_DAMAGE:format(amount, GetSchoolString(spellSchool or 0x1)))
end
end
I have been following the tutorials on corona website and everything has been going well so far.
But in the tutorial "Displaying and saving score" i seem to have the following runtime error.
attempt to call field setPreferences' (a nil value)
This is the code of score.lua
local M = {}
M.score = 0
function M.init( options )
local customOptions = options or {} -- nice use of "or" operator
local opt = {}
opt.fontSize = customOptions.fontSize or 24
opt.font = customOptions.font or native.systemFont
opt.x = customOptions.x or display.contentCenterX
opt.y = customOptions.y or opt.fontSize*0.5 -- such that the score is positioned at the top, half of its font size.
opt.maxDigits = customOptions.maxDigits or 6
opt.leadingZeros = customOptions.leadingZeros or false
local prefix = ""
if ( opt.leadingZeros ) then
prefix = "0"
end
M.format = "%" .. prefix .. opt.maxDigits .. "d" -- so that its accesible in other modules.
-- Create the score display object
M.scoreText = display.newText( string.format( M.format, 0 ), opt.x, opt.y, opt.font, opt.fontSize ) -- string.format() works like printf and scanf statements
M.scoreText:setFillColor(1,0,0)
return M.scoreText
end
function M.set( value )
M.score = tonumber(value)
M.scoreText.text = string.format( M.format, M.score )
end
function M.get()
return M.score
end
function M.add( amount )
M.score = M.score + tonumber(amount)
M.scoreText.text = string.format( M.format, M.score )
end
function M.save()
print (" the score is " .. M.score)
local saved = system.setPreferences( "app", { currentScore=M.score } )
if ( saved == false) then
print ( "ERROR: could not save score" )
end
end
function M.load()
local score = system.getPreference( "app", "currentScore", "number" )
if ( score ) then
return tonumber(score)
else
print( "ERROR: could not load score (score may not exist in storage)" )
end
end
return M
This is the code of main.lua
local score = require( "score" )
local scoreText = score.init(
{
fontSize = 20,
font = "CoolCustomFont.ttf",
x = display.contentCenterX,
y = 30,
maxDigits = 7,
leadingZeros = true
})
local savedScore = score.load()
score.set( 1000 ) -- Sets the score to value
score.save()
I am aware there are other ways of keeping score, but I want to know what the problem is in my code. I googled everywhere but couldn't come up with any solution. Maybe I have made a mistake somewhere that I'm not able to identify.
Even tried a build on my smart phone, but ended up getting the same error.
From corona docs
Syntax
system.setPreferences( category, preferences )
category (required)
String. Indicates which set of preferences should be accessed on the system. Currently, only the "app" category is supported — this is the application's custom preferences defined by the Corona app developer.
preferences (required)
Table. Table of preferences to be written to storage. This table should contain key-value pairs where the key is the unique name of the preference and its value is either a boolean, number, or string.
if your M.score is nil then you might get an error
try this
local saved = system.setPreferences( "app", { currentScore=M.score or 0 } )
I have just implemented adbuddiz reward video in my app and it works as expected but I have a slight challenge.
After watching the video, it triggers the "didComplete" event for adbuddiz where it adds the needed value into a json file.
The challenge now is the value does not automatically reflect on the screen except I go out of the scene and go back before the new value shows.
Is there a way to refresh the screen so the new value appears immediately?
Note: This all happens on a button click
local savecount = Lib.getSaveValue("savecount")
-- Events (rewarded video)
local function listenerRewardedVideo( event )
if event.value == "didFetch" then
print( "didFetch" )
end
if event.value == "didComplete" then
print( "didComplete" )
-- Reward user here
print ("savecount")
savecount = savecount + 1
Lib.setSaveValue("savecount", savecount, true);
local alert = native.showAlert("Successful","Count saved successfully!", {"OK"})
end
if event.value == "didNotComplete" then
print( "didNotComplete" )
end
if event.value == "didFail" then
print( "didFail - " .. event.detail )
end
end
Runtime:addEventListener( "AdBuddizRewardedVideoEvent", listenerRewardedVideo )
This displays the value on the menu scene
label_saveme = display.newText({parent=uiGroup, text=savecount, x=0, y=0, font=native.systemFont, fontSize=24})
label_saveme.xScale = 0.92
label_saveme.x = button_buysaveme.x + 22
label_saveme.y = button_buysaveme.y + 6
label_saveme:setFillColor(255/255, 255/255, 255/255)
label_saveme.alpha = 0.4
uiGroup:insert(label_saveme)
Thanks
So you want to put savecount value on label_saveme?
if your local label_save me on the same file as your button click code, change the "didComplete"
if event.value == "didComplete" then
print( "didComplete" )
-- Reward user here
print ("savecount")
savecount = savecount + 1
label_saveme.text = savecount
Lib.setSaveValue("savecount", savecount, true);
local alert = native.showAlert("Successful","Count saved successfully!", {"OK"})
end
i need help to solve the problem. i really cant know why this error occur.
i use this code to develop a tourism app for my final year project. please help me to solve this
local accomodation = require( "accomodation")
local function onComplete( event )
local action = event.action
if "clicked" == event.action then
if 2 == event.index then
-- Open url if "Learn More" was clicked by the user
system.openURL( "http://www.trivago.com.my/?iPathId=74807&iGeoDistanceItem=0&aDateRange%5Barr%5D=2016-04-17&aDateRange%5Bdep%5D=2016-04-18&iRoomType=7&cpt=7480703&iViewType=0&bIsSeoPage=false&bIsSitemap=false&" )
end
elseif "cancelled" == event.action then
-- our cancelAlert timer function dismissed the alert so do nothing
end
end
-- Show alert
local alert = native.showAlert( "GoPenang", "You will be directed to trivago.com", { "Cancel", "Ok" }, onComplete )
-- Dismisses alert after 10 seconds
local function cancelAlert()
native.cancelAlert( alert )
end
function scene:createScene(event)
local group = self.view
end
function scene: enterScene(event)
local group = self.view
end
function scene:exitScene(event)
local group = self.view
end
function scene:destroyScene(event)
local group = self.view
end
timer.performWithDelay( 10000, cancelAlert )
scene:addEventListener("createScene", scene)
scene:addEventListener("enterScene", scene)
scene:addEventListener("exitScene", scene)
scene:addEventListener("destroyScene",scene)
return scene
this is my accomodation code. the error will appear like this :
enter image description here
The error message says that it can't load the "accomodation" module. I don't know what that module does, but in the very first line you are writing
local accomodation = require( "accomodation")
That piece of code is trying to load the accomodation module - which you seem to never use anywhere in the posted code. Try removing that line and see what follows.