小游戏源代码
Python实现我的世界小游戏源代码

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⼩游戏源代码内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!。
Java猜拳小游戏源代码

第一个文件:public class Computer {String name;int score;public int showfist(){int quan;quan=(int)(Math.random()*10);if(quan<=2){quan=1;}else if(quan<=5){quan=2;}else{quan=3;}switch(quan){case 1:System.out.println(name+"出拳:剪刀");break;case 2:System.out.println(name+"出拳:石头");break;case 3:System.out.println(name+"出拳:布");break;}return quan;}}第二个文件:import java.util.Scanner;public class Game {int count=0;int countP=0;Person person=new Person();Computer computer=new Computer();Scanner input=new Scanner(System.in);public void initial(){System.out.print("请选择你的角色(1.刘备 2.孙权 3.曹操):");int juese=input.nextInt();switch(juese){case 1:="刘备";break;case 2:="孙权";break;case 3:="曹操";break;}System.out.print("请选择对手角色(1.关羽 2.张飞 3.赵云):");int JueSe=input.nextInt();switch(JueSe){case 1:="关羽";break;case 2:="张飞";break;case 3:="赵云";break;}}public void begin(){System.out.print("\n要开始吗? (y/n)");String ans=input.next();if(ans.equals("y")){String answ;do{int a=person.showFist();int b=computer.showfist();if(a==1&&b==3||a==2&&b==1||a==3&&b==2){System.out.println("结果:你赢了!");person.score++;}else if(a==1&&b==1||a==2&&b==2||a==3&&b==3){System.out.println("结果:平局,真衰!嘿嘿,等着瞧吧!");countP++;}else{System.out.println("结果:你输了!");computer.score++;}count++;System.out.print("\n是否开始下一轮? (y/n)");answ=input.next();}while(answ.equals("y"));}}public String calcResult(){String a;if(person.score>computer.score){a="最终结果:恭喜恭喜!你赢了!";}else if(person.score==computer.score){a="最终结果:打成平手,下次再和你一决高下!";}else{a="最终结果:呵呵,你输了!笨笨,下次加油啊!";}return a;}public void showResult(){System.out.println("---------------------------------------------------");System.out.println("\t\t"++" VS"++"\n");System.out.println("对战次数:"+count+"次");System.out.println("平局:"+countP+"次");System.out.println(+"得:"+person.score+"分");System.out.println(+"得:"+computer.score+"分\n");System.out.println(calcResult());System.out.println("---------------------------------------------------");}}第三个文件:import java.util.Scanner;public class Person {String name;int score;Scanner input=new Scanner(System.in);public int showFist(){System.out.print("\n请出拳:1.剪刀2.石头3.布");int quan=input.nextInt();switch(quan){case 1:System.out.println("你出拳:剪刀");break;case 2:System.out.println("你出拳:石头");break;case 3:System.out.println("你出拳:布");break;}return quan;}}第四个文件:public class Test {public static void main(String[]args){Game g=new Game();System.out.println("-----------------欢迎进入游戏世界--------------------\n\n");System.out.println("\t\t******************");System.out.println("\t\t** 猜拳开始 **");System.out.println("\t\t******************\n\n");System.out.println("出拳规则:1.剪刀2.石头3.布");g.initial();g.begin();g.showResult();}}。
安卓小游戏--附加标准源代码(吃豆豆)

