• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
DavitosanX

Hexagonal grid - Code review request

6 posts in this topic

Hello! I'm not sure if this belongs here, or in the beginners' section, so excuse me if this code is too bad, or too basic.

 

I had set a short term goal for myself as an amateur programmer: To implement a hexagonal grid, similar to the one found in the original Fallout. You should be able to move your mouse around and the hexagon that contains the mouse pointer should be highlighted. I thought it would be a good exercise, because unlike a square grid, determining which hexagon contains the mouse pointer is trickier.

 

I did finish the program, and it does exactly what I want, but I do tend to overcomplicate things and I would appreciate it if people with more  experienced took a look at it and gave me any tips. This was coded in python with pygame.

import pygame
import math

INITIAL_HEXAGON_VERTICES = ((-40,-40),(40,-40),(45,0),(40,40),(-40,40),(-45,0))
GRID_HEIGHT = 10
GRID_WIDTH = 10
VERTEX_COUNT = 6
X_ELEMENT = 0
Y_ELEMENT = 1
FIXED_ANGLE = 0.122 #7 degrees in radians
NOT_MOVING = (0,0)




def calculate_angle(fixed_point,var_point):

    opposite = math.fabs(fixed_point[X_ELEMENT] - var_point[X_ELEMENT])
    adjacent = math.fabs(fixed_point[Y_ELEMENT] - var_point[Y_ELEMENT])
    if adjacent == 0:
        adjacent = 0.1

    angle = math.atan((opposite/adjacent))

    return angle


class Hexagon:

    def __init__(self,num,ver):

        self.number = num
        self.vertices = ver



class InputManager:

    def check_events(self):

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game.running = False



    def mouse_in_grid(self,mouse_pos,hexagons):

        result = 0

        for counter,hexagon in enumerate(hexagons):

            if (mouse_pos[X_ELEMENT] > hexagon.vertices[5][X_ELEMENT]
                and mouse_pos[X_ELEMENT] < hexagon.vertices[2][X_ELEMENT]
                and mouse_pos[Y_ELEMENT] >= hexagon.vertices[0][Y_ELEMENT]
                and mouse_pos[Y_ELEMENT] < hexagon.vertices[3][Y_ELEMENT]):

                    result = hexagon.number

                    if (mouse_pos[X_ELEMENT] < hexagon.vertices[0][X_ELEMENT]
                        and mouse_pos[Y_ELEMENT] < hexagon.vertices[5][Y_ELEMENT]):
                            
                            angle = calculate_angle(hexagon.vertices[0],mouse_pos)
                            
                            if angle < FIXED_ANGLE:
                                result = hexagon.number
  
                    if (mouse_pos[X_ELEMENT] > hexagon.vertices[1][X_ELEMENT]
                        and mouse_pos[Y_ELEMENT] < hexagon.vertices[2][Y_ELEMENT]):
                                
                            angle = calculate_angle(hexagon.vertices[1],mouse_pos)
                                
                            if angle < FIXED_ANGLE:
                                result = hexagon.number

                    if (mouse_pos[X_ELEMENT] > hexagon.vertices[3][X_ELEMENT]
                        and mouse_pos[Y_ELEMENT] > hexagon.vertices[2][Y_ELEMENT]):
                               
                            angle = calculate_angle(hexagon.vertices[3],mouse_pos)
                                
                            if angle < FIXED_ANGLE:
                                result = hexagon.number

                    if (mouse_pos[X_ELEMENT] < hexagon.vertices[4][X_ELEMENT]
                        and mouse_pos[Y_ELEMENT] > hexagon.vertices[5][Y_ELEMENT]):
                                
                            angle = calculate_angle(hexagon.vertices[4],mouse_pos)
                                
                            if angle < FIXED_ANGLE:
                                result = hexagon.number

        return result




class Game:



    def __init__(self,resolution,caption):

        self.screen = pygame.display.set_mode(resolution)
        pygame.display.set_caption(caption)
        self.clock = pygame.time.Clock()
        self.running = True
        self.gray = (220,220,220)
        self.green = (50,240,50)
        self.black = (0,0,0)
        self.hexagons = []
        self.current_hexagon = 0



    def draw_screen(self):
        self.screen.fill(self.gray)

        if pygame.mouse.get_rel() != NOT_MOVING:
            self.current_hexagon = input_manager.mouse_in_grid(pygame.mouse.get_pos(),self.hexagons)

        pygame.draw.polygon(self.screen,self.green,self.hexagons[self.current_hexagon].vertices,3)

        pygame.display.flip()



    def calculate_grid_points(self):

        number = 0

        for column in range(GRID_WIDTH):

            for row in range(GRID_HEIGHT):

                points = []
                lift_hexagon = 0

                if column % 2 != 0:
                    lift_hexagon = 40

                for point in range(VERTEX_COUNT):

                    points.append(  ((INITIAL_HEXAGON_VERTICES[point][X_ELEMENT] + (85 * column)),
                                    ((INITIAL_HEXAGON_VERTICES[point][Y_ELEMENT] + (80 * row))-lift_hexagon)  ) )

                new_hexagon = Hexagon(number,points)
                self.hexagons.append(new_hexagon)
                number += 1
                



    def main_loop(self,framerate):

        self.calculate_grid_points()

        while self.running:

            self.clock.tick(framerate)
            input_manager.check_events()

            self.draw_screen()

        pygame.quit()





