我的世界电脑板源代码.java
- 格式:doc
- 大小:12.00 KB
- 文档页数:2
我的世界代码大全在《我的世界》这款游戏中,代码是游戏的基本构成部分之一,它可以帮助玩家实现各种各样的功能和效果。
本文将为大家介绍一些常用的《我的世界》代码,希望能够对大家有所帮助。
1. 刷怪代码。
在《我的世界》中,玩家可以通过输入指定的代码来刷出各种怪物。
例如,输入“/summon zombie”可以召唤出僵尸,输入“/summon skeleton”可以召唤出骷髅。
这些代码可以帮助玩家在游戏中获得更多的挑战和乐趣。
2. 召唤物品代码。
除了可以召唤怪物,玩家还可以通过代码来召唤各种各样的物品。
例如,输入“/give @p diamond 64”可以给予玩家64个钻石,输入“/give @p iron_sword”可以给予玩家一把铁剑。
这些代码可以帮助玩家在游戏中获得更多的资源和装备。
3. 游戏模式切换代码。
在《我的世界》中,有不同的游戏模式供玩家选择,包括生存模式、创造模式和冒险模式等。
玩家可以通过输入指定的代码来切换游戏模式。
例如,输入“/gamemode creative”可以将游戏模式切换为创造模式,输入“/gamemode survival”可以将游戏模式切换为生存模式。
这些代码可以帮助玩家在游戏中更灵活地切换不同的模式。
4. 时间控制代码。
在《我的世界》中,时间是一个重要的元素,它会影响到游戏中的各种活动。
玩家可以通过输入指定的代码来控制游戏中的时间。
例如,输入“/time set day”可以将时间设置为白天,输入“/time set night”可以将时间设置为黑夜。
这些代码可以帮助玩家更好地控制游戏中的时间流逝。
5. 游戏规则设置代码。
除了以上介绍的代码之外,玩家还可以通过输入指定的代码来设置游戏中的各种规则。
例如,输入“/gamerule keepInventory true”可以设置玩家死亡后不掉落物品,输入“/gamerule doDaylightCycle false”可以设置游戏中的时间暂停不流逝。
Python实现我的世界⼩游戏源代码我的世界⼩游戏使⽤⽅法:移动前进:W,后退:S,向左:A,向右:D,环顾四周:⿏标,跳起:空格键,切换飞⾏模式:Tab;选择建筑材料砖:1,草:2,沙⼦:3,删除建筑:⿏标左键单击,创建建筑块:⿏标右键单击ESC退出程序。
完整程序包请通过⽂末地址下载,程序运⾏截图如下:from __future__ import divisionimport sysimport mathimport randomimport timefrom collections import dequefrom pyglet import imagefrom pyglet.gl import *from pyglet.graphics import TextureGroupfrom pyglet.window import key, mouseTICKS_PER_SEC = 60# Size of sectors used to ease block loading.SECTOR_SIZE = 16WALKING_SPEED = 5FLYING_SPEED = 15GRAVITY = 20.0MAX_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) / 2JUMP_SPEED = math.sqrt(2 * GRAVITY * MAX_JUMP_HEIGHT)TERMINAL_VELOCITY = 50PLAYER_HEIGHT = 2if sys.version_info[0] >= 3:xrange = range""" 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, # topx-n,y-n,z-n, x+n,y-n,z-n, x+n,y-n,z+n, x-n,y-n,z+n, # bottomx-n,y-n,z-n, x-n,y-n,z+n, x-n,y+n,z+n, x-n,y+n,z-n, # leftx+n,y-n,z+n, x+n,y-n,z-n, x+n,y+n,z-n, x+n,y+n,z+n, # rightx-n,y-n,z+n, x+n,y-n,z+n, x+n,y+n,z+n, x-n,y+n,z+n, # frontx+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 / ndx = x * mdy = y * mreturn dx, dy, dx + m, dy, dx + m, dy + m, dx, dy + mdef 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 resultTEXTURE_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 blockcontaining that position.Parameters----------position : tuple of len 3Returns-------block_position : tuple of ints of len 3"""x, y, z = positionx, 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 3Returns-------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() callsself.queue = deque()self._initialize()def _initialize(self):""" Initialize the world by placing all the blocks.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 randomlyo = n - 10for _ in xrange(120):a = random.randint(-o, o) # x position of the hillb = random.randint(-o, o) # z position of the hillc = -1 # base of the hillh = random.randint(1, 6) # height of the hills = random.randint(4, 8) # 2 * s is the side length of the hilld = 1 # how quickly to taper off the hillst = 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:continueif (x - 0) ** 2 + (z - 0) ** 2 < 5 ** 2:continueself.add_block((x, y, z), t, immediate=False)s -= d # decrement side lenth so hills taper offdef hit_test(self, position, vector, max_distance=8):""" Line of sight search from current position. If a block isintersected it is returned, along with the block previously in the lineof sight. If no block is found, return None, None.Parameters----------position : tuple of len 3The (x, y, z) position to check visibility from.vector : tuple of len 3The line of sight vector.max_distance : intHow many blocks away to search for a hit."""m = 8x, y, z = positiondx, dy, dz = vectorprevious = Nonefor _ in xrange(max_distance * m):key = normalize((x, y, z))if key != previous and key in self.world:return key, previousprevious = keyx, y, z = x + dx / m, y + dy / m, z + dz / mreturn None, Nonedef exposed(self, position):""" Returns False is given `position` is surrounded on all 6 sides byblocks, True otherwise."""x, y, z = positionfor dx, dy, dz in FACES:if (x + dx, y + dy, z + dz) not in self.world:return Truereturn Falsedef add_block(self, position, texture, immediate=True):""" Add a block with the given `texture` and `position` to the world.Parameters----------position : tuple of len 3The (x, y, z) position of the block to add.texture : list of len 3The coordinates of the texture squares. Use `tex_coords()` togenerate.immediate : boolWhether or not to draw the block immediately."""if position in self.world:self.remove_block(position, immediate)self.world[position] = textureself.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 3The (x, y, z) position of the block to remove.immediate : boolWhether 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 visualstate 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 = positionfor dx, dy, dz in FACES:key = (x + dx, y + dy, z + dz)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 3The (x, y, z) position of the block to show.immediate : boolWhether or not to show the block immediately."""texture = self.world[position]self.shown[position] = textureif 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 3The (x, y, z) position of the block to show.texture : list of len 3The coordinates of the texture squares. Use `tex_coords()` togenerate."""x, y, z = positionvertex_data = cube_vertices(x, y, z, 0.5)texture_data = list(texture)# create vertex list# FIXME Maybe `add_indexed()` should be used insteadself._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 3The (x, y, z) position of the block to hide.immediate : boolWhether 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 aredrawn 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 acontiguous x, y sub-region of world. Sectors are used to speed up world rendering."""before_set = set()after_set = set()pad = 4for 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:continueif before:x, y, z = beforebefore_set.add((x + dx, y + dy, z + dz))if after:x, y, z = afterafter_set.add((x + dx, y + dy, z + dz))show = after_set - before_sethide = before_set - after_setfor 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))""" 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 allowsthe game loop to run smoothly. The queue contains calls to_show_block() and _hide_block() so this method should be called ifadd_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.bel = bel('', 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 Falsethe game will ignore the mouse."""super(Window, self).set_exclusive_mouse(exclusive)self.exclusive = exclusivedef get_sight_vector(self):""" Returns the current line of sight vector indicating the directionthe 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)) * mdz = math.sin(math.radians(x - 90)) * mreturn (dx, dy, dz)def get_motion_vector(self):""" Returns the current motion vector indicating the velocity of theplayer.Returns-------vector : tuple of len 3Tuple containing the velocity in x, y, and z respectively.if any(self.strafe):x, y = self.rotationstrafe = 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.0m = 1if 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) * mdz = math.sin(x_angle) * melse:dy = 0.0dx = math.cos(x_angle)dz = math.sin(x_angle)else:dy = 0.0dx = 0.0dz = 0.0return (dx, dy, dz)def update(self, dt):""" This method is scheduled to be called repeatedly by the pygletclock.Parameters----------dt : floatThe 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 = sectorm = 8dt = 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 : floatThe change in time since the last call."""# walkingspeed = FLYING_SPEED if self.flying else WALKING_SPEEDd = 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# gravityif 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 * GRAVITYself.dy = max(self.dy, -TERMINAL_VELOCITY)dy += self.dy * dt# collisionsx, y, z = self.positionx, 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 3The (x, y, z) position to check for collisions at.height : int or floatThe height of the player.Returns-------position : tuple of len 3The 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.25p = list(position)np = normalize(position)for face in FACES: # check all surrounding blocksfor i in xrange(3): # check each dimension independentlyif not face[i]:continue# How much overlap you have with this dimension.d = (p[i] - np[i]) * face[i]if d < pad:continuefor dy in xrange(height): # check each heightop = list(np)op[1] -= dyop[i] += face[i]if tuple(op) not in self.model.world:continuep[i] -= (d - pad) * face[i]if face == (0, -1, 0) or face == (0, 1, 0):# You are colliding with the ground or ceiling, so stopbreakreturn 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 : intThe coordinates of the mouse click. Always center of the screen if the mouse is captured.button : intNumber representing mouse button that was clicked. 1 = left button, 4 = right button.modifiers : intNumber 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 : intThe coordinates of the mouse click. Always center of the screen if the mouse is captured.dx, dy : floatThe movement of the mouse."""if self.exclusive:m = 0.15x, y = self.rotationx, y = x + dx * m, y + dy * my = 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 keymappings.Parameters----------symbol : intNumber representing the key that was pressed.modifiers : intNumber representing any modifying keys that were pressed."""if symbol == key.W:self.strafe[0] -= 1elif symbol == key.S:self.strafe[0] += 1elif symbol == key.A:self.strafe[1] -= 1elif symbol == key.D:self.strafe[1] += 1elif symbol == key.SPACE:if self.dy == 0:self.dy = JUMP_SPEEDelif symbol == key.ESCAPE:self.set_exclusive_mouse(False)elif symbol == key.TAB:self.flying = not self.flyingelif 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 keymappings.Parameters----------symbol : intNumber representing the key that was pressed.modifiers : intNumber representing any modifying keys that were pressed."""if symbol == key.W:self.strafe[0] += 1elif symbol == key.S:self.strafe[0] -= 1elif symbol == key.A:self.strafe[1] += 1elif symbol == key.D:self.strafe[1] -= 1def on_resize(self, width, height):""" Called when the window is resized to a new `width` and `height`."""# labelbel.y = height - 10# reticleif self.reticle:self.reticle.delete()x, y = self.width // 2, self.height // 2n = 10self.reticle = pyglet.graphics.vertex_list(4,('v2i', (x - n, y, x + n, y, x, y - n, x, y + n)))"""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.rotationglRotatef(x, 0, 1, 0)glRotatef(-y, math.cos(math.radians(x)), 0, math.sin(math.radians(x)))x, y, z = self.positionglTranslatef(-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 thecrosshairs."""vector = self.get_sight_vector()block = self.model.hit_test(self.position, vector)[0]if block:x, y, z = blockvertex_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.positionbel.text = '%02d (%.2f, %.2f, %.2f) %d / %d' % (pyglet.clock.get_fps(), x, y, z,len(self.model._shown), len(self.model.world))bel.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源代码包下载地址:提取码: rya9到此这篇关于Python实现我的世界⼩游戏源代码的⽂章就介绍到这了,更多相关Python⼩游戏源代码内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!。
贪吃蛇源代码将Location、LocationRO、SnakeFrame、SnakeModel、SnakePanel放到命名为snake的文件夹里,主函数MainApp放到外面运行主函数即可实现。
主函数package snake;import javax.swing.*;import snake.*;public class MainApp {public static void main(String[] args) {JFrame.setDefaultLookAndFeelDecorated(true);SnakeFrame frame=new SnakeFrame();frame.setSize(350,350);frame.setResizable(false);frame.setLocation(330,220);frame.setTitle("贪吃蛇");frame.setV isible(true);}}package snake;public class Location {private int x;private int y;Location(int x,int y){this.x=x;this.y=y;}int getX(){return x;}int getY(){return y;}void setX(int x){this.x=x;}void setY(int y){this.y=y;}public boolean equalOrRev(Location e){return ((e.getX()==getX())&&(e.getY()==getY()))||((e.getX()==getX())&&(e.getY()==-1*getY()))||((e.getX()==-1*getX())&&(e.getY()==getY()));}public boolean equals(Location e){return(e.getX()==getX())&&(e.getY()==getY());}public boolean reverse(Location e){return ((e.getX()==getX())&&(e.getY()==-1*getY()))||((e.getX()==-1*getX())&&(e.getY()==getY()));}}package snake;public class LocationRO{private int x;private int y;LocationRO(int x,int y){this.x=x;this.y=y;}int getX(){return x;}int getY(){return y;}public boolean equalOrRev(LocationRO e){return ((e.getX()==getX())&&(e.getY()==getY()))||((e.getX()==getX())&&(e.getY()==-1*getY()))||((e.getX()==-1*getX())&&(e.getY()==getY()));}public boolean equals(LocationRO e){return(e.getX()==getX())&&(e.getY()==getY());}public boolean reverse(LocationRO e){return ((e.getX()==getX())&&(e.getY()==-1*getY()))||((e.getX()==-1*getX())&&(e.getY()==getY()));}}package snake;import java.awt.*;import java.awt.event.*;import javax.swing.*;class SnakeFrame extends JFrame implements ActionListener{final SnakePanel p=new SnakePanel(this);JMenuBar menubar=new JMenuBar();JMenu fileMenu=new JMenu("文件");JMenuItem newgameitem=new JMenuItem("开始");JMenuItem stopitem=new JMenuItem("暂停");JMenuItem runitem=new JMenuItem("继续");JMenuItem exititem=new JMenuItem("退出");//"设置"菜单JMenu optionMenu=new JMenu("设置");//等级选项ButtonGroup groupDegree = new ButtonGroup();JRadioButtonMenuItem oneItem= new JRadioButtonMenuItem("初级");JRadioButtonMenuItem twoItem= new JRadioButtonMenuItem("中级");JRadioButtonMenuItem threeItem= new JRadioButtonMenuItem("高级");JMenu degreeMenu=new JMenu("等级");JMenu helpMenu=new JMenu("帮助");JMenuItem helpitem=new JMenuItem("操作指南");final JCheckBoxMenuItem showGridItem = new JCheckBoxMenuItem("显示网格");JLabel scorelabel;public JTextField scoreField;private long speedtime=200;private String helpstr = "游戏说明:\n1 :方向键控制蛇移动的方向."+"\n2 :单击菜单'文件->开始'开始游戏."+"\n3 :单击菜单'文件->暂停'或者单击键盘空格键暂停游戏."+"\n4 :单击菜单'文件->继续'继续游戏."+"\n5 :单击菜单'设置->等级'可以设置难度等级."+"\n6 :单击菜单'设置->显示网格'可以设置是否显示网格."+ "\n7 :红色为食物,吃一个得10分同时蛇身加长."+"\n8 :蛇不可以出界或自身相交,否则结束游戏.";SnakeFrame(){setJMenuBar(menubar);fileMenu.add(newgameitem);fileMenu.add(stopitem);fileMenu.add(runitem);fileMenu.add(exititem);menubar.add(fileMenu);oneItem.setSelected(true);groupDegree.add(oneItem);groupDegree.add(twoItem);groupDegree.add(threeItem);degreeMenu.add(oneItem);degreeMenu.add(twoItem);degreeMenu.add(threeItem);optionMenu.add(degreeMenu);// 风格选项showGridItem.setSelected(true);optionMenu.add(showGridItem);menubar.add(optionMenu);helpMenu.add(helpitem);menubar.add(helpMenu);Container contentpane=getContentPane();contentpane.setLayout(new FlowLayout());contentpane.add(p);scorelabel=new JLabel("得分: ");scoreField=new JTextField("0",15);scoreField.setEnabled(false);scoreField.setHorizontalAlignment(0);JPanel toolPanel=new JPanel();toolPanel.add(scorelabel);toolPanel.add(scoreField);contentpane.add(toolPanel);oneItem.addActionListener(this);twoItem.addActionListener(this);threeItem.addActionListener(this);newgameitem.addActionListener(this);stopitem.addActionListener(this);runitem.addActionListener(this);exititem.addActionListener(this);helpitem.addActionListener(this);showGridItem.addActionListener(this);}public void actionPerformed(ActionEvent e){try{if(e.getSource()==helpitem){JOptionPane.showConfirmDialog(p,helpstr,"操纵说明",JOptionPane.PLAIN_MESSAGE);}else if(e.getSource()==exititem)System.exit(0);else if(e.getSource()==newgameitem)p.newGame(speedtime);else if(e.getSource()==stopitem)p.stopGame();else if(e.getSource()==runitem)p.returnGame();else if(e.getSource()==showGridItem){if(!showGridItem.isSelected()){p.setBackground(Color.lightGray);}else{p.setBackground(Color.darkGray);}}else if(e.getSource()==oneItem) speedtime=200;else if(e.getSource()==twoItem) speedtime=100;else if(e.getSource()==threeItem) speedtime=50;}catch(Exception ee){ee.printStackTrace();}}}package snake;import java.util.*;import javax.swing.JOptionPane;public class SnakeModel {private int rows,cols;//行列数private Location snakeHead,runingDiriction;//运行方向private LocationRO[][] locRO;//LocationRO类数组private LinkedList snake,playBlocks;//蛇及其它区域块private LocationRO snakeFood;//目标食物private int gameScore=0; //分数private boolean AddScore=false;//加分// 获得蛇头public LocationRO getSnakeHead(){return (LocationRO)(snake.getLast());}//蛇尾public LocationRO getSnakeTail(){return (LocationRO)(snake.getFirst());}//运行路线public Location getRuningDiriction(){return runingDiriction;}//获得蛇实体区域public LinkedList getSnake(){return snake;}//其他区域public LinkedList getOthers(){return playBlocks;}//获得总分public int getScore(){return gameScore;}//获得增加分数public boolean getAddScore(){return AddScore;}//设置蛇头方向private void setSnakeHead(Location snakeHead){ this.snakeHead=snakeHead;}//获得目标食物public LocationRO getSnakeFood(){return snakeFood;}//随机设置目标食物private void setSnakeFood(){snakeFood=(LocationRO)(playBlocks.get((int)(Math.random()*playBlocks.size()))); }//移动private void moveTo(Object a,LinkedList fromlist,LinkedList tolist){fromlist.remove(a);tolist.add(a);}//初始设置public void init(){playBlocks.clear();snake.clear();gameScore=0;for(int i=0;i<rows;i++){for(int j=0;j<cols;j++){playBlocks.add(locRO[i][j]);}}//初始化蛇的形状for(int i=4;i<7;i++){moveTo(locRO[4][i],playBlocks,snake);}//蛇头位置snakeHead=new Location(4,6);//设置随机块snakeFood=new LocationRO(0,0);setSnakeFood();//初始化运动方向runingDiriction=new Location(0,1);}//Snake构造器public SnakeModel(int rows1,int cols1){rows=rows1;cols=cols1;locRO=new LocationRO[rows][cols];snake=new LinkedList();playBlocks=new LinkedList();for(int i=0;i<rows;i++){for(int j=0;j<cols;j++){locRO[i][j]=new LocationRO(i,j);}}init();}/**定义布尔型move方法,如果运行成功则返回true,否则返回false*参数direction是Location类型,*direction 的值:(-1,0)表示向上;(1,0)表示向下;*(0,-1)表示向左;(0,1)表示向右;**/public boolean move(Location direction){//判断设定的方向跟运行方向是不是相反if (direction.reverse(runingDiriction)){snakeHead.setX(snakeHead.getX()+runingDiriction.getX());snakeHead.setY(snakeHead.getY()+runingDiriction.getY());}else{snakeHead.setX(snakeHead.getX()+direction.getX());snakeHead.setY(snakeHead.getY()+direction.getY());}//如果蛇吃到了目标食物try{if ((snakeHead.getX()==snakeFood.getX())&&(snakeHead.getY()==snakeFood.getY())){moveTo(locRO[snakeHead.getX()][snakeHead.getY()],playBlocks,snake);setSnakeFood();gameScore+=10;AddScore=true;}else{AddScore=false;//是否出界if((snakeHead.getX()<rows)&&(snakeHead.getY()<cols)&&(snakeHead.getX()>=0&&(snak eHead.getY()>=0))){//如果不出界,判断是否与自身相交if(snake.contains(locRO[snakeHead.getX()][snakeHead.getY()])){//如果相交,结束游戏JOptionPane.showMessageDialog(null, "Game Over!", "游戏结束",RMA TION_MESSAGE);return false;}else{//如果不相交,就把snakeHead加到snake里面,并且把尾巴移出moveTo(locRO[snakeHead.getX()][snakeHead.getY()],playBlocks,snake);moveTo(snake.getFirst(),snake,playBlocks);}}else{//出界,游戏结束JOptionPane.showMessageDialog(null, "Game Over!", "游戏结束", RMA TION_MESSAGE);return false;}}}catch(ArrayIndexOutOfBoundsException e){return false;}//设置运行方向if (!(direction.reverse(runingDiriction)||direction.equals(runingDiriction))){runingDiriction.setX(direction.getX());runingDiriction.setY(direction.getY());}return true;}}package snake;import javax.swing.*;import java.awt.*;import java.awt.event.*;import java.util.*;public class SnakePanel extends JPanel implements Runnable,KeyListener{JFrame parent=new JFrame();private int row=20; //网格行数private int col=30; //列数private JPanel[][] gridsPanel; //面板网格private Location direction;//方向定位private SnakeModel snake; //贪吃蛇private LinkedList snakeBody; //蛇的身体private LinkedList otherBlocks; //其他区域private LocationRO snakeHead; //蛇的头部private LocationRO snakeFood; //目标食物private Color bodyColor=Color.orange;//蛇的身体颜色private Color headColor=Color.black; //蛇的头部颜色private Color foodColor=Color.red; //目标食物颜色private Color othersColor=Color.lightGray;//其他区域颜色private int gameScore=0; //总分private long speed; //速度(难度设置)private boolean AddScore; //加分private Thread t; //线程private boolean isEnd; //暂停private static boolean notExit;// 构造器,初始化操作public SnakePanel(SnakeFrame parent){this.parent=parent;gridsPanel=new JPanel[row][col];otherBlocks=new LinkedList();snakeBody=new LinkedList();snakeHead=new LocationRO(0,0);snakeFood=new LocationRO(0,0);direction=new Location(0,1);// 布局setLayout(new GridLayout(row,col,1,1));for(int i=0;i<row;i++){for(int j=0;j<col;j++){gridsPanel[i][j]=new JPanel();gridsPanel[i][j].setBackground(othersColor);add(gridsPanel[i][j]);}}addKeyListener(this);}// 开始游戏public void newGame(long speed){this.speed=speed;if (notExit) {snake.init();}else{snake=new SnakeModel(row,col);notExit=true;t=new Thread(this);t.start();}requestFocus();direction.setX(0);direction.setY(1);gameScore=0;updateTextFiled(""+gameScore);isEnd=false;}// 暂停游戏public void stopGame(){requestFocus();isEnd=true;}// 继续public void returnGame(){requestFocus();isEnd=false;}// 获得总分public int getGameScore(){return gameScore;}//更新总分private void updateTextFiled(String str){((SnakeFrame)parent).scoreField.setText(str); }//更新各相关单元颜色private void updateColors(){// 设定蛇身颜色snakeBody=snake.getSnake();Iterator i =snakeBody.iterator();while(i.hasNext()){LocationRO t=(LocationRO)(i.next());gridsPanel[t.getX()][t.getY()].setBackground(bodyColor);}//设定蛇头颜色snakeHead=snake.getSnakeHead();gridsPanel[snakeHead.getX()][snakeHead.getY()].setBackground(headColor);//设定背景颜色otherBlocks=snake.getOthers();i =otherBlocks.iterator();while(i.hasNext()){LocationRO t=(LocationRO)(i.next());gridsPanel[t.getX()][t.getY()].setBackground(othersColor);}//设定临时块的颜色snakeFood=snake.getSnakeFood();gridsPanel[snakeFood.getX()][snakeFood.getY()].setBackground(foodColor); }public boolean isFocusTraversable(){return true;}//实现Runnable接口public void run(){while(true){try{Thread.sleep(speed);}catch (InterruptedException e){}if(!isEnd){isEnd=!snake.move(direction);updateColors();if(snake.getAddScore()){gameScore+=10;updateTextFiled(""+gameScore);}}}}//实现KeyListener接口public void keyPressed(KeyEvent event){int keyCode = event.getKeyCode();if(notExit){if (keyCode == KeyEvent.VK_LEFT) { //向左direction.setX(0);direction.setY(-1);}else if (keyCode == KeyEvent.VK_RIGHT) { //向右direction.setX(0);direction.setY(1);}else if (keyCode == KeyEvent.VK_UP) { //向上direction.setX(-1);direction.setY(0);}else if (keyCode == KeyEvent.VK_DOWN) { //向下direction.setX(1);direction.setY(0);}else if (keyCode == KeyEvent.VK_SPACE){ //空格键isEnd=!isEnd;}}}public void keyReleased(KeyEvent event){}public void keyTyped(KeyEvent event){}}。
Java教程Java的诞⽣Java:由Sun Microsystems公司于1995年5⽉推出的Java程序设计语⾔和Java平台的总称。
Java语⾔是⼀种可以撰写跨平台应⽤软件的⾯向对象的程序设计语⾔,由当时任职太阳微系统的詹姆斯·⾼斯林(James Gosling)等⼈于1990年代初开发,它最初被命名为Oak。
Java伴随着互联⽹的迅猛发展⽽发展,逐渐成为重要的⽹络编程语⾔。
更多请参考Java历史什么是JavaJava简介Java是⼀种⼴泛使⽤的计算机编程语⾔,拥有跨平台、⾯向对象、泛型编程的特性,⼴泛应⽤于企业级Web应⽤开发和移动应⽤开发。
任职于太阳微系统的詹姆斯·⾼斯林等⼈于1990年代初开发Java语⾔的雏形,最初被命名为Oak,⽬标设置在家⽤电器等⼩型系统的编程语⾔,应⽤在电视机、电话、闹钟、烤⾯包机等家⽤电器的控制和通信。
由于这些智能化家电的市场需求没有预期的⾼,Sun公司放弃了该项计划。
随着1990年代互联⽹的发展,Sun公司看见Oak在互联⽹上应⽤的前景,于是改造了Oak,于1995年5⽉以Java的名称正式发布。
Java伴随着互联⽹的迅猛发展⽽发展,逐渐成为重要的⽹络编程语⾔。
Java编程语⾔的风格⼗分接近C++语⾔。
继承了C++语⾔⾯向对象技术的核⼼,舍弃了容易引起错误的指针,以引⽤取代;移除了C++中的运算符重载和多重继承特性,⽤接⼝取代;增加垃圾回收器功能。
在Java SE 1.5版本中引⼊了泛型编程、类型安全的枚举、不定长参数和⾃动装/拆箱特性。
太阳微系统对Java语⾔的解释是:“Java编程语⾔是个简单、⾯向对象、分布式、解释性、健壮、安全与系统⽆关、可移植、⾼性能、多线程和动态的语⾔”Java不同于⼀般的编译语⾔或解释型语⾔。
它⾸先将源代码编译成字节码,再依赖各种不同平台上的虚拟机来解释执⾏字节码,从⽽具有“⼀次编写,到处运⾏”的跨平台特性。
我的世界java版有一键生成基础小屋和怪物磨床模组
摘要:
1.介绍《我的世界》Java版的特点
2.介绍一键生成基础小屋功能
3.介绍怪物磨床模组功能
4.总结一键生成基础小屋和怪物磨床模组的优势
正文:
《我的世界》Java版是一款备受欢迎的沙盒游戏,它拥有丰富的游戏内容和高度自由的玩法。
为了方便玩家快速开始游戏,游戏内提供了一键生成基础小屋和怪物磨床模组的功能。
首先,我们来介绍一下一键生成基础小屋功能。
在《我的世界》Java版中,玩家可以通过开启这个功能,快速生成一个包含基本生活设施的小屋。
这个功能可以帮助玩家在游戏初期就拥有一个安全、舒适的生活环境,节省了玩家自己搭建房屋的时间和精力。
同时,这个功能还可以让玩家更快地进入探险和资源收集阶段,丰富游戏体验。
其次,我们来介绍一下怪物磨床模组功能。
在《我的世界》Java版中,怪物磨床是一种可以将怪物掉落的物品进行分类和整理的设备。
而怪物磨床模组则进一步扩展了这个功能,使得玩家可以更方便地管理和使用怪物掉落的物品。
通过使用怪物磨床模组,玩家可以更快地获取所需资源,提高游戏效率。
总之,一键生成基础小屋和怪物磨床模组功能为玩家提供了便利,使玩家能够更快速地进入游戏的核心玩法,享受更多的游戏乐趣。
第一个Java 文件:package ziaoA; import import import import j ava•awt•Color;java•awt•ReadiessException; j ava•awt•event•KeyEvent; j ava•awt•event•KeyListener ;import import importimport import j avaz•swing•Imageicon; j avax•swing•JFrame; j avax•swing•JLabel; j avax•swing•JOptionPane; j avax•swing•JPanel; public JPanel〃匸人 JLabel class GameFrame extends JFrame { zhuobu = new JPanel(); worker = null;//箱r JLabelbox = null; //目的地 JLabel goal = null; JLabel[] walls = null; public static final int SPEED = 12; //设s 图片人小 int imgSize = 48; public void setImgSize (int imgSize){ this •imgSize = imgSize; public GameFrame(String title) throws HeadlessException { super {title); //构造方法中调用本类的其它方法 this •initContentPane(); this •addKeyListener (new KeyListener() { //键盘按下爭件 public void keyPressed(KeyEvent e) { //E2.5]使匸人可以移动 int 次Speed = 0, ySpeed = 0; switch (e•getKeyCode()){case KeyEvent• VK LEFT :xSpeed = -SPEED;worker . seticon (new Imageicon {'* image / workerUp • gif'*)); break;case KeyEvent• VK」工GHT :xSpeed = SPEED;worker.seticon(new Imageicon("image/workerUp•gif")); break;case KeyEvent•VK_UP :ySpeed = -SPEED;worker . seticon (new Imageicon (image/workerUp . gif ")); break;case KeyEvent•VK_DOWN :ySpeed = SPEED;worker . seticon (new Imageicon {'* image/workerUp • gif'*)); break;default:return;worker • setBounds (x-zorker • getX () + KSpeed, worker • getY () + ySpeed, worker•getWidth(), worker•getHeight());//[2.7]判断匸人是否撞到墙壁for (int i = 0; i < walls.length; i++) {if (worker•getBounds{).intersects(walls[i].getBounds())) { worker • setBounds (x-zorker • getX () - :龙Speed, worker • getY () - ySpeed, worker•getWidth(), worker•getHeight());//E3.2]使I:人可以推动箱rif (worker•getBounds()•intersects(box•getBounds())){box•setBounds(box•getX() + xSpeed, box•getY () + ySpeed, box•getWidth(), box•getHeight());//[3.3]判断箱r是否撞到墙壁for (int i = 0; i < walls.length; i++) {if (box•getBounds()•intersects(walls[i].getBounds())) {worker•setBounds(worker•getX () - xSpeed, worker•getY () ySpeed, worker•getWidth(), worker•getHeight());box•setBounds(box•getX() - xSpeed, box•getY() - ySpeed, box•getWidth(), box•getHeight());//[3.4]判断是否胜利if (box•getX{)==goal•getX() && box•getY()==goal•getY()){JOptionPane > showMessageDialog(null, ”您贏啦!;public void keyReleased(KeyEvent e) {public void keyTyped(KeyEvent e) { }});*设置内容面板public void initContentPane() {zhuobu •setBackground(Color•red); zhuobu •setLayout (null);//调用父类的厲性和方法super •setcontentPane(zhuobu);public void addComponent (int tag. String imgPath, int x, int y) { Imageicon img = new Imageicon{imgPath); //创建JLabel^把工mage 工oon 通过构造方法传参传入〃把食物放到盘J"里JLabel componet = new JLabel(img);//设置盘f 在桌布上的位置和人小componet.setBounds(z, y, imgSize, imgSize);//把盘r 放到桌布上zhuobu •add(componet);switch (tag) {case 1:box = componet; break;case 2:*把某个图片以组件的力式加入窗体图片路径* @parain* Oparam* @param imgPath * Oparam 、* @param : * fireturn y width height y 宽度 拓度添加完的组件int index = 0;分别设置各个图片位置r(int i = 0; i < 14; i++) {//左边墙walls [index].setBounds(0, izhuobu •add (walls [index]); index++; //右边墙walls [index].setBounds(20 *for * imgSize , imgSize , imgSize );imgSize , i * imgSize , imgSize ,imgSize);zhuobu .add (walls [index]); index+-s-; for (int i = 0; i < 19; i++) {//上边墙walls [index].setBounds((i +1) * imgSize , 0, imgSize ,imgSize);zhuobu .add (walls [index]);index-5-+; //下边墙walls [index]•setBounds((i + 1) imgSize);zhuobu •add (walls [index]);inde:<++; * imgSize, 13 * imgSize, imgSize,goal = componet; break;case 3:worker = componet; break;for (int i = 0; i < walls .length; i++) {//创建没每■个闱墙,他们使用的是同 个图片walls [i] = new JLabel(walllmg);for (int i = 0; i < walls .length; i++) {//创建没每■个鬧墙,他们使用的是同■个图片walls [i] = new JLabel(walllmg);//添加中间障碍耦介解耦for (int i = 0; i < loactions.length; i++) {public void addWall(String Imageicon walllmg = new walls = new JLabel[66 +imgPath, int [][] loactions) {Imageicon(imgPath); loactions•length];walls[index]•setBounds(loactions[i][0]* imgSize, loactions[i][1]* imgSize, imgSize, imgSize);zhuobu.add(walls[index]);inde:<++;第二个Java文件:pubUc class Run {pubUc static void niain(String[] args) {GameFrame gameFramc = new GameFrame("推箱子游戏…”); 〃设置大小gameFrame.seiBoundsdOO. 50. 21 *48 + 5, 14*48 + 25); 〃窗体大小不可变ganieFrame.selRcsizable(false); ganieFrame5ClInigSize(48);ganieFrame.addComponenU3. '*workerUp.png"\ 4{M). 100):ganieFrame.addComponentf U "box,png*\ 160,60): ganieFrame.addComponenU2,"goal.png". 80.520); int[][] wallLocalions ={{4.5}.{5.5b(6.5|,{7.5},{8-5}.{9.51,(10,5}.{6-8}.{7-8}.{&8}・{9.8}.{10,8b{11.5}ganieFrame.addWall("wall.png"\ wallLocations);ganieFrame.setVisibleCtrue);。
JAVA我的世界海洋更新指令大全基本游戏指令人物:@a所有玩家@e所有实体@p距离最近的玩家@r随机玩家@s当前实体/advancement grant人物属性给予玩家进度/advancement revoke人物属性移除玩家进度/attribute人物属性值设置属性值∈Z属性:get得到实体的某一属性set修改某一属性的值base分为get和set这是用来修改基础值的。
其中:generic.max_health最大血量generic.follow_range跟踪距离:你离这个实体多远这个实体注意到你generic.knockback_resistance反击退,值为1.0完全反击退generic.movement_speed移动速度generic.attack_damage攻击伤害generic.attack_knockback击退力度,只有疣猪兽、僵尸疣猪兽、劫掠兽有generic.armor盔甲防御值generic.armor_toughness盔甲韧性generic.attackReach测试版本的攻击距离generic.reachDistance测试版本的触及半径generic.attack_speed攻击速度generic.luck幸运值generic.flying_speed鹦鹉飞行速度horse.jump_strength马的弹跳力zombie.spawn_reinforcements僵尸攻击时生成另一种僵尸的可能性/bossbar[add/set/get/list/remove]值设置boss栏(如改血改名等)值:bossID(set设置的ID){''text'':''文字''}set更改boss栏属性remove删除boss栏add增加boss栏(其他过于详细,暂不演示)/clear人物物品清除控制台/config查看配置文件项/clone X Y Z属性复制东西/data[get/merge/modify/remove]更改数据get得到merge合并modify修改remove移除/datapack数据包使用修复bug/defaultgamemode模式删除模式/difficulty[easy/hard/normal/peaceful]easy简单hard困难normal普通peaceful和平/enchant附魔指令(这个以后将仔细回答,记得关注动态)/effect[give/clear]人物效果时间等级药水效果/execute已一个或多个实体为中心执行指令(以后讲粒子效果会具体提) /experience[add/query/set]人物数值经验设置/fill X Y物品填充方式填充方块/forceload加载区块/forge模组/function/gamemode[adventure/creative/spectator/survival]人物更改模式属性:adventure冒险creative创造spectator旁观者survival生存/gamerule规则[TRUE/FALSE]更改游戏规则为是/否(如禁止火蔓延)/give人物物品数量[NBT]给予玩家物品(以后讲超级无敌附魔时会重新提到,记得关注我动态)/help帮助/kick玩家踢出游戏/kill人物杀死人物/list查看在线玩家/locate地点查看地图特殊地点位置如地牢/locatebiome地点生物群系距离你的位置/loot将战利品放入物品栏或世界/msg玩家''内容''私聊/me动作显示一条关于自己的信息/particle粒子名生成坐标显示粒子效果/playsound声音属性人物播放指定声音/publish端口对局域网开放单人游戏世界/recipe[give/take]人物配方给予/剥夺玩家配方/reload重新加载数据包/replaceitem[block/entity]人物槽位替换对象替换物品/say文字发送文字到聊天栏/schedule[function/clear]函数时间[append/replace]其中clear函数就终止命令了append添加等待运行的指定标签的函数replace取代等待运行的指定标签函数,被取代函数将不会运行/scoreboard[objectives/players]参数objectives是一个项,players是玩家objectives后面有add后面给计分板起名,再后面设置计分板的准则,再设置显示的名字list列出所有已创建的计分板项modify修改计分板的显示名称或显示样式remove即移除计分板setdisplay设置计分板显示位置players后面有add增加玩家的分数enable设置谁可以用/trigger修改计分板的分数get显示分数list列出所有的分数operation计算分数remove减少分数reset清空分数set设置分数/seed查看世界种子/setblock x y z方块名方块处理方式将一个方块替换为另一方块/setworldspawn x y z设置世界出生地到该坐标/spawnpoint人物x y z设置改实体(人物)出生地到该坐标/spectate目标人物使旁观者玩家进入另一个实体视角/spreadplayers x z分散间距最大范围[under最大高度]考虑队伍传送目标把实体随机传送到区域地表某位置/stopsound人物参数声音停止播放某声音/tag人物[add/remove/list]添加/移除/列出玩家拥有的标签/team[add/empty/join/leave/list/modify/remove]增加/空/加入/离开/列出队伍/修改队伍/移除队伍/teammsg消息/tm消息发送队伍消息/tp/tp人物人物1把人物传到人物1处/tp人物x y z传送人物到坐标/title人物[actionbar/clear/reset/subtitle/times/title]参数在物品栏上方放标题/清除标题/重设/副标题/标题显示时间/标题正中间/time[add/query/set]时间增加/减少/设置时间/tellraw人物文本显示文本/tell人物信息私聊/teleport参数传送人物到地点并修改旋转角度/trigger目标[add/set]值修改一个准则为触发器的记分板/w信息私聊/weather[clear/rain/thunder]晴朗/下雨/打雷/worldborder[add/center/damage/get/set/warning]添加/设置中心/伤害/获取/设置/警告世界边界/xp数值增加经验实用服务器指令/register密码密码注册账号/login密码登录/op玩家/deop玩家设置玩家/删除管理员/ban玩家/unban玩家封号/ext灭火/email[add/show/change/recover/code/setpassword/help]添加/展示/更改/通过邮箱改密码/submit code to recover password/设置新密码/帮助/undo撤销/jumpto跳跃到准星位置/kick玩家踢出玩家/ban-ip IP封禁IP地址下所有号。
J a v a程序源代码 It was last revised on January 2, 2021经典J a v a程序源代码1.加法器(该java源文件的名称是Adder.java)import java.awt.*;import javax.swing.*;public class Adder implements ActionListener{JFrame AdderFrame;JTextField TOprand1;JTextField TOprand2;JLabel LAdd,LSum;JButton BAdd,BClear;JPanel JP1,JP2;public Adder(){AdderFrame=new JFrame("AdderFrame");TOprand1=new JTextField("0.0");TOprand2=new JTextField("0.0");LAdd=new JLabel("+");LSum=new JLabel("= ");BAdd=new JButton("Add");BClear=new JButton("Clear");JP1=new JPanel();JP2=new JPanel();BAdd.addActionListener(this);BClear.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent event){TOprand1.setText("0.0");TOprand2.setText("0.0");LSum.setText("=");}});AdderFrame.add(JP1);JP1.add(TOprand1);JP1.add(LAdd);JP1.add(TOprand2);JP1.add(LSum);AdderFrame.add(JP2);JP2.add(BAdd);JP2.add(BClear);AdderFrame.getContentPane().setLayout(new BorderLayout());AdderFrame.getContentPane().add(JP1,BorderLayout.NORTH);AdderFrame.getContentPane().add(JP2,BorderLayout.SOUTH);AdderFrame.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent event){System.exit(0);}});AdderFrame.pack();AdderFrame.setVisible(true);AdderFrame.setResizable(false);AdderFrame.setSize(250,100);}public void actionPerformed(ActionEvent event){doublesum=(double)(Double.valueOf(TOprand1.getText()).doubleValue()+Double.valueOf(TOprand2 .getText()).doubleValue());LSum.setText("="+sum);}public static void main(String[] args){Adder adder=new Adder();}}2.小型记事本(该java源文件由两个类构成,名称为Notepad.java)import java.awt.*;import javax.swing.*;import java.io.*;class mynotepad extends JFrame{File file=null;Color color=Color.red;mynotepad(){initTextContent();initMenu();initAboutDialog();}void initTextContent(){getContentPane().add(new JScrollPane(content));}JTextPane content=new JTextPane();JFileChooser openfile=new JFileChooser();JColorChooser opencolor=new JColorChooser();JDialog about=new JDialog(this);JMenuBar menu=new JMenuBar();//菜单栏的各个菜单项JMenu[] menus=new JMenu[]{new JMenu("文件"),new JMenu("编辑"),new JMenu("关于")};//"文件"菜单项的四个下拉菜单//编辑菜单的四个下拉菜单JMenuItem optionofmenu[][]=new JMenuItem[][]{{new JMenuItem("新建"),new JMenuItem("打开"),new JMenuItem("保存"),new JMenuItem("退出")},{new JMenuItem("复制"),new JMenuItem("剪切"),new JMenuItem("粘贴"),new JMenuItem("颜色")},{new JMenuItem("关于")}};void initMenu(){for(int i=0;i<menus.length;i++){menu.add(menus[i]);for(int j=0;j<optionofmenu[i].length;j++){menus[i].add(optionofmenu[i][j]);optionofmenu[i][j].addActionListener( action );}}this.setJMenuBar(menu);}ActionListener action=new ActionListener(){ //添加事件监听public void actionPerformed(ActionEvent e){String name = e.getActionCommand();JMenuItem MI=(JMenuItem)e.getSource();if("新建".equals(name)){content.setText("");file=null;}else if("打开".equals(name)){if(file !=null)openfile.setSelectedFile(file);int returnVal=openfile.showOpenDialog(mynotepad.this);if(returnVal==JFileChooser.APPROVE_OPTION){file=openfile.getSelectedFile();unfold();}}else if("保存".equals(name)){if(file!=null) openfile.setSelectedFile(file);int returnVal=openfile.showSaveDialog(mynotepad.this); if(returnVal==JFileChooser.APPROVE_OPTION){file=openfile.getSelectedFile();saving();}}else if("退出".equals(name)){mynotepad f=new mynotepad();int s=JOptionPane.showConfirmDialog(f,"退出","退出",JOptionPane.YES_NO_OPTION);if(s==JOptionPane.YES_OPTION)System.exit(0);}else if("剪切".equals(name)){content.cut();}else if("复制".equals(name)){content.copy();}else if("粘贴".equals(name)){content.paste();}else if("颜色".equals(name)){color=JColorChooser.showDialog(mynotepad.this,"",color); content.setForeground(color);}else if("关于".equals(name)){about.setSize(300,150);about.show();}}};void saving(){try{FileWriter Writef=new FileWriter(file);Writef.write(content.getText());Writef.close();}catch(Exception e){e.printStackTrace();}}void unfold(){try{FileReader Readf=new FileReader(file);int len=(int)file.length();char []buffer=new char[len];Readf.read(buffer,0,len);Readf.close();content.setText(new String(buffer));}catch(Exception e){e.printStackTrace();}}void initAboutDialog(){about.setLayout(new GridLayout(3,1));about.getContentPane().setBackground(Color.white);about.getContentPane().add(new JLabel("我的记事本程序"));//对话框内容 about.getContentPane().add(new JLabel("制作者:Fwx"));about.getContentPane().add(new JLabel("2007年12月"));about.setModal(true); //设置对话框前端显示about.setSize(100,100);about.setLocation(250,170); //设置对话框显示位置};}public class Notepad{public static void main(String args[]){ //入口main函数mynotepad noted=new mynotepad();noted.addWindowListener(new WindowAdapter(){});noted.setTitle("我的记事本程序"); //记事本标题noted.setSize(640,320); //设置记事本大小noted.show();noted.setLocation(150,100); //设置记事本显示位置}}3.简单计算器(该java源文件的名称是simplecalculator.java)import java.awt.*;import javax.swing.*;class simplecalculator{static String point=new String();static String Amal=new String();static String ONE=new String();static String TWO=new String();static String THREE=new String();static String FOUR=new String();static String FIVE=new String();static String SIX=new String();static String SEVEN=new String();static String EIGHT=new String();static String NINE=new String();static String ZERO=new String();static String ResultState=new String();static Double QF;static JButton zero=new JButton("0");static JButton one=new JButton("1");static JButton two=new JButton("2");static JButton three=new JButton("3");static JButton four=new JButton("4");static JButton five=new JButton("5");static JButton six=new JButton("6");static JButton seven=new JButton("7");static JButton eight=new JButton("8");static JButton nine=new JButton("9");static JButton add=new JButton("+");static JButton sub=new JButton("-");static JButton mul=new JButton("*");static JButton div=new JButton("/");static JButton QuFan=new JButton("+/-"); static JButton Dian=new JButton(".");static JButton equal=new JButton("=");static JButton clear=new JButton("C");static JButton BaiFen=new JButton("%"); static JButton FenZhiYi=new JButton("1/x"); static int i=0;static Double addNumber;static Double subNumber;static Double mulNumber;static Double divNumber;static Double equalNumber;static Double temp;static JTextArea result=new JTextArea(1,20); public static void main(String[] args){JFrame frame=new JFrame("计算器");result.setEditable(false);result.setText("");ResultState="窗口空";JPanel ForResult=new JPanel();JPanel ForButton7_clear=new JPanel(); JPanel ForButton4_mul=new JPanel();JPanel ForButton1_sub=new JPanel();JPanel ForButton0_equal=new JPanel(); FlowLayout FLO=new FlowLayout();ForResult.add(result);ForButton7_clear.setLayout(FLO);ForButton7_clear.add(seven);ForButton7_clear.add(eight);ForButton7_clear.add(nine);ForButton7_clear.add(div);ForButton7_clear.add(clear);ForButton4_mul.setLayout(FLO);ForButton4_mul.add(four);ForButton4_mul.add(five);ForButton4_mul.add(six);ForButton4_mul.add(mul);ForButton4_mul.add(BaiFen);ForButton1_sub.setLayout(FLO);ForButton1_sub.add(one);ForButton1_sub.add(two);ForButton1_sub.add(three);ForButton1_sub.add(sub);ForButton1_sub.add(FenZhiYi);ForButton0_equal.setLayout(FLO);ForButton0_equal.add(zero);ForButton0_equal.add(QuFan);ForButton0_equal.add(Dian);ForButton0_equal.add(add);ForButton0_equal.add(equal);frame.getContentPane().setLayout(FLO);frame.getContentPane().add(ForResult);frame.getContentPane().add(ForButton7_clear); frame.getContentPane().add(ForButton4_mul);frame.getContentPane().add(ForButton1_sub);frame.getContentPane().add(ForButton0_equal); frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE); frame.setBounds(250,250,245,245);frame.setResizable(false);frame.setVisible(true);clear.addActionListener( new ActionListener(){public void actionPerformed(ActionEvent e){result.setText("");ZERO="";ONE="";TWO="";THREE="";FOUR="";FIVE="";SIX="";SEVEN="";EIGHT="";NINE="";ResultState="窗口空";point="";i=0;}});zero.addActionListener( new ActionListener(){public void actionPerformed(ActionEvent e){ZERO="已经点击";ResultState="窗口不为空";if(ONE=="已经点击"||TWO=="已经点击"||THREE=="已经点击"||FOUR=="已经点击"||FIVE=="已经点击"||SIX=="已经点击"||SEVEN=="已经点击"||EIGHT=="已经点击"||NINE=="已经点击"){result.append("0");}if(ResultState=="窗口空"){result.setText("0");}}});one.addActionListener( new ActionListener(){public void actionPerformed(ActionEvent e){ONE="已经点击";ResultState="窗口不为空";if(point=="已经点击"||ZERO!="已经点击"||ONE=="已经点击"||TWO=="已经点击"||THREE=="已经点击"||FIVE=="已经点击"||SIX=="已经点击"||SEVEN=="已经点击"||EIGHT=="已经点击"||NINE=="已经点击"&&result.getText()!="0"){result.append("1");}if(ResultState=="窗口空"){result.setText("1");}}});two.addActionListener( new ActionListener(){public void actionPerformed(ActionEvent e){TWO="已经点击";ResultState="窗口不为空";if(point=="已经点击"||ZERO!="已经点击"||ONE=="已经点击"||TWO=="已经点击"||THREE=="已经点击"||FIVE=="已经点击"||SIX=="已经点击"||SEVEN=="已经点击"||EIGHT=="已经点击"||NINE=="已经点击"&&result.getText()!="0"){result.append("2");}if(ResultState=="窗口空"){result.setText("2");}}});three.addActionListener( new ActionListener(){public void actionPerformed(ActionEvent e){THREE="已经点击";ResultState="窗口不为空";if(point=="已经点击"||ZERO!="已经点击"||ONE=="已经点击"||TWO=="已经点击"||THREE=="已经点击"||FIVE=="已经点击"||SIX=="已经点击"||SEVEN=="已经点击"||EIGHT=="已经点击"||NINE=="已经点击"&&result.getText()!="0"){result.append("3");}if(ResultState=="窗口空"){result.setText("3");}}});four.addActionListener( new ActionListener(){public void actionPerformed(ActionEvent e){FOUR="已经点击";ResultState="窗口不为空";if(point=="已经点击"||ZERO!="已经点击"||ONE=="已经点击"||TWO=="已经点击"||THREE=="已经点击"||FIVE=="已经点击"||SIX=="已经点击"||SEVEN=="已经点击"||EIGHT=="已经点击"||NINE=="已经点击"&&result.getText()!="0"){result.append("4");}if(ResultState=="窗口空"){result.setText("4");}}});five.addActionListener( new ActionListener(){public void actionPerformed(ActionEvent e){FIVE="已经点击";ResultState="窗口不为空";if(point=="已经点击"||ZERO!="已经点击"||ONE=="已经点击"||TWO=="已经点击"||THREE=="已经点击"||FIVE=="已经点击"||SIX=="已经点击"||SEVEN=="已经点击"||EIGHT=="已经点击"||NINE=="已经点击"&&result.getText()!="0"){result.append("5");}if(ResultState=="窗口空"){result.setText("6");}}});six.addActionListener( new ActionListener(){public void actionPerformed(ActionEvent e){SIX="已经点击";ResultState="窗口不为空";if(point=="已经点击"||ZERO!="已经点击"||ONE=="已经点击"||TWO=="已经点击"||THREE=="已经点击"||FIVE=="已经点击"||SIX=="已经点击"||SEVEN=="已经点击"||EIGHT=="已经点击"||NINE=="已经点击"&&result.getText()!="0"){result.append("6");}if(ResultState=="窗口空"){result.setText("6");}}});seven.addActionListener( new ActionListener(){public void actionPerformed(ActionEvent e){SEVEN="已经点击";ResultState="窗口不为空";if(point=="已经点击"||ZERO!="已经点击"||ONE=="已经点击"||TWO=="已经点击"||THREE=="已经点击"||FIVE=="已经点击"||SIX=="已经点击"||SEVEN=="已经点击"||EIGHT=="已经点击"||NINE=="已经点击"&&result.getText()!="0"){result.append("7");}if(ResultState=="窗口空"){result.setText("7");}}});eight.addActionListener( new ActionListener(){public void actionPerformed(ActionEvent e){EIGHT="已经点击";ResultState="窗口不为空";if(point=="已经点击"||ZERO!="已经点击"||ONE=="已经点击"||TWO=="已经点击"||THREE=="已经点击"||FIVE=="已经点击"||SIX=="已经点击"||SEVEN=="已经点击"||EIGHT=="已经点击"||NINE=="已经点击"&&result.getText()!="0"){result.append("8");}if(ResultState=="窗口空"){result.setText("8");}}});nine.addActionListener( new ActionListener(){public void actionPerformed(ActionEvent e){NINE="已经点击";ResultState="窗口不为空";if(point=="已经点击"||ZERO!="已经点击"||ONE=="已经点击"||TWO=="已经点击"||THREE=="已经点击"||FIVE=="已经点击"||SIX=="已经点击"||SEVEN=="已经点击"||EIGHT=="已经点击"||NINE=="已经点击"&&result.getText()!="0"){result.append("9");}if(ResultState=="窗口空"){result.setText("9");}}});Dian.addActionListener( new ActionListener(){public void actionPerformed(ActionEvent e){point="已经点击";i=i+1;if(ResultState=="窗口不为空"&&i==1){result.append(".");}}});add.addActionListener( new ActionListener(){public void actionPerformed(ActionEvent e){Amal="已经选择加号";addNumber=Double.valueOf(result.getText()).doubleValue();result.setText("");i=0;}});sub.addActionListener( new ActionListener(){public void actionPerformed(ActionEvent e){Amal="已经选择减号";subNumber=Double.valueOf(result.getText()).doubleValue();result.setText("");i=0;}});mul.addActionListener( new ActionListener(){public void actionPerformed(ActionEvent e){Amal="已经选择乘号";mulNumber=Double.valueOf(result.getText()).doubleValue();result.setText("");i=0;}});div.addActionListener( new ActionListener(){public void actionPerformed(ActionEvent e){Amal="已经选择除号";divNumber=Double.valueOf(result.getText()).doubleValue();result.setText("");i=0;}});QuFan.addActionListener( new ActionListener(){public void actionPerformed(ActionEvent e){QF=new Double(Double.valueOf(result.getText()).doubleValue());QF=QF*(-1);result.setText(QF.toString());}});equal.addActionListener( new ActionListener(){public void actionPerformed(ActionEvent e){equalNumber=Double.valueOf(result.getText()).doubleValue();if(Amal=="已经选择加号"){temp=addNumber+equalNumber;result.setText(temp.toString());}if(Amal=="已经选择减号"){temp=subNumber-equalNumber;result.setText(temp.toString());}if(Amal=="已经选择乘号"){temp=mulNumber*equalNumber;result.setText(temp.toString());}if(Amal=="已经选择除号"){temp=divNumber/equalNumber;result.setText(temp.toString());}}});BaiFen.addActionListener( new ActionListener(){public void actionPerformed(ActionEvent e){if(ResultState=="窗口不为空"){temp=Double.valueOf(result.getText()).doubleValue()/100;result.setText(temp.toString());}}});FenZhiYi.addActionListener( new ActionListener(){public void actionPerformed(ActionEvent e){temp=1/(Double.valueOf(result.getText()).doubleValue());result.setText(temp.toString());}});}}4.图形化写字板(该java源文件的名称是JNotePadUI.java)//JNotePadUI.javaimport java.awt.*;import java.io.*;import javax.swing.*;public class JNotePadUI extends JPanel{// 变量定义JTextArea jta = new JTextArea("", 24, 40);JScrollPane jsp = new JScrollPane(jta);// 菜单条JMenuBar jmb = new JMenuBar();JMenu file = new JMenu("文件(F)", true);JMenu edit = new JMenu("编辑(E)", true);JMenu help = new JMenu("帮助(H)", true);// 工具条JToolBar toolBar = new JToolBar();// 菜单内容JMenuItem jmi;// 实例化剪切板Clipboard clipbd = getToolkit().getSystemClipboard();String text = "";// 构造函数public JNotePadUI(){class newL implements ActionListener{public void actionPerformed(ActionEvent e){jta.setDocument(new PlainDocument());}}// 打开功能class openL implements ActionListener{public void actionPerformed(ActionEvent e){JFileChooser fc = new JFileChooser();int returnVal = fc.showDialog(JNotePadUI.this, "打开");if (returnVal == JFileChooser.APPROVE_OPTION){String file = fc.getSelectedFile().getPath();if (file == null){return;}// 读取文件try{Reader in = new FileReader(file);char[] buff = new char[4096];int nch;while ((nch = in.read(buff, 0,buff.length)) != -1){jta.setDocument(new PlainDocument());jta.append(new String(buff, 0, nch));}}catch (IOException io){}}else{return;}}}// 保存文件class saveL implements ActionListener{public void actionPerformed(ActionEvent e){JFileChooser fc = new JFileChooser();int returnVal = fc.showSaveDialog(JNotePadUI.this);if (returnVal == JFileChooser.APPROVE_OPTION){String savefile = fc.getSelectedFile().getPath();if (savefile == null){return;}else{String docToSave = jta.getText();if (docToSave != null){FileOutputStream fstrm = null;BufferedOutputStream ostrm = null;try{fstrm = newFileOutputStream(savefile);ostrm = new BufferedOutputStream(fstrm);byte[] bytes = null;try{bytes = docToSave.getBytes();}catch (Exception e1){e1.printStackTrace();}ostrm.write(bytes);}catch (IOException io){}finally{try{ostrm.flush();fstrm.close();ostrm.close();}catch (IOException ioe){}}}}}else{return;}}}// 退出class exitL implements ActionListener{public void actionPerformed(ActionEvent e){System.exit(0);}}// 复制class copyL implements ActionListener{public void actionPerformed(ActionEvent e){String selection = jta.getSelectedText();StringSelection clipString = new StringSelection(selection);clipbd.setContents(clipString, clipString);}}// 剪切class cutL implements ActionListener{public void actionPerformed(ActionEvent e){String selection = jta.getSelectedText();StringSelection clipString = new StringSelection(selection);clipbd.setContents(clipString, clipString);jta.replaceRange("", jta.getSelectionStart(), jta.getSelectionEnd());}}// 粘贴class pasteL implements ActionListener{public void actionPerformed(ActionEvent e){Transferable clipData =clipbd.getContents(JNotePadUI.this);try{String clipString = (String) clipData.getTransferData(DataFlavor.stringFlavor);jta.replaceRange(clipString,jta.getSelectionStart(), jta.getSelectionEnd());}catch (Exception ex){}}}// 删除class deleteL implements ActionListener{public void actionPerformed(ActionEvent e){jta.replaceRange("", jta.getSelectionStart(),jta.getSelectionEnd());}}//帮助class help_h implements ActionListener{public void actionPerformed(ActionEvent e){JOptionPane.showMessageDialog(jta,"写字板支持拖入文本读取\n" + "由于对编码不熟悉做得\n不是很好 \n ", "帮助主题",RMATION_MESSAGE);}}//关于class help_a implements ActionListener{public void actionPerformed(ActionEvent e){JOptionPane.showMessageDialog(jta,"有不懂的地方联系\n" + " " + " JAVA图形界面练习\n", "关于记事本", RMATION_MESSAGE);}}// 事件监听class jtaL implements ActionListener{public void actionPerformed(ActionEvent e){}}// 快捷键设置file.add(jmi = new JMenuItem("新建N", 'N'));jmi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,InputEvent.CTRL_MASK));jmi.addActionListener(new newL());file.add(jmi = new JMenuItem("打开O", 'O'));jmi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,InputEvent.CTRL_MASK));jmi.addActionListener(new openL());file.add(jmi = new JMenuItem("保存S", 'S'));jmi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,InputEvent.CTRL_MASK));jmi.addActionListener(new saveL());file.addSeparator();file.add(jmi = new JMenuItem("退出E", 'E'));jmi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, InputEvent.CTRL_MASK));jmi.addActionListener(new exitL());edit.add(jmi = new JMenuItem("复制C", 'C'));jmi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK));jmi.addActionListener(new copyL());edit.add(jmi = new JMenuItem("剪切X", 'X'));jmi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, InputEvent.CTRL_MASK));jmi.addActionListener(new cutL());edit.add(jmi = new JMenuItem("粘帖V",'V'));jmi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_MASK));jmi.addActionListener(new pasteL());edit.add(jmi = new JMenuItem("删除D", 'D'));jmi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, InputEvent.CTRL_MASK));jmi.addActionListener(new deleteL());edit.addSeparator();help.add(jmi = new JMenuItem("帮助(H)", 'H'));jmi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, InputEvent.CTRL_MASK));jmi.addActionListener(new help_h());help.add(jmi = new JMenuItem("关于(A)", 'A'));jmi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK));jmi.addActionListener(new help_a());help.addSeparator();setLayout(new BorderLayout());file.setMnemonic('F');edit.setMnemonic('E');help.setMnemonic('H');jmb.add(file);jmb.add(edit);jmb.add(help);toolBar.setFloatable(true);add(jmb, BorderLayout.NORTH);add(toolBar, BorderLayout.CENTER);add(jsp, BorderLayout.SOUTH);jta.getCaret().setVisible(true);jta.setCaretPosition(0);}// 关闭窗口protected static final class appCloseL extends WindowAdapter{public void windowClosing(WindowEvent e){System.exit(0);}}// 主函数,程序入口public static void main(String args[]){JFrame f = new JFrame();JNotePadUI applet = new JNotePadUI();f.setTitle("写字板");f.setBackground(Color.lightGray);f.getContentPane().add(applet, BorderLayout.CENTER);f.addWindowListener(new appCloseL());f.setSize(800, 500);f.setLocation(500,170);f.setVisible(true);f.pack();f.setResizable(false);}}5.数字化的连连看(该java源文件的名称是lianliankan.java)import javax.swing.*;import java.awt.*;public class lianliankan implements ActionListener{JFrame mainFrame; //主面板Container thisContainer;JPanel centerPanel,southPanel,northPanel; //子面板JButton diamondsButton[][] = new JButton[6][5];//游戏按钮数组JButton exitButton,resetButton,newlyButton; //退出,重列,重新开始按钮JLabel fractionLable=new JLabel("0"); //分数标签JButton firstButton,secondButton; //分别记录两次被选中的按钮int grid[][] = new int[8][7];//储存游戏按钮位置static boolean pressInformation=false; //判断是否有按钮被选中int x0=0,y0=0,x=0,y=0,fristMsg=0,secondMsg=0,validateLV; //游戏按钮的位置坐标int i,j,k,n;//消除方法控制public void init(){mainFrame=new JFrame("JKJ连连看");thisContainer = mainFrame.getContentPane();thisContainer.setLayout(new BorderLayout());centerPanel=new JPanel();southPanel=new JPanel();northPanel=new JPanel();thisContainer.add(centerPanel,"Center");thisContainer.add(southPanel,"South");thisContainer.add(northPanel,"North");centerPanel.setLayout(new GridLayout(6,5));for(int cols = 0;cols < 6;cols++){for(int rows = 0;rows < 5;rows++ ){diamondsButton[cols][rows]=newJButton(String.valueOf(grid[cols+1][rows+1]));diamondsButton[cols][rows].addActionListener(this);centerPanel.add(diamondsButton[cols][rows]);}}exitButton=new JButton("退出");exitButton.addActionListener(this);resetButton=new JButton("重列");resetButton.addActionListener(this);newlyButton=new JButton("再来一局");newlyButton.addActionListener(this);southPanel.add(exitButton);southPanel.add(resetButton);southPanel.add(newlyButton);fractionLable.setText(String.valueOf(Integer.parseInt(fractionLable.getText()) ));northPanel.add(fractionLable);mainFrame.setBounds(280,100,500,450);mainFrame.setVisible(true);}public void randomBuild(){int randoms,cols,rows;for(int twins=1;twins<=15;twins++){randoms=(int)(Math.random()*25+1);for(int alike=1;alike<=2;alike++){cols=(int)(Math.random()*6+1);rows=(int)(Math.random()*5+1);while(grid[cols][rows]!=0){cols=(int)(Math.random()*6+1);rows=(int)(Math.random()*5+1);}this.grid[cols][rows]=randoms;}}}public void fraction(){fractionLable.setText(String.valueOf(Integer.parseInt(fractionLable.getText()) +100));}public void reload(){int save[] = new int[30];int n=0,cols,rows;int grid[][]= new int[8][7];for(int i=0;i<=6;i++){for(int j=0;j<=5;j++){if(this.grid[i][j]!=0){save[n]=this.grid[i][j];n++;}}}n=n-1;this.grid=grid;while(n>=0){cols=(int)(Math.random()*6+1);rows=(int)(Math.random()*5+1);while(grid[cols][rows]!=0){。
我的世界MinecraftMod开发学习笔记-Mod开发环境设置和HelloWorld⽰例概述本⽂通过⼀个简单的Helll World Mod⽰例, 介绍了使⽤Forge MDK (Mod Development Kit)开发Minecraft Mod的基本环境设置和过程.运⾏环境Java 1.8 JDKMinecraft Java Edition 1.12.2安装Forge和MDK从下载Minecraft Forge - MC 1.12.2 installer和Mod Development Kit (MDK)包.运⾏Forge installer安装Forge将MDK压缩包解压的指定⽬录, 例如C:\mdk.设置MDK在MDK⽬录下, 运⾏如下命令gradlew setupDecompWorkspace项⽬⽂件结构MDK设置完毕后会⽣成以下的项⽬⽂件结构mdk/├── build/├── gradle/│└── wrapper/│├── gradle-wrapper.jar│└── gradle-wrapper.properties├── src/│├── main/│├── java/│└── resources/│├── │└── pack.mcmeta├── build.gradle├── gradlew└── gradlew.bat设置Gradle build⽂件编辑build.gradle并修改version, group和archivesBaseNameversion = "1.0.0"group= "minecraftfun"archivesBaseName = "helloWorldMod"修改 {}编辑以修改modid, name和description."modid": "helloworldmod","name": "Hello World Mod","description": "Hello World",提⽰: modid只能使⽤⼩写字母.创建mod Java类src/main/java/minecraftfun/HelloWorldMod.javapackage minecraftfun;import org.apache.logging.log4j.Logger;import mon.MinecraftForge;import mon.Mod;import mon.Mod.EventHandler;import mon.event.FMLInitializationEvent;import mon.event.FMLPreInitializationEvent;@Mod(modid = HelloWorldMod.MODID, name = , version = HelloWorldMod.VERSION)public class HelloWorldMod {public static final String MODID = "helloworldmod";public static final String NAME = "Hello World Mod";public static final String VERSION = "1.0.0";private static Logger logger;@EventHandlerpublic void preInit(FMLPreInitializationEvent event){logger = event.getModLog();}@EventHandlerpublic void init(FMLInitializationEvent event){("Mod initlialised :" + NAME);}}创建⼀个Java类⽤于处理放下Block的事件src/main/java/minecraftfun/BlockPlaceHandler.javapackage minecraftfun;import net.minecraft.util.text.TextComponentString;import net.minecraftforge.event.world.BlockEvent.PlaceEvent;import mon.eventhandler.SubscribeEvent;public class BlockPlaceHandler {@SubscribeEventpublic void onPlaceEvent(PlaceEvent event) {event.getPlayer().sendMessage(new TextComponentString("You placed a block : " + event.getPlacedBlock().getBlock().getLocalizedName()));}}使⽤@SubscribeEvent标记处理放下Block事件的⽅法.在Mod类的init⽅法中注册事件处理类.@EventHandlerpublic void init(FMLInitializationEvent event){("Mod initlialised :" + NAME);MinecraftForge.EVENT_BUS.register(new BlockPlaceHandler());}编译Mod运⾏如下命令以编译Modgradlew build.该命令在build/libs⽬录下⽣成[archivesBaseName]-[version].jar⽂件.测试Mod将编译⽣成的mod jar⽂件放⼊Minecraft mods⽬录(在Windows下为 %appdata%.minecraft\mods), 运⾏Minecraft.当玩家放下⼀个Block时, 该mod会显⽰⼀条对话消息并输出放下的Block的名称.⼩结对Minecraft Mod开发感兴趣的朋友不妨试⼀试, 所有源代码和mod jar⽂件也可以从下载.。
Java版WorldWind源代码学习笔记该文档编写者系数学系毕业且未满一年工作经验的职场新人,java知识有限,对于新事物Worldwind刚接触不久,总结一下。
不足之处,希望得到各位大师的指点。
刚开始,我看了一些WorldWind的相关简介,感觉从整体上给了WorldWind非常好的框架感,所以我将它拷贝了过来。
之后,我们的研究就从大的框架转到细节去。
毕竟,“研究”不只是看大的框架,还要将细节进行分析。
我作为一个新手,对此也非常陌生,那么,就让我们一起来学习吧。
不足之处请见谅。
首先,我们贴出官网上给出的WorldWind的源代码结构如下•顶级包•用于awt的组件• GPS轨道格式• GPS轨道格式•几何与数学类•地球、火星等星球的实现•图层•专用于地球的图层WorldWindow和View接口以下是WorldWindow接口:•set/getModel(Model)•set/getView(View)•getSceneController(...)pick以下监听器:•PositionListener•SelectListener•RenderingListener•repaint()View 接口:•Fields•Position, direction, field of view, altitude, heading, pitch, roll,•Actionso apply()o goto(lat/lon/elev/altitude)o project(Point 3Dpoint)•Computeo horizon()o positionFromScreenPoint(...)o rayFromScreenPoint(...)在Applet中使用WorldWind要使用Applet,需要Java API for OpenGL(JOGL) Applet Launcher。
新版本的JOGL Applet Launcher具备在applet中创建和部署基于OpenGL的3D图形的功能,而不需要客户端安装任何软件。