效果图:图片资源文件夹:小球资源:玩家资源:代码部分(按上面类从上到下排列):package com.abtc.game.prettyball.main;import com.abtc.game.prettyball.main.game.GameController; import ;import android.app.Activity;import android.content.pm.ActivityInfo;import android.content.res.AssetManager;import android.graphics.Rect;import android.os.Bundle;import android.view.Display;import android.view.KeyEvent;import android.view.MotionEvent;import android.view.Window;import android.view.WindowManager;public class MainActivity extends Activity {private GameController gameController;/** 游戏界面区域对象**/private static final Rect RECT_GAMESCREEN = new Rect();/** 资源文件夹管理对象**/private static AssetManager asset;@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);/** step1 1,去除标题栏2,去除任务栏3,获取实际设备的像素4,创建游戏的控制台5,控制台添加绘制功能* 6,控制台加入touch功能,按键功能*/// 去除标题栏requestWindowFeature(Window.FEATURE_NO_TITLE);// 去除任务栏getWindow().setFlags(youtParams.FLAG_FULLSCREEN, youtParams.FLAG_FULLSCREEN);// 强制横屏setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);// 获得显示器对象Display dis = getWindowManager().getDefaultDisplay();int niScreenWidth = dis.getWidth();int niScreenHeight = dis.getHeight();// 计算游戏界面位置和区域RECT_GAMESCREEN.left = (niScreenWidth - Info.NI_GAMESCREEN_WIDTH) / 2;RECT_GAMESCREEN.top = (niScreenHeight - Info.NI_GAMESCREEN_HEIGHT) / 2;RECT_GAMESCREEN.right = RECT_GAMESCREEN.left + Info.NI_GAMESCREEN_WIDTH;RECT_GAMESCREEN.bottom = RECT_GAMESCREEN.top+ Info.NI_GAMESCREEN_HEIGHT;// 初始化资源文件夹管理对象asset = this.getAssets();// 初始化游戏的控制台;gameController = new GameController(this);setContentView(gameController);}public static final AssetManager getAsset() {return asset;}@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) {// TODO Auto-generated method stubgameController.onKDown(keyCode, event);return super.onKeyDown(keyCode, event);}@Overridepublic boolean onTouchEvent(MotionEvent event) { // TODO Auto-generated method stubgameController.onTouch(event);return super.onTouchEvent(event);}/*** 获取游戏界面水平位置** @return*/public static final int getScreenX() {return RECT_GAMESCREEN.left;}/*** 获取游戏界面垂直位置** @return*/public static final int getScreenY() {return RECT_GAMESCREEN.top;}/*** 获取游戏界面宽** @return*/public static final int getScreenWidth() {return Info.NI_GAMESCREEN_WIDTH;}/*** 获取游戏界面高** @return*/public static final int getScreenHeight() {return Info.NI_GAMESCREEN_HEIGHT;}}package com.abtc.game.prettyball.main.game;import android.graphics.Bitmap;import android.graphics.Canvas;import android.graphics.Paint;import com.abtc.game.prettyball.main.MainActivity;import com.abtc.game.prettyball.main.tools.Tools;/*** 游戏背景类** @author Administrator**/public class Background {/** 背景切换时间(分钟) **/private final int NI_BACKGROUND_CHANGE_TIME = (1000 * 60) * 5;/** 背景图片总数**/private final int NI_BACKGROUND_MAX = 3;/** 图片-当前背景**/private Bitmap bmpBackground;/** 图片-渐变背景**/private Bitmap bmpBackgroundAlpha;/** 笔刷-渐变**/private Paint paintBackground;/** 当前背景编号**/private int niBackgroundId;/** 线程开关**/private boolean isThread;/** 是否渐变中**/private boolean isShowing;public Background() {paintBackground = new Paint();paintBackground.setAlpha(0);// 设置笔刷的透明度(0:完全透明, 255:不透明)bmpBackground = Tools.readBitmapFromAssets("image/background/"+ niBackgroundId + ".png");}/*** 重置*/public void reset() {// 当前背景重置if (niBackgroundId != 0) {niBackgroundId = 0;bmpBackground = Tools.readBitmapFromAssets("image/background/"+ niBackgroundId + ".png");}// 重置渐变背景if (bmpBackgroundAlpha != null) {bmpBackgroundAlpha = null;paintBackground.setAlpha(0);isShowing = false;}}public void onDraw(Canvas canvas) {canvas.drawBitmap(bmpBackground, MainActivity.getScreenX(),MainActivity.getScreenY(), null);if (bmpBackgroundAlpha != null)canvas.drawBitmap(bmpBackgroundAlpha, MainActivity.getScreenX(), MainActivity.getScreenY(), paintBackground);}private void logic() {// 渐变状态if (isShowing) {// 渐变休眠时间try {Thread.sleep(80);} catch (InterruptedException e) {}// 透明值变化int niOldAlpha = paintBackground.getAlpha();niOldAlpha++;// 检测透明值变化结束if (niOldAlpha >= 255) {// 渐变背景图交给当前背景图bmpBackground = bmpBackgroundAlpha;// 等待渐变图交付完毕try {Thread.sleep(80);} catch (InterruptedException e) {}// 渐变背景图销毁bmpBackgroundAlpha = null;// 还原相关数值isShowing = false;paintBackground.setAlpha(0);} elsepaintBackground.setAlpha(niOldAlpha);}// 等待切换状态else {// 切换间隔休眠时间try {Thread.sleep(NI_BACKGROUND_CHANGE_TIME);} catch (InterruptedException e) {}// 渐变背景图得到图片niBackgroundId++;if (niBackgroundId == NI_BACKGROUND_MAX)niBackgroundId = 0;bmpBackgroundAlpha = Tools.readBitmapFromAssets("image/background/"+ niBackgroundId + ".png");// 改变状态isShowing = true;}}public void start() {if (!isThread) {isThread = true;new Thread(new LogicMonitor()).start();}}public void close() {isThread = false;}private class LogicMonitor implements Runnable {@Overridepublic void run() {while (isThread) {logic();}}}}package com.abtc.game.prettyball.main.game;import android.graphics.Bitmap;import android.graphics.Canvas;import android.graphics.Rect;import com.abtc.game.prettyball.main.MainActivity;import com.abtc.game.prettyball.main.tools.Tools;/*** 小球对象** @author Administrator**/public class Ball {/** 球类型-草莓型(增加玩家角色生命值10点) **/public static final int NI_TYPE_0 = 0;/** 球类型-苹果型(增加玩家50分) **/public static final int NI_TYPE_1 = 1;/** 球类型-海洋型(5秒内停止减少生命,当已经进入此状态时,则增加50点生命值) **/public static final int NI_TYPE_2 = 2;/** 球类型-太阳型(升级,如果已经是满级状态,则当前的生命值直接加满) **/public static final int NI_TYPE_3 = 3;/** 球类型-黑洞型(减少玩家角色生命值30点) **/public static final int NI_TYPE_4 = 4;/** 球类型-金币型(减少分数值200分) **/public static final int NI_TYPE_5 = 5;/** 球类型-炸弹型(直接降一级,如果已经是1级状态,则进入gameover) **/ public static final int NI_TYPE_6 = 6;/** 类型总数**/private static final int NI_TYPE_MAX = 7;/** 重生时间累计标准值**/private static final int NI_RELIVE_TIME = 30;/** 动画帧总数**/private static final int NI_FRAME_MAX = 6;/** 尺寸**/private static final int NI_SIZE = 32;/** 图片组-动画**/private static final Bitmap[][] ARR_BMP;static {// 样式ARR_BMP = new Bitmap[NI_TYPE_MAX][];for (int i = 0; i < ARR_BMP.length; i++)ARR_BMP[i] = Tools.readBitmapFolderFromAssets("image/balls/" + i);}/** 监听回调对象**/private BallCallBack callback;/** 区域-位置**/private Rect rectPosition;/** 速度**/private int niSpeed;/** 帧**/private int niFrame;/** 类型**/private int niType;/** 重生时间累计(>0:代表正处于等待重生, -1代表此小球可用, 0代表此小球正在使用) **/private int niReliveTimeCount;public Ball() {this.niSpeed = 4;rectPosition = new Rect();reset();}public void reset() {// 动画niFrame = 0;// 位置rectPosition.left = Tools.getRandomInt(MainActivity.getScreenX(),MainActivity.getScreenX() + MainActivity.getScreenWidth()- NI_SIZE);rectPosition.top = MainActivity.getScreenY() - NI_SIZE;rectPosition.right = rectPosition.left + NI_SIZE;rectPosition.bottom = rectPosition.top + NI_SIZE;// 累计重生时间niReliveTimeCount = NI_RELIVE_TIME;// 类型boolean isGoodBall = Tools.getRandomInt(0, 2) == 0;// 先根据第一个随机值获得好、坏球之分int niRandom = 0;if (isGoodBall) {niRandom = Tools.getRandomInt(0, 10);// 根据第二个随机值获得具体的小球类型if (niRandom < 5)this.niType = Ball.NI_TYPE_0;else if (niRandom < 7)this.niType = Ball.NI_TYPE_1;else if (niRandom < 9)this.niType = Ball.NI_TYPE_2;elsethis.niType = Ball.NI_TYPE_3;} else {niRandom = Tools.getRandomInt(0, 4);// 根据第二个随机值获得具体的小球类型if (niRandom < 2)this.niType = Ball.NI_TYPE_4;else if (niRandom < 3)this.niType = Ball.NI_TYPE_5;elsethis.niType = Ball.NI_TYPE_6;}}public void onDraw(Canvas canvas) {if (niReliveTimeCount == 0)canvas.drawBitmap(ARR_BMP[niType][niFrame], rectPosition.left,rectPosition.top, null);}public void logic() {// 正在使用中if (niReliveTimeCount == 0) {niFrame = ++niFrame % NI_FRAME_MAX;rectPosition.top += niSpeed;rectPosition.bottom += niSpeed;// 检测小球是否超出屏幕底端if (rectPosition.top > MainActivity.getScreenY()+ MainActivity.getScreenHeight()) {reset();} else {callback.collideCheck(this);}}// 重生中else if (niReliveTimeCount != -1) {niReliveTimeCount--;if (niReliveTimeCount == 0)niReliveTimeCount = -1;}}/*** 使小球进入使用状态*/public void use() {niReliveTimeCount = 0;}/*** 是否可用** @return*/public boolean isEnable() {return niReliveTimeCount == -1;}/*** 是否与指定对象发生碰撞** @param p* : 玩家角色对象* @return*/public boolean isCollideWith(Player p) {return Rect.intersects(rectPosition, p.getRect()); }/*** 获取类型** @return*/public int getType() {return niType;}/*** 加入小球监听** @param callback*/public void addBallListener(BallCallBack callback) { this.callback = callback;}/*** 删除小球监听*/public void removeListener() {if (callback != null)callback = null;}}package com.abtc.game.prettyball.main.game; public interface BallCallBack {void collideCheck(Ball ball);}package com.abtc.game.prettyball.main.game; import java.util.Timer;import java.util.TimerTask;import android.annotation.SuppressLint;import android.graphics.Canvas;@SuppressLint("WrongCall")public class BallManager {/** 小球数量总数**/private final int NI_NUMBER_MAX = 10;/** 小球生产间隔(毫秒)**/private final int NI_ADD_BALL_TIME = 1500;/** 小球对象**/private Ball[] arrBall;/** 小球回调对象**/private BallCallBack callback;/** 计时器-生产球**/private Timer timerAddBall;/** 线程开关**/private boolean isThread;public BallManager(BallCallBack callback) { this.callback = callback;arrBall = new Ball[NI_NUMBER_MAX];}public void reset() {for (int i = 0; i < arrBall.length; i++)if (arrBall[i] != null)arrBall[i].reset();}public void onDraw(Canvas canvas) {for (int i = 0; i < arrBall.length; i++)if (arrBall[i] != null)arrBall[i].onDraw(canvas);}private void logic() {for (int i = 0; i < arrBall.length; i++)if (arrBall[i] != null)arrBall[i].logic();}public void start() {if (!isThread) {isThread = true;new Thread(new LogicMonitor()).start();}if (timerAddBall == null) {timerAddBall = new Timer();timerAddBall.schedule(new AddBall(), 10, NI_ADD_BALL_TIME);}}public void close() {isThread = false;if (timerAddBall != null) {timerAddBall.cancel();timerAddBall = null;}}private class LogicMonitor implements Runnable {@Overridepublic void run() {while (isThread) {try {Thread.sleep(80);} catch (InterruptedException e) {}logic();}}}private class AddBall extends TimerTask {@Overridepublic void run() {boolean isAddBall = false;// 让等待的小球投入工作for (int i = 0; i < arrBall.length; i++) {if (arrBall[i] != null && arrBall[i].isEnable()) {arrBall[i].use();isAddBall = true;break;}}// 加入新球if (!isAddBall) {for (int i = 0; i < arrBall.length; i++) {if (arrBall[i] == null) {// 初始化一个新球arrBall[i] = new Ball(); // 构造小球对象arrBall[i].addBallListener(callback); // 添加监听break;}}}}}}package com.abtc.game.prettyball.main.game;import android.annotation.SuppressLint;import android.content.Context;import android.graphics.Bitmap;import android.graphics.Canvas;import android.view.KeyEvent;import android.view.MotionEvent;import android.view.View;import com.abtc.game.prettyball.main.MainActivity;import com.abtc.game.prettyball.main.tools.Tools;public class GameController extends View implements Runnable { /** 背景对象**/private Background background;/** 玩家对象**/private Player player;/** 小球对象**/// private Ball ball;private BallManager ballManager;/** 游戏结束的标志**/private boolean isGameOver;/** 游戏结束时显示的图片**/private Bitmap bmpGameOver;public GameController(Context context) {super(context);background = new Background();player = new Player();player.addStateListener(new StateMonitor());// 添加回调// ball = new Ball();// ball.addBallListener(new BallMonitor());ballManager = new BallManager(new BallMonitor());new Thread(this).start();// 开启绘制线程background.start();// 开启背景动画player.start();// 开启玩家线程// ball.start();ballManager.start();}@SuppressLint("WrongCall")protected void onDraw(Canvas canvas) {if (isGameOver) {if (bmpGameOver != null) {canvas.drawBitmap(bmpGameOver, MainActivity.getScreenX(),MainActivity.getScreenY(), null);}} else {background.onDraw(canvas);// 绘制背景player.onDraw(canvas);// 绘制玩家角色// ball.onDraw(canvas);ballManager.onDraw(canvas);}}public void onTouch(MotionEvent event) {int niTouchX = (int) event.getX();switch (event.getAction()) {case MotionEvent.ACTION_DOWN:if (!isGameOver)player.setState(true, niTouchX < MainActivity.getScreenX()+ MainActivity.getScreenWidth() / 2);break;case MotionEvent.ACTION_UP:if (!isGameOver)player.setState(false, niTouchX < MainActivity.getScreenX()+ MainActivity.getScreenWidth() / 2);else {restart();}break;}}/*** 重新开始游戏private void restart() {// TODO Auto-generated method stubbackground.reset();player.reset();// ball.reset();ballManager.reset();isGameOver = false;bmpGameOver = null;background.start();player.start();// ball.start();ballManager.start();}public void onKDown(int keyCode, KeyEvent event) {// player.lvUp();// player.updateScore(200);}@Overridepublic void run() {while (true) {try {Thread.sleep(20);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}this.postInvalidate();}}private class StateMonitor implements StateCallBack {@Overridepublic void notifyGameOver() {// 状态改变isGameOver = true;background.close();player.close();bmpGameOver = Tools.readBitmapFromAssets("image/system/gameover.png");}private class BallMonitor implements BallCallBack {@Overridepublic void collideCheck(Ball ball) {if (ball.isCollideWith(player)) {// 获取小球的类型,根据不同的类型做相应的处理switch (ball.getType()) {case Ball.NI_TYPE_0:player.addHP(20);break;case Ball.NI_TYPE_1:player.updateScore(50);break;case Ball.NI_TYPE_2:if (!player.stopAutoHurt(5))player.addHP(50);// 已启动自动减血功能,增加50点生命break;case Ball.NI_TYPE_3:if (!player.lvUp())player.addHP(Player.NI_HPBAR_WIDTH);break;case Ball.NI_TYPE_4:player.hurt(50);break;case Ball.NI_TYPE_5:player.updateScore(-50);break;case Ball.NI_TYPE_6:player.hurt(player.getHp());break;}ball.reset();}}}}package com.abtc.game.prettyball.main.game;public interface Info {/** 游戏界面的宽**/int NI_GAMESCREEN_WIDTH = 480;/** 游戏界面的高**/int NI_GAMESCREEN_HEIGHT = 320;/** Log的标签**/String STR_LOG_TAG = "sysout";}package com.abtc.game.prettyball.main.game;import java.util.Timer;import java.util.TimerTask;import android.graphics.Bitmap;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.graphics.Paint.Style;import android.graphics.Point;import android.graphics.Rect;import com.abtc.game.prettyball.main.MainActivity;import com.abtc.game.prettyball.main.tools.Tools;/**** 玩家角色1、将玩家角色显示在指定的位置2、让玩家角色实现简单的移动3、让玩家角色实现连续的移动4、让玩家角色实现动画移动* 5、玩家touch离开时,角色处于站立状态** @author Administrator**/public class Player {/** 玩家的基础移动速度**/private final int NI_SPEED_BASIC = 15;/** 玩家角色的帧宽**/private final int NI_WIDTH = 42;/** 玩家角色的帧高**/private final int NI_HEIGTH = 42;/** 玩家等级上限**/private final int NI_LV_MAX = 3;/** 玩家动画最大帧数**/private final int NI_FRAME_MAX = 6;/** 动画组-玩家角色动画**/private Bitmap[][] arrBmpAnimation;/** 玩家的当前速度**/// private int niSpeed;/** 玩家动画当前帧**/private int niFrame;/** 是否在移动中**/private boolean isMoving;/** 方向(true:左,false:右) **/private boolean isLeft;/** 区域-玩家角色位置**/private Rect rectPosition;/** 线程开关**/private boolean isThread;/** 生命体的最大宽度**/public static final int NI_HPBAR_WIDTH = 240;/** 生命体的最大高度**/private final int NI_HPBAR_HEIGHT = 8;/** 玩家生命条区域**/private Rect rectHpBar;/** 笔刷-玩家生命条**/private Paint paintHpBar;/** 笔刷-玩家生命条框**/private Paint paintHpBarBound;/** 生命条颜色组**/private int[] arrNIHpColor = { Color.RED, Color.BLUE, Color.MAGENTA }; /** 等级**/private int niLv;/** 角色生命值**/private int niHp;/** 生命条自动消减线程的频率(毫秒)**/private final int NI_HP_AUTO_HURT_ROTATE = 100;/** 线程-生命条自动消减的控制器**/private Timer timerHpAutoHurt;/** 文本-等级**/private final String STR_TEXT_LV = "lv:";/** 文本-分数**/private final String STR_TEXT_SCORE = "score:";/** 笔刷-玩家文本数据**/private Paint paintText;/** 位置-级别和分数**/private Point pLv;private Point pScore;/** **/private String strLv;private String strScore;private int niScore;/** 状态回调**/private StateCallBack callBack;/** 停止自动消减生命值(0代表非停止状态,非0只代表停止减血) **/ private int niStopAutoHurtValue;/*** 添加回调功能** @param callBack* 回调对象*/public void addStateListener(StateCallBack callBack) {this.callBack = callBack;}/*** 删除回调功能*/public void removeStateListener() {if (callBack != null) {callBack = null;}}public Player() {arrBmpAnimation = new Bitmap[NI_LV_MAX][NI_FRAME_MAX];for (int i = 0; i < arrBmpAnimation.length; i++) {for (int j = 0; j < arrBmpAnimation[i].length; j++) {arrBmpAnimation[i][j] = Tools.readBitmapFromAssets("image/player/p" + (i + 1) + "_"+ j + ".png");}}rectPosition = new Rect();rectPosition.left = MainActivity.getScreenX()+ (MainActivity.getScreenWidth() - NI_WIDTH) / 2;rectPosition.top = MainActivity.getScreenY()+ MainActivity.getScreenHeight() - (int) (NI_HEIGTH * 1.5);rectPosition.right = rectPosition.left + NI_WIDTH;rectPosition.bottom = rectPosition.top + NI_HEIGTH;// niSpeed = NI_SPEED_BASIC;niFrame = isLeft ? 1 : 4;rectHpBar = new Rect();rectHpBar.left = MainActivity.getScreenX()+ (MainActivity.getScreenWidth() - NI_HPBAR_WIDTH) / 2;rectHpBar.top = MainActivity.getScreenY()+ MainActivity.getScreenHeight() - NI_HPBAR_HEIGHT;rectHpBar.right = rectHpBar.left + NI_HPBAR_WIDTH;rectHpBar.bottom = rectHpBar.top + NI_HPBAR_HEIGHT;paintHpBar = new Paint();paintHpBarBound = new Paint();paintHpBarBound.setStyle(Style.STROKE);paintHpBarBound.setStrokeWidth(1);niHp = NI_HPBAR_WIDTH;paintText = new Paint();paintText.setTextSize(11);pLv = new Point(MainActivity.getScreenX() + 5,MainActivity.getScreenY() + MainActivity.getScreenHeight() - 5);pScore = new Point(MainActivity.getScreenX()+ MainActivity.getScreenWidth() - 5- (int) paintText.measureText(STR_TEXT_SCORE + niScore), pLv.y);strLv = STR_TEXT_LV + (niLv + 1);strScore = STR_TEXT_SCORE + niScore;}public void onDraw(Canvas canvas) {canvas.drawBitmap(arrBmpAnimation[niLv][niFrame], rectPosition.left, rectPosition.top, null);// 绘制上一级生命条if (niLv > 0 && niHp != NI_HPBAR_WIDTH) {paintHpBar.setColor(arrNIHpColor[niLv - 1]);canvas.drawRect(rectHpBar, paintHpBar);}paintHpBar.setColor(arrNIHpColor[niLv]);// 绘制生命条canvas.drawRect(rectHpBar.left, rectHpBar.top, rectHpBar.left + niHp, rectHpBar.bottom, paintHpBar);// 绘制生命条边框canvas.drawRect(rectHpBar, paintHpBarBound);// 绘制文本canvas.drawText(strLv, pLv.x, pLv.y, paintText);canvas.drawText(strScore, pScore.x, pScore.y, paintText);}/*** 设置状态** @param isMoving* :true 移动,false停止移动** @param isLeft* true 左移false 右移*/public void setState(boolean isMoving, boolean isLeft) {this.isLeft = isLeft;this.isMoving = isMoving;if (isMoving) {niFrame = isLeft ? 0 : 3;} else {niFrame = isLeft ? 1 : 4;}}/*** 玩家逻辑首先判断是否移动--》左或者右**/public void logic() {if (isMoving) {if (isLeft) {moveLeft();} else {moveRight();}}}/*** 设定玩家角色移动的区域*/private void moveRight() {niFrame++;if (niFrame == 6) {niFrame = 3;}int niSpeed = NI_SPEED_BASIC + niLv;rectPosition.left += niSpeed;rectPosition.right += niSpeed;if (rectPosition.right >= MainActivity.getScreenX()+ MainActivity.getScreenWidth()) {rectPosition.right = MainActivity.getScreenX()+ MainActivity.getScreenWidth();rectPosition.left = rectPosition.right - NI_WIDTH;}}/*** 设定玩家角色移动的区域*/private void moveLeft() {niFrame++;if (niFrame == 3) {niFrame = 0;}int niSpeed = NI_SPEED_BASIC + niLv;rectPosition.left -= niSpeed;rectPosition.right -= niSpeed;if (rectPosition.left <= MainActivity.getScreenX()) { rectPosition.left = MainActivity.getScreenX();rectPosition.right = rectPosition.left + NI_WIDTH;}}public void start() {if (!isThread) {isThread = true;new Thread(new LogicMonitor()).start();// 生命条自动消减线程timerHpAutoHurt = new Timer();timerHpAutoHurt.schedule(new HpAutoHurtMonitior(), 1000,NI_HP_AUTO_HURT_ROTATE);}}public void close() {isThread = false;if (timerHpAutoHurt != null) {timerHpAutoHurt.cancel();timerHpAutoHurt = null;}}/*** 增加生命值** @param niValue*/public void addHP(int niValue) {niHp += niValue;if (niHp > NI_HPBAR_WIDTH) {if (lvUp()) {niHp = niHp - NI_HPBAR_WIDTH;} else {niHp = NI_HPBAR_WIDTH;}}}/*** 更新分数** @param niValue*/public void updateScore(int niValue) {niScore += niValue;if (niScore <= 0) {niScore = 0;}strScore = STR_TEXT_SCORE + niScore;pScore.x = MainActivity.getScreenX() + MainActivity.getScreenWidth() - 5 - (int) paintText.measureText(STR_TEXT_SCORE + niScore); }/*** 玩家升级*/public boolean lvUp() {if (niLv < NI_LV_MAX - 1) {niLv++;strLv = STR_TEXT_LV + (niLv + 1);return true;}return false;}public int getHp() {return niHp;}/*** 受伤** @param niValue*/public void hurt(int niValue) {niHp -= niValue;if (niHp <= 0) {if (niLv > 0) {niLv--;strLv = STR_TEXT_LV + (niLv + 1);niHp = NI_HPBAR_WIDTH;} else {niHp = 0;gameOver();}}}/*** GameOver*/private void gameOver() {if (callBack != null) {callBack.notifyGameOver();}}public Rect getRect() {return this.rectPosition;}/*** 重置*/public void reset() {// 重置人物出现的位置rectPosition.left = MainActivity.getScreenX()+ (MainActivity.getScreenWidth() - NI_WIDTH) / 2;rectPosition.top = MainActivity.getScreenY()+ MainActivity.getScreenHeight() - (int) (NI_HEIGTH * 1.5);rectPosition.right = rectPosition.left + NI_WIDTH;rectPosition.bottom = rectPosition.top + NI_HEIGTH;// 重置等级和分数niLv = 0;strLv = STR_TEXT_LV + (niLv + 1);niScore = 0;strScore = STR_TEXT_SCORE + niScore;pScore.x = MainActivity.getScreenX() + MainActivity.getScreenWidth() - 5 - (int) paintText.measureText(STR_TEXT_SCORE + niScore);// 重置角色状态setState(false, true);// 重置生命条niHp = NI_HPBAR_WIDTH;}/*** 开始停止自动减血** @param niValue* 停止时长* @return true 代表成功启动停止减血,false代表已处于自动减血状态*/public boolean stopAutoHurt(int niValue) {if (niStopAutoHurtValue != 0) {return false;}niStopAutoHurtValue = 10 * niValue;return true;}private class LogicMonitor implements Runnable { @Overridepublic void run() {while (isThread) {try {Thread.sleep(800);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}// 执行玩家逻辑logic();}}}private class HpAutoHurtMonitior extends TimerTask { @Overridepublic void run() {if (niStopAutoHurtValue == 0) {hurt(1);} else {niStopAutoHurtValue--;}}}}package com.abtc.game.prettyball.main.game;public interface StateCallBack {void notifyGameOver();}package com.abtc.game.prettyball.main.tools;import java.io.IOException;import java.io.InputStream;import java.util.Random;import android.content.res.AssetManager;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.util.Log;import com.abtc.game.prettyball.main.MainActivity;import ;public final class Tools {private static final Random random = new Random();/*** 获取随机整数** @param min* @param max* @return*/public static final int getRandomInt(int min, int max) {// int niRan = random.nextInt();//-2的32~ 2的32-1return Math.abs(random.nextInt()) % (max - min) + min;}/*** 获取assets指定文件夹下的所有资源图片** @param strDir* @return*/public static final Bitmap[] readBitmapFolderFromAssets(String strDir) { // 获取指定文件夹中所有资源图片的名称String[] arrStrFileName = null;try {arrStrFileName = MainActivity.getAsset().list(strDir);} catch (IOException e) {e.printStackTrace();Tools.logError(strDir + " error!");}if (arrStrFileName.length == 0) {return null;}Bitmap[] arrBmp = new Bitmap[arrStrFileName.length];for (int i = 0; i < arrBmp.length; i++) {arrBmp[i] = readBitmapFromAssets(strDir + "/" + arrStrFileName[i]);}return arrBmp;}public static final Bitmap readBitmapFromAssets(String strFileName) { Bitmap bmp = null;InputStream is = null;try {is = MainActivity.getAsset().open(strFileName);bmp = BitmapFactory.decodeStream(is);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();Tools.logError("read bitmap error: " + strFileName);} finally {if (is != null) {try {is.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}return bmp;}/*** 获取assets文件夹下的资源图片** @param asset* :资源文件夹对象* @param strFileName* :文件的名称* @return :图片*/public static final Bitmap readBitmapFromAssets(AssetManager asset, String strFileName) {Bitmap bmp = null;InputStream is = null;try {is = asset.open(strFileName);bmp = BitmapFactory.decodeStream(is);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {if (is != null) {try {is.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}return bmp;}/*** 打印错误信息** @param strMsg* :信息*/public static final void logError(String strMsg) {Log.e(Info.STR_LOG_TAG, strMsg);}public static final void logInfo(String strMsg) {Log.i(Info.STR_LOG_TAG, strMsg);}}。
java小游戏源代码