input_manager = InputManager()
game = Game((800,600),"Game")
game.main_loop(60)

Thanks in advance!

1

Share this post


Link to post
Share on other sites

Thank you both for the encouragement! I wil definitely take some time to really get into your answers. It may be evident now that my knowledge of vector math is poor, and I don't really know how to apply it. I'll read into that, as it seems it'll be far more useful than trigonometry for computer graphics.
 

About encapsulation, I'm still trying to get it right. I've struggled to grasp OO concepts, but it appears I'm not so far off now.

 

About optimization, well, I'll certainly take your suggestions into account. But maybe I'll wait a little before applying it, as it may turn a small concept program into a more complex, daunting task.

 

Thank you again!

0

Share this post


Link to post
Share on other sites

. This means instead of checking angles, you can find what center is closest to the point and that will be the hexagon the point is inside.

 

Won't this mean that you are basically treating the hexagons like circles when you check for boundaries?  How will this affect the corners?  Seems to be a possibility of error-tracking there to me, based on the "sort order" of those hexagons, but maybe it won't be much noticeable?

 

I am thinking if you are going for the circle method, that you can:

 

1. Check the closest centre.

2a. if it is inside a circumscribed circle of a hexagon, you are good.

2b. If it is between a circumscribed and inscribed circle of a hexagon, you are in the ambiguous zone and need to do some more calculations to know for sure that you are not actually in a neighbouring hexagon.

 

If you end up having to do vector math anyway to determine the point 2b, I would certainly go for that method, unless you need some form of optimisation, and point 1 actually will optimise.  Beware premature optimisation though.

 

Alternatively, you could just reject border cases, but players would probably like continuity, that the selected hexagon flows fluently between hexagons, not blinking on and off between them.

 

I would go for Thinias solution, as that is the way I have heard about in a distant past, it is exact, and should be fairly fast.

 

Optimisation possibility so you don't need to test all hexagons:

You do sort of have an estimate on where in your grid the mouse pointer is, just not the exact hexagon.  That means you should not need to search the whole map of hexagons, just a few inside an imagined square around the mouse pointer.  An exercise would be to find the right size of this "search"-square to be sure to find your hexagon.  I imagine you should be able to minimise the amount of hexagons that you need to test to about 9-16, depending on how clever you are about finding the optimum "search square".

 

Edit:

Just came up with a third method that will work, not exactly elegant, but quick to make, if you are not into vector and matrix math:

 

Treat each hexagon as a square (or rectangle).

If the mouse pointer is inside the square, then you need to test the diagonal areas to see which side you are.

To do this part of the test, you need to imagine four more squares that contain each diagonal only.

Now you test which of the four imagined squares you are inside.  Then you test if you are on the correct side of the diagonal inside that square.

You are done!  If you are on the correct side, you know the mouse pointer is inside that hexagon.  If it is on the wrong side, you need to test for another hexagon.

 

I see room for optimisations here too, like only testing two adjacent of those four imagined squares, since the other two will belong to one of the other hexagons anyway.

OR BETTER:  If you test one of the imagined squares, and find that you are outside of it, then you still know which hexagon you are in.  You are in the neighbouring hexagon of that square!

 

My idea that you do know the general area where the mouse pointer is, as mentioned above still applies, so you should still not need to test all hexagons on the map.

 

Talking about elegance, I don't think this last method is bad at all.  There are plenty of opportunities to bail out of testing early, and the tests you have to perform should be fast in themselves.

Edited by aregee
0

Share this post


Link to post
Share on other sites

 

. This means instead of checking angles, you can find what center is closest to the point and that will be the hexagon the point is inside.

 

Won't this mean that you are basically treating the hexagons like circles when you check for boundaries?  How will this affect the corners?  Seems to be a possibility of error-tracking there to me, based on the "sort order" of those hexagons, but maybe it won't be much noticeable?

 

It works. At its core, it is a voronoi pattern.

 

Here is a lengthy article that explains hexagonal grids. Look in point #2b in the Pixel to Hex section. It describes the method of finding the nearest center.

1

Share this post


Link to post
Share on other sites

 

 

It works. At its core, it is a voronoi pattern.

 

Here is a lengthy article that explains hexagonal grids. Look in point #2b in the Pixel to Hex section. It describes the method of finding the nearest center.

 

 

Ah that is a great article indeed!  Never thought about the connection between Voronoi and hexagonal grids before though. :)  I think I will make my own hexagonal implementation soon, it is about time, and hexagonals are fun, just need to finish my current project first! :)

0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0