Python实现我的世界小游戏源代码
程序员文章站
2022-03-02 11:37:00
我的世界小游戏使用方法:移动前进:w,后退:s,向左:a,向右:d,环顾四周:鼠标,跳起:空格键,切换飞行模式:tab;选择建筑材料砖:1,草:2,沙子:3,删除建筑:鼠标左键单击,创建建筑块:鼠标右...
我的世界小游戏使用方法:
移动
前进:w,后退:s,向左:a,向右:d,环顾四周:鼠标,跳起:空格键,切换飞行模式:tab;
选择建筑材料
砖:1,草:2,沙子:3,删除建筑:鼠标左键单击,创建建筑块:鼠标右键单击
esc退出程序。
完整程序包请通过文末地址下载,程序运行截图如下:
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 lenth 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.time()- 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 图片 # 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=1800, height=1600, 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()
我的世界小游戏python源代码包下载地址:
链接: https://pan.baidu.com/s/1gkaherzaenmrxgsu-a4ppg
提取码: rya9
到此这篇关于python实现我的世界小游戏源代码的文章就介绍到这了,更多相关python小游戏源代码内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
上一篇: jsp的九大内置对象深入讲解
下一篇: 用python将pdf转化为有声读物
推荐阅读
-
python自动登录12306并自动点击验证码完成登录的实现源代码
-
python的小游戏---欢乐世界(骰子猜大小游戏)
-
微软将开放《我的世界》的AI开发平台源代码
-
Python实现的摇骰子猜大小功能小游戏示例
-
python+pygame实现坦克大战小游戏的示例代码(可以自定义子弹速度)
-
Python实现扑克24点小游戏 ,从此我就没输过
-
python爬取酷我音乐(收费的也可以实现)
-
《我的世界》Python编程入门(1)Minecraft(我的世界)Python编程环境搭建
-
1秒内通关扫雷?他创造属于自己的世界记录!Python实现自动扫雷
-
荐 通过python我实现了照片转化为动漫模式,媳妇儿再也不用愁没有好看的头像了~