What is the easiest way to create a clickable grid for a game in C++?
I haven't used C++ in a while, so I decided to take on a small project to become familiar with it again. I am trying to make 开发者_StackOverflowa chinese checkers game, but I have no experience with GUI design in C++. Is there a real simple way to just make grid (i.e. bitmap hexagons or something) that when clicked on, will give me the index number of the one I've clicked on? If someone has any examples of how to do this, even with just a 2D grid of squares, that would be helpful. Any help is appreciated, thanks!
Depends on what you take for simple way.
Qt could be a simple way, but it would take time to get used to it (if you aren't).
If I were you, I would use create a simple winapi application, write handlers for WM_CLICK
messages and add a simple grid renderer.
The first thing is to decide which API you are going to use for your app. Qt? SDL? Win32? OpenGL? My recommendation is to use Qt and its QGraphicsView class (you could start with one of the Qt example apps that uses QGraphicsView and modify it to suit your taste).
It would vary depending on your GUI toolkit. However, I believe that the two most likely ways would likely either be some variation on
Store coordinates for each of the squares, holes, or whatever it is you're trying to click on for the game and have the click event handler use the coordinates that it gets to determine which square was clicked on.
Make each square its own widget. That way, when it's clicked on, it's the square itself that gets the click event and it can be handled in a nice, object-oriented manner. However, that would mean quite a lot of widgets for a Chinese Checkers game.
Typically the GUI tookit will let you override (for example through virtual functions) the event handler of the widget representing the board, so you'd then handle a mouse click event by calling some function of your own like MouseClicked(int x, int y), where the handler will also give you the mouse coordinates x and y.
If it's a rectangular grid, just integer divide the coordinate by the cell width in pixels.
If it's a grid of hexagonal cells, then figuring that out will be more difficult. I imagine you could first define a rectangular grid marking the rectangular centers of the hexagons, then add more detection for within the four triangular areas around the edges. The game might be fairly usable with just the rectangular cell definitions, though, just ignoring the triangular edges.
It's easy enough to convert mouse coordinates to game-grid coordinates using a single line of math:
POINT grid_loc = POINT(click.x / grid.cell.width, click.y / grid.cell.height);
Of course that's a zero-based game-grid.
精彩评论