def __init__(self, canvas, window): threading.Thread.__init__(self) self.list_rectangles = [] self.player_bat = go.Bat(100, 580) self.canvas = canvas self.score = go.GameText(10, 10) self.window = window
def load_level(levelnumber, game_objects): opencfg = configparser.ConfigParser() opencfg.read("levels/" + levelnumber + ".ini") # ast.literal_eval приводит строку к простым типам питона # (в данном случае в список позиций - туплу, в которой тупла) trees_list = ast.literal_eval(opencfg.get("GameObjects", 'trees')) # заполняем массив деревьев с помощью генераторного выражения game_objects.trees = [ GameObjects.Tree(batch, current_cell) for current_cell in trees_list ] game_objects.bricks = [ GameObjects.Brick(batch, current_cell) for current_cell in ast.literal_eval( opencfg.get("GameObjects", 'bricks')) ] game_objects.boxes = [ GameObjects.Box(batch, current_cell) for current_cell in ast.literal_eval( opencfg.get("GameObjects", 'boxes')) ] game_objects.box_targets = [ GameObjects.BoxTarget(batch, current_cell) for current_cell in ast.literal_eval( opencfg.get("GameObjects", 'box_targets')) ] return game_objects
def __init__(self, title, screen_width=800, screen_height=600, framerate=30, size=200): self.screen_width = screen_width self.screen_height = screen_height self.title = title self.running = True self.english = True self.stance = [GAME.INTRO] self.intro = True self.option = False self.sound = True self.clock = pygame.time.Clock() self.framerate = framerate self.screen = pygame.display.set_mode([screen_width, screen_height]) pygame.display.set_caption("Plumber") self.map = GameObjects.Map([], self.screen_height // size, self.screen_width // size, size) self.flow = flow.Flow(0, 0, 1000) print("game object has been created") self.size = size self.renderer = GameObjects.Renderer(size) pipe_list = mapgenerator.generate_map(self.map.rows, self.map.cols) self.map.full_map(pipe_list)
def CreateScreenBorders(self): x = self.border_width tb = GameObjects.border([-(x), -(x), self.mb[0] + 2 * (x), x]) rb = GameObjects.border([self.mb[0], 0, x, self.mb[1]]) bb = GameObjects.border([-(x), self.mb[1], self.mb[0] + 2 * (x), x]) lb = GameObjects.border([-(x), 0, x, self.mb[1]]) self.objects += [tb, rb, bb, lb]
def test_location_1(): vertical_wall_image = pygame.Surface((16, 240)) vertical_wall_image.fill((128, 128, 128)) left_wall = GameObjects.Wall(image=vertical_wall_image, coords=(0, 0)) right_wall = GameObjects.Wall(image=vertical_wall_image, coords=(240, 0)) horizontal_wall_image = pygame.Surface((256, 16)) horizontal_wall_image.fill((128, 128, 128)) bottom_wall = GameObjects.Wall(image=horizontal_wall_image, coords=(0, 160)) return Location([('default', (120, 80)), ('top', (120, 0))], [left_wall, right_wall, bottom_wall])
def initGameOver(self): gameOverMenu = pygame.sprite.Sprite() gameOverMenu.image = GameObjects.load_images('gameover') gameOverMenu.rect = pygame.Rect((410, 238), (460, 245)) self.gameOverMenu = pygame.sprite.Group(gameOverMenu) retryButton = GameObjects.Button(648, 425, 'retry') MMButton = GameObjects.Button(790, 425, 'mainmenu') newSongButton = GameObjects.Button(484, 425, 'newsong') self.gameOverButtons = pygame.sprite.Group([retryButton, MMButton, newSongButton])
def register(id, username): global f if f == True: owl = go.Owl(id, username) owls.append(owl) else: mouse = go.Mouse(id, username) mice.append(mouse) f = True
def initHelp(self): self.helpIndex = 0 helpSprite = pygame.sprite.Sprite() self.pageList = ['helpscreen', 'helpscreen1'] helpSprite.image = GameObjects.load_images(self.pageList[self.helpIndex]) helpSprite.rect = pygame.Rect(0, 0, WIDTH, HEIGHT) self.helpscreen = pygame.sprite.Group(helpSprite) next = GameObjects.Button(1160, 680, 'next') back = GameObjects.Button(120, 680, 'back') self.nextButton = pygame.sprite.Group(next) self.backButton = pygame.sprite.Group(back)
def initStart(self): # create starting conditions startSprite = pygame.sprite.Sprite() startSprite.image = GameObjects.load_images('startscreen') startSprite.rect = pygame.Rect(0, 0, WIDTH, HEIGHT) self.startScreen = pygame.sprite.Group(startSprite) self.startHero = pygame.sprite.Group(GameObjects.startHero()) self.spawnedNotes = pygame.sprite.Group() play = GameObjects.Button(640, 540, 'select') help = GameObjects.Button(640, 650, 'help') options = GameObjects.Button(1100, 665, 'options') self.startButtons = pygame.sprite.Group(play, help, options)
def table(self): global Meteor_list, Ship1 pygame.mixer.music.load("Musik\menu_musik.mp3") pygame.mixer.music.play(999999) done = True punct = 0 while done: self.window.fill((0, 0, 0)) self.render(self.window, punct, self.puncts) for e in pygame.event.get(): if e.type == pygame.QUIT: return if e.type == pygame.KEYDOWN: if e.key == pygame.K_UP: if punct > 0: punct -= 1 else: punct = len(self.puncts) - 1 if e.key == pygame.K_DOWN: if punct < len(self.puncts) - 1: punct += 1 else: punct = 0 if e.key == pygame.K_RETURN: if punct == 0: self.player.score = 0 self.player.monets = 0 Meteor_list = [] k = GameObjects.Meteor(Res.meteorImage, self.display) Meteor_list.append(k) Ship1 = GameObjects.Ship(Res.shipImage, self.display) self.main() elif punct == 1: self.main() elif punct == 2: self.instructions() elif punct == 3: Save.Score.showScore(Res.font1, self.display, self.window) elif punct == 4: return self.display.blit(self.window, (0, 0)) pygame.display.update()
def __init__(self, surface, b_config, e_config): # UI stuff self.stfont = pygame.font.SysFont('Consolas', 15, bold=False) self.drawing = True self.surface = surface # neat-python variables self.b_conf = b_config self.e_conf = e_config self.b_pop = neat.Population(b_config) self.e_pop = neat.Population(e_config) self.b_brains = [ neat.nn.FeedForwardNetwork.create(self.b_pop.population[i], b_config) for i in self.b_pop.population ] self.e_brains = [ neat.nn.FeedForwardNetwork.create(self.e_pop.population[i], e_config) for i in self.e_pop.population ] # game objects self.bow_gen = [ BowCreature(self.surface, GameObjects.Bow(self.surface)) for i in range(0, len(self.b_pop.population)) ] self.enemy_gen = [ SquareCreature(self.surface, GameObjects.Enemy(self.surface, 100)) for i in range(0, len(self.e_pop.population)) ] self.managers = [ GameObjects.WaveManager([self.enemy_gen[i].game_model], self.bow_gen[i].game_model) for i in range(0, len(self.bow_gen)) ] self.timers = [0 for i in range(0, len(self.bow_gen))] # statistics self.generations = 1 self.avg_b_fitness = [] self.avg_e_fitness = [] self.kills = [] self.e_stdev = None self.b_stdev = None self.b_gen_fitness = [] self.e_gen_fitness = []
def GameOver(window,display,player): global Ship1 D=True guy=FileWorker.Writer.nameRead(Res.file_max_score) pygame.mixer.music.load("Musik\menu_musik.mp3") pygame.mixer.music.play(999999) while D: window.fill((0, 0, 0)) GO = Res.font1.render(" GAME OVER ", 1, (200, 155, 77)) window.blit(GO, (350, 50)) GO = Res.font1.render("The best was " + guy[1][0:-1]+" with score : "+ guy[0][0:-1] ,1, (200, 155, 77)) window.blit(GO, (150, 150)) GO = Res.font1.render(' Your Score: ' + str(player.score), 1, (200, 155, 77)) window.blit(GO, (150, 250)) GO = Res.font1.render(' Press any key to continue', 1, (55, 155, 77)) window.blit(GO, (150, 350)) for e in pygame.event.get(): if e.type == pygame.QUIT: sys.exit() if e.type == pygame.MOUSEBUTTONDOWN or e.type==pygame.KEYDOWN: Ship1 = GameObjects.Ship(Res.shipImage,display) player.score = 0 player.monets = 0 D = False display.blit(window, (0, 0)) pygame.display.update()
def play_game(): game_screen = pygame.Surface((SCREEN_WIDTH, GAME_SCREEN_HEIGHT)) bg_color = BLACK all_objects = pygame.sprite.Group() player = GameObjects.Player(all_objects, coords=(120, 80)) # TESTING BELOW ''' wall_group = pygame.sprite.Group() wall_image = pygame.Surface((32, 32)) wall_image.fill((128, 128, 128)) wall_1 = Game_Object(all_objects, wall_group, image=wall_image, coords=(50, 50)) wall_2 = Game_Object(all_objects, wall_group, image=wall_image, coords=(98, 50)) ''' enter_coords, wall_group, door_group, enemy_group = load_location( locations.test_location_1()) print 'enter_coords = {}'.format(enter_coords) player.set_coords(enter_coords[1]) all_objects.add(wall_group) # TESTING ABOVE while True: if len(pygame.event.get(QUIT)) > 0: terminate() game_screen.fill(bg_color) player.update(wall_group) all_objects.draw(game_screen) SCREEN.blit(game_screen, (0, SCREEN_HEIGHT - GAME_SCREEN_HEIGHT)) pygame.display.update() GAME_CLOCK.tick(FPS)
def start_game(self): # Runs once at beginning of game for i in range(10): new_platform = GameObjects.get_new_platform(self) self.platforms.append(new_platform) self.mode = "game"
def __init__(self, master, **kwargs): tk.Canvas.__init__(self, master, width=600, height=800, bg="#a3c6ff", **kwargs) self.master = master self.width = int(self.cget("width")) self.height = int(self.cget("height")) self.mode = "splash" self.player = GameObjects.Player(self.width / 2, self.height / 2, 74, 100, "assets/player.gif") self.player.velocity.y = -20 self.platforms = [] self.keys_down = set() self.master.bind("<KeyPress>", self.handle_key_press) self.master.bind("<KeyRelease>", self.handle_key_release) self.game_loop()
def Death(self): global Meteor_list life = False Meteor_list = [] big_blast.boom = False big_blast.place.y = -60 big_blast.big_boom_time = 0 k = GameObjects.Meteor(Res.meteorImage, display) Meteor_list.append(k) if player.monets >= 1: life = menu.table2() pygame.mixer.music.load("Musik\game_musik.mp3") pygame.mixer.music.play(999999) if life == False: nik = str(Save.Score.putName(Res.font1, display, window)) FileWorker.Writer.write(Res.file_score, player.score, nik, "a") if player.score > player.max_score: FileWorker.Writer.write(Res.file_max_score, player.score, nik, "w") player.max_score = player.score Game_Over.GameOver(window, display, player) return False return True
def Game(): player = GameObjects.Player(100, 100, game_screen, player_sprite) while True: print(player.gravity, player.vel) events = pygame.event.get() for event in events: if event.type == QUIT: pygame.quit() sys.exit() for brick in bricks: if player.checkCollison(brick.hitbox): player.stopping = True player.pos.y = brick.pos.y else: player.stopping = False player.update(events) game_screen.fill((0, 0, 0)) for brick in bricks: brick.draw() player.draw() # check collision between player and platforms pygame.display.update()
def generateInputModes(self): y = 155 modesList = [] for i in range(len(GameObjects.InputModes.modes)): mode = GameObjects.InputModes(IMX, y, i) modesList.append(mode) y += IMDY return modesList
def generateSongFiles(self): x = 200 songFiles = [] for i in range(len(GameObjects.SongFile.songs)): song = GameObjects.SongFile(x, SFY, i) songFiles.append(song) x += SFDX return songFiles
def generateNotesModes(self): y = 250 notesList = [] for i in range(len(GameObjects.NotesModes.modes)): mode = GameObjects.NotesModes(315, y, i) notesList.append(mode) y += 300 return notesList
def load_objects(self, location_data): if 'walls' in location_data.keys(): walls = location_data['walls'] for obj in walls: obj_image = pygame.Surface((obj['width'], obj['height'])) obj_image.fill(obj['color']) self.add_object( GameObjects.Wall(image=obj_image, coords=obj['coords']))
def initOptions(self): # define graphics/functions for options menu optionsSprite = pygame.sprite.Sprite() optionsSprite.image = GameObjects.load_images('optionsscreen') optionsSprite.rect = pygame.Rect(0, 0, WIDTH, HEIGHT) self.optionsScreen = pygame.sprite.Group(optionsSprite) self.InputModes = pygame.sprite.Group(self.generateInputModes()) self.NotesModes = pygame.sprite.Group(self.generateNotesModes())
def initSelect(self): # define screen/attributes for this song selection selectSprite = pygame.sprite.Sprite() selectSprite.image = GameObjects.load_images('selectscreen') selectSprite.rect = pygame.Rect(0, 0, WIDTH, HEIGHT) self.selectScreen = pygame.sprite.Group(selectSprite) self.songFiles = pygame.sprite.Group(self.generateSongFiles()) self.currNote, self.currOctave = 'C', '3'
def generate_bodies(bodies): starting_x = {num for num in range(0, 400, 45)} empty_spaces = random.randint(0, 3) dmg_block_locations = set(random.sample(starting_x, 8 - empty_spaces)) for x in dmg_block_locations: bodies.append( GameObjects.Damage(x, GameObjects.Damage.square, random.randint(2, 10))) food_chance = random.randint(1, int(1 / chance_of_food)) # if(food_chance == 2): for x in (starting_x - dmg_block_locations): bodies.append( GameObjects.Food( x + (GameObjects.Damage.square - GameObjects.Food.square) / 2, (GameObjects.Damage.square) + GameObjects.Food.square, "normal"))
def play_game(): game_screen = pygame.Surface((SCREEN_WIDTH, GAME_SCREEN_HEIGHT)) bg_color = BLACK all_objects = pygame.sprite.Group() #TODO -- load player and location(s) from file player = GameObjects.Player(all_objects, coords=(128, 80)) debug_screen = debug.DebugPane(player) '''# TEST LOCATIONS CONSTRUCTED BELOW v_wall_image = pygame.Surface((TILE_SIZE, GAME_SCREEN_HEIGHT)) h_wall_image_full = pygame.Surface((SCREEN_WIDTH - 2 * TILE_SIZE, TILE_SIZE)) h_wall_image_half = pygame.Surface((SCREEN_WIDTH / 2 - TILE_SIZE, TILE_SIZE)) left_wall = GameObjects.Wall(image=v_wall_image, coords=(0,0)) right_wall = GameObjects.Wall(image=v_wall_image, coords=(SCREEN_WIDTH - TILE_SIZE, 0)) bottom_wall = GameObjects.Wall(image=h_wall_image_full, coords=(TILE_SIZE, GAME_SCREEN_HEIGHT - TILE_SIZE)) top_left_wall = GameObjects.Wall(image=h_wall_image_half, coords=(0, 0)) top_right_wall = GameObjects.Wall(image=h_wall_image_half, coords=(SCREEN_WIDTH / 2 + TILE_SIZE, 0)) test_loc_1 = [left_wall, right_wall, bottom_wall, top_left_wall, top_right_wall] for wall in test_loc_1: wall.image.fill((128, 128, 128)) #test_loc_2 = all_objects.add(test_loc_1) # TEST LOCATIONS CONSTRUCTED ABOVE''' current_screen = Locations.Location() current_screen.load_screen('level01.json', 'home') for obj in current_screen: all_objects.add(obj) while True: if len(pygame.event.get(QUIT)): terminate() # TESTING if player.rect.centery <= 0 and current_screen.name == 'home': new_objects = change_location(game_screen, all_objects, 'UP', 'level01.json', 'other') all_objects.empty() all_objects.add(new_objects) player.set_coords((120, GAME_SCREEN_HEIGHT - TILE_SIZE)) all_objects.add(player) current_screen.name = 'other' elif player.rect.centery > GAME_SCREEN_HEIGHT and current_screen.name == 'other': new_objects = change_location(game_screen, all_objects, 'DOWN', 'level01.json', 'home') all_objects.empty() all_objects.add(new_objects) player.set_coords((120, 0)) all_objects.add(player) current_screen.name = 'home' # END TESTING #TODO -- check for game over (return if so) game_screen.fill(bg_color) player.update(all_objects) #TODO -- update objects by group (enemies, ....?) all_objects.draw(game_screen) SCREEN.blit(game_screen, (0, SCREEN_HEIGHT - GAME_SCREEN_HEIGHT)) debug_screen.update(player) debug_screen.draw(SCREEN) pygame.display.update() GAME_CLOCK.tick(FPS)
def __init__(self, window_dimensions, mapBorders): self.start_time = time.time() self.score = 0 self.fail = False self.wd = window_dimensions self.target = GameObjects.player([200, 200, 40, 40]) self.objects = [self.target] self.border_width = 20 self.mb = mapBorders self.CreateScreenBorders() self.acceleration = 800
def initGame(self): self.initGameOver() self.player = Player(MusicAnalyzer.generateSong(self.filename)) clefs = (GameObjects.TrebleClef(90, 186), GameObjects.BassClef(90, 504)) self.Lines = pygame.sprite.Group(GameObjects.Lines.generateStaff()) self.Clefs = pygame.sprite.Group(clefs) self.Notes = pygame.sprite.Group(self.player.musicNotes) self.Treble = pygame.sprite.Group(self.player.getTrebleNotes()) self.Bass = pygame.sprite.Group(self.player.getBassNotes()) self.Hero = pygame.sprite.Group(GameObjects.Hero(y=135)) self.heroSpawn = pygame.sprite.Group() if self.gameMode == 'treble': self.targetNotes = self.Treble self.CPUTargets = self.Bass self.Portal = pygame.sprite.Group(GameObjects.NotePortal(180)) cpuHeight = 540 else: self.getHero().y = 540 self.targetNotes = self.Bass self.CPUTargets = self.Treble self.Portal = pygame.sprite.Group(GameObjects.NotePortal(495)) cpuHeight = 135 if self.hasCPU: self.CPU = pygame.sprite.Group(GameObjects.Hero(y=cpuHeight)) self.getNextCPU() self.moveCPU() self.total = len(self.player.notesList) self.pianoTargets = None self.getNextTarget() self.numerator, self.denominator = self.player.song.getTimeSignature()
def add_platforms(self): new_platforms = [] num_new_platforms = randint(1, 1) print(num_new_platforms) while len(new_platforms) < num_new_platforms: platform = GameObjects.get_new_platform(self) platform.position.y -= self.width collides = False for p in self.platforms: if platform.check_collide(p): collides = True if not collides: new_platforms.append(platform) self.platforms += new_platforms
def __init__(self): pygame.init() # Initializing file manager and loading icon self.fileManager = FileManager.FileManager('Textures', 'Sounds') # Display properties pygame.display.set_icon(self.fileManager.icon) self.screen = pygame.display.set_mode((800, 600)) pygame.display.set_caption('Pulse') # Setting background self.fileManager.loadBackground() self.background = self.fileManager.backgroundTexture # Display update self.cleanWindow() pygame.display.flip() # Initializing game files self.fileManager.loadGameFiles() # Initializing game objects self.gameObjects = GameObjects.GameObjects() # Initializing level manager self.levelManager = LevelManager.LevelManager(self.fileManager, self.gameObjects) # Initializing menues self.menues = Menues.Menues(self.fileManager, self.levelManager) # Initializing HUD self.HUD = pygame.sprite.RenderPlain() self.HUDObject = HUD.HUD(self.levelManager.currentLevel(), True) self.HUD.add(self.HUDObject) # Adding notifieras to gameObjects self.gameObjects.addNotifier(self.HUDObject) self.gameObjects.addNotifier(self.levelManager) # Initializing clock self.clock = pygame.time.Clock() # Game running. Showing nenu on False. self.gameRunning = False # Starting music pygame.mixer.music.play(-1) # Showing main menu self.menues.main()
def init(self): self.mode = 'start' self.pianoOn = False self.gameOver = False self.hasDual = False self.filename = 'music/fur_elise.mid' self.timer = 0 self.noteQ = deque(maxlen=5) self.NoteFont = pygame.font.SysFont('alba', 80) self.GameFont = pygame.font.SysFont('alba', 35) self.GameOverFont = pygame.font.SysFont('alba', 38) self.FileFont = pygame.font.SysFont('agency fb', 45) self.timeFont = pygame.font.Font('assets/Aruvarb.ttf', 116) self.gameMode = 'treble' self.inputText = '' self.backarrow = pygame.sprite.Group(GameObjects.Button(60, 34, 'backarrow')) self.hasCPU = True self.isPaused = False # start screen self.initStart() self.initSelect()
print "mousebuttondown: ", MouseX,MouseY; bullet.Shoot(MouseX,MouseY); print "bulletstatus,hit ", bullet.status,bullet.hit; if bullet.hit: bullet.v = 0; bullet.hit = False; bullet.status = False; if not bullet.hit and not bullet.status: (bullet.x,bullet.y) = Player1.player(); screen.fill(black); pygame.draw.rect(screen,white,field,1); pygame.draw.line(screen,white,Player1.player(),Player2.player(),1); pygame.draw.circle(screen,red,Player1.player(),shipSize,3); pygame.draw.circle(screen,green,Player2.player(),shipSize,3); points = GameObjects.DirectionLine(Player1.player(), Player1.dx, Player1.dy); pygame.draw.line(screen, white,points[0],points[1],1); points = GameObjects.DirectionLine(Player2.player(),Player2.dx,Player2.dy); pygame.draw.line(screen,white,points[0],points[1],1); if GameObjects.getDistance(Player1.player(),Player2.player())<Player1.r+Player2.r: print "ship 1 collided"; if GameObjects.getDistance(Player2.player(),Player1.player())<Player2.r+Player1.r: print "ship 2 collided"; pygame.draw.circle(screen,(250,250,0),bullet.projectile(), bulletSize, 0); pygame.display.flip();