Page 1 of 1

draw sprite on mouse click

Posted: Fri Dec 07, 2012 10:00 pm
by smileymkd
I want to make a simle Tic-Tac-Toe game with Love2D. So my question is:

How can I make to draw the X.bmp or O.bmp when I click with the mouse on some position (I have the logic how to find where to draw them, but I don't know how to make the stay there when I click). So I need to know (currently with my code I am holding the image, and its following the mouse cursor, but I need when I click somewhere it should be placed there, and the image for example from X.bmp to be changed to O.bmp)

Thanks

Re: draw sprite on mouse click

Posted: Sat Dec 08, 2012 3:39 am
by Jasoco
A simple example, tables are everything...

Code: Select all

object = {}

function love.draw()
  for i, o in pairs(object) do
    love.graphics.draw(yourImage, o.x, o.y)
  end
end

function love.mousepressed(x, y, button)
  if button == "l" then 
    local newObjectID = #object + 1
    object[newObjectID] = { x = x, y = y }
  end
end
What is happening is object is a table. Everything in Lua is a table. I won't go into what a table is here because it would take a few pages. Basically you create an empty table to hold your objects. When it's empty the for i, o in pairs part will not do anything until you click. At which point the image thing you want to show up there will be added to the table. Then the loop in draw will run through, and for every object created, will draw an image at that location. The location being o.x and o.y. The o part being a reference to the current object the loop is currently on.

Play around with that code and see what you can do. Because that's just a simple example.

But for a Tic Tac Toe game you are better off creating a grid table. i.e. a table with two dimensions. 3 across and 3 down. You do this by creating the grid as such:

Code: Select all

grid = {}
for x = 1, 3 do
  grid[x] = {}
  for y = 1, 3 do
    grid[x][y] = ""
  end
end
You can then refer to a grid cell as grid[x][y]. By making it equal whatever symbol you want. Then run through the grid in a similar fashion for both the update and draw parts like so:

Code: Select all

for x = 1, 3 do
  for y = 1, 3 do
    --Handle the current cell here. Remember the format will be grid[x][y].
  end
end
A hint is when drawing an X or O for the current grid square, keep in mind the size of the grid and the placement of it on screen. Then calculate the location of the image to draw like this: (x - 1) * gridSquareWidth + gridOffsetX (Do the same for y with height and OffsetY)

Re: draw sprite on mouse click

Posted: Sat Dec 08, 2012 2:39 pm
by smileymkd
thanks A LOT :D