Skip to content

Instantly share code, notes, and snippets.

@dermotbalson
Created July 11, 2014 05:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dermotbalson/d3399f48e889891545d7 to your computer and use it in GitHub Desktop.
Save dermotbalson/d3399f48e889891545d7 to your computer and use it in GitHub Desktop.
Threes part 1
function setup()
Settings()
CreateBoard()
Initialise()
end
function Settings()
cellWidth,cellHeight,cellGap,textSize=100,133,10,48
boardValues={ [0]={0,0,0},
[1]={color(255),color(0,0,255),0},
[2]={color(255),color(255,0,0),0},
[3]={color(0),color(255),3},
[6]={color(0),color(255),9},
[12]={color(255,0,0),color(255),27},
[24]={color(255,0,0),color(255),81},
[48]={color(255,0,0),color(255),243},
[96]={color(255,0,0),color(255),729},
[192]={color(255,0,0),color(255),2187},
[384]={color(255,0,0),color(255),6561}}
end
function CreateBoard()
imgBoard=image(cellWidth*4+cellGap*5,cellHeight*4+cellGap*5)
setContext(imgBoard)
background(150, 192, 211, 255)
fill(177, 199, 210, 255)
local w=cellGap
for r=1,4 do
local h=cellGap
for c=1,4 do
rect(w,h,cellWidth,cellHeight)
h=h+cellHeight+cellGap
end
w=w+cellWidth+cellGap
end
setContext()
GetNextTile()
end
function Initialise()
--create 9 random tiles valued 1,2 or 3 and put them somewhere in the table called board
--board is a 4x4 table
--start off by creating an empty 4x4 table with all values = 0
board={}
for i=1,4 do
board[i]={0,0,0,0}
end
--now create the initial tiles
for i=1,9 do
local n=RandInt(3)
while true do
local r=RandInt(4)
local c=RandInt(4)
if board[c][r]==0 then
board[c][r]=n
break
end
end
end
NextTile=RandInt(3) --get the next tile to be added so we can show it to the player
--calculate the position of each tile on the screen
--first calculate bottom left position of board
bottomPos=vec2(WIDTH/2-cellWidth*2-cellGap*2.5,HEIGHT/2-cellHeight*2-cellGap*2.5)
boardPos={} --table to hold positions
for c=1,4 do
boardPos[c]={}
for r=1,4 do
boardPos[c][r]=vec2(bottomPos.x+(cellWidth+cellGap)*(c-1)+cellGap,
bottomPos.y+(cellHeight+cellGap)*(r-1)+cellGap)
end
end
nextTilePos=vec2(bottomPos.x-cellWidth-10,HEIGHT/2)
end
function draw()
background(135, 187, 213, 255)
DrawBoard()
end
function DrawBoard()
--draw board itself
sprite(imgBoard,WIDTH/2,HEIGHT/2)
--draw the tiles
for c=1,4 do
for r=1,4 do
if board[c][r]>0 then
DrawTile(boardPos[c][r],board[c][r])
end
end
end
--show next tile to come
DrawTile(nextTilePos,NextTile)
end
function RandInt(a) --returns random integer between 1 and b (inclusive)
return math.floor(math.random()*a)+1
end
function DrawTile(p,v)
fill(boardValues[v][2])
rect(p.x,p.y,cellWidth,cellHeight)
fill(boardValues[v][1])
font("ArialRoundedMTBold")
fontSize(textSize)
text(v,p.x+cellWidth/2,p.y+cellHeight/2)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment