Last active
April 19, 2022 04:05
-
-
Save kevinthompson/0887a165c016e205153e8226478e3b9a to your computer and use it in GitHub Desktop.
High Score Library for PICO-8
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- highscore | |
-- by @kevinthompson | |
_hs_chars="abcdefghijklmnopqrstuvwxyz " | |
_hs_max_records=10 | |
_hs_record_bytesize=5 | |
_hs_records={} | |
_hs_char_index=function(char) | |
for i=1,#_hs_chars do | |
if sub(_hs_chars,i,i)==char then | |
return i | |
end | |
end | |
return 1 | |
end | |
_hs_save=function() | |
for i=0,#_hs_records-1 do | |
if _hs_records[i+1] then | |
local addr=_hs_memory_addr+_hs_record_bytesize*i | |
for n=1,3 do | |
poke(addr+n-1,_hs_char_index(sub(_hs_records[i+1][1],n,n))) | |
end | |
poke2(addr+3,_hs_records[i+1][2]) | |
end | |
end | |
_hs_refresh_table() | |
end | |
_hs_reset=function() | |
_hs_records={} | |
memset(_hs_memory_addr,0,_hs_max_records*_hs_record_bytesize) | |
end | |
_hs_load=function() | |
for i=0,_hs_max_records-1 do | |
local name="" | |
local addr=_hs_memory_addr+_hs_record_bytesize*i | |
for n=0,2 do | |
local v=peek(addr+n) or 1 | |
name=name..sub(_hs_chars,v,v) | |
end | |
_hs_records[i+1]={name,peek2(addr+3)} | |
end | |
_hs_refresh_table() | |
end | |
_hs_record_index = function(score) | |
for i=1,#_hs_records do | |
if score>tonum(_hs_records[i][2]) then | |
return i | |
end | |
end | |
if #_hs_records < _hs_max_records then | |
return #_hs_records+1 | |
end | |
end | |
_hs_init=function(memory_addr) | |
_hs_memory_addr=memory_addr or 0x5e00 | |
_hs_load() | |
end | |
_hs_add=function(name, score) | |
local index=_hs_record_index(score) | |
if index then | |
for i=_hs_max_records,index+1,-1 do | |
_hs_records[i]=_hs_records[i-1] | |
end | |
_hs_records[index]={name, score} | |
end | |
_hs_save() | |
end | |
_hs_refresh_table=function() | |
highscore={ | |
records=_hs_records, | |
new_record_index=_hs_record_index, | |
init=_hs_init, | |
reset=_hs_reset, | |
add=_hs_add | |
} | |
end | |
_hs_refresh_table() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment