while true do
box = {}
boxdistr = {}
boxdistl = {}
boxstate = {}
ry = mainmemory.read_u8(0x0202)
ly = mainmemory.read_u8(0x020A)
boxnextr=255
boxnextl=255
for k=1, 8, 1 do
box[k] = mainmemory.read_u8(0x0215+(k-1)*0x0008)
boxstate[k] = mainmemory.read_u8(0x0213+(k-1)*0x0008)
if boxstate[k] == 1 then
if box[k] >= 0 and box[k] <= 2
then
boxdistr[k] = 2-box[k]
elseif box[k] >= 3 and box[k] <= 20
then
boxdistr[k] = 20-box[k]
elseif box[k] >= 21 and box[k] <= 38
then
boxdistr[k] = 38-box[k]
else boxdistr[k] = 255
end
if box[k] >= 0 and box[k] <= 11
then
boxdistl[k] = 11-box[k]
elseif box[k] >= 12 and box[k] <= 29
then
boxdistl[k] = 29-box[k]
elseif box[k] >= 30 and box[k] <= 47
then
boxdistl[k] = 47-box[k]
else boxdistl[k] = 255
end
if boxdistr[k] < boxnextr
then
boxnextr = boxdistr[k]
end
if boxdistl[k] < boxnextl
then
boxnextl = boxdistl[k]
end
end
end
for k=1, 8, 1 do
if boxstate[k] == 1 then
if boxnextr == boxdistr[k]
then
if box[k] >= 0 and box[k] <= 2 and (ry == 2 or ry == 1)
then
joypad.set({B=true})
elseif box[k] >= 3 and box[k] <= 20 and ry == 2
then
joypad.set({B=true})
elseif box[k] >= 3 and box[k] <= 20 and ry == 0
then
joypad.set({A=true})
elseif box[k] >= 21 and box[k] <= 38 and (ry == 1 or ry == 0)
then
joypad.set({A=true})
end
end
if boxnextl == boxdistl[k]
then
if box[k] >= 0 and box[k] <= 11 and (ly == 2 or ly == 1)
then
joypad.set({Down=true})
elseif box[k] >= 12 and box[k] <= 29 and ly == 2
then
joypad.set({Down=true})
elseif box[k] >= 12 and box[k] <= 29 and ly == 0
then
joypad.set({Up=true})
elseif box[k] >= 30 and box[k] <= 47 and (ly == 1 or ly == 0)
then
joypad.set({Up=true})
end
end
end
end
emu.frameadvance()
end