├── .gitignore ├── LICENSE ├── MANIFEST.in ├── README.rst ├── VERSION ├── hexmap ├── __init__.py ├── map.py └── render.py ├── setup.py └── tests ├── Map.py ├── Render.py └── __init__.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *~ 3 | /.project 4 | /.pydevproject 5 | /MANIFEST 6 | /dist/ 7 | /virtualenv/ 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | 9 | This version of the GNU Lesser General Public License incorporates 10 | the terms and conditions of version 3 of the GNU General Public 11 | License, supplemented by the additional permissions listed below. 12 | 13 | 0. Additional Definitions. 14 | 15 | As used herein, "this License" refers to version 3 of the GNU Lesser 16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 17 | General Public License. 18 | 19 | "The Library" refers to a covered work governed by this License, 20 | other than an Application or a Combined Work as defined below. 21 | 22 | An "Application" is any work that makes use of an interface provided 23 | by the Library, but which is not otherwise based on the Library. 24 | Defining a subclass of a class defined by the Library is deemed a mode 25 | of using an interface provided by the Library. 26 | 27 | A "Combined Work" is a work produced by combining or linking an 28 | Application with the Library. The particular version of the Library 29 | with which the Combined Work was made is also called the "Linked 30 | Version". 31 | 32 | The "Minimal Corresponding Source" for a Combined Work means the 33 | Corresponding Source for the Combined Work, excluding any source code 34 | for portions of the Combined Work that, considered in isolation, are 35 | based on the Application, and not on the Linked Version. 36 | 37 | The "Corresponding Application Code" for a Combined Work means the 38 | object code and/or source code for the Application, including any data 39 | and utility programs needed for reproducing the Combined Work from the 40 | Application, but excluding the System Libraries of the Combined Work. 41 | 42 | 1. Exception to Section 3 of the GNU GPL. 43 | 44 | You may convey a covered work under sections 3 and 4 of this License 45 | without being bound by section 3 of the GNU GPL. 46 | 47 | 2. Conveying Modified Versions. 48 | 49 | If you modify a copy of the Library, and, in your modifications, a 50 | facility refers to a function or data to be supplied by an Application 51 | that uses the facility (other than as an argument passed when the 52 | facility is invoked), then you may convey a copy of the modified 53 | version: 54 | 55 | a) under this License, provided that you make a good faith effort to 56 | ensure that, in the event an Application does not supply the 57 | function or data, the facility still operates, and performs 58 | whatever part of its purpose remains meaningful, or 59 | 60 | b) under the GNU GPL, with none of the additional permissions of 61 | this License applicable to that copy. 62 | 63 | 3. Object Code Incorporating Material from Library Header Files. 64 | 65 | The object code form of an Application may incorporate material from 66 | a header file that is part of the Library. You may convey such object 67 | code under terms of your choice, provided that, if the incorporated 68 | material is not limited to numerical parameters, data structure 69 | layouts and accessors, or small macros, inline functions and templates 70 | (ten or fewer lines in length), you do both of the following: 71 | 72 | a) Give prominent notice with each copy of the object code that the 73 | Library is used in it and that the Library and its use are 74 | covered by this License. 75 | 76 | b) Accompany the object code with a copy of the GNU GPL and this license 77 | document. 78 | 79 | 4. Combined Works. 80 | 81 | You may convey a Combined Work under terms of your choice that, 82 | taken together, effectively do not restrict modification of the 83 | portions of the Library contained in the Combined Work and reverse 84 | engineering for debugging such modifications, if you also do each of 85 | the following: 86 | 87 | a) Give prominent notice with each copy of the Combined Work that 88 | the Library is used in it and that the Library and its use are 89 | covered by this License. 90 | 91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 92 | document. 93 | 94 | c) For a Combined Work that displays copyright notices during 95 | execution, include the copyright notice for the Library among 96 | these notices, as well as a reference directing the user to the 97 | copies of the GNU GPL and this license document. 98 | 99 | d) Do one of the following: 100 | 101 | 0) Convey the Minimal Corresponding Source under the terms of this 102 | License, and the Corresponding Application Code in a form 103 | suitable for, and under terms that permit, the user to 104 | recombine or relink the Application with a modified version of 105 | the Linked Version to produce a modified Combined Work, in the 106 | manner specified by section 6 of the GNU GPL for conveying 107 | Corresponding Source. 108 | 109 | 1) Use a suitable shared library mechanism for linking with the 110 | Library. A suitable mechanism is one that (a) uses at run time 111 | a copy of the Library already present on the user's computer 112 | system, and (b) will operate properly with a modified version 113 | of the Library that is interface-compatible with the Linked 114 | Version. 115 | 116 | e) Provide Installation Information, but only if you would otherwise 117 | be required to provide such information under section 6 of the 118 | GNU GPL, and only to the extent that such information is 119 | necessary to install and execute a modified version of the 120 | Combined Work produced by recombining or relinking the 121 | Application with a modified version of the Linked Version. (If 122 | you use option 4d0, the Installation Information must accompany 123 | the Minimal Corresponding Source and Corresponding Application 124 | Code. If you use option 4d1, you must provide the Installation 125 | Information in the manner specified by section 6 of the GNU GPL 126 | for conveying Corresponding Source.) 127 | 128 | 5. Combined Libraries. 129 | 130 | You may place library facilities that are a work based on the 131 | Library side by side in a single library together with other library 132 | facilities that are not Applications and are not covered by this 133 | License, and convey such a combined library under terms of your 134 | choice, if you do both of the following: 135 | 136 | a) Accompany the combined library with a copy of the same work based 137 | on the Library, uncombined with any other library facilities, 138 | conveyed under the terms of this License. 139 | 140 | b) Give prominent notice with the combined library that part of it 141 | is a work based on the Library, and explaining where to find the 142 | accompanying uncombined form of the same work. 143 | 144 | 6. Revised Versions of the GNU Lesser General Public License. 145 | 146 | The Free Software Foundation may publish revised and/or new versions 147 | of the GNU Lesser General Public License from time to time. Such new 148 | versions will be similar in spirit to the present version, but may 149 | differ in detail to address new problems or concerns. 150 | 151 | Each version is given a distinguishing version number. If the 152 | Library as you received it specifies that a certain numbered version 153 | of the GNU Lesser General Public License "or any later version" 154 | applies to it, you have the option of following the terms and 155 | conditions either of that published version or of any later version 156 | published by the Free Software Foundation. If the Library as you 157 | received it does not specify a version number of the GNU Lesser 158 | General Public License, you may choose any version of the GNU Lesser 159 | General Public License ever published by the Free Software Foundation. 160 | 161 | If the Library as you received it specifies that a proxy can decide 162 | whether future versions of the GNU Lesser General Public License shall 163 | apply, that proxy's public statement of acceptance of any version is 164 | permanent authorization for you to choose that version for the 165 | Library. -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include VERSION 2 | include README.rst 3 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ======== 2 | HexMap 3 | ======== 4 | ------------------------------------ 5 | A HexGrid implementation for PyGame 6 | ------------------------------------ 7 | 8 | Introduction 9 | ============ 10 | HexMap is a python module for use on top of pygame. It is designed to take a lot of the work out of utilizing a hexgrid. 11 | 12 | Classes 13 | ======= 14 | 15 | Map( object ) 16 | ~~~~~~~~~~~~~~~~~~~~ 17 | 18 | Map.__init__( (rows, cols) ) 19 | ++++++++++++++++++++++++++++ 20 | 21 | The Map object manages most of the basic data manipulation and access for the hexMap. You can think of it as the table tracking all the positioning information regarding your grid. It is capable of telling you the distance between two cells, the direction from one cell to another, and all the valid cells in a variety of shapes. 22 | 23 | *valid cells are cells which are present on this map* 24 | 25 | A Map is numbered as Follows:: 26 | 27 | ___ ___ ___ 28 | /0,0\___/1,2\___/2,4\ 29 | \___/1,1\___/2,3\___/ 30 | /1,0\___/2,2\___/3,4\ 31 | \___/2,1\___/3,3\___/ 32 | /2,0\___/3,2\___/4,4\ 33 | \___/3,1\___/4,3\___/ 34 | /3,0\___/4,2\___/5,4\ 35 | \___/4,1\___/5,3\___/ 36 | /4,0\___/5,2\___/6,4\ 37 | \___/5,1\___/6,3\___/ 38 | \___/ \___/ 39 | 40 | 41 | Map.distance( start, destination ) 42 | ++++++++++++++++++++++++++++++++++ 43 | 44 | This method will tell you the straight distance between two cells, ignoring any obstacles in the way.: 45 | 46 | Map.direction( start, destination ) 47 | +++++++++++++++++++++++++++++++++++ 48 | 49 | This method will tell you the direction from the start point to the destination point.: 50 | 51 | Map.neighbors( cell ) 52 | +++++++++++++++++++++ 53 | 54 | This will tell you the **valid** cells adjoining this cell. *does not include the cell itself*: 55 | 56 | Map.spread( cell, radius=1 ) 57 | ++++++++++++++++++++++++++++ 58 | 59 | Returns all the **valid** cells within *radius* of *cell*, including the cell itself.: 60 | 61 | Map.cone( cell, direction, length=1 ) 62 | +++++++++++++++++++++++++++++++++++++ 63 | 64 | This method returns the set of **valid** cells expanding out from 3 cells facing *direction* from *cell*, extending *length*. 65 | 66 | Grid( dict ) 67 | ~~~~~~~~~~~~ 68 | Grid.__init__( map ) 69 | ++++++++++++++++++++ 70 | 71 | MapUnit( object ) 72 | ~~~~~~~~~~~~~~~~~ 73 | 74 | MapUnit.__init__( grid ) 75 | ++++++++++++++++++++++++ 76 | 77 | Render( object ) 78 | ~~~~~~~~~~~~~~~~ 79 | 80 | Render.__init__( map, radius=16 ) 81 | +++++++++++++++++++++++++++++++++ 82 | 83 | RenderUnits( Render ) 84 | ~~~~~~~~~~~~~~~~~~~~~ 85 | 86 | RenderGrid( Render ) 87 | ~~~~~~~~~~~~~~~~~~~~ 88 | 89 | RenderFog( Render ) 90 | ~~~~~~~~~~~~~~~~~~~ 91 | 92 | Example 93 | ======= 94 | 95 | -------------------------------------------------------------------------------- /VERSION: -------------------------------------------------------------------------------- 1 | 0.1.1 2 | -------------------------------------------------------------------------------- /hexmap/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mklauber/pygame-hex-grid/a458fa13d4660108433e6148d4c9aa266ab060f2/hexmap/__init__.py -------------------------------------------------------------------------------- /hexmap/map.py: -------------------------------------------------------------------------------- 1 | from abc import ABCMeta, abstractmethod 2 | import argparse 3 | import math 4 | import operator 5 | import pygame 6 | import random 7 | 8 | import logging 9 | logger = logging.getLogger( __name__ ) 10 | 11 | 12 | class Map( object ): 13 | """ 14 | An top level object for managing all game data related to positioning. 15 | """ 16 | directions = [ ( 0, 1 ), ( 1, 1 ), ( 1, 0 ), ( 0, -1 ), ( -1, -1 ), ( -1, 0 ) ] 17 | 18 | def __init__( self, ( rows, cols ), *args, **keywords ): 19 | #Map size 20 | self.rows = rows 21 | self.cols = cols 22 | 23 | def __str__( self ): 24 | return "Map (%d, %d)" % ( self.rows, self.cols ) 25 | 26 | @property 27 | def size( self ): 28 | """Returns the size of the grid as a tuple (row, col)""" 29 | return ( self.rows, self.cols ) 30 | 31 | @classmethod 32 | def distance( self, start, destination ): 33 | """Takes two hex coordinates and determine the distance between them.""" 34 | logger.debug( "Start: %s, Dest: %s", start, destination ) 35 | diffX = destination[0] - start[0] 36 | diffY = destination[1] - start[1] 37 | 38 | distance = min( abs( diffX ), abs( diffY ) ) + abs( diffX - diffY ) 39 | 40 | logger.debug( "diffX: %d, diffY: %d, distance: %d", diffX, diffY, distance ) 41 | return distance 42 | 43 | @classmethod 44 | def direction( self, origin, destination ): 45 | """ 46 | Reports the dominating direction from an origin to a destination. if even, chooses randomly 47 | Useful for calculating any type of forced movement 48 | """ 49 | offset = ( destination[0] - origin[0], destination[1] - origin[1] ) 50 | scale = float( max( abs( offset[0] ), abs( offset[1] ) ) ) 51 | if scale == 0: 52 | return ( 0, 0 ) 53 | direction = ( offset[0] / scale, offset[1] / scale ) 54 | 55 | #Handle special cases 56 | if direction == ( 1, -1 ): 57 | return random.choice( [ ( 1, 0 ), ( 0, -1 ) ] ) 58 | elif direction == ( -1, 1 ): 59 | return random.choice( [ ( -1, 0 ), ( 0, 1 ) ] ) 60 | 61 | 62 | def choose( i ): 63 | if i == 0.5: 64 | return random.choice( ( 0, 1 ) ) 65 | elif i == -0.5: 66 | return random.choice( ( 0, -1 ) ) 67 | else: 68 | return int( round( i ) ) 69 | 70 | return ( choose( direction[0] ), choose( direction[1] ) ) 71 | 72 | def ascii( self, numbers=True ): 73 | """ Debug method that draws the grid using ascii text """ 74 | 75 | table = "" 76 | 77 | if numbers: 78 | text_length = len( 79 | str( self.rows - 1 if self.cols % 2 == 1 else self.rows ) + 80 | ',' + 81 | str( int( self.rows - 1 + math.floor( self.cols / 2 ) ) ) 82 | ) 83 | else: 84 | text_length = 3 85 | 86 | #Header for first row 87 | for col in range( self.cols ): 88 | if col % 2 == 0: 89 | table += " " + '_' * text_length 90 | else: 91 | table += " " + ' ' * text_length 92 | table += "\n" 93 | # Each row 94 | for row in range( self.rows ): 95 | top = "/" 96 | bottom = "\\" 97 | 98 | for col in range( self.cols ): 99 | # unit = "U" if units and self.positions.get( ( row + col / 2, col ) ) else "" 100 | if col % 2 == 0: 101 | text = "%d,%d" % ( row + col / 2, col ) if numbers else "" 102 | top += ( text ).center( text_length ) + "\\" 103 | bottom += ( "" ).center( text_length, '_' ) + "/" 104 | else: 105 | text = "%d,%d" % ( 1 + row + col / 2, col ) if numbers else " " 106 | top += ( "" ).center( text_length, '_' ) + "/" 107 | bottom += ( text ).center( text_length ) + "\\" 108 | # Clean up tail slashes on even numbers of columns 109 | if self.cols % 2 == 0: 110 | if row == 0: top = top[:-1] 111 | table += top + "\n" + bottom + "\n" 112 | 113 | # Footer for last row 114 | footer = " " 115 | for col in range( 0, self.cols - 1, 2 ): 116 | footer += " " * text_length + "\\" + '_' * text_length + "/" 117 | table += footer + "\n" 118 | return table 119 | 120 | def valid_cell( self, cell ): 121 | row, col = cell 122 | if col < 0 or col >= self.cols: return False 123 | if row < math.ceil( col / 2.0 ) or row >= math.ceil( col / 2.0 ) + self.rows: return False 124 | return True 125 | 126 | def neighbors( self, center ): 127 | """ 128 | Return the valid cells neighboring the provided cell. 129 | """ 130 | return filter( self.valid_cell, [ 131 | ( center[0] - 1, center[1] ), ( center[0], center[1] + 1 ), 132 | ( center[0] + 1, center[1] + 1 ), ( center[0] + 1, center[1] ), 133 | ( center[0], center[1] - 1 ), ( center[0] - 1, center[1] - 1 ) 134 | ] ) 135 | 136 | def spread( self, center, radius=1 ): 137 | """ 138 | A slice of a map is a collection of valid cells, starting at an origin, 139 | and encompassing all cells within a given radius. 140 | """ 141 | result = set( ( center, ) ) #Start out with this center cell 142 | neighbors = self.neighbors( center ) #Get the neighbors for use later 143 | if radius == 1: #Recursion end case 144 | result = result | set( neighbors ) #Return the set of this cell and its neighbors 145 | else: #Otherwise, recurse over all the neghbors, 146 | for n in neighbors: #decrementing the radius by one. 147 | result = result | set( self.spread( n, radius - 1 ) ) 148 | return filter( self.valid_cell, result )#filter invalid cells before returning. 149 | 150 | def cone( self, origin, direction, length=1 ): 151 | """ 152 | A slice of a map is a section of cells, originating a a single cell and 153 | extending outward through two cells separated by one cell between them. 154 | In the example below, starting at (0,0), (0,1) and (1,0) define a slice, 155 | as do (-1,-1) and (0,1). 156 | _____ 157 | _____/-1,0 \_____ 158 | /-1,-1\_____/ 0,1 \ 159 | \_____/ 0,0 \_____/ 160 | /0,-1 \_____/ 1,1 \ 161 | \_____/ 1,0 \_____/ 162 | \_____/ 163 | """ 164 | result = self.slice( origin, direction, length ) 165 | result.extend( self.slice( origin, ( direction + 1 ) % 6, length ) ) 166 | return filter( self.valid_cell, set( result ) ) 167 | 168 | def slice( self, origin, direction, length=2 ): 169 | """ 170 | A slice of a map is a section of cells, originating a a single cell and 171 | extending outward through two neighboring cells. In the example below, 172 | starting at (0,0), (0,1) and (1,1) define a slice, as do (-1,0) and 173 | (-1,-1). 174 | _____ 175 | _____/-1,0 \_____ 176 | /-1,-1\_____/ 0,1 \ 177 | \_____/ 0,0 \_____/ 178 | /0,-1 \_____/ 1,1 \ 179 | \_____/ 1,0 \_____/ 180 | \_____/ 181 | """ 182 | # The edge wheel described in the docnotes above, used for calculating edges and steps 183 | 184 | 185 | # edge is the step we take for each distance, 186 | # step is the increment for each cell that distance out 187 | edge, step = self.directions[ direction % 6], self.directions[( direction + 2 ) % 6] 188 | 189 | logger.debug( "Edge: %s, Step: %s", edge, step ) 190 | 191 | result = [ origin ] 192 | # Work each row, i units out along an edge 193 | for i in range( 1, length + 1 ): 194 | start = ( origin[0] + edge[0] * i, origin[1] + edge[1] * i ) 195 | for j in range( i + 1 ): 196 | # calculate 197 | pos = ( start[0] + step[0] * j, start[1] + step[1] * j ) 198 | result.append( pos ) 199 | return filter( self.valid_cell, result ) 200 | 201 | def line( self, origin, direction, length=3 ): 202 | """ 203 | Returns all the cells along a given line, starting at an origin 204 | """ 205 | offset = self.directions[direction] 206 | results = [ origin ] 207 | # Work each row, i units out along an edge 208 | for i in range( 1, length + 1 ): 209 | results.append( ( origin[0] + offset[0] * i, origin[1] + offset[1] * i ) ) 210 | return filter( self.valid_cell, results ) 211 | 212 | def cells( self ): 213 | cells = [] 214 | for row in range( self.rows + self.cols / 2 ): 215 | cells.extend( 216 | [( row, col ) for col in range( 1 + 2 * row ) ] 217 | ) 218 | return filter( self.valid_cell, cells ) 219 | 220 | class Grid( dict ): 221 | """An extension of a basic dictionary with a fast, consistent lookup by value implementation.""" 222 | 223 | def __init__( self, default=None, *args, **keywords ): 224 | super( Grid, self ).__init__( *args, **keywords ) 225 | self.default = default 226 | 227 | def __getitem__( self, key ): 228 | return super( Grid, self ).get( key, self.default ) 229 | 230 | def find( self, item ): 231 | """ 232 | A fast lookup by value implementation 233 | """ 234 | for pos, value in self.items(): 235 | if item == value: 236 | return pos 237 | return None 238 | 239 | class MapUnit( object ): 240 | """ 241 | An abstract base class that will contain or require implementation of all 242 | the methods necessary for a unit to be managed by a map object. 243 | """ 244 | 245 | __metaclass__ = ABCMeta 246 | 247 | def __init__( self, grid ): 248 | self.grid = grid 249 | 250 | @property 251 | def position( self ): 252 | """A property that looks up the position of this unit on it's associated map.""" 253 | return self.grid.find( self ) 254 | 255 | @abstractmethod 256 | def paint( self, surface ): 257 | """An abstract base method to contain the painting code for a given unit.""" 258 | pass 259 | 260 | if __name__ == '__main__': 261 | 262 | 263 | 264 | # Setup arguments for testing this code 265 | parser = argparse.ArgumentParser( description='Process some integers.' ) 266 | parser.add_argument( '-r', '--rows', dest='rows', type=int, default=5, help='Number of rows in grid. Defaults to 5.' ) 267 | parser.add_argument( '-c', '--cols', dest='cols', type=int, default=5, help='Number of columns in grid. Defaults to 5.' ) 268 | parser.add_argument( '-n', '--numbers', action="store_true", dest="numbers", default=False, help='Display grid numbers on tiles. Defaults to false.' ) 269 | parser.add_argument( '-i', '--interactive', action="store_true", dest="interactive", default=False, help="Provide a ncurses interactive interface." ) 270 | 271 | 272 | 273 | args = parser.parse_args() 274 | print( "Args: %s" % ( args ) ) 275 | m = Map( ( args.rows, args.cols ) ) 276 | m.units = Grid() 277 | numbers = args.numbers 278 | 279 | if args.interactive: 280 | try: 281 | import curses 282 | import re 283 | stdscr = curses.initscr() 284 | stdscr.keypad( 1 ) 285 | 286 | while True: 287 | stdscr.addstr( 1, 0, m.ascii( numbers=numbers ) ) 288 | c = stdscr.getstr() 289 | stdscr.clear() 290 | if c == 'q': break 291 | elif c == 'N': numbers = not numbers 292 | 293 | finally: 294 | curses.nocbreak() 295 | stdscr.keypad( 0 ) 296 | curses.echo() 297 | curses.endwin() 298 | else: 299 | print( m.ascii( numbers ) ) 300 | -------------------------------------------------------------------------------- /hexmap/render.py: -------------------------------------------------------------------------------- 1 | from abc import ABCMeta, abstractmethod 2 | import pygame 3 | import math 4 | from hexmap.map import Grid 5 | 6 | SQRT3 = math.sqrt( 3 ) 7 | 8 | class Render( pygame.Surface ): 9 | 10 | __metaclass__ = ABCMeta 11 | 12 | 13 | 14 | def __init__( self, map, radius=24, *args, **keywords ): 15 | self.map = map 16 | self.radius = radius 17 | 18 | # Colors for the map 19 | self.GRID_COLOR = pygame.Color( 50, 50, 50 ) 20 | 21 | super( Render, self ).__init__( ( self.width, self.height ), *args, **keywords ) 22 | 23 | self.cell = [( .5 * self.radius, 0 ), 24 | ( 1.5 * self.radius, 0 ), 25 | ( 2 * self.radius, SQRT3 / 2 * self.radius ), 26 | ( 1.5 * self.radius, SQRT3 * self.radius ), 27 | ( .5 * self.radius, SQRT3 * self.radius ), 28 | ( 0, SQRT3 / 2 * self.radius ) 29 | ] 30 | 31 | 32 | 33 | @property 34 | def width( self ): 35 | return self.map.cols * self.radius * 1.5 + self.radius / 2.0 36 | @property 37 | def height( self ): 38 | return ( self.map.rows + .5 ) * self.radius * SQRT3 + 1 39 | 40 | def get_surface( self, ( row, col ) ): 41 | """ 42 | Returns a subsurface corresponding to the surface, hopefully with trim_cell wrapped around the blit method. 43 | """ 44 | width = 2 * self.radius 45 | height = self.radius * SQRT3 46 | 47 | top = ( row - math.ceil( col / 2.0 ) ) * height + ( height / 2 if col % 2 == 1 else 0 ) 48 | left = 1.5 * self.radius * col 49 | 50 | return self.subsurface( pygame.Rect( left, top, width, height ) ) 51 | 52 | # Draw methods 53 | @abstractmethod 54 | def draw( self ): 55 | """ 56 | An abstract base method for various render objects to call to paint 57 | themselves. If called via super, it fills the screen with the colorkey, 58 | if the colorkey is not set, it sets the colorkey to magenta (#FF00FF) 59 | and fills this surface. 60 | """ 61 | color = self.get_colorkey() 62 | if not color: 63 | magenta = pygame.Color( 255, 0, 255 ) 64 | self.set_colorkey( magenta ) 65 | color = magenta 66 | self.fill( color ) 67 | 68 | # Identify cell 69 | def get_cell( self, ( x, y ) ): 70 | """ 71 | Identify the cell clicked in terms of row and column 72 | """ 73 | # Identify the square grid the click is in. 74 | row = math.floor( y / ( SQRT3 * self.radius ) ) 75 | col = math.floor( x / ( 1.5 * self.radius ) ) 76 | 77 | # Determine if cell outside cell centered in this grid. 78 | x = x - col * 1.5 * self.radius 79 | y = y - row * SQRT3 * self.radius 80 | 81 | # Transform row to match our hex coordinates, approximately 82 | row = row + math.floor( ( col + 1 ) / 2.0 ) 83 | 84 | # Correct row and col for boundaries of a hex grid 85 | if col % 2 == 0: 86 | if y < SQRT3 * self.radius / 2 and x < .5 * self.radius and \ 87 | y < SQRT3 * self.radius / 2 - x: 88 | row, col = row - 1, col - 1 89 | elif y > SQRT3 * self.radius / 2 and x < .5 * self.radius and \ 90 | y > SQRT3 * self.radius / 2 + x: 91 | row, col = row, col - 1 92 | else: 93 | if x < .5 * self.radius and abs( y - SQRT3 * self.radius / 2 ) < SQRT3 * self.radius / 2 - x: 94 | row, col = row - 1 , col - 1 95 | elif y < SQRT3 * self.radius / 2: 96 | row, col = row - 1, col 97 | 98 | 99 | return ( row, col ) if self.map.valid_cell( ( row, col ) ) else None 100 | 101 | def fit_window( self, window ): 102 | top = max( window.get_height() - self.height, 0 ) 103 | left = max( window.get_width() - map.width, 0 ) 104 | return ( top, left ) 105 | 106 | class RenderUnits( Render ): 107 | """ 108 | A premade render object that will automatically draw the Units from the map 109 | 110 | """ 111 | 112 | def __init__( self, map, *args, **keywords ): 113 | super( RenderUnits, self ).__init__( map, *args, **keywords ) 114 | if not hasattr( self.map, 'units' ): 115 | self.map.units = Grid() 116 | 117 | def draw( self ): 118 | """ 119 | Calls unit.paint for all units on self.map 120 | """ 121 | super( RenderUnits, self ).draw() 122 | units = self.map.units 123 | 124 | for position, unit in units.items(): 125 | surface = self.get_surface( position ) 126 | unit.paint( surface ) 127 | 128 | class RenderGrid( Render ): 129 | def draw( self ): 130 | """ 131 | Draws a hex grid, based on the map object, onto this Surface 132 | """ 133 | super( RenderGrid, self ).draw() 134 | # A point list describing a single cell, based on the radius of each hex 135 | 136 | for col in range( self.map.cols ): 137 | # Alternate the offset of the cells based on column 138 | offset = self.radius * SQRT3 / 2 if col % 2 else 0 139 | for row in range( self.map.rows ): 140 | # Calculate the offset of the cell 141 | top = offset + SQRT3 * row * self.radius 142 | left = 1.5 * col * self.radius 143 | # Create a point list containing the offset cell 144 | points = [( x + left, y + top ) for ( x, y ) in self.cell] 145 | # Draw the polygon onto the surface 146 | pygame.draw.polygon( self, self.GRID_COLOR, points, 1 ) 147 | 148 | class RenderFog( Render ): 149 | 150 | OBSCURED = pygame.Color( 00, 00, 00, 255 ) 151 | SEEN = pygame.Color( 00, 00, 00, 100 ) 152 | VISIBLE = pygame.Color( 00, 00, 00, 0 ) 153 | 154 | def __init__( self, map, *args, **keywords ): 155 | 156 | super( RenderFog, self ).__init__( map, *args, flags=pygame.SRCALPHA, **keywords ) 157 | if not hasattr( self.map, 'fog' ): 158 | self.map.fog = Grid( default=self.OBSCURED ) 159 | 160 | def draw( self ): 161 | 162 | #Some constants for the math 163 | height = self.radius * SQRT3 164 | width = 1.5 * self.radius 165 | offset = height / 2 166 | 167 | self.fill( self.OBSCURED ) 168 | 169 | for cell in self.map.cells(): 170 | row, col = cell 171 | surface = self.get_cell( cell ) 172 | 173 | # Calculate the position of the cell 174 | top = row * height - offset * col 175 | left = width * col 176 | 177 | #Determine the points that corresponds with 178 | points = [( x + left, y + top ) for ( x, y ) in self.cell] 179 | # Draw the polygon onto the surface 180 | pygame.draw.polygon( self, self.map.fog[ cell ], points, 0 ) 181 | 182 | 183 | 184 | 185 | def trim_cell( surface ): 186 | pass 187 | 188 | 189 | if __name__ == '__main__': 190 | from .map import Map, MapUnit 191 | import sys 192 | 193 | class Unit( MapUnit ): 194 | color = pygame.Color( 200, 200, 200 ) 195 | def paint( self, surface ): 196 | radius = surface.get_width() / 2 197 | pygame.draw.circle( surface, self.color, ( radius, int( SQRT3 / 2 * radius ) ), int( radius - radius * .3 ) ) 198 | 199 | m = Map( ( 5, 5 ) ) 200 | 201 | grid = RenderGrid( m, radius=32 ) 202 | units = RenderUnits( m, radius=32 ) 203 | fog = RenderFog( m, radius=32 ) 204 | 205 | m.units[( 0, 0 ) ] = Unit( m ) 206 | m.units[( 3, 2 ) ] = Unit( m ) 207 | m.units[( 5, 3 ) ] = Unit( m ) 208 | m.units[( 5, 4 ) ] = Unit( m ) 209 | 210 | for cell in m.spread( ( 3, 2 ), radius=2 ): 211 | m.fog[cell] = fog.SEEN 212 | 213 | for cell in m.spread( ( 3, 2 ) ): 214 | m.fog[cell] = fog.VISIBLE 215 | 216 | print( m.ascii() ) 217 | 218 | 219 | try: 220 | pygame.init() 221 | fpsClock = pygame.time.Clock() 222 | 223 | window = pygame.display.set_mode( ( 640, 480 ), 1 ) 224 | from pygame.locals import QUIT, MOUSEBUTTONDOWN 225 | 226 | #Leave it running until exit 227 | while True: 228 | for event in pygame.event.get(): 229 | if event.type == QUIT: 230 | pygame.quit() 231 | sys.exit() 232 | if event.type == MOUSEBUTTONDOWN: 233 | print( units.get_cell( event.pos ) ) 234 | 235 | window.fill( pygame.Color( 'white' ) ) 236 | grid.draw() 237 | units.draw() 238 | fog.draw() 239 | window.blit( grid, ( 0, 0 ) ) 240 | window.blit( units, ( 0, 0 ) ) 241 | window.blit( fog, ( 0, 0 ) ) 242 | pygame.display.update() 243 | fpsClock.tick( 10 ) 244 | finally: 245 | pygame.quit() 246 | 247 | 248 | 249 | 250 | 251 | 252 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from distutils.core import setup 2 | import os.path 3 | 4 | def read( filename ): 5 | path = os.path.join(os.path.dirname(__file__), filename) 6 | return open(path) 7 | 8 | setup( 9 | name='pyghexmap', 10 | version=read( 'VERSION' ).read().strip(), 11 | url='https://github.com/mklauber/pygame-hex-grid/', 12 | packages=['hexmap'], 13 | license='GNU LESSER GENERAL PUBLIC LICENSE', 14 | author="Matt Lauber", 15 | author_email="pygame-hexmap@mklauber.com", 16 | description="A hex map implementation that provides a Map class, a abstract Render class that abstracts most of the drawing requirements, and a couple basic Render subclasses to get things started.", 17 | classifiers=[ 18 | "Programming Language :: Python", 19 | "Development Status :: 3 - Alpha", 20 | "Environment :: Other Environment", 21 | "Intended Audience :: Developers", 22 | "License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)", 23 | "Operating System :: OS Independent", 24 | "Topic :: Software Development :: Libraries :: Python Modules", 25 | "Topic :: Games/Entertainment :: Turn Based Strategy" 26 | ], 27 | long_description=read( 'README.rst' ).read(), 28 | install_requires=[ 'pygame'] 29 | ) 30 | -------------------------------------------------------------------------------- /tests/Map.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from hexmap.Map import Map, Grid, MapUnit 4 | 5 | class TestMap( unittest.TestCase ): 6 | def setUp( self ): 7 | pass 8 | 9 | def test_size( self ): 10 | sizes = [ ( 1, 1 ), ( 2, 2 ), ( 3, 4 ), ( 5, 5 ), ( 10, 8 ) ] 11 | 12 | for rows, cols in sizes: 13 | m = Map( ( rows, cols ) ) 14 | size = m.size 15 | self.assertTrue( rows == size[0], 16 | "Map %s returned %s rows, expected %s." % ( m, size[0], rows ) ) 17 | 18 | self.assertTrue( cols == size[1], 19 | "Map %s returned %s rows, expected %s." % ( m, size[1], cols ) ) 20 | 21 | def test_distance( self ): 22 | rows, cols = ( 8, 8 ) 23 | tests = [ 24 | ( ( 0, 0 ), ( 1, 0 ), 1 ), 25 | ( ( 0, 0 ), ( 1, 1 ), 1 ), 26 | ( ( 0, 0 ), ( 1, 2 ), 2 ), 27 | ( ( 5, 3 ), ( 9, 5 ), 4 ), 28 | ( ( 9, 5 ), ( 5, 3 ), 4 ), 29 | ( ( 7, 4 ), ( 3, 2 ), 4 ), 30 | ] 31 | 32 | m = Map( ( rows, cols ) ) 33 | 34 | for start, end, distance in tests: 35 | d = m.distance( start, end ) 36 | self.assertTrue( distance == d, 37 | "Distance between %s, %s, expected to be %s, got %s" 38 | % ( start, end, distance, d ) ) 39 | 40 | def test_direction( self ): 41 | rows, cols = ( 8, 8 ) 42 | m = Map( ( rows, cols ) ) 43 | 44 | # Test dominated directions 45 | tests = [ 46 | ( ( 0, 0 ), ( 1, 0 ), ( 1, 0 ) ), 47 | ( ( 0, 0 ), ( 1, 1 ), ( 1, 1 ) ), 48 | ( ( 0, 0 ), ( 0, 1 ), ( 0, 1 ) ), 49 | ( ( 0, 1 ), ( 0, 0 ), ( 0, -1 ) ), 50 | ( ( 1, 1 ), ( 0, 0 ), ( -1, -1 ) ), 51 | ( ( 1, 0 ), ( 0, 0 ), ( -1, 0 ) ), 52 | 53 | ( ( 0, 0 ), ( 3, 1 ), ( 1, 0 ) ), 54 | ( ( 5, 3 ), ( 8, 5 ), ( 1, 1 ) ), 55 | ( ( 8, 5 ), ( 5, 3 ), ( -1, -1 ) ), 56 | ] 57 | 58 | for start, end, direction in tests: 59 | d = m.direction( start, end ) 60 | self.assertTrue( direction == d, 61 | "Direction between %s, %s, expected to be %s, got %s" 62 | % ( start, end, direction, d ) ) 63 | 64 | # Test directions with a random component 65 | tests = [ 66 | ( ( 0, 0 ), ( 2, 1 ), [ ( 1, 0 ), ( 1, 1 ) ] ), 67 | ( ( 2, 2 ), ( 3, 4 ), [ ( 0, 1 ), ( 1, 1 ) ] ), 68 | ( ( 5, 4 ), ( 6, 3 ), [ ( 1, 0 ), ( 0, -1 ) ] ), 69 | ( ( 6, 3 ), ( 5, 4 ), [ ( -1, 0 ), ( 0, 1 ) ] ), 70 | ] 71 | 72 | for start, end, directions in tests: 73 | d = m.direction( start, end ) 74 | self.assertTrue( d in directions, 75 | "Direction between %s, %s, expected to be in %s, got %s" 76 | % ( start, end, directions, d ) ) 77 | 78 | def test_neighbors( self ): 79 | tests = { 80 | ( 0, 0 ) : [ ( 1, 0 ), ( 1, 1 ) ], 81 | ( 1, 2 ) : [ ( 1, 1 ), ( 2, 2 ), ( 2, 3 ) ], 82 | ( 1, 1 ) : [ ( 0, 0 ), ( 1, 0 ), ( 2, 1 ), ( 2, 2 ), ( 1, 2 ) ], 83 | ( 2, 1 ) : [ ( 1, 1 ), ( 1, 0 ), ( 2, 0 ), ( 3, 1 ), ( 3, 2 ), ( 2, 2 ) ], 84 | ( 7, 0 ) : [ ( 6, 0 ), ( 7, 1 ), ( 8, 1 ) ], 85 | ( 8, 1 ) : [ ( 7, 0 ), ( 7, 1 ), ( 8, 2 ) ], 86 | ( 3, 6 ) : [ ( 3, 5 ), ( 4, 6 ), ( 4, 7 ) ], 87 | ( 4, 7 ) : [ ( 3, 6 ), ( 4, 6 ), ( 5, 7 ) ], 88 | ( 9, 4 ) : [ ( 9, 3 ), ( 8, 3 ), ( 8, 4 ), ( 9, 5 ), ( 10, 5 ) ], 89 | ( 11, 7 ): [ ( 10, 6 ), ( 10, 7 ) ] 90 | } 91 | 92 | m = Map( ( 8, 8 ) ) 93 | for node, results in tests.items(): 94 | neighbors = m.neighbors( node ) 95 | self.assertEqual( set( neighbors ), set( results ), 96 | "Got incorrect neighbors for node %s:\n Expected: %s\nReceived: %s" 97 | % ( node, results, neighbors ) ) 98 | 99 | def test_spread( self ): 100 | raise NotImplementedError 101 | 102 | def test_cone( self ): 103 | raise NotImplementedError 104 | 105 | def test_slice( self ): 106 | raise NotImplementedError 107 | 108 | def test_line( self ): 109 | raise NotImplementedError 110 | 111 | class TestGrid( unittest.TestCase ): 112 | def setUp( self ): 113 | self.grid = Grid() 114 | 115 | def test_assignment( self ): 116 | key, value = ( 0, 0 ), "U" 117 | self.grid[ key ] = value 118 | self.assertTrue( key in self.grid, 119 | "Failed to create key %s" % str( key ) ) 120 | self.assertTrue( value == self.grid[ key ], 121 | "Key %s does not return value %s" % ( key, value ) ) 122 | 123 | def test_find( self ): 124 | key, value = ( 0, 0 ), "U" 125 | self.grid[ key ] = value 126 | self.assertTrue( key == self.grid.find( value ), 127 | "Find %s did not correctly return key %s " % ( value, key ) ) 128 | 129 | class TestMapUnit( unittest.TestCase ): 130 | 131 | class TestUnit( MapUnit ): 132 | def paint( self, surface ): 133 | pass 134 | 135 | def setUp( self ): 136 | self.map = Map( ( 5, 5 ) ) 137 | self.map.units = Grid() 138 | 139 | def test_position_succeeds( self ): 140 | pos, unit = ( 3, 2 ), self.TestUnit( self.map.units ) 141 | self.map.units[ pos ] = unit 142 | self.assertTrue( unit.position == pos, 143 | "Unit %s position was returned as %s, instead of %s." % ( unit, unit.position, pos ) ) 144 | 145 | unit = self.TestUnit( self.map.units ) 146 | self.assertTrue( unit.position == None, 147 | "Unit %s position was returned as %s, but it should not be on the map." % ( unit, unit.position ) ) 148 | 149 | def load_tests( loader, tests, pattern ): 150 | tests = [ TestMap, TestGrid, TestMapUnit ] 151 | 152 | suite = unittest.TestSuite() 153 | for test_class in tests: 154 | tests = loader.loadTestsFromTestCase( test_class ) 155 | suite.addTests( tests ) 156 | return suite 157 | 158 | if __name__ == '__main__': 159 | loader = unittest.TestLoader() 160 | tests = load_tests( loader, None, None ) 161 | unittest.TextTestRunner( verbosity=2 ).run( tests ) 162 | -------------------------------------------------------------------------------- /tests/Render.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from hexmap.Map import Map 4 | from hexmap.Render import Render, RenderUnits, RenderGrid, RenderFog 5 | 6 | class TestRender( unittest.TestCase ): 7 | 8 | class TestRender( Render ): 9 | def draw( self ): 10 | super( self.TestRender, self ).draw() 11 | 12 | 13 | def load_tests( loader, tests, pattern ): 14 | tests = [ TestRender ] 15 | 16 | suite = unittest.TestSuite() 17 | for test_class in tests: 18 | tests = loader.loadTestsFromTestCase( test_class ) 19 | suite.addTests( tests ) 20 | return suite 21 | 22 | if __name__ == '__main__': 23 | loader = unittest.TestLoader() 24 | tests = load_tests( loader, None, None ) 25 | unittest.TextTestRunner( verbosity=2 ).run( tests ) 26 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | import tests.Map as Map 4 | import tests.Render as Render 5 | 6 | def load_tests( loader, standard_tests, pattern ): 7 | tests = [ Map, Render ] 8 | 9 | return unittest.TestSuite( tests=[ test.load_tests( loader, standard_tests, None ) for test in tests] ) 10 | 11 | if __name__ == '__main__': 12 | 13 | loader = unittest.TestLoader() 14 | tests = load_tests( loader, None, None ) 15 | unittest.TextTestRunner( verbosity=1 ).run( tests ) 16 | 17 | --------------------------------------------------------------------------------