From 0fd908f1cb77ba7408b9a4df0561c3e98284ce7c Mon Sep 17 00:00:00 2001 From: jminardi Date: Wed, 3 Apr 2013 12:48:03 -0500 Subject: [PATCH] more docstrings --- main.py | 298 ++++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 289 insertions(+), 9 deletions(-) diff --git a/main.py b/main.py index 71fb99d0..a146e0bc 100644 --- a/main.py +++ b/main.py @@ -13,7 +13,8 @@ def cube_vertices(x, y, z, n): - """ Return the vertices of the cube at position x, y, z with size n. + """ Return the vertices of the cube at position x, y, z with size 2*n. + """ return [ x-n,y+n,z-n, x-n,y+n,z+n, x+n,y+n,z+n, x+n,y+n,z-n, # top @@ -27,6 +28,7 @@ def cube_vertices(x, y, z, n): def tex_coord(x, y, n=4): """ Return the bounding vertices of the texture square. + """ m = 1.0 / n dx = x * m @@ -36,6 +38,7 @@ def tex_coord(x, y, n=4): def tex_coords(top, bottom, side): """ Return a list of the texture squares for the top, bottom and side. + """ top = tex_coord(*top) bottom = tex_coord(*bottom) @@ -110,6 +113,7 @@ def __init__(self): self.group = TextureGroup(image.load(TEXTURE_PATH).get_texture()) # A mapping from position to the texture of the block at that position. + # This defines all the blocks that are currently in the world. self.world = {} # Same mapping as `world` but only contains blocks that are shown. @@ -121,12 +125,15 @@ def __init__(self): # Mapping from sector to a list of positions inside that sector. self.sectors = {} - # Simple function queue implemementation. + # Simple function queue implementation. self.queue = [] self._initialize() def _initialize(self): + """ Initialize the world by placing all the blocks. + + """ n = 80 # 1/2 width and height of world s = 1 # step size y = 0 # initial y height @@ -163,7 +170,16 @@ def _initialize(self): def hit_test(self, position, vector, max_distance=8): """ Line of sight search from current position. If a block is intersected it is returned, along with the block previously in the line - of sight. + of sight. If no block is found, return None, None. + + Parameters + ---------- + position : tuple of len 3 + The (x, y, z) position to check visibility from. + vector : tuple of len 3 + The line of sight vector. + max_distance : int + How many blocks away to search for a hit. """ m = 8 @@ -179,6 +195,10 @@ def hit_test(self, position, vector, max_distance=8): return None, None def exposed(self, position): + """ Returns False is given `position` is surrounded on all 6 sides by + blocks, True otherwise. + + """ x, y, z = position for dx, dy, dz in FACES: if (x + dx, y + dy, z + dz) not in self.world: @@ -186,17 +206,32 @@ def exposed(self, position): return False def init_block(self, position, texture): + """ Initialize a block at the given `position` and `texture`, but do + not draw it. + + Parameters + ---------- + position : tuple of len 3 + The (x, y, z) position of the block to initialize. + texture : list of len 3 + The coordinates of the texture squares. Use `tex_coords()` to + generate. + + """ self.add_block(position, texture, False) def add_block(self, position, texture, sync=True): - """ + """ Add a block with the given `texture` and `position` to the world. + Parameters ---------- position : tuple of len 3 - The (x, y, z) position of the block to add - texture : list or len 3 + The (x, y, z) position of the block to add. + texture : list of len 3 The coordinates of the texture squares. Use `tex_coords()` to - generate + generate. + sync : bool + Whether or not to draw the block immediately. """ if position in self.world: @@ -209,6 +244,16 @@ def add_block(self, position, texture, sync=True): self.check_neighbors(position) def remove_block(self, position, sync=True): + """ Remove the block at the given `position`. + + Parameters + ---------- + position : tuple of len 3 + The (x, y, z) position of the block to remove. + sync : bool + Whether or not to immediately remove block from canvas. + + """ del self.world[position] self.sectors[sectorize(position)].remove(position) if sync: @@ -217,6 +262,12 @@ def remove_block(self, position, sync=True): self.check_neighbors(position) def check_neighbors(self, position): + """ Check all blocks surrounding `position` and ensure their visual + state is current. This means hiding blocks that are not exposed and + ensuring that all exposed blocks are shown. Usually used after a block + is added or removed. + + """ x, y, z = position for dx, dy, dz in FACES: key = (x + dx, y + dy, z + dz) @@ -230,11 +281,25 @@ def check_neighbors(self, position): self.hide_block(key) def show_blocks(self): + """ Ensure all exposed blocks are shown. + + """ + # FIXME This method is not currently used for position in self.world: if position not in self.shown and self.exposed(position): self.show_block(position) def show_block(self, position, immediate=True): + """ Show the block at the given `position`. + + Parameters + ---------- + position : tuple of len 3 + The (x, y, z) position of the block to show. + immediate : bool + Whether or not to show the block immediately. + + """ texture = self.world[position] self.shown[position] = texture if immediate: @@ -243,6 +308,17 @@ def show_block(self, position, immediate=True): self._enqueue(self._show_block, position, texture) def _show_block(self, position, texture): + """ Private implementation of the `show_block()` method. + + Parameters + ---------- + position : tuple of len 3 + The (x, y, z) position of the block to show. + texture : list of len 3 + The coordinates of the texture squares. Use `tex_coords()` to + generate. + + """ x, y, z = position # only show exposed faces index = 0 @@ -250,6 +326,7 @@ def _show_block(self, position, texture): vertex_data = cube_vertices(x, y, z, 0.5) texture_data = list(texture) for dx, dy, dz in []: # FACES: + # FIXME This block never gets called. if (x + dx, y + dy, z + dz) in self.world: count -= 4 i = index * 12 @@ -264,6 +341,17 @@ def _show_block(self, position, texture): ('t2f/static', texture_data)) def hide_block(self, position, immediate=True): + """ Hide the block at the given `position`. Hiding does not remove the + block from the world. + + Parameters + ---------- + position : tuple of len 3 + The (x, y, z) position of the block to hide. + immediate : bool + Whether or not to immediately remove the block from the canvas. + + """ self.shown.pop(position) if immediate: self._hide_block(position) @@ -271,19 +359,35 @@ def hide_block(self, position, immediate=True): self._enqueue(self._hide_block, position) def _hide_block(self, position): + """ Private implementation of the 'hide_block()` method. + + """ self._shown.pop(position).delete() def show_sector(self, sector): + """ Ensure all blocks in the given sector that should be shown are + drawn to the canvas. + + """ for position in self.sectors.get(sector, []): if position not in self.shown and self.exposed(position): self.show_block(position, False) def hide_sector(self, sector): + """ Ensure all blocks in the given sector that should be hidden are + removed from the canvas. + + """ for position in self.sectors.get(sector, []): if position in self.shown: self.hide_block(position, False) def change_sectors(self, before, after): + """ Move from sector `before` to sector `after`. A sector is a + contiguous x, y sub-region of world. Sectors are used to speed up + world rendering. + + """ before_set = set() after_set = set() pad = 4 @@ -306,18 +410,30 @@ def change_sectors(self, before, after): self.hide_sector(sector) def _enqueue(self, func, *args): + """ Add `func` to the internal queue. + + """ self.queue.append((func, args)) def _dequeue(self): + """ Pop the top function from the internal queue and call it. + + """ func, args = self.queue.pop(0) func(*args) def process_queue(self): + """ Process the entire queue while taking periodic breaks. + + """ start = time.clock() while self.queue and time.clock() - start < 1 / 60.0: self._dequeue() def process_entire_queue(self): + """ Process the entire queue with no breaks. + + """ while self.queue: self._dequeue() @@ -326,30 +442,71 @@ class Window(pyglet.window.Window): def __init__(self, *args, **kwargs): super(Window, self).__init__(*args, **kwargs) + + # Whether or not the window exclusively captures the mouse. self.exclusive = False + + # When flying gravity has no effect and speed is increased. self.flying = False + + # First element is -1 when moving forward, 1 when moving back, and 0 + # otherwise. The second element is -1 when moving left, 1 when moving + # right, and 0 otherwise. self.strafe = [0, 0] + + # Current (x, y, z) position in the world, specified with floats. self.position = (0, 0, 0) + + # First element is rotation of the player in the x-z plane (ground + # plane) measured from the z-axis down. The second is the rotation + # angle from the ground plane up. self.rotation = (0, 0) + + # Which sector the player is currently in. self.sector = None + + # The crosshairs at the center of the screen. self.reticle = None + + # Velocity in the y (upward) direction. self.dy = 0 + + # A list of blocks the player can place. Hit num keys to cycle. self.inventory = [BRICK, GRASS, SAND] + + # The current block the user can place. Hit num keys to cycle. self.block = self.inventory[0] + + # Convenience list of num keys. self.num_keys = [ key._1, key._2, key._3, key._4, key._5, key._6, key._7, key._8, key._9, key._0] + + # Instance of the model that handles the world. self.model = Model() + + # The label that is displayed in the top left of the canvas. self.label = pyglet.text.Label('', font_name='Arial', font_size=18, x=10, y=self.height - 10, anchor_x='left', anchor_y='top', color=(0, 0, 0, 255)) + + # This call schedules the `update()` method to be called 60 times a + # second. This is the main game event loop. pyglet.clock.schedule_interval(self.update, 1.0 / 60) def set_exclusive_mouse(self, exclusive): + """ If `exclusive` is True, the game will capture the mouse, if False + the game will ignore the mouse. + + """ super(Window, self).set_exclusive_mouse(exclusive) self.exclusive = exclusive def get_sight_vector(self): + """ Returns the current line of sight vector indicating the direction + the player is looking. + + """ x, y = self.rotation m = math.cos(math.radians(y)) dy = math.sin(math.radians(y)) @@ -358,6 +515,15 @@ def get_sight_vector(self): return (dx, dy, dz) def get_motion_vector(self): + """ Returns the current motion vector indicating the velocity of the + player. + + Returns + ------- + vector : tuple of len 3 + Tuple containing the velocity in x, y, and z respectively. + + """ if any(self.strafe): x, y = self.rotation strafe = math.degrees(math.atan2(*self.strafe)) @@ -382,7 +548,14 @@ def get_motion_vector(self): return (dx, dy, dz) def update(self, dt): - """ This method is scheduled to be called repeadetly. + """ This method is scheduled to be called repeatedly by the pyglet + clock. + + Parameters + ---------- + dt : float + The change in time since the last call. + """ self.model.process_queue() sector = sectorize(self.position) @@ -397,6 +570,15 @@ def update(self, dt): self._update(dt / m) def _update(self, dt): + """ Private implementation of the `update()` method. This is where most + of the motion logic lives, along with gravity and collision detection. + + Parameters + ---------- + dt : float + The change in time since the last call. + + """ # walking speed = 15 if self.flying else 5 d = dt * speed @@ -404,7 +586,8 @@ def _update(self, dt): dx, dy, dz = dx * d, dy * d, dz * d # gravity if not self.flying: - self.dy -= dt * 0.044 # g force, should be = jump_speed * 0.5 / max_jump_height + # g force, should be = jump_speed * 0.5 / max_jump_height + self.dy -= dt * 0.044 self.dy = max(self.dy, -0.5) # terminal velocity dy += self.dy # collisions @@ -413,6 +596,22 @@ def _update(self, dt): self.position = (x, y, z) def collide(self, position, height): + """ Checks to see if the player at the given `position` and `height` + is colliding with any blocks in the world. + + Parameters + ---------- + position : tuple of len 3 + The (x, y, z) position to check for collisions at. + height : int or float + The height of the player. + + Returns + ------- + position : tuple of len 3 + The new position of the player taking into account collisions. + + """ pad = 0.25 p = list(position) np = normalize(position) @@ -437,6 +636,10 @@ def collide(self, position, height): return tuple(p) def on_mouse_scroll(self, x, y, scroll_x, scroll_y): + """ Called when the player scrolls the mouse. + + """ + # FIXME This method is not used at all. return x, y, z = self.position dx, dy, dz = self.get_sight_vector() @@ -444,6 +647,22 @@ def on_mouse_scroll(self, x, y, scroll_x, scroll_y): self.position = (x + dx * d, y + dy * d, z + dz * d) def on_mouse_press(self, x, y, button, modifiers): + """ Called when a mouse button is pressed. See pyglet docs for button + amd modifier mappings. + + Parameters + ---------- + x, y : int + The coordinates of the mouse click. Always center of the screen if + the mouse is captured. + button : int + Number representing mouse button that was clicked. 1 = left button, + 4 = right button. + modifiers : int + Number representing any modifying keys that were pressed when the + mouse button was clicked. + + """ if self.exclusive: vector = self.get_sight_vector() block, previous = self.model.hit_test(self.position, vector) @@ -459,6 +678,17 @@ def on_mouse_press(self, x, y, button, modifiers): self.set_exclusive_mouse(True) def on_mouse_motion(self, x, y, dx, dy): + """ Called when the player moves the mouse. + + Parameters + ---------- + x, y : int + The coordinates of the mouse click. Always center of the screen if + the mouse is captured. + dx, dy : float + The movement of the mouse. + + """ if self.exclusive: m = 0.15 x, y = self.rotation @@ -467,6 +697,17 @@ def on_mouse_motion(self, x, y, dx, dy): self.rotation = (x, y) def on_key_press(self, symbol, modifiers): + """ Called when the player presses a key. See pyglet docs for key + mappings. + + Parameters + ---------- + symbol : int + Number representing the key that was pressed. + modifiers : int + Number representing any modifying keys that were pressed. + + """ if symbol == key.W: self.strafe[0] -= 1 elif symbol == key.S: @@ -487,6 +728,17 @@ def on_key_press(self, symbol, modifiers): self.block = self.inventory[index] def on_key_release(self, symbol, modifiers): + """ Called when the player releases a key. See pyglet docs for key + mappings. + + Parameters + ---------- + symbol : int + Number representing the key that was pressed. + modifiers : int + Number representing any modifying keys that were pressed. + + """ if symbol == key.W: self.strafe[0] += 1 elif symbol == key.S: @@ -497,6 +749,9 @@ def on_key_release(self, symbol, modifiers): self.strafe[1] -= 1 def on_resize(self, width, height): + """ Called when the window is resized to a new `width` and `height`. + + """ # label self.label.y = height - 10 # reticle @@ -509,6 +764,9 @@ def on_resize(self, width, height): ) def set_2d(self): + """ Configure OpenGL to draw in 2d. + + """ width, height = self.get_size() glDisable(GL_DEPTH_TEST) glViewport(0, 0, width, height) @@ -519,6 +777,9 @@ def set_2d(self): glLoadIdentity() def set_3d(self): + """ Configure OpenGL to draw in 3d. + + """ width, height = self.get_size() glEnable(GL_DEPTH_TEST) glViewport(0, 0, width, height) @@ -534,6 +795,9 @@ def set_3d(self): glTranslatef(-x, -y, -z) def on_draw(self): + """ Called by pyglet to draw the canvas. + + """ self.clear() self.set_3d() glColor3d(1, 1, 1) @@ -544,6 +808,10 @@ def on_draw(self): self.draw_reticle() def draw_focused_block(self): + """ Draw black edges around the block that is currently under the + crosshairs. + + """ vector = self.get_sight_vector() block = self.model.hit_test(self.position, vector)[0] if block: @@ -555,6 +823,9 @@ def draw_focused_block(self): glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) def draw_label(self): + """ Draw the label in the top left of the screen. + + """ x, y, z = self.position self.label.text = '%02d (%.2f, %.2f, %.2f) %d / %d' % ( pyglet.clock.get_fps(), x, y, z, @@ -562,11 +833,17 @@ def draw_label(self): self.label.draw() def draw_reticle(self): + """ Draw the crosshairs in the center of the screen. + + """ glColor3d(0, 0, 0) self.reticle.draw(GL_LINES) def setup_fog(): + """ Configure the OpenGL fog properties. + + """ glEnable(GL_FOG) glFogfv(GL_FOG_COLOR, (GLfloat * 4)(0.5, 0.69, 1.0, 1)) glHint(GL_FOG_HINT, GL_DONT_CARE) @@ -577,6 +854,9 @@ def setup_fog(): def setup(): + """ Basic OpenGL configuration. + + """ glClearColor(0.5, 0.69, 1.0, 1) glEnable(GL_CULL_FACE) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)