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
draw sprite on mouse click
- Jasoco
- Inner party member
- Posts: 3726
- Joined: Mon Jun 22, 2009 9:35 am
- Location: Pennsylvania, USA
- Contact:
Re: draw sprite on mouse click
A simple example, tables are everything...
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:
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:
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)
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
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
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
Re: draw sprite on mouse click
thanks A LOT
Who is online
Users browsing this forum: Majestic-12 [Bot] and 0 guests