j a v a小游戏源代码 Document number:NOCG-YUNOO-BUYTT-UU986-1986UTJava小游戏第一个Java文件:import class GameA_B {public static void main(String[] args) {Scanner reader=new Scanner;int area;"Game Start…………Please enter the area:(1-9)" +'\n'+"1,2,3 means easy"+'\n'+"4,5,6 means middle"+'\n'+"7,8,9 means hard"+'\n'+"Please choose:");area=();switch((area-1)/3){case 0:"You choose easy! ");break;case 1:"You choose middle! ");break;case 2:"You choose hard! ");break;}"Good Luck!");GameProcess game1=new GameProcess(area);();}}第二个Java文件:import class GameProcess {int area,i,arrcount,right,midright,t;int base[]=new int[arrcount],userNum[]=newint[area],sysNum[]=new int[area];Random random=new Random();Scanner reader=new Scanner;GameProcess(int a){area=a;arrcount=10;right=0;midright=0;t=0;base=new int[arrcount];userNum=new int[area];sysNum=new int[area];for(int i=0;i<arrcount;i++){base[i]=i;// }}void process(){rand();while(right!=area){scanf();compare();print();check();}}void rand(){for(i=0;i<area;i++){t=(arrcount);//sysNum[i]=base[t];delarr(t);}}void delarr(int t){for(int j=t;j<arrcount-1;j++)base[j]=base[j+1];arrcount--;}void scanf(){"The system number has created!"+"\n"+"Please enter "+area+" Numbers");for(int i=0;i<area;i++){userNum[i]=();}}void check(){if(right==area)"You win…………!");}boolean check(int i){return true;}void compare(){int i=0,j=0;right=midright=0;for(i=0;i<area;i++){for(j=0;j<area;j++){if(userNum[i]==sysNum[j]){if(i==j)right++;elsemidright++;}}}}void print(){" A "+right+" B "+midright);}}。
Python小游戏代码

Python5个小游戏代码1. 猜数字游戏import randomdef guess_number():random_number = random.randint(1, 100)attempts = 0while True:user_guess = int(input("请输入一个1到100之间的数字:"))attempts += 1if user_guess > random_number:print("太大了,请再试一次!")elif user_guess < random_number:print("太小了,请再试一次!")else:print(f"恭喜你,猜对了!你用了{attempts}次尝试。
")breakguess_number()这个猜数字游戏的规则很简单,程序随机生成一个1到100之间的数字,然后玩家通过输入猜测的数字来与随机数进行比较。
如果猜测的数字大于或小于随机数,程序会给出相应的提示。
直到玩家猜对为止,程序会显示恭喜消息,并告诉玩家猜对所用的尝试次数。
2. 石头、剪刀、布游戏import randomdef rock_paper_scissors():choices = ['石头', '剪刀', '布']while True:user_choice = input("请选择(石头、剪刀、布):")if user_choice not in choices:print("无效的选择,请重新输入!")continuecomputer_choice = random.choice(choices)print(f"你选择了:{user_choice}")print(f"电脑选择了:{computer_choice}")if user_choice == computer_choice:print("平局!")elif (user_choice == '石头' and computer_choice == '剪刀') or \(user_choice == '剪刀' and computer_choice == '布') or \(user_choice == '布' and computer_choice == '石头'):print("恭喜你,你赢了!")else:print("很遗憾,你输了!")play_again = input("再玩一局?(是/否)")if play_again.lower() != "是" and play_again.lower() != "yes":print("游戏结束。
python小游戏代码

python小游戏代码import randomdef display_instructions():print("欢迎来到石头剪刀布游戏!")print("游戏规则:")print("1. 石头:普通攻击")print("2. 剪刀:剪切攻击,可以打败石头")print("3. 布:防护,可以打败剪刀")print("每一轮游戏,电脑会随机选择石头、剪刀或布。
")print("如果你想退出游戏,请输入'退出'。
")def get_user_choice():user_choice = input("请选择(石头、剪刀或布):")while user_choice not in ['石头', '剪刀', '布'] anduser_choice != '退出':print("无效的选择,请重新选择(石头、剪刀或布)或输入'退出':") user_choice = input("请选择(石头、剪刀或布):")return user_choicedef get_computer_choice():choices = ['石头', '剪刀', '布']return random.choice(choices)def determine_winner(user_choice, computer_choice):if user_choice == '退出':print("游戏结束,你选择了退出。
")elif user_choice == computer_choice:print("平局!")elif (user_choice == '石头' and computer_choice == '剪刀') or \(user_choice == '剪刀' and computer_choice == '布') or \ (user_choice == '布' and computer_choice == '石头'):print("你赢了!")else:print("你输了!")returndef play_game():display_instructions()while True:user_choice = get_user_choice()if user_choice == '退出':breakcomputer_choice = get_computer_choice()print("电脑选择了:", computer_choice)determine_winner(user_choice, computer_choice)print("谢谢游玩!")play_game()这个游戏的流程是:首先,电脑会显示游戏说明。
python小游戏源代码

# --按键检测
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
key_pressed = pygame.key.get_pressed()
#播放背景音乐
pygame.mixer.music.load(cfg.AUDIO_PATHS['bgm'])
pygame.mixer.music.play(-1, 0.0)
#字体加载
font = pygame.font.Font(cfg.FONT_PATH, 40)
#定义hero
hero = Hero(game_images['hero'], position=(375, 520))
pygame.display.flip()
clock.tick(cfg.FPS)
#游戏结束,记录最高分并显示游戏结束画面
fp = open(cfg.HIGHEST_SCORE_RECORD_FILEPATH, 'w')
fp.write(str(highest_score))
fp.close()
return showEndGameInterface(screen, cfg, score, highest_score)
#定义食物组
food_sprites_group = pygame.sprite.Group()
generate_food_freq = random.randint(10, 20)
Python天天酷跑小游戏源码

天天酷跑小游戏制作一、天天酷跑小游戏二、首先安装PYcharm软件,python3.7解释器三、先展示效果图如下四、分享代码:#库定义:import pygame,sysimport random#游戏配置width = 1200 #窗口宽度height = 508 #窗口高度size = width, heightscore=None #分数myFont=myFont1=None #字体surObject=None #障碍物图片surGameOver=None #游戏结束图片bg=None #背景对象role=None #人物对象object=None #障碍物对象objectList=[] #障碍物对象数组clock=None #时钟gameState=None #游戏状态(0,1)表示(游戏中,游戏结束)#写人物class Role: #人物def __init__(self,surface=None,y=None):self.surface=surfaceself.y=yself.w=(surface.get_width())/12self.h=surface.get_height()/2self.currentFrame=-1self.state=0 #0代表跑步状态,1代表跳跃状态,2代表连续跳跃self.g=1 #重力加速度self.vy=0 #y轴速度self.vy_start=-20 #起跳开始速度def getRect(self):return (0,self.y+12,self.w,self.h)#写障碍物class Object: #障碍物def __init__(self,surface,x=0,y=0):self.surface=surfaceself.x=xself.y=yself.w=surface.get_width()self.h=surface.get_height()self.currentFrame=random.randint(0,6)self.w = 100self.h = 100def getRect(self):return (self.x,self.y,self.w,self.h)def collision(self,rect1,rect2):#碰撞检测if (rect2[0]>=rect1[2]-20) or (rect1[0]+40>=rect2[2])or (rect1[1]+rect1[3]<rect2[1]+20) or (r ect2[1]+rect2[3]<rect1[1]+20):return Falsereturn True#写背景class Bg: #背景def __init__(self,surface):self.surface=surfaceself.dx=-10self.w=surface.get_width()self.rect=surface.get_rect()def initGame():global bg,role,clock,gameState,surObject,surGameOver,score,myFo nt,myFont1,objectList#分数初始化score=0#初始化objectList=[]#加载字体myFont=pygame.font.Font("./freesansbold.ttf",32)myFont1=pygame.font.Font("./freesansbold.ttf",64)# 创建时钟对象 (可以控制游戏循环频率)clock = pygame.time.Clock()#初始化游戏状态gameState=0#游戏背景surBg=pygame.image.load("image/bg.bmp").convert_alpha()bg=Bg(surBg)#结束画面surGameOver=pygame.image.load("image/gameover.bmp").convert _alpha()#人物图片surRole=pygame.image.load("image/role.png").convert_alpha() role=Role(surRole,508-85)#障碍物图片surObject=pygame.image.load("image/object.png").convert_alpha()def addObject():global surObject,object,objectList,objectrate=4#是否生成障碍物if not random.randint(0,300)<rate:returny=random.choice([height-100,height-200,height-300,height-400]) object=Object(surObject,width+40,y)objectList.append(object)def updateLogic():global gameState,score#键盘事件处理for event in pygame.event.get():if event.type == pygame.QUIT:sys.exit()elif event.type==pygame.KEYDOWN: #空格键跳跃if gameState==0:if event.key==pygame.K_SPACE: if role.state==0:role.state=1role.vy=role.vy_startelif role.state==1:role.state=2role.vy=role.vy_startelif gameState==1:if event.key==pygame.K_SPACE:#重新开始游戏initGame()if gameState==0:#背景的移动bg.dx+=10if bg.dx==1200:bg.dx=0#人物的移动if role.state==0:role.currentFrame+=1if role.currentFrame==12: role.currentFrame=0 else:role.y+=role.vyrole.vy+=role.gif role.y>=508-85:role.y=508-85role.state=0#障碍物的移动addObject()for object in objectList:object.x-=10 #障碍物移动# 障碍物超出屏幕,移除障碍物if object.x+object.w<=0:objectList.remove(object)score+=10 #避开障碍物,加10分print("移除了一个目标")#碰撞检测if object.collision(role.getRect(),object.getRect()): if(object.currentFrame==6):objectList.remove(object)score+=100 #吃金币加100分print(score)print("吃了一个金币")else:gameState=1 #游戏失败print("发生了碰撞!")。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
}
}
}
return true;
}
/* judge if the block can rotate */
int CanRotate()
{
int i,j,tempX,tempY;
/* update buffer */
memcpy(BufferCells, , 16);
RotateCells(BufferCells,;
for(i=0;i<;i++)
{
for(j=0;j<;j++)
{
if(BufferCells[i][j])
}
/* create a new block by key number,
* the block anchor to the top-left corner of 4*4 cells
*/
void _INNER_HELPER GenerateBlock(Block *block)
{
int key=(random(13)*random(17)+random(1000)+random(3000))%7;
int InfoLeft=300;
int InfoTop=200;
int InfoColor=YELLOW;
int BorderColor=DARKGRAY;
int BkGndColor=BLACK;
int GameRunning=true;
int TopLine=BoardHeight-1; /* top empty line */
block->color=LIGHTGRAY;
block->c[1][0]=1;
block->c[1][1]=1;
block->c[1][2]=1, block->c[0][2]=1;
break;
case 3:
block->name='z';
block->color=CYAN;
block->c[0][0]=1, block->c[1][0]=1;
int FrameTime= 1300;
int CellSize= 18;
int BoardLeft= 30;
int BoardTop= 30;
/* next block grid */
int NBBoardLeft= 300;
int NBBoardTop= 30;
int NBCellSize= 10;
=1,=0;
DrawBlock(&nextBlock,NBBoardLeft,NBBoardTop,NBCellSize);
}
/* rotate the block, update the block struct data */
int _INNER_HELPER RotateCells(char c[4][4],char blockSize)
typedef struct tagBlock
{
char c[4][4]; /* cell fill info array, 0-empty, 1-filled */
int x; /* block position cx [ 0,BoardWidht -1] */
int y; /* block position cy [-4,BoardHeight-1] */
block->size=3;/* because most blocks' size=3 */
memset(block->c,0,16);
switch(key)
{
case 0:
block->name='T';
block->color=RED;
block->c[1][0]=1;
block->c[1][1]=1, block->c[2][1]=1;
{
char temp,i,j;
switch(blockSize)
{
case 3:
temp=c[0][0];
c[0][0]=c[2][0], c[2][0]=c[2][2], c[2][2]=c[0][2], c[0][2]=temp;
temp=c[0][1];
c[0][1]=c[1][0], c[1][0]=c[2][1], c[2][1]=c[1][2], c[1][2]=temp;
/* score board position */
int ScoreBoardLeft= 300;
int ScoreBoardTop=100;
int ScoreBoardWidth=200;
int ScoreBoardHeight=35;
int ScoreColor=LIGHTCYAN;
/* infor text postion */
int GetKeyCode();
int CanMove(int dx,int dy);
int CanRotate();
int RotateBlock(Block *block);
int MoveBlock(Block *block,int dx,int dy);
void DrawBlock(Block *block,int,int,int);
block->c[1][1]=1, block->c[2][1]=1;
break;
case 4:
block->name='5';
block->color=LIGHTBLUE;
block->c[1][0]=1, block->c[2][0]=1;
block->c[0][1]=1, block->c[1][1]=1;
int TotalScore=100;
char info_score[20];
char info_help[255];
char info_common[255];
/* our board, Board[x][y][0]-isFilled, Board[x][y][1]-fillColor */
unsigned char Board[BoardWidth][BoardHeight][2];
/************************************
* Desc:俄罗斯方块游戏
* By: hoodlum1980
:30
************************************/
#include <>
#include <>
#include <>
#include <>
enum KEYCODES
{
K_ESC =0x011b,
K_UP =0x4800, /* up =0x4b00,
K_DOWN =0x5000,
K_RIGHT =0x4d00,
K_SPACE =0x3920,
K_P =0x1970
};
/* the data structure of the block */
{
/* cannot move leftward or rightward */
tempX = + i + dx;
if(tempX<0 || tempX>(BoardWidth-1)) return false; /* make sure x is valid! */
/* cannot move downward */
void EraseBlock(Block *block,int,int,int);
void DisplayScore();
void DisplayInfo(char* text);
void GenerateBlock(Block *block);
void NextBlock();
void InitGame();
tempY = + j + dy;
if(tempY>(BoardHeight-1)) return false; /* y is only checked lower bound, maybe negative!!!! */
/* the cell already filled, we must check Y's upper bound before check cell ! */
block->c[1][2]=1;
break;
case 1:
block->name='L';
block->color=YELLOW;
block->c[1][0]=1;
block->c[1][1]=1;
block->c[1][2]=1, block->c[2][2]=1;
break;
case 2:
block->name='J';
#include <>
#include <>
#define true 1
#define false 0
#define BoardWidth 12
#define BoardHeight 23
#define _INNER_HELPER /*inner helper method */
/*Scan Codes Define*/