-- mine.lua -- -- todo: -- bomb count shouldn't be random -- first picked square should always be safe w=10 h=10 cw=floor(160/w) ch=floor(160/h) mcount=0 board={} function waitclick() while(pevent()~=penDown) do end while(pevent()~=penUp) do end end -- board cell values: -- " " empty, covered -- "." empty, uncovered -- "B" bomb, covered -- "b" bomb, uncovered function initboard() mcount=0 board={} for y=0, h-1,1 do for x=0,w-1,1 do local a=" " if( random() < 0.2 ) then a = "B" else mcount = mcount + 1 end board[x+y*w] = a end end end function drawboard() pclear() for y=0, h-1,1 do for x=0,w-1,1 do pbox( x*cw, y*ch, cw-1, ch-1) end end end -- show all hidden bombs function showbombs() for y=0, h-1,1 do for x=0,w-1,1 do if( board[y*w + x ] == "B" ) then pbox( x*cw+3, y*ch+2, cw-7, ch-5,0) pmoveto( x*cw+5, y*ch+2 ) print("B") end end end end function valid( x,y ) if( x<0 ) then return 0 end if( x>=w ) then return 0 end if( y<0 ) then return 0 end if( y>=h ) then return 0 end return 1 end function probe( x,y ) if( valid(x,y)==1 ) then if( board[y*w + x ] == "B" ) then return 1 end end return 0 end function count( x,y ) local c=0 c=c+probe(x-1,y-1) c=c+probe(x,y-1) c=c+probe(x+1,y-1) c=c+probe(x-1,y) c=c+probe(x+1,y) c=c+probe(x-1,y+1) c=c+probe(x,y+1) c=c+probe(x+1,y+1) return c end -- returns: -- "" uncovered a safe cell -- "B" hit a bomb -- "D" done - all safe squares cleared function uncover(x,y) if( valid(x,y)==0 ) then return end local m = board[x+y*w] if(m==".") then return "" end pbox( x*cw, y*ch, cw-1, ch-1,0) prect( x*cw, y*ch, cw-1, ch-1) pmoveto( x*cw+4, y*ch+3 ) if( m=="B" ) then -- hide from showbombs() board[x+y*w] = "b" print( "B!" ) return "B" else board[x+y*w] = "." local c = count(x,y) if( c>0 ) then print( c ) else uncover(x-1,y-1) uncover(x,y-1) uncover(x+1,y-1) uncover(x-1,y) uncover(x+1,y) uncover(x-1,y+1) uncover(x,y+1) uncover(x+1,y+1) end end mcount = mcount - 1 if( mcount <= 0 ) then return "D" end return "" end pmode() while( 1 ) do initboard() drawboard() done = 0 while(done==0) do e,px,py = pevent() if(e==penDown ) then x=floor(px/cw) y=floor(py/ch) if( valid(x,y) ) then m=uncover(x,y) if(m=="B") then done=1 palert( "Kaboom.\nGame over.") end if(m=="D") then done=1 palert( "Woo hoo!\nNice one!") end end end end showbombs() pmoveto( 42,75 ) print("tap for new game") waitclick() end