diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..4c1c36b5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +# Virtual Environment +.venv +/pycache/ +*.pyc \ No newline at end of file diff --git a/MainMenu.py b/MainMenu.py new file mode 100644 index 00000000..e69de29b diff --git a/MainMenu_background.jpg b/MainMenu_background.jpg new file mode 100644 index 00000000..e123857e Binary files /dev/null and b/MainMenu_background.jpg differ diff --git a/LICENSE b/OLD/LICENSE similarity index 100% rename from LICENSE rename to OLD/LICENSE diff --git a/README.md b/OLD/README.md similarity index 100% rename from README.md rename to OLD/README.md diff --git a/OLD/main_old.py b/OLD/main_old.py new file mode 100644 index 00000000..61afe41c --- /dev/null +++ b/OLD/main_old.py @@ -0,0 +1,902 @@ +from __future__ import division + +import sys +import math +import random +import time + +from collections import deque +from pyglet import image +from pyglet.gl import * +from pyglet.graphics import TextureGroup +from pyglet.window import key, mouse + +TICKS_PER_SEC = 60 + +# Size of sectors used to ease block loading. +SECTOR_SIZE = 16 + +WALKING_SPEED = 5 +FLYING_SPEED = 15 + +GRAVITY = 20.0 +MAX_JUMP_HEIGHT = 1.0 # About the height of a block. +# To derive the formula for calculating jump speed, first solve +# v_t = v_0 + a * t +# for the time at which you achieve maximum height, where a is the acceleration +# due to gravity and v_t = 0. This gives: +# t = - v_0 / a +# Use t and the desired MAX_JUMP_HEIGHT to solve for v_0 (jump speed) in +# s = s_0 + v_0 * t + (a * t^2) / 2 +JUMP_SPEED = math.sqrt(2 * GRAVITY * MAX_JUMP_HEIGHT) +TERMINAL_VELOCITY = 50 + +PLAYER_HEIGHT = 2 + +if sys.version_info[0] >= 3: + xrange = range + +def cube_vertices(x, y, z, 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 + x-n,y-n,z-n, x+n,y-n,z-n, x+n,y-n,z+n, x-n,y-n,z+n, # bottom + x-n,y-n,z-n, x-n,y-n,z+n, x-n,y+n,z+n, x-n,y+n,z-n, # left + x+n,y-n,z+n, x+n,y-n,z-n, x+n,y+n,z-n, x+n,y+n,z+n, # right + x-n,y-n,z+n, x+n,y-n,z+n, x+n,y+n,z+n, x-n,y+n,z+n, # front + x+n,y-n,z-n, x-n,y-n,z-n, x-n,y+n,z-n, x+n,y+n,z-n, # back + ] + + +def tex_coord(x, y, n=4): + """ Return the bounding vertices of the texture square. + + """ + m = 1.0 / n + dx = x * m + dy = y * m + return dx, dy, dx + m, dy, dx + m, dy + m, dx, dy + m + + +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) + side = tex_coord(*side) + result = [] + result.extend(top) + result.extend(bottom) + result.extend(side * 4) + return result + + +TEXTURE_PATH = 'OLD/texture.png' + +GRASS = tex_coords((1, 0), (0, 1), (0, 0)) +SAND = tex_coords((1, 1), (1, 1), (1, 1)) +BRICK = tex_coords((2, 0), (2, 0), (2, 0)) +STONE = tex_coords((2, 1), (2, 1), (2, 1)) + +FACES = [ + ( 0, 1, 0), + ( 0,-1, 0), + (-1, 0, 0), + ( 1, 0, 0), + ( 0, 0, 1), + ( 0, 0,-1), +] + + +def normalize(position): + """ Accepts `position` of arbitrary precision and returns the block + containing that position. + + Parameters + ---------- + position : tuple of len 3 + + Returns + ------- + block_position : tuple of ints of len 3 + + """ + x, y, z = position + x, y, z = (int(round(x)), int(round(y)), int(round(z))) + return (x, y, z) + + +def sectorize(position): + """ Returns a tuple representing the sector for the given `position`. + + Parameters + ---------- + position : tuple of len 3 + + Returns + ------- + sector : tuple of len 3 + + """ + x, y, z = normalize(position) + x, y, z = x // SECTOR_SIZE, y // SECTOR_SIZE, z // SECTOR_SIZE + return (x, 0, z) + + +class Model(object): + + def __init__(self): + + # A Batch is a collection of vertex lists for batched rendering. + self.batch = pyglet.graphics.Batch() + + # A TextureGroup manages an OpenGL texture. + 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. + self.shown = {} + + # Mapping from position to a pyglet `VertextList` for all shown blocks. + self._shown = {} + + # Mapping from sector to a list of positions inside that sector. + self.sectors = {} + + # Simple function queue implementation. The queue is populated with + # _show_block() and _hide_block() calls + self.queue = deque() + + 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 + for x in xrange(-n, n + 1, s): + for z in xrange(-n, n + 1, s): + # create a layer stone an grass everywhere. + self.add_block((x, y - 2, z), GRASS, immediate=False) + self.add_block((x, y - 3, z), STONE, immediate=False) + if x in (-n, n) or z in (-n, n): + # create outer walls. + for dy in xrange(-2, 3): + self.add_block((x, y + dy, z), STONE, immediate=False) + + # generate the hills randomly + o = n - 10 + for _ in xrange(120): + a = random.randint(-o, o) # x position of the hill + b = random.randint(-o, o) # z position of the hill + c = -1 # base of the hill + h = random.randint(1, 6) # height of the hill + s = random.randint(4, 8) # 2 * s is the side length of the hill + d = 1 # how quickly to taper off the hills + t = random.choice([GRASS, SAND, BRICK]) + for y in xrange(c, c + h): + for x in xrange(a - s, a + s + 1): + for z in xrange(b - s, b + s + 1): + if (x - a) ** 2 + (z - b) ** 2 > (s + 1) ** 2: + continue + if (x - 0) ** 2 + (z - 0) ** 2 < 5 ** 2: + continue + self.add_block((x, y, z), t, immediate=False) + s -= d # decrement side length so hills taper off + + 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. 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 + x, y, z = position + dx, dy, dz = vector + previous = None + for _ in xrange(max_distance * m): + key = normalize((x, y, z)) + if key != previous and key in self.world: + return key, previous + previous = key + x, y, z = x + dx / m, y + dy / m, z + dz / m + 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: + return True + return False + + def add_block(self, position, texture, immediate=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 of len 3 + The coordinates of the texture squares. Use `tex_coords()` to + generate. + immediate : bool + Whether or not to draw the block immediately. + + """ + if position in self.world: + self.remove_block(position, immediate) + self.world[position] = texture + self.sectors.setdefault(sectorize(position), []).append(position) + if immediate: + if self.exposed(position): + self.show_block(position) + self.check_neighbors(position) + + def remove_block(self, position, immediate=True): + """ Remove the block at the given `position`. + + Parameters + ---------- + position : tuple of len 3 + The (x, y, z) position of the block to remove. + immediate : bool + Whether or not to immediately remove block from canvas. + + """ + del self.world[position] + self.sectors[sectorize(position)].remove(position) + if immediate: + if position in self.shown: + self.hide_block(position) + 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) + if key not in self.world: + continue + if self.exposed(key): + if key not in self.shown: + self.show_block(key) + else: + if key in self.shown: + self.hide_block(key) + + def show_block(self, position, immediate=True): + """ Show the block at the given `position`. This method assumes the + block has already been added with add_block() + + 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: + self._show_block(position, texture) + else: + 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 + vertex_data = cube_vertices(x, y, z, 0.5) + texture_data = list(texture) + # create vertex list + # FIXME Maybe `add_indexed()` should be used instead + self._shown[position] = self.batch.add(24, GL_QUADS, self.group, + ('v3f/static', vertex_data), + ('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) + else: + 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 + for dx in xrange(-pad, pad + 1): + for dy in [0]: # xrange(-pad, pad + 1): + for dz in xrange(-pad, pad + 1): + if dx ** 2 + dy ** 2 + dz ** 2 > (pad + 1) ** 2: + continue + if before: + x, y, z = before + before_set.add((x + dx, y + dy, z + dz)) + if after: + x, y, z = after + after_set.add((x + dx, y + dy, z + dz)) + show = after_set - before_set + hide = before_set - after_set + for sector in show: + self.show_sector(sector) + for sector in hide: + 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.popleft() + func(*args) + + def process_queue(self): + """ Process the entire queue while taking periodic breaks. This allows + the game loop to run smoothly. The queue contains calls to + _show_block() and _hide_block() so this method should be called if + add_block() or remove_block() was called with immediate=False + + """ + start = time.perf_counter() + while self.queue and time.perf_counter() - start < 1.0 / TICKS_PER_SEC: + self._dequeue() + + def process_entire_queue(self): + """ Process the entire queue with no breaks. + + """ + while self.queue: + self._dequeue() + + +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 + + # Strafing is moving lateral to the direction you are facing, + # e.g. moving to the left or right while continuing to face forward. + # + # 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. Note + # that, perhaps unlike in math class, the y-axis is the vertical axis. + 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. Rotation is in degrees. + # + # The vertical plane rotation ranges from -90 (looking straight down) to + # 90 (looking straight up). The horizontal rotation range is unbounded. + 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 + # TICKS_PER_SEC. This is the main game event loop. + pyglet.clock.schedule_interval(self.update, 1.0 / TICKS_PER_SEC) + + 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 + # y ranges from -90 to 90, or -pi/2 to pi/2, so m ranges from 0 to 1 and + # is 1 when looking ahead parallel to the ground and 0 when looking + # straight up or down. + m = math.cos(math.radians(y)) + # dy ranges from -1 to 1 and is -1 when looking straight down and 1 when + # looking straight up. + dy = math.sin(math.radians(y)) + dx = math.cos(math.radians(x - 90)) * m + dz = math.sin(math.radians(x - 90)) * m + 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)) + y_angle = math.radians(y) + x_angle = math.radians(x + strafe) + if self.flying: + m = math.cos(y_angle) + dy = math.sin(y_angle) + if self.strafe[1]: + # Moving left or right. + dy = 0.0 + m = 1 + if self.strafe[0] > 0: + # Moving backwards. + dy *= -1 + # When you are flying up or down, you have less left and right + # motion. + dx = math.cos(x_angle) * m + dz = math.sin(x_angle) * m + else: + dy = 0.0 + dx = math.cos(x_angle) + dz = math.sin(x_angle) + else: + dy = 0.0 + dx = 0.0 + dz = 0.0 + return (dx, dy, dz) + + def update(self, dt): + """ 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) + if sector != self.sector: + self.model.change_sectors(self.sector, sector) + if self.sector is None: + self.model.process_entire_queue() + self.sector = sector + m = 8 + dt = min(dt, 0.2) + for _ in xrange(m): + 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 = FLYING_SPEED if self.flying else WALKING_SPEED + d = dt * speed # distance covered this tick. + dx, dy, dz = self.get_motion_vector() + # New position in space, before accounting for gravity. + dx, dy, dz = dx * d, dy * d, dz * d + # gravity + if not self.flying: + # Update your vertical speed: if you are falling, speed up until you + # hit terminal velocity; if you are jumping, slow down until you + # start falling. + self.dy -= dt * GRAVITY + self.dy = max(self.dy, -TERMINAL_VELOCITY) + dy += self.dy * dt + # collisions + x, y, z = self.position + x, y, z = self.collide((x + dx, y + dy, z + dz), PLAYER_HEIGHT) + 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. + + """ + # How much overlap with a dimension of a surrounding block you need to + # have to count as a collision. If 0, touching terrain at all counts as + # a collision. If .49, you sink into the ground, as if walking through + # tall grass. If >= .5, you'll fall through the ground. + pad = 0.25 + p = list(position) + np = normalize(position) + for face in FACES: # check all surrounding blocks + for i in xrange(3): # check each dimension independently + if not face[i]: + continue + # How much overlap you have with this dimension. + d = (p[i] - np[i]) * face[i] + if d < pad: + continue + for dy in xrange(height): # check each height + op = list(np) + op[1] -= dy + op[i] += face[i] + if tuple(op) not in self.model.world: + continue + p[i] -= (d - pad) * face[i] + if face == (0, -1, 0) or face == (0, 1, 0): + # You are colliding with the ground or ceiling, so stop + # falling / rising. + self.dy = 0 + break + return tuple(p) + + 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) + if (button == mouse.RIGHT) or \ + ((button == mouse.LEFT) and (modifiers & key.MOD_CTRL)): + # ON OSX, control + left click = right click. + if previous: + self.model.add_block(previous, self.block) + elif button == pyglet.window.mouse.LEFT and block: + texture = self.model.world[block] + if texture != STONE: + self.model.remove_block(block) + else: + 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 + x, y = x + dx * m, y + dy * m + y = max(-90, min(90, y)) + 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: + self.strafe[0] += 1 + elif symbol == key.A: + self.strafe[1] -= 1 + elif symbol == key.D: + self.strafe[1] += 1 + elif symbol == key.SPACE: + if self.dy == 0: + self.dy = JUMP_SPEED + elif symbol == key.ESCAPE: + self.set_exclusive_mouse(False) + elif symbol == key.TAB: + self.flying = not self.flying + elif symbol in self.num_keys: + index = (symbol - self.num_keys[0]) % len(self.inventory) + 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: + self.strafe[0] -= 1 + elif symbol == key.A: + self.strafe[1] += 1 + elif symbol == key.D: + 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 + if self.reticle: + self.reticle.delete() + x, y = self.width // 2, self.height // 2 + n = 10 + self.reticle = pyglet.graphics.vertex_list(4, + ('v2i', (x - n, y, x + n, y, x, y - n, x, y + n)) + ) + + def set_2d(self): + """ Configure OpenGL to draw in 2d. + + """ + width, height = self.get_size() + glDisable(GL_DEPTH_TEST) + viewport = self.get_viewport_size() + glViewport(0, 0, max(1, viewport[0]), max(1, viewport[1])) + glMatrixMode(GL_PROJECTION) + glLoadIdentity() + glOrtho(0, max(1, width), 0, max(1, height), -1, 1) + glMatrixMode(GL_MODELVIEW) + glLoadIdentity() + + def set_3d(self): + """ Configure OpenGL to draw in 3d. + + """ + width, height = self.get_size() + glEnable(GL_DEPTH_TEST) + viewport = self.get_viewport_size() + glViewport(0, 0, max(1, viewport[0]), max(1, viewport[1])) + glMatrixMode(GL_PROJECTION) + glLoadIdentity() + gluPerspective(65.0, width / float(height), 0.1, 60.0) + glMatrixMode(GL_MODELVIEW) + glLoadIdentity() + x, y = self.rotation + glRotatef(x, 0, 1, 0) + glRotatef(-y, math.cos(math.radians(x)), 0, math.sin(math.radians(x))) + x, y, z = self.position + glTranslatef(-x, -y, -z) + + def on_draw(self): + """ Called by pyglet to draw the canvas. + + """ + self.clear() + self.set_3d() + glColor3d(1, 1, 1) + self.model.batch.draw() + self.draw_focused_block() + self.set_2d() + self.draw_label() + 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: + x, y, z = block + vertex_data = cube_vertices(x, y, z, 0.51) + glColor3d(0, 0, 0) + glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) + pyglet.graphics.draw(24, GL_QUADS, ('v3f/static', vertex_data)) + 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, + len(self.model._shown), len(self.model.world)) + 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. + + """ + # Enable fog. Fog "blends a fog color with each rasterized pixel fragment's + # post-texturing color." + glEnable(GL_FOG) + # Set the fog color. + glFogfv(GL_FOG_COLOR, (GLfloat * 4)(0.5, 0.69, 1.0, 1)) + # Say we have no preference between rendering speed and quality. + glHint(GL_FOG_HINT, GL_DONT_CARE) + # Specify the equation used to compute the blending factor. + glFogi(GL_FOG_MODE, GL_LINEAR) + # How close and far away fog starts and ends. The closer the start and end, + # the denser the fog in the fog range. + glFogf(GL_FOG_START, 20.0) + glFogf(GL_FOG_END, 60.0) + + +def setup(): + """ Basic OpenGL configuration. + + """ + # Set the color of "clear", i.e. the sky, in rgba. + glClearColor(0.5, 0.69, 1.0, 1) + # Enable culling (not rendering) of back-facing facets -- facets that aren't + # visible to you. + glEnable(GL_CULL_FACE) + # Set the texture minification/magnification function to GL_NEAREST (nearest + # in Manhattan distance) to the specified texture coordinates. GL_NEAREST + # "is generally faster than GL_LINEAR, but it can produce textured images + # with sharper edges because the transition between texture elements is not + # as smooth." + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) + setup_fog() + + +def main(): + window = Window(width=800, height=600, caption='Pyglet', resizable=True) + # Hide the mouse cursor and prevent the mouse from leaving the window. + window.set_exclusive_mouse(True) + setup() + pyglet.app.run() + + +if __name__ == '__main__': + main() diff --git a/OLD/texture.png b/OLD/texture.png new file mode 100644 index 00000000..9d05a7e2 Binary files /dev/null and b/OLD/texture.png differ diff --git a/Textures.png b/Textures.png new file mode 100644 index 00000000..4b9ffcd2 Binary files /dev/null and b/Textures.png differ diff --git a/Textures_Numbered.png b/Textures_Numbered.png new file mode 100644 index 00000000..fbd4219d Binary files /dev/null and b/Textures_Numbered.png differ diff --git a/__pycache__/block.cpython-312.pyc b/__pycache__/block.cpython-312.pyc new file mode 100644 index 00000000..0a13aae9 Binary files /dev/null and b/__pycache__/block.cpython-312.pyc differ diff --git a/__pycache__/inventory.cpython-312.pyc b/__pycache__/inventory.cpython-312.pyc new file mode 100644 index 00000000..54bb372f Binary files /dev/null and b/__pycache__/inventory.cpython-312.pyc differ diff --git a/__pycache__/mmath.cpython-312.pyc b/__pycache__/mmath.cpython-312.pyc new file mode 100644 index 00000000..2dcaff75 Binary files /dev/null and b/__pycache__/mmath.cpython-312.pyc differ diff --git a/__pycache__/model.cpython-312.pyc b/__pycache__/model.cpython-312.pyc new file mode 100644 index 00000000..d5bea804 Binary files /dev/null and b/__pycache__/model.cpython-312.pyc differ diff --git a/__pycache__/player.cpython-312.pyc b/__pycache__/player.cpython-312.pyc new file mode 100644 index 00000000..d928b444 Binary files /dev/null and b/__pycache__/player.cpython-312.pyc differ diff --git a/__pycache__/window.cpython-312.pyc b/__pycache__/window.cpython-312.pyc new file mode 100644 index 00000000..2e6ab489 Binary files /dev/null and b/__pycache__/window.cpython-312.pyc differ diff --git a/block.py b/block.py new file mode 100644 index 00000000..6bb9e18f --- /dev/null +++ b/block.py @@ -0,0 +1,51 @@ +def tex_coord(x, y, w=32, h=16): + """ Return the bounding vertices of the texture square. + + """ + width = 1.0 / w + height = 1.0 / h + dx = x * width + dy = y * height + return dx, dy, dx + width, dy, dx + width, dy + height, dx, dy + height + +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) + side = tex_coord(*side) + result = [] + result.extend(top) + result.extend(bottom) + result.extend(side * 4) + return result + +NONE = None +#Row 1 +STONE = tex_coords((19, 15), (19, 15), (19, 15)) +GRASS_BLOCK = tex_coords((2, 15), (18, 14), (10, 15)) +DIRT = tex_coords((18, 14), (18, 14), (18, 14)) +PODZOL = tex_coords((19, 14), (18, 14), (20, 14)) +COBBLESTONE = tex_coords((26, 15), (26, 15), (26, 15)) +OAK_WOOD_PLANK = tex_coords((21, 14), (21, 14), (21, 14)) +SPRUCE_WOOD_PLANK = tex_coords((22, 14), (22, 14), (22, 14)) +BIRCH_WOOD_PLANK = tex_coords((23, 14), (23, 14), (23, 14)) +JUNGLE_WOOD_PLANK = tex_coords((24, 14), (24, 14), (24, 14)) +ACACIA_WOOD_PLANK = tex_coords((25, 14), (25, 14), (25, 14)) +DARK_OAK_WOOD_PLANK = tex_coords((26, 14), (26, 14), (26, 14)) +#Row 2 +BRICK = tex_coords((29, 14), (29, 14), (29, 14)) +BEDROCK = tex_coords((0, 14), (0, 14), (0, 14)) +SAND = tex_coords((5, 14), (5, 14), (5, 14)) +CACTUS = tex_coords((15, 10), (15, 10), (16, 10)) +#Row 5 +LAMP = tex_coords((25, 7), (25, 7), (25, 7)) +PORTAL = tex_coords((26, 6), (26, 6), (26, 6)) + +STONE_SLAB = tex_coords((27, 14),(27, 14),(28, 14)) + +WATER_BLOCK = tex_coords((0, 1),(0, 1),(0, 1)) + +OAK_LOG = tex_coords((4, 12), (4, 12), (3, 12)) +OAK_LEAF = tex_coords((7, 10), (7, 10), (7, 10)) \ No newline at end of file diff --git a/inventory.py b/inventory.py new file mode 100644 index 00000000..21d587ab --- /dev/null +++ b/inventory.py @@ -0,0 +1,6 @@ +import block + +class Inventory: + def __init__(self, *args, **kwargs): + self.hotbar = [block.PORTAL, block.STONE, block.SPRUCE_WOOD_PLANK, block.BIRCH_WOOD_PLANK, block.JUNGLE_WOOD_PLANK, block.ACACIA_WOOD_PLANK, block.DARK_OAK_WOOD_PLANK] + self.index = 0 \ No newline at end of file diff --git a/main.py b/main.py index 6332d97a..707a1786 100644 --- a/main.py +++ b/main.py @@ -1,902 +1,17 @@ -from __future__ import division - -import sys -import math -import random -import time - -from collections import deque -from pyglet import image -from pyglet.gl import * -from pyglet.graphics import TextureGroup -from pyglet.window import key, mouse - -TICKS_PER_SEC = 60 - -# Size of sectors used to ease block loading. -SECTOR_SIZE = 16 - -WALKING_SPEED = 5 -FLYING_SPEED = 15 - -GRAVITY = 20.0 -MAX_JUMP_HEIGHT = 1.0 # About the height of a block. -# To derive the formula for calculating jump speed, first solve -# v_t = v_0 + a * t -# for the time at which you achieve maximum height, where a is the acceleration -# due to gravity and v_t = 0. This gives: -# t = - v_0 / a -# Use t and the desired MAX_JUMP_HEIGHT to solve for v_0 (jump speed) in -# s = s_0 + v_0 * t + (a * t^2) / 2 -JUMP_SPEED = math.sqrt(2 * GRAVITY * MAX_JUMP_HEIGHT) -TERMINAL_VELOCITY = 50 - -PLAYER_HEIGHT = 2 - -if sys.version_info[0] >= 3: - xrange = range - -def cube_vertices(x, y, z, 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 - x-n,y-n,z-n, x+n,y-n,z-n, x+n,y-n,z+n, x-n,y-n,z+n, # bottom - x-n,y-n,z-n, x-n,y-n,z+n, x-n,y+n,z+n, x-n,y+n,z-n, # left - x+n,y-n,z+n, x+n,y-n,z-n, x+n,y+n,z-n, x+n,y+n,z+n, # right - x-n,y-n,z+n, x+n,y-n,z+n, x+n,y+n,z+n, x-n,y+n,z+n, # front - x+n,y-n,z-n, x-n,y-n,z-n, x-n,y+n,z-n, x+n,y+n,z-n, # back - ] - - -def tex_coord(x, y, n=4): - """ Return the bounding vertices of the texture square. - - """ - m = 1.0 / n - dx = x * m - dy = y * m - return dx, dy, dx + m, dy, dx + m, dy + m, dx, dy + m - - -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) - side = tex_coord(*side) - result = [] - result.extend(top) - result.extend(bottom) - result.extend(side * 4) - return result - - -TEXTURE_PATH = 'texture.png' - -GRASS = tex_coords((1, 0), (0, 1), (0, 0)) -SAND = tex_coords((1, 1), (1, 1), (1, 1)) -BRICK = tex_coords((2, 0), (2, 0), (2, 0)) -STONE = tex_coords((2, 1), (2, 1), (2, 1)) - -FACES = [ - ( 0, 1, 0), - ( 0,-1, 0), - (-1, 0, 0), - ( 1, 0, 0), - ( 0, 0, 1), - ( 0, 0,-1), -] - - -def normalize(position): - """ Accepts `position` of arbitrary precision and returns the block - containing that position. - - Parameters - ---------- - position : tuple of len 3 - - Returns - ------- - block_position : tuple of ints of len 3 - - """ - x, y, z = position - x, y, z = (int(round(x)), int(round(y)), int(round(z))) - return (x, y, z) - - -def sectorize(position): - """ Returns a tuple representing the sector for the given `position`. - - Parameters - ---------- - position : tuple of len 3 - - Returns - ------- - sector : tuple of len 3 - - """ - x, y, z = normalize(position) - x, y, z = x // SECTOR_SIZE, y // SECTOR_SIZE, z // SECTOR_SIZE - return (x, 0, z) - - -class Model(object): - - def __init__(self): - - # A Batch is a collection of vertex lists for batched rendering. - self.batch = pyglet.graphics.Batch() - - # A TextureGroup manages an OpenGL texture. - 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. - self.shown = {} - - # Mapping from position to a pyglet `VertextList` for all shown blocks. - self._shown = {} - - # Mapping from sector to a list of positions inside that sector. - self.sectors = {} - - # Simple function queue implementation. The queue is populated with - # _show_block() and _hide_block() calls - self.queue = deque() - - 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 - for x in xrange(-n, n + 1, s): - for z in xrange(-n, n + 1, s): - # create a layer stone an grass everywhere. - self.add_block((x, y - 2, z), GRASS, immediate=False) - self.add_block((x, y - 3, z), STONE, immediate=False) - if x in (-n, n) or z in (-n, n): - # create outer walls. - for dy in xrange(-2, 3): - self.add_block((x, y + dy, z), STONE, immediate=False) - - # generate the hills randomly - o = n - 10 - for _ in xrange(120): - a = random.randint(-o, o) # x position of the hill - b = random.randint(-o, o) # z position of the hill - c = -1 # base of the hill - h = random.randint(1, 6) # height of the hill - s = random.randint(4, 8) # 2 * s is the side length of the hill - d = 1 # how quickly to taper off the hills - t = random.choice([GRASS, SAND, BRICK]) - for y in xrange(c, c + h): - for x in xrange(a - s, a + s + 1): - for z in xrange(b - s, b + s + 1): - if (x - a) ** 2 + (z - b) ** 2 > (s + 1) ** 2: - continue - if (x - 0) ** 2 + (z - 0) ** 2 < 5 ** 2: - continue - self.add_block((x, y, z), t, immediate=False) - s -= d # decrement side length so hills taper off - - 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. 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 - x, y, z = position - dx, dy, dz = vector - previous = None - for _ in xrange(max_distance * m): - key = normalize((x, y, z)) - if key != previous and key in self.world: - return key, previous - previous = key - x, y, z = x + dx / m, y + dy / m, z + dz / m - 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: - return True - return False - - def add_block(self, position, texture, immediate=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 of len 3 - The coordinates of the texture squares. Use `tex_coords()` to - generate. - immediate : bool - Whether or not to draw the block immediately. - - """ - if position in self.world: - self.remove_block(position, immediate) - self.world[position] = texture - self.sectors.setdefault(sectorize(position), []).append(position) - if immediate: - if self.exposed(position): - self.show_block(position) - self.check_neighbors(position) - - def remove_block(self, position, immediate=True): - """ Remove the block at the given `position`. - - Parameters - ---------- - position : tuple of len 3 - The (x, y, z) position of the block to remove. - immediate : bool - Whether or not to immediately remove block from canvas. - - """ - del self.world[position] - self.sectors[sectorize(position)].remove(position) - if immediate: - if position in self.shown: - self.hide_block(position) - 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) - if key not in self.world: - continue - if self.exposed(key): - if key not in self.shown: - self.show_block(key) - else: - if key in self.shown: - self.hide_block(key) - - def show_block(self, position, immediate=True): - """ Show the block at the given `position`. This method assumes the - block has already been added with add_block() - - 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: - self._show_block(position, texture) - else: - 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 - vertex_data = cube_vertices(x, y, z, 0.5) - texture_data = list(texture) - # create vertex list - # FIXME Maybe `add_indexed()` should be used instead - self._shown[position] = self.batch.add(24, GL_QUADS, self.group, - ('v3f/static', vertex_data), - ('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) - else: - 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 - for dx in xrange(-pad, pad + 1): - for dy in [0]: # xrange(-pad, pad + 1): - for dz in xrange(-pad, pad + 1): - if dx ** 2 + dy ** 2 + dz ** 2 > (pad + 1) ** 2: - continue - if before: - x, y, z = before - before_set.add((x + dx, y + dy, z + dz)) - if after: - x, y, z = after - after_set.add((x + dx, y + dy, z + dz)) - show = after_set - before_set - hide = before_set - after_set - for sector in show: - self.show_sector(sector) - for sector in hide: - 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.popleft() - func(*args) - - def process_queue(self): - """ Process the entire queue while taking periodic breaks. This allows - the game loop to run smoothly. The queue contains calls to - _show_block() and _hide_block() so this method should be called if - add_block() or remove_block() was called with immediate=False - - """ - start = time.perf_counter() - while self.queue and time.perf_counter() - start < 1.0 / TICKS_PER_SEC: - self._dequeue() - - def process_entire_queue(self): - """ Process the entire queue with no breaks. - - """ - while self.queue: - self._dequeue() - - -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 - - # Strafing is moving lateral to the direction you are facing, - # e.g. moving to the left or right while continuing to face forward. - # - # 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. Note - # that, perhaps unlike in math class, the y-axis is the vertical axis. - 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. Rotation is in degrees. - # - # The vertical plane rotation ranges from -90 (looking straight down) to - # 90 (looking straight up). The horizontal rotation range is unbounded. - 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 - # TICKS_PER_SEC. This is the main game event loop. - pyglet.clock.schedule_interval(self.update, 1.0 / TICKS_PER_SEC) - - 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 - # y ranges from -90 to 90, or -pi/2 to pi/2, so m ranges from 0 to 1 and - # is 1 when looking ahead parallel to the ground and 0 when looking - # straight up or down. - m = math.cos(math.radians(y)) - # dy ranges from -1 to 1 and is -1 when looking straight down and 1 when - # looking straight up. - dy = math.sin(math.radians(y)) - dx = math.cos(math.radians(x - 90)) * m - dz = math.sin(math.radians(x - 90)) * m - 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)) - y_angle = math.radians(y) - x_angle = math.radians(x + strafe) - if self.flying: - m = math.cos(y_angle) - dy = math.sin(y_angle) - if self.strafe[1]: - # Moving left or right. - dy = 0.0 - m = 1 - if self.strafe[0] > 0: - # Moving backwards. - dy *= -1 - # When you are flying up or down, you have less left and right - # motion. - dx = math.cos(x_angle) * m - dz = math.sin(x_angle) * m - else: - dy = 0.0 - dx = math.cos(x_angle) - dz = math.sin(x_angle) - else: - dy = 0.0 - dx = 0.0 - dz = 0.0 - return (dx, dy, dz) - - def update(self, dt): - """ 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) - if sector != self.sector: - self.model.change_sectors(self.sector, sector) - if self.sector is None: - self.model.process_entire_queue() - self.sector = sector - m = 8 - dt = min(dt, 0.2) - for _ in xrange(m): - 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 = FLYING_SPEED if self.flying else WALKING_SPEED - d = dt * speed # distance covered this tick. - dx, dy, dz = self.get_motion_vector() - # New position in space, before accounting for gravity. - dx, dy, dz = dx * d, dy * d, dz * d - # gravity - if not self.flying: - # Update your vertical speed: if you are falling, speed up until you - # hit terminal velocity; if you are jumping, slow down until you - # start falling. - self.dy -= dt * GRAVITY - self.dy = max(self.dy, -TERMINAL_VELOCITY) - dy += self.dy * dt - # collisions - x, y, z = self.position - x, y, z = self.collide((x + dx, y + dy, z + dz), PLAYER_HEIGHT) - 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. - - """ - # How much overlap with a dimension of a surrounding block you need to - # have to count as a collision. If 0, touching terrain at all counts as - # a collision. If .49, you sink into the ground, as if walking through - # tall grass. If >= .5, you'll fall through the ground. - pad = 0.25 - p = list(position) - np = normalize(position) - for face in FACES: # check all surrounding blocks - for i in xrange(3): # check each dimension independently - if not face[i]: - continue - # How much overlap you have with this dimension. - d = (p[i] - np[i]) * face[i] - if d < pad: - continue - for dy in xrange(height): # check each height - op = list(np) - op[1] -= dy - op[i] += face[i] - if tuple(op) not in self.model.world: - continue - p[i] -= (d - pad) * face[i] - if face == (0, -1, 0) or face == (0, 1, 0): - # You are colliding with the ground or ceiling, so stop - # falling / rising. - self.dy = 0 - break - return tuple(p) - - 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) - if (button == mouse.RIGHT) or \ - ((button == mouse.LEFT) and (modifiers & key.MOD_CTRL)): - # ON OSX, control + left click = right click. - if previous: - self.model.add_block(previous, self.block) - elif button == pyglet.window.mouse.LEFT and block: - texture = self.model.world[block] - if texture != STONE: - self.model.remove_block(block) - else: - 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 - x, y = x + dx * m, y + dy * m - y = max(-90, min(90, y)) - 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: - self.strafe[0] += 1 - elif symbol == key.A: - self.strafe[1] -= 1 - elif symbol == key.D: - self.strafe[1] += 1 - elif symbol == key.SPACE: - if self.dy == 0: - self.dy = JUMP_SPEED - elif symbol == key.ESCAPE: - self.set_exclusive_mouse(False) - elif symbol == key.TAB: - self.flying = not self.flying - elif symbol in self.num_keys: - index = (symbol - self.num_keys[0]) % len(self.inventory) - 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: - self.strafe[0] -= 1 - elif symbol == key.A: - self.strafe[1] += 1 - elif symbol == key.D: - 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 - if self.reticle: - self.reticle.delete() - x, y = self.width // 2, self.height // 2 - n = 10 - self.reticle = pyglet.graphics.vertex_list(4, - ('v2i', (x - n, y, x + n, y, x, y - n, x, y + n)) - ) - - def set_2d(self): - """ Configure OpenGL to draw in 2d. - - """ - width, height = self.get_size() - glDisable(GL_DEPTH_TEST) - viewport = self.get_viewport_size() - glViewport(0, 0, max(1, viewport[0]), max(1, viewport[1])) - glMatrixMode(GL_PROJECTION) - glLoadIdentity() - glOrtho(0, max(1, width), 0, max(1, height), -1, 1) - glMatrixMode(GL_MODELVIEW) - glLoadIdentity() - - def set_3d(self): - """ Configure OpenGL to draw in 3d. - - """ - width, height = self.get_size() - glEnable(GL_DEPTH_TEST) - viewport = self.get_viewport_size() - glViewport(0, 0, max(1, viewport[0]), max(1, viewport[1])) - glMatrixMode(GL_PROJECTION) - glLoadIdentity() - gluPerspective(65.0, width / float(height), 0.1, 60.0) - glMatrixMode(GL_MODELVIEW) - glLoadIdentity() - x, y = self.rotation - glRotatef(x, 0, 1, 0) - glRotatef(-y, math.cos(math.radians(x)), 0, math.sin(math.radians(x))) - x, y, z = self.position - glTranslatef(-x, -y, -z) - - def on_draw(self): - """ Called by pyglet to draw the canvas. - - """ - self.clear() - self.set_3d() - glColor3d(1, 1, 1) - self.model.batch.draw() - self.draw_focused_block() - self.set_2d() - self.draw_label() - 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: - x, y, z = block - vertex_data = cube_vertices(x, y, z, 0.51) - glColor3d(0, 0, 0) - glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) - pyglet.graphics.draw(24, GL_QUADS, ('v3f/static', vertex_data)) - 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, - len(self.model._shown), len(self.model.world)) - 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. - - """ - # Enable fog. Fog "blends a fog color with each rasterized pixel fragment's - # post-texturing color." - glEnable(GL_FOG) - # Set the fog color. - glFogfv(GL_FOG_COLOR, (GLfloat * 4)(0.5, 0.69, 1.0, 1)) - # Say we have no preference between rendering speed and quality. - glHint(GL_FOG_HINT, GL_DONT_CARE) - # Specify the equation used to compute the blending factor. - glFogi(GL_FOG_MODE, GL_LINEAR) - # How close and far away fog starts and ends. The closer the start and end, - # the denser the fog in the fog range. - glFogf(GL_FOG_START, 20.0) - glFogf(GL_FOG_END, 60.0) - - -def setup(): - """ Basic OpenGL configuration. - - """ - # Set the color of "clear", i.e. the sky, in rgba. - glClearColor(0.5, 0.69, 1.0, 1) - # Enable culling (not rendering) of back-facing facets -- facets that aren't - # visible to you. - glEnable(GL_CULL_FACE) - # Set the texture minification/magnification function to GL_NEAREST (nearest - # in Manhattan distance) to the specified texture coordinates. GL_NEAREST - # "is generally faster than GL_LINEAR, but it can produce textured images - # with sharper edges because the transition between texture elements is not - # as smooth." - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) - setup_fog() - +# from window import Window +# from pyglet import image +# from pyglet.gl import * # noqa: F403 +# from pyglet.graphics import TextureGroup +import window +from pyglet.gl import * # noqa: F403 def main(): - window = Window(width=800, height=600, caption='Pyglet', resizable=True) + userWindow = window.Window(width=1280, height=720, caption='Py Minecraft', resizable=True) # Hide the mouse cursor and prevent the mouse from leaving the window. - window.set_exclusive_mouse(True) - setup() - pyglet.app.run() - + userWindow.set_exclusive_mouse(False) + userWindow.setup() + pyglet.app.run() # noqa: F405 if __name__ == '__main__': main() + diff --git a/mmath.py b/mmath.py new file mode 100644 index 00000000..ed1c11b0 --- /dev/null +++ b/mmath.py @@ -0,0 +1,31 @@ +from opensimplex import OpenSimplex +import random + +gen = OpenSimplex(random.randrange(1, 10000)) +def noise(nx, ny): + # Rescale from -1.0:+1.0 to 0.0:1.0 + return gen.noise2(nx, ny) / 2.0 + 0.5 + +def normalize(position): + """ Accepts `position` of arbitrary precision and returns the block + containing that position. + + Parameters + ---------- + position : tuple of len 3 + + Returns + ------- + block_position : tuple of ints of len 3 + """ + x, y, z = position + x, y, z = (int(round(x)), int(round(y)), int(round(z))) + return (x, y, z) + +def clamp(number, min, max): + if number < min: + return min + elif number > max: + return max + else: + return number \ No newline at end of file diff --git a/model.py b/model.py new file mode 100644 index 00000000..6b4274a2 --- /dev/null +++ b/model.py @@ -0,0 +1,503 @@ +from __future__ import division + +import sys +import random +import time +import block +import mmath + +from collections import deque +from pyglet import image +from pyglet.gl import * # noqa: F403 +from pyglet.graphics import TextureGroup + + + +if sys.version_info[0] >= 3: + xrange = range + +# Size of sectors used to ease block loading. +SECTOR_SIZE = 16 + +TICKS_PER_SEC = 60 + +def cube_vertices(x, y, z, 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 + x-n,y-n,z-n, x+n,y-n,z-n, x+n,y-n,z+n, x-n,y-n,z+n, # bottom + x-n,y-n,z-n, x-n,y-n,z+n, x-n,y+n,z+n, x-n,y+n,z-n, # left + x+n,y-n,z+n, x+n,y-n,z-n, x+n,y+n,z-n, x+n,y+n,z+n, # right + x-n,y-n,z+n, x+n,y-n,z+n, x+n,y+n,z+n, x-n,y+n,z+n, # front + x+n,y-n,z-n, x-n,y-n,z-n, x-n,y+n,z-n, x+n,y+n,z-n, # back + ] + +TEXTURE_PATH = 'Textures.png' + +FACES = [ + ( 0, 1, 0), + ( 0,-1, 0), + (-1, 0, 0), + ( 1, 0, 0), + ( 0, 0, 1), + ( 0, 0,-1), + ] + +def sectorize(position): + """ Returns a tuple representing the sector for the given `position`. + + Parameters + ---------- + position : tuple of len 3 + + Returns + ------- + sector : tuple of len 3 + + """ + x, y, z = mmath.normalize(position) + x, y, z = x // SECTOR_SIZE, y // SECTOR_SIZE, z // SECTOR_SIZE + return (x, 0, z) + +class Model(object): + + def __init__(self): + # A Batch is a collection of vertex lists for batched rendering. + self.batch = pyglet.graphics.Batch() # noqa: F405 + + # A TextureGroup manages an OpenGL texture. + 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. + self.shown = {} + + # Mapping from position to a pyglet `VertextList` for all shown blocks. + self._shown = {} + + # Mapping from sector to a list of positions inside that sector. + self.sectors = {} + + # Simple function queue implementation. The queue is populated with + # _show_block() and _hide_block() calls + self.queue = deque() + + #A constant running list for placed teleport blocks in the world and their positions + self.teleport_blocks = {} + self.count = 0 + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) # noqa: F405 + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) # noqa: F405 + + self._initialize() + + def _initialize(self): + """ Initialize the world by placing all the blocks. + + """ + n = 160 # 1/2 width and length of world + h = 0 # y-level for bottom layer (bedrock) + s = 1 # step size + y = 0 # initial y height + f = 4 # frequency + a = (1, 0.5, 0.334) # amplitude layers + exp = 2 # elevation exponent + adj = 1.2 # adjustment to pre-power elevation value + + elevation = [] + for l in xrange(n*2): + elevation.append([0] * n*2) + for w in xrange(n): + nx = w/n - 0.5 + ny = l/n - 0.5 + e = a[0] * mmath.noise(f * nx, f * ny) + e += a[1] * mmath.noise((f * 2) * nx + 5.3, (f * 2) * ny + 9.1) + e += a[2] * mmath.noise((f * 4) * nx + 17.8, (f * 4) * ny + 23.5) + e = e / (a[0] + a[1] + a[2]) + elevation[l][w] = pow(e * adj, exp) + + + for x in xrange(0, n, s): + for z in xrange(0, n, s): + y = int(elevation[z][x]*10) + if y <= 0: + y = 1 + block_texture = self.set_environment(elevation[z][x]) + self.add_block((x, y, z), block_texture, immediate=False) + + # Add tree + if block_texture == block.GRASS_BLOCK and random.random() < 0.01: + self.grow_tree((x, y, z)) + elif block_texture == block.SAND and random.random() < 0.005: + self.grow_cactus((x, y, z)) + + # Add bottom of the map + self.add_block((x, -h, z), block.BEDROCK, immediate=True) + + if y > 1: + # Fill below the surface + if block_texture == block.STONE: + for dy in xrange(h+1, y): + self.add_block((x, dy, z), block.STONE, immediate=False) + else: + midpoint = int(y / 2) + for dy in xrange(h+1, y): + if dy >= midpoint: + self.add_block((x, dy, z), block.DIRT, immediate=False) + else: + self.add_block((x, dy, z), block.STONE, immediate=False) + + # create outer walls. + if x in (0, n-1) or z in (0, n-1): + for dy in xrange(-5, 18): + self.add_block((x, y + dy, z), block.STONE_SLAB, immediate=False) + + def set_environment(self, elevation): + block_texture = block.STONE + if (elevation < 0.1): + block_texture = block.WATER_BLOCK + elif (elevation < 0.2): + block_texture = block.SAND + elif (elevation < 0.6): + block_texture = block.GRASS_BLOCK + return block_texture + + def grow_tree(self, position): + y = random.randrange(3, 6) + for ty in xrange(1, y): + self.add_block((position[0], position[1] + ty, position[2]), block.OAK_LOG, immediate=False) + + for tx in xrange(-2, 3, 1): + for tz in xrange(-2, 3, 1): + if tx in (1, -1) or tz in (1, -1): + self.add_block((position[0]+tx, position[1] + y, position[2]+tz), block.OAK_LEAF, immediate=False) + elif tx == 0 or tz == 0: + self.add_block((position[0]+tx, position[1] + y, position[2]+tz), block.OAK_LEAF, immediate=False) + self.add_block((position[0]+tx, position[1] + y + 1, position[2]+tz), block.OAK_LEAF, immediate=False) + + for tx in xrange(-1, 2, 1): + for tz in xrange(-1, 2, 1): + self.add_block((position[0]+tx, position[1] + y+2, position[2]+tz), block.OAK_LEAF, immediate=False) + if tx == 0 or tz == 0: + self.add_block((position[0]+tx, position[1] + y+3, position[2]+tz), block.OAK_LEAF, immediate=False) + + def grow_cactus(self, position): + for ty in xrange(1, random.randrange(2, 5)): + self.add_block((position[0], position[1] + ty, position[2]), block.CACTUS, immediate=False) + + 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: + return True + return False + + def exposed_faces(self, position): + """ Returns any exposed faces. + """ + faces = [] + + x, y, z = position + for dx, dy, dz in FACES: + if (x + dx, y + dy, z + dz) not in self.world: + faces.append((x + dx, y + dy, z + dz)) + return faces + + + def add_block(self, position, texture, immediate=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 of len 3 + The coordinates of the texture squares. Use `tex_coords()` to + generate. + immediate : bool + Whether or not to draw the block immediately. + + """ + if (texture == block.NONE): + return + if position in self.world: + self.remove_block(position, immediate) + self.world[position] = texture + self.sectors.setdefault(sectorize(position), []).append(position) + if texture == block.PORTAL: + self.teleport_blocks[self.count] = position + self.count += 1 + print("portal added to list at" + (str)(position) + (str)(self.count)) + if immediate: + if self.exposed(position): + self.show_block(position) + self.check_neighbors(position) + + def remove_block(self, position, immediate=True): + """ Remove the block at the given `position`. + + Parameters + ---------- + position : tuple of len 3 + The (x, y, z) position of the block to remove. + immediate : bool + Whether or not to immediately remove block from canvas. + + """ + del self.world[position] + self.sectors[sectorize(position)].remove(position) + for index, valueP in list(self.teleport_blocks.items()): + if valueP == position: #is value correct position of block to be removed + del self.teleport_blocks[index] + self.count -= 1 + print("teleporter removed at" + (str)(position) + (str)(self.count)) + break + + #Fix indexes of remaining items + self.teleport_blocks = {i: pos for i, pos in enumerate(self.teleport_blocks.values())} + + if immediate: + if position in self.shown: + self.hide_block(position) + 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) + if key not in self.world: + continue + if self.exposed(key): + if key not in self.shown: + self.show_block(key) + else: + if key in self.shown: + self.hide_block(key) + + def show_block(self, position, immediate=True): + """ Show the block at the given `position`. This method assumes the + block has already been added with add_block() + + 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: + self._show_block(position, texture) + else: + 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 + vertex_data = cube_vertices(x, y, z, 0.5) + texture_data = list(texture) + # create vertex list + # FIXME Maybe `add_indexed()` should be used instead + self._shown[position] = self.batch.add(24, GL_QUADS, self.group, + ('v3f/static', vertex_data), + ('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) + else: + 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 + for dx in xrange(-pad, pad + 1): + for dy in [0]: # xrange(-pad, pad + 1): + for dz in xrange(-pad, pad + 1): + if dx ** 2 + dy ** 2 + dz ** 2 > (pad + 1) ** 2: + continue + if before: + x, y, z = before + before_set.add((x + dx, y + dy, z + dz)) + if after: + x, y, z = after + after_set.add((x + dx, y + dy, z + dz)) + show = after_set - before_set + hide = before_set - after_set + for sector in show: + self.show_sector(sector) + for sector in hide: + self.hide_sector(sector) + + def collide(self, player, position): + """ 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. + + """ + # How much overlap with a dimension of a surrounding block you need to + # have to count as a collision. If 0, touching terrain at all counts as + # a collision. If .49, you sink into the ground, as if walking through + # tall grass. If >= .5, you'll fall through the ground. + pad = 0.0 + p = list(position) + np = mmath.normalize(position) + + for face in FACES: # check all surrounding blocks + for i in xrange(3): # check each dimension independently + if not face[i]: + continue + + # How much overlap you have with this dimension. + d = (p[i] - np[i]) * face[i] + if d < pad: + continue + + for dy in xrange(player.PLAYER_HEIGHT): # check each height + op = list(np) + op[1] -= dy + op[i] += face[i] + if tuple(op) not in self.world: + continue + + p[i] -= (d - pad) * face[i] + if face == (0, -1, 0) or face == (0, 1, 0): + # You are colliding with the ground or ceiling, so stop + # falling / rising. + player.velocity[1] = 0 + break + for dx,dy,dz in FACES: + check_position = (p[0] + dx, p[1]-1, p[2] + dz) + if check_position in self.teleport_blocks.values(): + self.teleport_player(player, check_position) + return player.position # return new position + + return tuple(p) + + def teleport_player(self, player, c_position): #teleports to next block in list + if not self.teleport_blocks: + return # No teleport blocks exist + + # Find the current index of the block + current_index = None + for key, value in self.teleport_blocks.items(): + if value == c_position: + current_index = key + break + + if current_index is not None: + next_index = (current_index + 1) % len(self.teleport_blocks) # Cycle to next position + next_position = self.teleport_blocks[next_index] + player.position = (next_position[0] + 1, next_position[1] + 2,next_position[2]) # Teleport player (offset by 1 block on x and y) + print(f"Teleported to " +(str)(next_position)) + + 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.popleft() + func(*args) + + def process_queue(self): + """ Process the entire queue while taking periodic breaks. This allows + the game loop to run smoothly. The queue contains calls to + _show_block() and _hide_block() so this method should be called if + add_block() or remove_block() was called with immediate=False + + """ + start = time.perf_counter() + while self.queue and time.perf_counter() - start < 1.0 / TICKS_PER_SEC: + self._dequeue() + + def process_entire_queue(self): + """ Process the entire queue with no breaks. + + """ + while self.queue: + self._dequeue() \ No newline at end of file diff --git a/player.py b/player.py new file mode 100644 index 00000000..db3afa8e --- /dev/null +++ b/player.py @@ -0,0 +1,353 @@ +from __future__ import division + +import sys +import mmath +import math +import inventory +import block +from model import Model +from states import GameState + +from pyglet.gl import * # noqa: F403 +from pyglet.window import key, mouse + +if sys.version_info[0] >= 3: + xrange = range + +class Player(): + def __init__(self, model: Model, window, statemachine, position = (80, 10, 80), *args, **kwargs): + self.WALKING_SPEED = 5 + self.FLYING_SPEED = 15 + + self.CurrentSpeed = 0 + + self.GRAVITY = 20.0 + self.MAX_JUMP_HEIGHT = 1.0 # About the height of a block. + # To derive the formula for calculating jump speed, first solve + # v_t = v_0 + a * t + # for the time at which you achieve maximum height, where a is the acceleration + # due to gravity and v_t = 0. This gives: + # t = - v_0 / a + # Use t and the desired MAX_JUMP_HEIGHT to solve for v_0 (jump speed) in + # s = s_0 + v_0 * t + (a * t^2) / 2 + self.JUMP_SPEED = math.sqrt(2 * self.GRAVITY * self.MAX_JUMP_HEIGHT) + self.TERMINAL_VELOCITY = 50 + + self.PLAYER_HEIGHT = 2 + + self.inventory = inventory.Inventory() + self.model = model + self.window = window + self.state_machine = statemachine + self.window.push_handlers(self) + + # When flying gravity has no effect and speed is increased. + self.flying = False + + # Current (x, y, z) position in the world, specified with floats. Note + # that, perhaps unlike in math class, the y-axis is the vertical axis. + self.position = position + + # 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] + + # 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. Rotation is in degrees. + # + # The vertical plane rotation ranges from -90 (looking straight down) to + # 90 (looking straight up). The horizontal rotation range is unbounded. + self.rotation = (0, 0) + + # Whether or not the window exclusively captures the mouse. + self.exclusive = True + + # Velocity + self.velocity = [0, 0, 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] + + # Running + self.running = False + + def hit_test(self, 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. 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 + x, y, z = self.position + dx, dy, dz = vector + previous = None + for _ in xrange(max_distance * m): + key = mmath.normalize((x, y, z)) + if key != previous and key in self.model.world: + return key, previous + previous = key + x, y, z = x + dx / m, y + dy / m, z + dz / m + return None, None + + def get_sight_vector(self): + """ Returns the current line of sight vector indicating the direction + the player is looking. + + """ + + x, y = self.rotation + # y ranges from -90 to 90, or -pi/2 to pi/2, so m ranges from 0 to 1 and + # is 1 when looking ahead parallel to the ground and 0 when looking + # straight up or down. + m = math.cos(math.radians(y)) + # dy ranges from -1 to 1 and is -1 when looking straight down and 1 when + # looking straight up. + dy = math.sin(math.radians(y)) + dx = math.cos(math.radians(x - 90)) * m + dz = math.sin(math.radians(x - 90)) * m + 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. + + """ + #print(self.strafe) + if any(self.strafe): + x, y = self.rotation + strafe = math.degrees(math.atan2(*self.strafe)) + y_angle = math.radians(y) + x_angle = math.radians(x + strafe) + if self.flying: + m = math.cos(y_angle) + dy = math.sin(y_angle) + if self.strafe[1]: + # Moving left or right. + dy = 0.0 + m = 1 + if self.strafe[0] > 0: + # Moving backwards. + dy *= -1 + # When you are flying up or down, you have less left and right + # motion. + dx = math.cos(x_angle) * m + dz = math.sin(x_angle) * m + else: + dy = 0.0 + dx = math.cos(x_angle) + dz = math.sin(x_angle) + else: + dy = 0.0 + dx = 0.0 + dz = 0.0 + return (dx, dy, dz) + + + + 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.state_machine.state == GameState.PLAYING): + if self.exclusive: + vector = self.get_sight_vector() + selectedBlock, previous = self.hit_test(vector) + if (button == mouse.RIGHT) or ((button == mouse.LEFT) and (modifiers & key.MOD_CTRL)): + # ON OSX, control + left click = right click. + if previous: + self.model.add_block(previous, self.inventory.hotbar[self.inventory.index]) + elif button == pyglet.window.mouse.LEFT and selectedBlock: # noqa: F405 + texture = self.model.world[selectedBlock] + if texture != block.BEDROCK: + self.model.remove_block(selectedBlock) + elif button == mouse.MIDDLE: + if previous: + texture = self.model.world[selectedBlock] + self.inventory.hotbar[self.inventory.index] = texture + else: + self.window.set_exclusive_mouse(True) + if self.state_machine.state == GameState.PAUSED: + # Pass the mouse press event only to widgets in the pause menu batch + for widget in self.window.gui_widgets: + if hasattr(widget, '_batch') and widget._batch == self.window.pause_menu_batch: + widget.on_mouse_press(x, y, button, modifiers) + elif self.state_machine.state == GameState.MAIN_MENU: + # Pass the mouse press event only to widgets in the main menu batch + for widget in self.window.gui_widgets: + if hasattr(widget, '_batch') and widget._batch == self.window.main_menu_batch: + widget.on_mouse_press(x, y, button, modifiers) + + 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.state_machine.state == GameState.PLAYING): + if self.exclusive: + m = 0.15 + x, y = self.rotation + x, y = x + dx * m, y + dy * m + y = max(-90, min(90, y)) + self.rotation = (x, y) + if self.state_machine.state == GameState.PAUSED: + # Pass the mouse motion event to the GUI widgets + for widget in self.window.gui_widgets: + widget.on_mouse_motion(x, y, dx, dy) + if self.state_machine.state == GameState.MAIN_MENU: + # Pass the mouse motion event to the GUI widgets + for widget in self.window.gui_widgets: + widget.on_mouse_motion(x, y, dx, dy) + + 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 = self.FLYING_SPEED if self.flying else self.WALKING_SPEED + d = dt * speed * 2 if self.running else dt * speed # distance covered this tick. + dx, dy, dz = self.get_motion_vector() + # New position in space, before accounting for gravity. + dx, dy, dz = dx * d, dy * d, dz * d + # gravity + if not self.flying: + # Update your vertical speed: if you are falling, speed up until you + # hit terminal velocity; if you are jumping, slow down until you + # start falling. + self.velocity[1] -= dt * self.GRAVITY + self.velocity[1] = max(self.velocity[1], -self.TERMINAL_VELOCITY) + dy += self.velocity[1] * dt + else: + dy += self.velocity[1] * dt + # collisions + x, y, z = self.position + x, y, z = self.model.collide(self, (x + dx, y + dy, z + dz)) + self.position = (x, y, z) + + 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: + self.strafe[0] += 1 + elif symbol == key.A: + self.strafe[1] -= 1 + elif symbol == key.D: + self.strafe[1] += 1 + elif symbol == key.SPACE: + if self.velocity[1] == 0: + self.velocity[1] = self.JUMP_SPEED + elif symbol == key.LSHIFT: + if self.flying: + self.velocity[1] = -self.JUMP_SPEED + elif symbol == key.LCTRL: + self.running = True + elif symbol == key.ESCAPE: + self.window.set_exclusive_mouse(False) + elif symbol == key.TAB: + self.flying = not self.flying + elif symbol in self.num_keys: + index = (symbol - self.num_keys[0]) % len(self.inventory.hotbar) + self.inventory.index = index + + if self.state_machine.state == GameState.PLAYING: + if symbol == key.ESCAPE: + self.window.set_exclusive_mouse(False) + self.state_machine.change_state(GameState.PAUSED) + return pyglet.event.EVENT_HANDLED + if symbol == key.C: + self.window.set_exclusive_mouse(True) + self.state_machine.change_state(GameState.COMMAND_LINE) + elif self.state_machine.state == GameState.PAUSED: + if symbol == key.ESCAPE: + self.window.set_exclusive_mouse(True) + self.state_machine.change_state(GameState.PLAYING) + return pyglet.event.EVENT_HANDLED + elif self.state_machine.state == GameState.COMMAND_LINE: + if symbol == key.BACKSPACE: + self.command_text = self.window.command_text[:-1] + elif symbol == key.ENTER: + self.window.process_command(self.window.command_text) + self.state_machine.change_state(GameState.PLAYING) + return pyglet.event.EVENT_HANDLED + + 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: + self.strafe[0] -= 1 + elif symbol == key.A: + self.strafe[1] += 1 + elif symbol == key.D: + self.strafe[1] -= 1 + elif symbol == key.LCTRL: + self.running = False + elif symbol == key.SPACE: + if self.flying: + self.velocity[1] = 0 + elif symbol == key.LSHIFT: + if self.flying: + self.velocity[1] = 0 \ No newline at end of file diff --git a/states.py b/states.py new file mode 100644 index 00000000..4aeebe74 --- /dev/null +++ b/states.py @@ -0,0 +1,34 @@ +from enum import Enum, auto + +class GameState(Enum): + MAIN_MENU = auto() + PLAYING = auto() + PAUSED = auto() + INVENTORY = auto() + GAME_OVER = auto() + COMMAND_LINE = auto() + +class StateMachine: + def __init__(self, initial_state): + self.state = initial_state + self.states = {} + + def add_state(self, state, enter_callback=None, update_callback=None, exit_callback=None): + self.states[state] = { + 'enter': enter_callback, + 'update': update_callback, + 'exit': exit_callback + } + + def change_state(self, new_state): + if self.state in self.states and self.states[self.state]['exit']: + self.states[self.state]['exit']() + + self.state = new_state + + if self.state in self.states and self.states[self.state]['enter']: + self.states[self.state]['enter']() + + def update(self, dt): + if self.state in self.states and self.states[self.state]['update']: + self.states[self.state]['update'](dt) \ No newline at end of file diff --git a/texture.png b/texture.png index 9d05a7e2..d1462796 100644 Binary files a/texture.png and b/texture.png differ diff --git a/window.py b/window.py new file mode 100644 index 00000000..b24a9ecf --- /dev/null +++ b/window.py @@ -0,0 +1,549 @@ +from __future__ import division + +import math +import model +import player +import random +from states import GameState, StateMachine + +#from collections import deque +from pyglet.gl import * # noqa: F403 + + +class Window(pyglet.window.Window): + + def __init__(self, *args, **kwargs): + super(Window, self).__init__(*args, **kwargs) + + # Initialize the state machine + self.state_machine = StateMachine(GameState.MAIN_MENU) + self.command_text = "" + self.player_position = (0, 0, 0) # Placeholder for player position + + self.command_text = "" + self.player_position = (0, 0, 0) # Placeholder for player position + + # Add states with their respective callbacks + self.state_machine.add_state( + GameState.MAIN_MENU, + enter_callback=self.enter_main_menu, + update_callback=self.update_main_menu + ) + self.state_machine.add_state( + GameState.PLAYING, + enter_callback=self.enter_playing, + update_callback=self.update_playing + ) + self.state_machine.add_state( + GameState.PAUSED, + enter_callback=self.enter_paused, + update_callback=self.update_paused + ) + self.state_machine.add_state( + GameState.COMMAND_LINE, + enter_callback=self.enter_command_mode, + exit_callback=self.exit_command_mode + ) + self.state_machine.add_state( + GameState.COMMAND_LINE, + enter_callback=self.enter_command_mode, + exit_callback=self.exit_command_mode + ) + + # Instance of the model that handles the world. + self.model = model.Model() + + # Instance of the player that interacts with the world. + self.player = player.Player(self.model, self, self.state_machine) + + # Which sector the player is currently in. + self.sector = None + + # The crosshairs at the center of the screen. + self.reticle = None + + self.gui_widgets = [] + + # The label that is displayed in the top left of the canvas. + self.label = pyglet.text.Label('', font_name='Arial', font_size=18, # noqa: F405 + x=10, y=self.height - 10, anchor_x='left', anchor_y='top', + color=(0, 0, 0, 255)) + + self.command_prompt_label = pyglet.text.Label( + "Command: ", + font_name="Arial", + font_size=18, + x=10, y=10, + anchor_x="left", anchor_y="bottom", + color=(255, 255, 255, 255) + ) + + self.create_main_menu() + + # This call schedules the `update()` method to be called + # TICKS_PER_SEC. This is the main game event loop. + pyglet.clock.schedule_interval(self.update, 1.0 / model.TICKS_PER_SEC) # noqa: F405 + + def update(self, dt): + """ This method is scheduled to be called repeatedly by the pyglet + clock. + + Parameters + ---------- + dt : float + The change in time since the last call. + + """ + self.state_machine.update(dt) # Update the current state + + # Existing game logic + self.model.process_queue() + sector = model.sectorize(self.player.position) + if sector != self.sector: + self.model.change_sectors(self.sector, sector) + if self.sector is None: + self.model.process_entire_queue() + self.sector = sector + m = 8 + dt = min(dt, 0.2) + for _ in model.xrange(m): + self.player.update(dt / m) + + 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 on_resize(self, width, height): + """ Called when the window is resized to a new `width` and `height`. + + """ + # label + self.label.y = height - 10 + # reticle + if self.reticle: + self.reticle.delete() + x, y = self.width // 2, self.height // 2 + n = 10 + self.reticle = pyglet.graphics.vertex_list(4, + ('v2i', (x - n, y, x + n, y, x, y - n, x, y + n)) + ) + + def set_2d(self): + """ Configure OpenGL to draw in 2d. + + """ + width, height = self.get_size() + glDisable(GL_DEPTH_TEST) # noqa: F405 + viewport = self.get_viewport_size() + glViewport(0, 0, max(1, viewport[0]), max(1, viewport[1])) # noqa: F405 + glMatrixMode(GL_PROJECTION) + glLoadIdentity() + glOrtho(0, max(1, width), 0, max(1, height), -1, 1) + glMatrixMode(GL_MODELVIEW) + glLoadIdentity() + + def set_3d(self): + """ Configure OpenGL to draw in 3d. + + """ + width, height = self.get_size() + glEnable(GL_DEPTH_TEST) + viewport = self.get_viewport_size() + glViewport(0, 0, max(1, viewport[0]), max(1, viewport[1])) + glMatrixMode(GL_PROJECTION) + glLoadIdentity() + gluPerspective(65.0, width / float(height), 0.1, 60.0) + glMatrixMode(GL_MODELVIEW) + glLoadIdentity() + x, y = self.player.rotation + glRotatef(x, 0, 1, 0) + glRotatef(-y, math.cos(math.radians(x)), 0, math.sin(math.radians(x))) + x, y, z = self.player.position + glTranslatef(-x, -y, -z) + + def on_draw(self): + """ Called by pyglet to draw the canvas. + + """ + self.clear() + self.set_3d() + glColor3d(1, 1, 1) # noqa: F405 + self.model.batch.draw() + self.draw_focused_block() + self.set_2d() + self.draw_label() + self.draw_reticle() + # Draw the background image first + if self.state_machine.state == GameState.MAIN_MENU: + self.background_sprite.draw() + # Draw the UI elements (buttons, labels, etc.) + if self.state_machine.state == GameState.MAIN_MENU: + self.main_menu_batch.draw() + elif self.state_machine.state == GameState.PAUSED: + self.pause_menu_batch.draw() + elif self.state_machine.state == GameState.COMMAND_LINE: + self.command_batch.draw() + + elif self.state_machine.state == GameState.COMMAND_LINE: + self.command_prompt_label.text = 'Command: ' + self.command_text + self.command_batch.draw() + self.command_prompt_label.draw() + + def draw_focused_block(self): + """ Draw black edges around the block that is currently under the + crosshairs. + + """ + vector = self.player.get_sight_vector() + block = self.player.hit_test(vector)[0] + if block: + x, y, z = block + vertex_data = model.cube_vertices(x, y, z, 0.51) + glColor3d(0, 0, 0) + glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) + pyglet.graphics.draw(24, GL_QUADS, ('v3f/static', vertex_data)) # noqa: F405 + glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) # noqa: F405 + + def draw_label(self): + """ Draw the label in the top left of the screen. + + """ + x, y, z = self.player.position + self.label.text = '%02d (%.2f, %.2f, %.2f) %d / %d' % ( + pyglet.clock.get_fps(), x, y, z, + len(self.model._shown), len(self.model.world)) + 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(self): + """ Configure the OpenGL fog properties. + """ + # Enable fog. Fog "blends a fog color with each rasterized pixel fragment's + # post-texturing color." + glEnable(GL_FOG) # noqa: F405 + # Set the fog color. + glFogfv(GL_FOG_COLOR, (GLfloat * 4)(0.5, 0.69, 1.0, 1)) # noqa: F405 + # Say we have no preference between rendering speed and quality. + glHint(GL_FOG_HINT, GL_DONT_CARE) # noqa: F405 + # Specify the equation used to compute the blending factor. + glFogi(GL_FOG_MODE, GL_LINEAR) # noqa: F405 + # How close and far away fog starts and ends. The closer the start and end, + # the denser the fog in the fog range. + glFogf(GL_FOG_START, 20.0) # noqa: F405 + glFogf(GL_FOG_END, 60.0) # noqa: F405 + + def setup(self): + """ Basic OpenGL configuration. + """ + # Set the color of "clear", i.e. the sky, in rgba. + glClearColor(0.5, 0.69, 1.0, 1) # noqa: F405 + # Enable culling (not rendering) of back-facing facets -- facets that aren't + # visible to you. + glEnable(GL_CULL_FACE) # noqa: F405 + # Set the texture minification/magnification function to GL_NEAREST (nearest + # in Manhattan distance) to the specified texture coordinates. GL_NEAREST + # "is generally faster than GL_LINEAR, but it can produce textured images + # with sharper edges because the transition between texture elements is not + # as smooth." + self.setup_fog() + + def enter_main_menu(self): + print("Entering Main Menu") + self.create_main_menu() + self.set_exclusive_mouse(False) + # Unregister pause menu buttons (if necessary) + for widget in self.gui_widgets: + if widget._batch == self.pause_menu_batch: + widget.enabled = False + + def update_main_menu(self, dt): + # Handle input for the main menu (e.g., start game, quit) + pass + + def enter_playing(self): + print("Entering Playing State") + self.set_exclusive_mouse(True) + + def update_playing(self, dt): + # Handle game logic (e.g., player movement, block placement) + pass + + def enter_paused(self): + self.create_pause_menu() + # Unregister main menu buttons (if necessary) + for widget in self.gui_widgets: + if widget._batch == self.main_menu_batch: + widget.enabled = False + + def update_paused(self, dt): + # Handle input for the pause menu (e.g., resume, quit) + pass + + def create_pause_menu(self): + # Create a container for the pause menu + self.pause_menu_batch = pyglet.graphics.Batch() + + window_size = self.get_size() + + # Create images for the button states + resume_depressed_image = pyglet.image.SolidColorImagePattern((100, 100, 100, 255)).create_image(150, 50) # Gray + resume_pressed_image = pyglet.image.SolidColorImagePattern((150, 150, 150, 255)).create_image(150, 50) # Light gray + quit_depressed_image = pyglet.image.SolidColorImagePattern((100, 100, 100, 255)).create_image(275, 50) # Gray + quit_pressed_image = pyglet.image.SolidColorImagePattern((150, 150, 150, 255)).create_image(275, 50) # Light gray + + # Create a semi-transparent background + self.background = pyglet.shapes.Rectangle( + x=0, + y=0, + width=window_size[0], + height=window_size[1], + color=(0, 0, 0), + batch=self.pause_menu_batch + ) + self.background.opacity = 25 + + # Create "PAUSED" label + self.paused_label = pyglet.text.Label( + "PAUSED", + font_name="Arial", + font_size=36, + x=window_size[0] // 2, + y=window_size[1] // 2 + 100, + anchor_x="center", + anchor_y="center", + batch=self.pause_menu_batch + ) + + # Create "Resume" button + self.resume_button = pyglet.gui.PushButton( + x=window_size[0] // 2 - 75, + y=window_size[1] // 2, + pressed=resume_pressed_image, + depressed=resume_depressed_image, + batch=self.pause_menu_batch + ) + self.resume_button_label = pyglet.text.Label( + "Resume", + font_name="Arial", + font_size=24, + x=self.resume_button.x + (self.resume_button.width // 2), + y=self.resume_button.y + (self.resume_button.height // 2), + anchor_x="center", + anchor_y="center", + batch=self.pause_menu_batch + ) + self.resume_button.on_press = self.resume_button_pressed # Set the callback + + # Create "Quit" button + self.quittomain_button = pyglet.gui.PushButton( + x=window_size[0] / 2 - 135, + y=window_size[1] / 2 - 100, + pressed=quit_pressed_image, + depressed=quit_depressed_image, + batch=self.pause_menu_batch, + ) + self.quittomain_button_label = pyglet.text.Label( + "Quit to Main Menu", + font_name="Arial", + font_size=24, + x=self.quittomain_button.x + (self.quittomain_button.width // 2), + y=self.quittomain_button.y + (self.quittomain_button.height // 2), + anchor_x="center", + anchor_y="center", + batch=self.pause_menu_batch + ) + self.quittomain_button.on_press = self.quittomain_button_pressed # Set the callback + + # Add buttons to the GUI widgets list + self.gui_widgets.extend([self.quittomain_button, self.resume_button]) + + def resume_button_pressed(self): + print("Resume button pressed") + self.state_machine.change_state(GameState.PLAYING) + + def quittomain_button_pressed(self): + self.state_machine.change_state(GameState.MAIN_MENU) + + def create_main_menu(self): + # Create a container for the pause menu + self.main_menu_batch = pyglet.graphics.Batch() + + window_size = self.get_size() + + # Create a semi-transparent background + self.background_image = pyglet.image.load('MainMenu_background.jpg') + self.background_sprite = pyglet.sprite.Sprite(self.background_image) + self.background_sprite.scale_x = self.width / self.background_image.width + self.background_sprite.scale_y = self.height / self.background_image.height + + # Create images for the button states + resume_depressed_image = pyglet.image.SolidColorImagePattern((100, 100, 100, 255)).create_image(150, 50) # Gray + resume_pressed_image = pyglet.image.SolidColorImagePattern((150, 150, 150, 255)).create_image(150, 50) # Light gray + quit_depressed_image = pyglet.image.SolidColorImagePattern((100, 100, 100, 255)).create_image(275, 50) # Gray + quit_pressed_image = pyglet.image.SolidColorImagePattern((150, 150, 150, 255)).create_image(275, 50) # Light gray + + self.splash_Text_label = pyglet.text.Label( + "Now in Python!!!", + font_name="Arial", + font_size=36, + x=window_size[0] // 2, + y=window_size[1] // 2 + 100, + anchor_x="center", + anchor_y="center", + batch=self.main_menu_batch + ) + + self.play_button = pyglet.gui.PushButton( + x=window_size[0] // 2 - 75, + y=window_size[1] // 2, + pressed=resume_pressed_image, + depressed=resume_depressed_image, + batch=self.main_menu_batch + ) + self.play_button_label = pyglet.text.Label( + "Play", + font_name="Arial", + font_size=24, + x=self.play_button.x + (self.play_button.width // 2), + y=self.play_button.y + (self.play_button.height // 2), + anchor_x="center", + anchor_y="center", + batch=self.main_menu_batch + ) + self.play_button.on_press = self.play_button_pressed # Set the callback + + # Create "Quit" button + self.quit_button = pyglet.gui.PushButton( + x=window_size[0] / 2 - 135, + y=window_size[1] / 2 - 100, + pressed=quit_pressed_image, + depressed=quit_depressed_image, + batch=self.main_menu_batch, + ) + self.quit_button_label = pyglet.text.Label( + "Quit to Desktop", + font_name="Arial", + font_size=24, + x=self.quit_button.x + (self.quit_button.width // 2), + y=self.quit_button.y + (self.quit_button.height // 2), + anchor_x="center", + anchor_y="center", + batch=self.main_menu_batch + ) + self.quit_button.on_press = self.quit_button_pressed # Set the callback + + # Add buttons to the GUI widgets list + self.gui_widgets.extend([self.quit_button, self.play_button]) + + def play_button_pressed(self): + print("Resume button pressed") + self.state_machine.change_state(GameState.PLAYING) + + def quit_button_pressed(self): + pyglet.app.exit() + + def enter_command_mode(self): + self.command_text = "" + self.create_command_line() + print("Entered command mode. Type a command and press Enter.") + + def exit_command_mode(self): + print("Exited command mode.") + + def create_command_line(self): + # Create a container for the pause menu + self.command_batch = pyglet.graphics.Batch() + window_size = self.get_size() + + # Create a semi-transparent background + self.background = pyglet.shapes.Rectangle( + x=0, + y=0, + width=window_size[0], + height=window_size[1]/8, + color=(0, 0, 0), + batch=self.command_batch + ) + self.background.opacity = 25 + + self.command_prompt_label = pyglet.text.Label( + "Command: " + self.command_text, + font_name="Arial", + font_size=18, + x=10, y=10, + anchor_x="left", anchor_y="bottom", + color=(255, 255, 255, 255), + batch= self.command_batch + ) + + def on_text(self, text): + """Handles text input in command mode.""" + if self.state_machine.state == GameState.COMMAND_LINE: + self.command_text += text + print(self.command_text) + + def process_command(self, command): + """Processes player commands.""" + parts = command.split() + if len(parts) == 4 and parts[0].lower() == "teleport": + try: + x, y, z = float(parts[1]), float(parts[2]), float(parts[3]) + self.player.position = (x, y, z) # Move player + print(f"Teleported to ({x}, {y}, {z})") + except ValueError: + print("Invalid coordinates!") + else: + print("Invalid command. Use: teleport x y z") + + def enter_command_mode(self): + self.command_text = "" + self.create_command_line() + print("Entered command mode. Type a command and press Enter.") + + def exit_command_mode(self): + print("Exited command mode.") + + def create_command_line(self): + # Create a container for the pause menu + self.command_batch = pyglet.graphics.Batch() + window_size = self.get_size() + + # Create a semi-transparent background + self.background = pyglet.shapes.Rectangle( + x=0, + y=0, + width=window_size[0], + height=window_size[1]/8, + color=(0, 0, 0), + batch=self.command_batch + ) + self.background.opacity = 25 + + + def on_text(self, text): + """Handles text input in command mode.""" + if self.state_machine.state == GameState.COMMAND_LINE: + self.command_text += text + print(self.command_text) + + def process_command(self, command): + """Processes player commands.""" + parts = command.split() + if len(parts) == 4 and parts[0].lower() == "teleport": + try: + x, y, z = float(parts[1]), float(parts[2]), float(parts[3]) + self.player.position = (x, y, z) # Move player + print(f"Teleported to ({x}, {y}, {z})") + except ValueError: + print("Invalid coordinates!") + else: + print("Invalid command. Use: teleport x y z") \ No newline at end of file