Bowlman wrote: ↑Thu Apr 08, 2021 11:02 am
Im been working with my first little try-out out project. I try to make small memory game. I thought I could just wrap around few hours of code and get the basic commands, but its been like four days. I have working prototype and everything I wanted is there at the moment. But the whole code and the struckture is a mess. Maybe I should start over and try to make it with the whole basic idea in mind. I dont really mind that its been days. Its been cool to learn new things and learn new way to think programing. Thanks for the advices. I think now Im again one step closer to "get it". Thanks.
If you have been working in languages where GOTO is a thing, you probably don't have much experienced with structured programming... so now is definitely the time to learn to use code blocks and for, while, and if/else commands to control your program flow.
Unlike BASIC, which practically invented the term "Spaghetti code", the program flow within a function in Lua always goes from the top down, except for loops. This is an important concept to wrap your brain around, because it fundamentally changes how you code. When I started programming in C after learning on BASIC, it took a long time to undo the bad habits learned in BASIC and assembly language.
Also, you can use object oriented programming in some fun ways to drastically change a program's behavior at runtime. Switching out two objects, both with a "draw" command, can quickly change how your game behaves.
So one way you can switch states is something like this: you can create multiple objects, each with its own :draw() method. For example:
game:draw() draws the playing field
game:mousePressed() handles the mouse events during the game play
menu:draw() displays the menu
menu:mousepressed() handles mouse events when the menu is displayed
so in love.load(), you might set up something like this:
mode = game
and then in love.draw() you would call
mode:draw()
So now "mode" is just an alias for "game", and any time you call mode:draw(), it's actually calling game:draw().
But somewhere deep in your game loop, you're going to have a function named game:gameOver(), and in there...
mode = menu
Now when you call mode:draw(), you're actually drawing the main menu, rather than the game screen.
And if you pass your other event handlers through, they will do the same thing. For example:
function love:keypressed(k,s,r)
mode:keypressed(k,s,r)
end
So you don't need an IF block or a GOTO to dramatically change how the game runs. You just assign mode to change the game's state.