All,
I've got a program that will react depending on which key is pressed (A~X). Currently I'm using a switch statement that reacts to 8 different keys. I'm wanting to expand that to 24. Do I really need 24 case statements or is there a better / compact way of accomplishing this?
Thanks
Using a switch statement with 24 case statements is a reasonable approach, especially if each key has a unique action associated with it. However, there might be more compact ways to achieve this, depending on your requirements.
One alternative is to use an array or a map to store the function pointers or objects representing the actions for each key. This solution works well if the actions can be easily represented as functions or objects and can generally make the code more manageable and potentially more extensible.
Here's an example using an array of function pointers:
If you find that there's a pattern to the actions or if they share some common logic, you might be able to simplify the code further by creating a single function that handles multiple keys based on their attributes. In this case, you can still use a switch statement or if-else conditions to determine which group of keys was pressed and perform the appropriate action.
It's also essential to consider code readability and maintainability with any approach. While a more compact solution may save some lines of code, it's important to ensure that the code is still easy to understand and modify later on.
Thanks Matthew. I'll give it a look, thanks
Currently the cases are the same except it sets a true condition based on an array index. At the moment, I'm using numbers instead of letters. 1~8. So if I hit 2 then the case for ALLEGRO_KEY_2 will make Blocks[2].bFlipped = true. If I figure out a way to use a variable for the array index then I could use a function to activate the correct .bFlipped and increment the other variables.
Thanks.
In that case, you could create a single function to handle the key press event and set the bFlipped value in the Blocks array. If you're using numeric keys (1-8) and want to expand it to letters (A-X), you can easily adjust the index calculation accordingly.
Here's an example of how you can update the bFlipped value using a single function:
This should simplify the event handling code and make it easier to add or modify behavior based on the array index.
Thanks Matthew. I did something similar. First I'm sorry for the confusion but I am replacing the 1~8 with A~X. Not adding to. Right now I'm just playing with different ideas to get a process figured out. I started with 1~8 but expanded to 24 blocks and didn't want to figure out a way to do two digit numbers.
I went with ..
I had to add the iKey because I use the event.keyboard as an index and my array starts with 0. Having event.keyboard.keycode -1 as an index seemed a little busy.
In case the goal seems odd, I'm creating a rough draft of a concentration / match type game.