----------------------------- -- Levak ©2014 -------------- -- http://levak.free.fr/ ---- -- levak92@gmail.com -------- ----------------------------- Game = class() function Game:init() self.grid = Grid(10/320, 2/240, 4) self.lost = false self.score = 0 self.win = false end function Game:paint(gc) self.grid:paint(gc) local m = 4/320*ww do -- Score gc:setColorRGB(187, 173, 160) fillRoundedRect(gc, 224/320*ww, 2/240*wh, 90/320*ww, 50/240*wh, m) gc:setColorRGB(255, 255, 255) gc:setFont("sansserif", "b", 10/320*ww) gc:drawString("SCORE", 250/320*ww, 2/240*wh, "top") gc:setFont("sansserif", "b", 12/320*ww) local s = tostring(self.score) local sw = gc:getStringWidth(s) gc:drawString(s, 270/320*ww - sw/2, 20/240*wh, "top") end do -- Best score gc:setColorRGB(187, 173, 160) fillRoundedRect(gc, 224/320*ww, 60/240*wh, 90/320*ww, 50/240*wh, m) gc:setColorRGB(255, 255, 255) gc:setFont("sansserif", "b", 10/320*ww) gc:drawString("BEST", 255/320*ww, 60/240*wh, "top") gc:setFont("sansserif", "b", 12/320*ww) local s = tostring(best) local sw = gc:getStringWidth(s) gc:drawString(s, 270/320*ww - sw/2, 80/240*wh, "top") end if self.lost then gc:setFont("sansserif", "b", 20/320*ww) drawStringOutline(gc, "Game Over", 0.1*ww, 0.55*wh, "middle") gc:setFont("sansserif", "b", 12/320*ww) drawStringOutline(gc, "PRESS ENTER", 0.2*ww, 0.65*wh, "middle") elseif self.win then gc:setFont("sansserif", "b", 20/320*ww) drawStringOutline(gc, "You Won!", 0.12*ww, 0.55*wh, "middle") gc:setFont("sansserif", "b", 12/320*ww) drawStringOutline(gc, "ENTER TO CONTINUE", 0.1*ww, 0.65*wh, "middle") end end function Game:move(dir) if self.lost or self.win then return end local hasMoved = false local tile local grid = self.grid for tile in grid:getTiles(dir) do if not tile.dead then local tilex, tiley = grid:getFarPos(tile, dir) if tile.data.x ~= tilex or tile.data.y ~= tiley then hasMoved = true grid:moveTile(tile, tilex, tiley) end tilex = (tilex-1) * TILE_SIZE / ww tiley = (tiley-1) * TILE_SIZE / ww tile:Complete(1) :Animate({x=tilex, y=tiley}, TILE_ANIM) local t = grid:doesMerge(tile, dir) if t then hasMoved = true t.dead = true grid:killTile(t) tile.data.value = tile.data.value * 2 if tile.data.value == 2048 then self.win = true end self.score = self.score + tile.data.value t:Complete(1) :Animate({x=tilex, y=tiley}, TILE_ANIM, function(self) tile:setValue(tile.value * 2) grid:buryTile(self) end) end end end collectgarbage() if hasMoved then grid:addRandomTile(TILE_ANIM) end if not grid:canMove() then self.lost = true if self.score > best then best = self.score document.markChanged(true) end end end