def generateRocks(self, area): numRocks = randrange(0, int(area.height*area.width*0.005)) for rock in range(numRocks): randx = randrange(area.x-area.width//2+2, area.x+area.width//2-2) randy = randrange(area.y-area.height//2+2, area.y+area.height//2-2) foundCollision = False if ((randx, randy) in area.objList.values()): foundCollision = True; if not foundCollision: typeOfRock = randrange(0,101) if typeOfRock > 90: bigRock = GameObject('#', (102,51,0), randx, randy, visionBlock=True, moveBlock=True) area.objList[(bigRock.x, bigRock.y)] = bigRock for x in range(bigRock.x-1, bigRock.x+2): for y in range(bigRock.y-1, bigRock.y+2): foundCollision = False if ((x, y) in area.objList.values()): foundCollision = True; if not foundCollision: if randrange(0,101) > 35: smallRock = GameObject('o', (153, 102, 0), x, y, moveBlock=True) area.objList[(smallRock.x, smallRock.y)] = smallRock else: smallRock = GameObject('o', (153, 102, 0), randx, randy, moveBlock=True) area.objList[(smallRock.x, smallRock.y)] = smallRock
def generate_object(self, desc, x, y): """ Retourne un GameObject qui dépends de la description que l'on donne. Il est placé directement aux coordonnées x, y demandées. """ words = desc.split(";") identifiant = int(words[0]) behaviour = 0 if len(words) > 1: behaviour = int(words[1]) if identifiant == 0: game_object = None elif identifiant == 1: game_object = GameObject( pygame.image.load('assets/Herbe' + str(random.randint(0, 1) + 1) + '.png'), self, x, y, identifiant, False) elif identifiant in range(2, 4) or identifiant in range(10, 12): game_object = Unit( pygame.image.load('assets/' + str(identifiant) + '.png'), self, x, y, identifiant, behaviour) self.units.append(game_object) elif identifiant in range(4, 10): game_object = GameObject( pygame.image.load('assets/' + str(identifiant) + '.png'), self, x, y, identifiant, True) else: game_object = GameObject( pygame.image.load('assets/' + str(identifiant) + '.png'), self, x, y, identifiant, False) return game_object
def initialize(self): self.score = 0 self.marisa = Marisa(image=MARISA_PATH, size=None, update_ms=60, pos=(150, 150), velocity=(1, 0)) self.apples = [] self.mushrooms = [] pygame.mixer.music.load(BGM_PATH) pygame.mixer.music.play(-1) while len(self.apples) < NUM_APPLE: collide = False new_apple = GameObject(image=APPLE_PATH, size=(30, 30), update_ms=1000, pos=get_rand_pos(self.window_sz, (128, 128)), velocity=(0, 0)) for apple in self.apples: if GameObject.collide(apple, new_apple): collide = True break if collide is False: self.apples.append(new_apple) else: del new_apple while len(self.mushrooms) < NUM_MUSHROOM: collide = False new_mushrooms = GameObject(image=MUSHROOM_PATH, size=(40, 40), update_ms=1000, pos=get_rand_pos( self.window_sz, (128, 128)), velocity=(0, 0)) for mushroom in self.mushrooms: if GameObject.collide(mushroom, new_mushrooms): collide = True break if collide is False: self.mushrooms.append(new_mushrooms) else: del new_mushrooms self.last_time = int(pygame.time.get_ticks())
def init_bins(self): '''initialize the bins their default state which involves identifying the images in the resources folder and applying them to the correct bin''' #get list of game_object files game_objects = os.listdir('resources/game_objects') for item in game_objects: self.object_bin.add_item( GameObject('resources/game_objects/{}'.format(item))) #get list of terrain files and add them to the texture bin tiles = os.listdir('resources/terrain') for item in tiles: self.tile_bin.add_item(Tile('resources/terrain/{}'.format(item))) for i in range(0, 450 / Tile.HEIGHT): self.tiles.append([]) for j in range(0, 450 / Tile.WIDTH): tile = Tile('resources/terrain/grass0.png', x=(self.object_bin.rect.width + j * Tile.WIDTH), y=i * Tile.HEIGHT) tile.in_bin = False self.tiles[i].append(tile) self.buttons.append(Button('Save', 600, 25, self.save)) self.buttons.append(Button('Load', 650, 25, self.load))
def on_key_press(key, modifiers): if key == pyglet.window.key.E: self.add_game_objects((GameObject( Collider.random_polygon(6, np.random.randint(50, 101)), Rigidbody(1., 2e4, np.array([650., 800 + i * 300]), np.pi / 3)) for i in range(8))) print(len(self.constraints)) elif key == pyglet.window.key.R: self.offset = np.zeros(2) self.objects = deepcopy(snapshot) elif key == pyglet.window.key.P: self.paused = not self.paused
def generateTrees(self, area): numPatches = randrange(0, int(area.height*area.width*0.001)) for patch in range(numPatches): randx = randrange(area.x-area.width//2+10, area.x+area.width//2-9) randy = randrange(area.y-area.height//2+10, area.y+area.height//2-9) numTrees = randrange(0, 81) for tree in range(numTrees): randTreeX = randrange(randx-10, randx+11) randTreeY = randrange(randy-10, randy+11) foundCollision = False if ((randTreeX, randTreeY) in area.objList.values()): foundCollision = True; if not foundCollision: newTree = GameObject('T', (0, 102, 0), randTreeX, randTreeY, moveBlock=True) area.objList[(newTree.x, newTree.y)] = newTree
def __init__(self, screen, settings, group): self.max_stars = 250 self.star_speed = 2 self.stars = [] self.group = group self.screen = screen # galaxy sprite self.galaxy_last_release = pygame.time.get_ticks() self.galaxy_released = True self.galaxy_period = 10000 self.galaxy_speedx = 0 self.galaxy_speedy = 3 self.galaxy = GameObject(group, self.galaxy_speedx, self.galaxy_speedy, randrange(100, 539), -100) self.galaxy.set_image("assets/objects/galaxy.png")
def getGameObjectFromXMLElement(element): # prefab means we should create an instance of a prefab and extend it prefab = element.get("prefab") name = element.get("name") or "unnamed game object" if prefab: go = getGameObjectFromPrefabFileName(prefab, name) else: # prefab attribute not set. Use a new game object go = GameObject(name) for go_or_comp in element: # a game object can contain game objects and components if go_or_comp.tag == "gameobject": xml_go = go_or_comp child = getGameObjectFromXMLElement(xml_go) child.parent = go else: # must be a component otherwise getComponentFromXMLElement(go_or_comp, go) return go
def load(self, path): f = open(path, 'r') line = f.readline() line = line.split(' ') print(line) num_cols = line[1] num_rows = line[2] x_offset = int(line[3]) y_offset = int(line[4]) tiles = [] for i in range(0, int(num_rows)): tiles.append([]) for j in range(0, int(num_cols)): line = f.readline().split(' ') tile = Tile(line[0], x=int(line[1]), y=int(line[2])) tile.in_bin = False tiles[i].append(tile) #end of row f.readline() #end of line f.readline() #GameObject header f.readline() objects = [] for line in f: line = line.split(' ') item = GameObject(line[0]) item.rect.x = int(line[1]) item.rect.y = int(line[2]) item.in_bin = False objects.append(item) f.close() return (tiles, objects, x_offset, y_offset)
from buttonpad import ButtonPad from gameobject import GameObject __author__ = "Victor RENÉ" __copyright__ = "Copyright 2014, Kivy widget library" __license__ = "MIT" __version__ = "1.0" __maintainer__ = "Victor RENÉ" __email__ = "*****@*****.**" __status__ = "Production" if __name__ == '__main__': layout = RelativeLayout() d = Dpad(size_hint=(.15, .2), pos_hint={'center_x': .1, 'center_y': .5}) layout.add_widget(d) b = ButtonPad(size_hint=(.15, .2), pos_hint={ 'center_x': .9, 'center_y': .5 }) layout.add_widget(b) go = GameObject(size_hint=(.075, .1), pos_hint={ 'center_x': .5, 'center_y': .5 }) d.listeners.append(go) b.listeners.append(go) layout.add_widget(go) runTouchApp(layout)
def getSceneFromXMLElement(element, root_name="scene", validate=True): root = GameObject(str(root_name)) for xml_go in element: go = getGameObjectFromXMLElement(xml_go) go.transform.parent = root.transform return root
def addObject(self, attributes): gameObject = GameObject(attributes, self, self.innerX, self.innerY, self.innerDimension, self.baseDimension) self.objects.append(gameObject)
import pgzrun from gameobject import GameObject # Window size WIDTH = 800 HEIGHT = 600 # Game values stored in "circle" circle = GameObject( color=(255, 0, 0), # Red x=WIDTH // 2, # horizontal position (pixels) y=HEIGHT // 2, # vertical position (pixels) r=WIDTH // 10, # circle radius (pixels) speed_x=0, # horizontal speed (pixels/second) speed_y=0, # vertical speed (pixels/second) move_speed=200, # speed to move up or down ) # The square object square = GameObject( color=(0, 0, 255), # Blue x=WIDTH, # horizontal position (pixels) y=HEIGHT // 2, # vertical position (pixels) s=WIDTH // 40, # half the edge size of the square (pixels) speed_x=-100, # horizontal speed (pixels/second) speed_y=0, # vertical speed (pixels/second) ) # The background background = GameObject(
import pgzrun from gameobject import GameObject # Window size WIDTH = 800 HEIGHT = 600 # Game values stored in "circle" circle = GameObject( x = 0, # horizontal position (pixels) y = HEIGHT // 2, # vertical position (pixels) r = WIDTH // 10, # circle radius (pixels) speed_x = 200, # horizontal speed (pixels/second) speed_y = 0, # vertical speed (pixels/second) ) # The square object square = GameObject( x = WIDTH, # horizontal position (pixels) y = HEIGHT // 2, # vertical position (pixels) s = WIDTH // 40, # half the edge size of the square (pixels) speed_x = -100, # horizontal speed (pixels/second) speed_y = 0, # vertical speed (pixels/second) ) # Press and hold arrow up/down to move up and down def on_key_down(key): # UP-arrow moves circle up if key == keys.UP:
def damage(self, amount, colliders): self.blood.append(GameObject(self.position, 'blood')) super().damage(amount, colliders) self.parent.damage(5 * amount, colliders) return BloodSplatter
from graphics import Camera from pygame.math import Vector2 from gameobject import GameObject pygame.init() display = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT)) pygame.display.set_caption("Ultimate Pong") clock = pygame.time.Clock() fps_delay = 60 fps_delta = 0 camera = Camera() background = GameObject(position=Vector2(0, 0), scale=Vector2(SCREENWIDTH, SCREENHEIGHT)) background.colorize(pygame.Color(255, 255, 255)) ball = GameObject(position=Vector2(40, 40)) ball.colorize(pygame.Color(255, 0, 0)) while True: #TODO: Move inputs into a custom class and handle with single function call for event in pygame.event.get(): if event.type == QUIT: print("Closing game...") pygame.quit() sys.exit(0) elif event.type == KEYDOWN: print("Key Down: ", event.key)
def build_world(self, scene, view_rect=None, current_frame=0): # This will be deprecated shortly # print("Starting build") # self.clear_collisions(scene) objects = 0 tiles = 0 if view_rect is None: row = 0 for layer_name in self.layers.keys(): while row < self.height: for tile in xrange(0, self.width): current_tile = self.get_tile_index( layer_name, tile, row) if current_tile != -1: is_special_tile = False for special_tile in self.special_tiles.keys(): if current_tile == special_tile: is_special_tile = True if is_special_tile: scene.insert_object( GameObject( self.resource_manager.get_images( 'tile_set')[current_tile], -1000, object_type=layer_name, properties=self. special_tiles[current_tile], tile_id=current_tile, sync=True), (16 * tile, 16 * row)) else: scene.insert_object( GameObject( self.resource_manager.get_images( 'tile_set')[current_tile], -1000, object_type=layer_name, tile_id=current_tile), (16 * tile, 16 * row)) # print(str(row) + " " + str(tile)) row += 1 else: tile_rect = (view_rect.x / self.tile_width, view_rect.y / self.tile_height, view_rect.width / self.tile_width, view_rect.height / self.tile_height) # print(str(view_rect[0]) + " " + str(view_rect[1]) + " " + str(view_rect[2]) + " " + str(view_rect[3])) # Build the map tiles for layer_name in self.layers.keys(): row = 0 while row < tile_rect[3]: for tile in xrange(0, tile_rect[2]): current_tile = self.get_tile_index( layer_name, tile_rect[0] + tile, tile_rect[1] + row) if current_tile != -1: is_special_tile = False for special_tile in self.special_tiles.keys(): if current_tile == special_tile: is_special_tile = True if is_special_tile: animated = False frames = 0 # for object_property in self.special_tiles[current_tile].keys(): # if object_property == "animate": # animated = True # frames = int(self.special_tiles[current_tile][object_property]) if "animate" in self.special_tiles[ current_tile]: animated = True frames = int( self.special_tiles[current_tile] ["animate"]) if animated: images = [] for x in xrange(current_tile, current_tile + frames): images.append( self.resource_manager.get_images( 'tile_set')[x]) scene.insert_object( GameObject(images, -1000, object_type=layer_name, properties=self. special_tiles[current_tile], tile_id=current_tile, animate=True, current_frame=current_frame, sync=True), (16 * (tile_rect[0] + tile), 16 * (tile_rect[1] + row))) else: scene.insert_object( GameObject( self.resource_manager.get_images( 'tile_set')[current_tile], -1000, object_type=layer_name, properties=self. special_tiles[current_tile], tile_id=current_tile), (16 * (tile_rect[0] + tile), 16 * (tile_rect[1] + row))) else: # Allow it to determine whether objects already exist and just make them visible if they do scene.insert_object( GameObject( self.resource_manager.get_images( 'tile_set')[current_tile], -1000, object_type=layer_name, tile_id=current_tile), (16 * (tile_rect[0] + tile), 16 * (tile_rect[1] + row))) tiles += 1 # print(str(row) + " " + str(tile)) row += 1 # Build the object layers for layer_name in self.object_layers.keys(): for object_rect in self.object_layers[layer_name]: if object_rect.colliderect(view_rect): # tile_rect): rect_index = str(object_rect[0]) + " " + str( object_rect[1]) + " " + str( object_rect[2]) + " " + str(object_rect[3]) scene.insert_object( GameObject( collision_rect=pygame.Rect( 0, 0, object_rect[2], object_rect[3]), handle_collisions=True, object_type=layer_name, visible=False, properties=self.object_properties[rect_index], layer=self.object_properties[rect_index] ["layer"]), (object_rect[0], object_rect[1])) objects += 1
def addRequestedGameObject(self, name=None): """Add a game object to the local scene (only this P3D instance).""" go = GameObject(name) go.transform.parent = Root(render) self.gameobjects.append(go)
def on_resize(width, height): # Override the default on_resize handler to create a 3D projection glViewport(0, 0, width, height) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(60., width / float(height), .1, 1000.) glMatrixMode(GL_MODELVIEW) return pyglet.event.EVENT_HANDLED @window.event def on_draw(): main.draw() main = GameObject() @main('onSetup') def MainSetup(self): # One-time GL setup glClearColor(1, 1, 1, 1) glColor3f(1, 0, 0) glEnable(GL_DEPTH_TEST) glEnable(GL_CULL_FACE) # Uncomment this line for a wireframe view #glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) # Simple light setup. On Windows GL_LIGHT0 is enabled by default, # but this is not the case on Linux or Mac, so remember to always