class ExplorableScreen(GameScreen): def __init__(self, config, model): super(ExplorableScreen, self).__init__(config, model) def setup(self): super(ExplorableScreen, self).setup() pastel_flowers = Image(os.path.join("sample_sprites", "tiles", "png", "pastel_flowers.png")) grass = Image(os.path.join("sample_sprites", "tiles", "png", "grass.png")) images = (pastel_flowers, grass) # XXX Just a demo, do not try this at home: this (rightly!) assumes that # pastel_flowers and grass have the same dimensions visible_width = int(self.screen_dimensions[GameConfig.WIDTH_INDEX] / pastel_flowers.width) visible_height = int(self.screen_dimensions[GameConfig.HEIGHT_INDEX] / pastel_flowers.height) area_tile_size = (visible_width + 2) * (visible_height + 2) self.tiles = Group() for i in range(area_tile_size): img = random.choice(images) img_xpos = img.width * (i % visible_width) img_ypos = img.height * (i % visible_height) self.tiles.add(PyRoSprite(img.clone((img_xpos, img_ypos)))) def draw_screen(self, window): self.tiles.draw(window) self.tiles.update()
def update(self, dt): Group.update(self, dt) self.spawn_timer += dt if self.spawn_timer >= self.spawn_rate: self.spawn() self.spawn_timer = 0
def run_game(): pygame.init() ai_settings = Settings() screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") # make a ship ship = Ship(ai_settings, screen) bullets = Group() aliens = Group() alien = Alien(ai_settings, screen) gf.create_fleet(ai_settings, screen, aliens) while True: gf.check_events(ai_settings, screen, ship, bullets) ship.update() gf.update_bullets(bullets) gf.update_screen(ai_settings, screen, ship, aliens, bullets) bullets.update() # Get rid of bullets that have disappeared. for bullet in bullets.copy(): if bullet.rect.bottom <= 0: bullets.remove(bullet) print(len(bullets))
def update(self): """Updates cells' positions only if target is followable""" if self.target.is_followable(): Group.update(self) if self.delay > 0: self.delay -= 1
class CollectCoinMicrogame(Microgame): def __init__(self): # TODO: Initialization code here Microgame.__init__(self) self.coins = coin(0) #coin(locals.HEIGHT + 70)] self.ironman = ironman() self.sprites = Group(self.ironman, self.coins) self.time = pygame.time.get_ticks() def start(self): # TODO: Startup code here music.load(os.path.join("games", "catching", "super_mario_levels.wav")) music.play() def stop(self): # TODO: Clean-up code here music.stop() self.lose() def update(self, events): # TODO: Update code here self.sprites.update() ctrls = pygame.key.get_pressed() if ctrls[K_q]: self.win() elif ctrls[K_a] or ctrls[K_LEFT]: self.ironman.rect.x = max(self.ironman.rect.x - 30, 0) elif ctrls[K_d] or ctrls[K_RIGHT]: self.ironman.rect.x = min(locals.WIDTH - 68, self.ironman.rect.x + 30) if self.coins.rect.colliderect(self.ironman): # self.time = pygame.time.get_ticks() # self.sprites.remove(self.coins) # print str(self.time) + " " + str(pygame.time.get_ticks()) # if self.time + 3000 <= pygame.time.get_ticks(): # self.coins = coin(0) # self.sprites.add(self.coins) self.coins.rect.y = 0 self.coins.velocity = 0 self.coins.rect.left = randint(0, locals.WIDTH - COIN_WIDTH) # self.sprites.update() elif self.coins.rect.top > locals.HEIGHT: self.lose() def render(self, surface): # TODO: Rendering code here surface.fill(Color(0, 0, 0)) imgpath = os.path.join("games", "catching", "8bitsky.jpg") test_image = pygame.image.load(imgpath) surface.blit(test_image,(0,0)) self.sprites.draw(surface) def get_timelimit(self ): # TODO: Return the time limit of this game (in seconds) return 15
class Panel: def __init__(self, world_map): self.world_map = world_map self.group = Group() self.energy_bar = EnergyBar(world_map.main_character, 15, 10, self.group) self.energy_bar.put(75, 13) self.energy_bar = LifeBar(world_map.main_character, 15, 10, self.group) self.energy_bar.put(75, 30) self.rect = Rect(0, 0, SCREEN_W, 40) self.background = data.load_image('panel.png') font = Font(data.filepath('fonts', 'vera.ttf'), 12) #font.set_bold(True) self.twister_text = font.render("Twister:", True, (0,0,0)) self.life_text = font.render("Life:", True, (0,0,0)) self.world_text = font.render("World: %s" % world_map.name, True, (0,0,0)) class TimeText(Sprite): def __init__(self, world_map, *groups): Sprite.__init__(self, *groups) self.world_map = world_map def update(self, *args): time = self.world_map.time time_str = self.world_map.get_time() if time < 60: color = (170, 0, 0) elif time < 120: color = (255, 100, 0) else: color = (0, 0, 0) self.image = font.render("Time: %s"% time_str , True, color) self.rect = self.image.get_rect() self.rect.move_ip(500, 0) TimeText(world_map, self.group) self.key = KeyItem(world_map) self.key.put(620, 20) self.key.remove(self.key.groups()) def draw(self, screen): if self.world_map.got_key: self.key.add(self.group) screen.set_clip(self.rect) self.group.clear(screen, self.background) self.group.update() self.group.draw(screen) def draw_background(self, screen): screen.blit(self.background, (0,0)) screen.blit(self.twister_text, (10, 0)) screen.blit(self.life_text, (10, 17)) screen.blit(self.world_text, (500, 17))
class Logo: "Escena que muestra el logotipo del grupo losersjuegos." def __init__(self, world): self.world = world self.sprites = Group() self._create_sprites() self._reset_timer() def _reset_timer(self): self.time_out = 50 def update(self): key = pygame.key.get_pressed() if key[pygame.K_ESCAPE]: self.world.state = Logo(self.world) self._reset_timer() return else: self.sprites.update() if self.time_out < 1 or key[pygame.K_RETURN]: self.world.change_state(scenes.mainmenu.MainMenu(self.world)) self.time_out -= 1 def draw(self, screen): screen.fill((92, 123, 94)) self.sprites.draw(screen) pygame.display.flip() def _create_sprites(self): steps = [0, 0, 0, 1, 2, 3, 4] losers = SimpleAnimation('logo', 'losers_5.png', steps, 2) sprite_losers = LogoSpriteAnimated(losers, LEFT, 190, 190) steps2 = [0, 0, 0, 1, 2, 3, 4] juegos = SimpleAnimation('logo', 'juegos_5.png', steps2, 2) sprite_juegos = LogoSpriteAnimated(juegos, RIGHT, 390, 190) steps3 = [0, 0, 0, 1, 1, 2, 3] ceferino = SimpleAnimation('logo', 'ceferino_4.png', steps3, 2) sprite_ceferino = LogoSpriteAnimated(ceferino, RIGHT, 40, 160) self.sprites.add([sprite_juegos, sprite_losers, sprite_ceferino]) def handle_event(self, event): pass
class Game(object): background = 80,80,80 def __init__(self): pygame.init() self.screen = pygame.display.set_mode((640,480)) self.players = Group() p1 = Player((255,0,0), self.players) p2 = Player((0,0,255), self.players) def draw(self): self.screen.fill(self.background) def update(self): self.players.update()
def run_game(): # Initialize game and create a screen object. pygame.init() ai_settings = Settings() screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Zombie Tower Ultimate Sonic The Next Generation Super EX") play_button = Button(ai_settings, screen, "Play") # Set the background color ship = Ship(screen, ai_settings) bullets = Group() bomb = Group() lasercheat = Group() nuke = Nuke(ai_settings, screen, ship) block = Block(ai_settings, screen, nuke) wall = Wall(ai_settings, screen, ship) lift = Lift(ai_settings, screen, nuke) aliens = Group() alien = Alien(ai_settings, screen) # Start the main loop for the game. stats = GameStats(ai_settings, bomb, aliens, bullets) sb = Scoreboard(ai_settings, screen, stats) gf.create_fleet(ai_settings, screen, ship, aliens) while True: # Watch for keyboard and mouse events. gf.check_events(ai_settings, screen, stats, ship, bullets, lasercheat, aliens, nuke, play_button, bomb, wall, lift) if stats.game_active: ship.update() gf.update_aliens(ai_settings, stats, screen, ship, aliens, bomb, wall) ai_settings.counterpnts -= 1 if ai_settings.counterpnts <=0: ai_settings.counterpnts = 60 stats.score += 1 sb.prep_score() bullets.update() bomb.update(aliens, ai_settings, screen) gf.update_screen(ai_settings, screen, stats, sb, ship, bullets, lasercheat, aliens, nuke, play_button, wall, bomb, lift, block) # Get rid of bullets that have disappeared. for bullet in bullets.copy(): if bullet.rect.right >= 1200: bullets.remove(bullet) print(len(bullets))
def game(): # init pygame.init() screen = pygame.display.set_mode(SCREEN_SIZE) clock = pygame.time.Clock() dude = PlayerShip(260, 500, screen.get_rect()) dude_grp = GroupSingle(dude) enemies = Group() enemies.add(Burger(200, 200, screen.get_rect())) enemies.add(Hotdog(100, 100, screen.get_rect())) #loop while True: # input for evt in pygame.event.get(): if evt.type == QUIT: return elif evt.type == KEYDOWN and evt.key == K_ESCAPE: return elif evt.type == KEYDOWN and evt.key == K_a: dude.dx = -10 elif evt.type == KEYDOWN and evt.key == K_d: dude.dx = 10 elif evt.type == KEYUP and evt.key == K_a and dude.dx == -10: dude.dx = 0 elif evt.type == KEYUP and evt.key == K_d and dude.dx == 10: dude.dx = 0 elif evt.type == KEYDOWN and evt.key == K_SPACE and dude.alive(): dude.shoot() # update clock.tick(FPS) dude.update() enemies.update() dude.bullets.update() pygame.sprite.groupcollide(enemies, dude.bullets, 1, 1) pygame.sprite.groupcollide(dude_grp, enemies, 1, 0) # draw screen.fill(BLACK) dude_grp.draw(screen) enemies.draw(screen) dude.bullets.draw(screen) pygame.display.flip()
class WvmSpritesList(): """A class listing all the Sprites of the game.""" def __init__(self, config, screen): """Initialize the sprite list.""" self.config = config self.screen = screen #initialize the sprites self.wiz = Wizard(config, self) self.monsters = Group() self.missiles = Group() def update_all(self): """Update the positions of all sprites.""" self.update_missiles() self.wiz.update() self.monsters.update() def update_missiles(self): """update magic missiles positions""" self.missiles.update() # remove the missiles that have left the screen for mi in self.missiles.copy(): if mi.rect.left >= self.screen.get_rect().right: self.missiles.remove(mi) def draw(self): self.screen.fill(self.config.bg_color) for mi in self.missiles: mi.draw_missile() self.wiz.blitme() for mo in self.monsters: mo.blitme() def fire_missile(self): """Fire a missile if limit not reached yet.""" if len(self.missiles) < self.wiz.magic_missile_allowed: self.missiles.add(MagicMissile(self.config, self)) def create_monster(self): """Create a new monster and place it randomly at the right.""" monster=Monster(self.config, self) #TODO move the monster self.monsters.add(monster)
def run_game(): # 初始化游戏设置 screen = gf.init() # 创建飞船 ship = Ship(screen, gf.s.ship_speed) # 创建子弹 bullets = Group() # 创建敌人 aliens = Group() while True: gf.update_screen(screen, ship, bullets, aliens) gf.check_events(ship, bullets) bullets.update() ship.update_seat() aliens.update()
def run_game(): pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") ship = Ship(ai_settings, screen) bullets = Group() while True: gf.check_events(ai_settings, screen, ship, bullets) ship.update() gf.update_bullets(bullets) bullets.update() for bullet in bullets.copy(): if bullet.rect.bottom <= 0: bullets.remove(bullet) gf.update_screen(ai_settings, screen, ship, bullets) pygame.display.flip()
def run_game(): pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alein Invasion") # 创建一艘飞船 ship = Ships(ai_settings, screen) # 创建一个用于存储子弹的编组 bullets = Group() # 开始游戏的主循环 while True: gf.check_events(ai_settings, screen, ship, bullets) ship.update() bullets.update() gf.update_screen(ai_settings, screen, ship, bullets)
def run_game(): # 初始化游戏并创建一个屏幕对象 pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption('Alien Invasion') # 创建Play按钮 play_button = Button(ai_settings, screen, "Play") # 创建存储游戏统计信息的实例,并创建记分牌 stats = GameStats(ai_settings) sb = Scoreboard(ai_settings, screen, stats) # 创建一艘飞船 ship = Ship(ai_settings, screen) # 创建一个用于存储子弹的编组 bullets = Group() # 创建一个外星人编组 aliens = Group() # 创建一个外星人 # alien = Alien(ai_settings, screen) # 创建外星人群 gf.create_fleet(ai_settings, screen, ship, aliens) # 开始游戏的主循环 while True: # 将事件循环替换为对函数check_events()的调用 gf.check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets) if stats.game_active: ship.update() # 将alien_invasion.py的while循环中更新的代码替换为对函数update_screen()的调用 bullets.update() gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets) gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens, bullets) gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button)
class WvmSpritesList(): """A class listing all the Sprites of the game.""" def __init__(self, config, screen): """Initialize the sprite list.""" self.config = config self.screen = screen #initialize the sprites self.wiz = Wizard(config, self) self.monsters = Group() self.missiles = Group() def update_all(self): """Update the positions of all sprites.""" self.update_missiles() self.wiz.update() self.monsters.update() def update_missiles(self): """update magic missiles positions""" self.missiles.update() # remove the missiles that have left the screen for mi in self.missiles.copy(): if mi.rect.left >= self.screen.get_rect().right: self.missiles.remove(mi) def draw(self): self.screen.fill(self.config.bg_color) for mi in self.missiles: mi.draw_missile() self.wiz.blitme() for mo in self.monsters: mo.blitme() def fire_missile(self): """Fire a missile if limit not reached yet.""" if len(self.missiles) < self.wiz.magic_missile_allowed: self.missiles.add(MagicMissile(self.config, self)) def create_monster(self): """Create a new monster and place it randomly at the right.""" monster = Monster(self.config, self) #TODO move the monster self.monsters.add(monster)
def run_game(): # Initialize game pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invaders by Diana Joya") # Game Stats stats = GameStats(ai_settings) sb = Scoreboard(ai_settings, screen, stats) # Screens start_screen = Start(ai_settings, screen) score_board = HighScores(ai_settings, screen, stats) # Sprite Groups ship = Ship(ai_settings, screen) bullets = Group() aliens = Group() bunkers = Group() random_ufo = UFO(ai_settings, screen) bullet_animation = BulletAnimation(ai_settings, screen, ship, bullets, aliens, stats, sb, random_ufo, bunkers) events = Update(ai_settings, screen, ship, bullets, aliens, stats, sb, start_screen, score_board, random_ufo, bunkers) collision = Collisions(ai_settings, screen, ship, bullets, aliens, stats, sb, start_screen, score_board, random_ufo, bunkers) # Game Loop while True: events.check_events() if stats.game_active: current_time = pygame.time.get_ticks() ship.update() bullet_animation.update_bullets() collision.update_aliens() bunkers.update() if ai_settings.ufo_allowed: random_ufo.update(current_time) events.update_screen()
def run_game(): #初始化游戏并创建一个屏幕对象 pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) #游戏名字 pygame.display.set_caption("怪兽入侵 (王子明制作)") # 创建一个用于存储游戏统计信息的实例 stats = GameStats(ai_settings) sb = Scoreboard(ai_settings, screen, stats) back_picture = Picture(ai_settings ,screen) # 创建 Play 按钮 play_button = Button(ai_settings, screen,"play" ) #创建一艘飞船 ship = Ship(ai_settings ,screen) bullets = Group() aliens = Group() #alien = Alien(ai_settings,screen) # 创建外星人群 gf.create_fleet(ai_settings, screen,ship,aliens) #开始游戏循环 while True: gf.check_events(ai_settings, screen, stats, sb,play_button, ship, aliens, bullets) if stats.game_active: ship.update() bullets.update() gf.update_bullets(ai_settings, screen,stats,sb, ship, aliens, bullets) gf.update_aliens(ai_settings,screen,stats,sb,ship, aliens,bullets) gf.update_screen(ai_settings,screen,back_picture ,stats,sb,ship,aliens,bullets,play_button )
def run_game(): # 初始化游戏并创建一个屏幕对象 pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("外星人入侵") # 创建Play按钮 play_button = Button(ai_settings, screen, "Play") # 创建一个用于存储游戏统计信息的实例 stats = GameStats(ai_settings) # 创建存储游戏统计信息的实例,创建记分牌 sb = ScoreBoard(ai_settings, screen, stats) # print(pygame.display.list_modes()) # 创建一艘飞船 ship = Ship(ai_settings, screen) # 创建一个外星人 alien = Alien(ai_settings, screen) # 创建存储子弹的编组 bullets = Group() # 创建存储外星人的编组 aliens = Group() gf.create_fleet(ai_settings, screen, ship, aliens) # 开始游戏的主循环 while True: # 监视键盘和鼠标事件 gf.check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets) if stats.game_active: ship.update() bullets.update() gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets) gf.update_aliens(ai_settings, stats, sb, screen, ship, aliens, bullets) gf.update_screen(ai_settings, screen, stats, sb, ship, bullets, aliens, play_button)
class KoalaKross(Microgame): def __init__(self): Microgame.__init__(self) self.rect= Rect(0,0, locals.WIDTH, locals.HEIGHT) ## surface=pygame.display.set_mode((1024,768)) ## surface.fill(Color(0,0,250)) koala=Koala(self) self.panda1=Panda(200,100,0,2) self.panda2=Panda(500,100,0,2) self.bread=Bread(self) self.sprites=Group((koala,self.panda1,self.panda2,self.panda3)) self.clock=pygame.time.Clock() def start(): pass def stop(): pass def update(self): time=pygame.time.get_ticks() self.sprites.update() for event in pygame.event.get(): if event.type == KEYDOWN: if event.key==K_DOWN: koala.velocity=(0,-3) elif event.key==K_UP: koala.velocity=(3,0) elif event.key == K_Right: koala.velocity=(3,0) elif event.key == K_Left: koala.velocity=(-3,0) elif event.key == K_q: self.lose() elif event.type == KEYUP: koala.velocity=(0,0) def render (self, surface): ## Surface=display.set_mode((1024,768)) surface.fill.Color(0,0,0) self.sprites.draw(surface)
def run_game(): """ Inicializa o jogo e cria um objeto para a a tela """ pygame.init() settings = Settings() screen = pygame.display.set_mode((settings.screen_width, settings.screen_height)) pygame.display.set_caption(settings.game_name) ship = Ship(settings, screen) bullets = Group() # Inicia o laço principal do jogo while True: gf.check_events(settings, screen, ship, bullets) # Observa eventos de teclado e de mouse ship.update() bullets.update() gf.update_screen(settings, screen, ship, bullets)
def run_game(): #Initialize game and create screen object. pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") # Make a ship ship = Ship(ai_settings, screen) # make a group to store bullets in. bullets = Group() #Start the main loop for the game. while True: gf.check_events(ai_settings, screen, ship, bullets) ship.update() bullets.update() gf.update_screen(ai_settings, screen, ship, bullets)
def main_air(): """侧面射击 : 编写一个游戏, 将一艘飞船放在屏幕左边, 并允许玩家上下移动飞船。 在玩家按空格键时, 让飞船发射一颗在屏幕中向右穿行的子弹, 并在子弹离开屏幕而消失后将其删除。""" pygame.init() air_set = Set() screen = pygame.display.set_mode((air_set.screen_width, air_set.screen_height)) air_ship = AirShip(screen, air_set) pygame.display.set_caption('飞船') bullets = Group() while True: mf.check_airship_event(air_set, screen, air_ship, bullets) air_ship.air_ship_update() bullets.update() for bullet in bullets.copy(): if bullet.rect.right > air_ship.screen_rect.right: bullets.remove(bullet) print(len(bullets)) mf.update_air_screen(air_set, screen, air_ship, bullets)
class TestScene(Scene): name = "test" def on_init(self): self.test_sprites = Group() spritemap = engine.loader.load("animsprite.png") rect = Rect(100, 100, 16, 16) test_sprite = AnimatedSprite(spritemap, rect, self.test_sprites) test_sprite.animate([0, 1, 2, 1], 5, True) def on_cleanup(self): pass def on_update(self, delta, events): self.test_sprites.update(delta) def on_render(self, screen): self.test_sprites.draw(screen)
def run_game(): #initialize game and create a screen object. pygame.init() mixer.pre_init(frequency=44100, size=-16, channels=2, buffer=4096) ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption('Alien Invasion') blaster = Blaster() music = Music() #make the Play button play_button = Button(ai_settings, screen, "Play") pause_button = Button(ai_settings, screen, "Pause") #create an instance to store game stats and create a scoreboard stats = GameStats(ai_settings) sb = Scoreboard(ai_settings, screen, stats) #make a ship, a group of bullets, and a group of aliens ship = Ship(ai_settings, screen) bullets = Group() aliens = Group() explosions = Group() #create a fleet of aliens gf.create_fleet(ai_settings, screen, ship, aliens) pygame.mixer.music.play(-1, 24.8) #start the main loop of the game while True: gf.check_events(ai_settings, screen, stats, play_button, ship, aliens, bullets, blaster, sb, pause_button) if stats.game_active == True: if stats.pause_game == False: ship.update() gf.update_bullets(ai_settings, screen, ship, aliens, bullets, blaster, explosions, sb, stats) gf.update_aliens(ai_settings, stats, screen, ship, aliens, bullets, sb) explosions.update() gf.update_screen(ai_settings, screen, stats, ship, aliens, bullets, play_button, explosions, sb, pause_button)
def run_game(): pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) ship = Ship(ai_settings, screen) stats = Game_stats(ai_settings) bullets = Group() aliens = Group() gf.create_fleet(ai_settings, screen, aliens, ship) pygame.display.set_caption(ai_settings.game_name) while True: gf.check_evens(ship, bullets, ai_settings, screen) ship.update() bullets.update() gf.update_bullets(bullets, aliens, ship, ai_settings, screen) gf.update_aliens(ai_settings, stats, aliens, ship, bullets, screen) gf.update_screen(ship, bullets, aliens, ai_settings, screen)
def run_game(): pygame.init() screen = pygame.display.set_mode((666, 555)) bgcolor = (222, 222, 255) screen.fill(bgcolor) stars = Group() pygame.display.set_caption("Blue Skey") generate_stars(screen, stars) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() screen.fill(bgcolor) stars.update() pygame.display.flip()
def run_game(): pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("INVASION") ship = Ship(ai_settings, screen) bullets = Group() alien = Alien(ai_settings, screen) bg_color = (230, 230, 230) while True: gf.check_events(ai_settings, screen, ship, bullets) ship.update() bullets.update() gf.update_bullets(bullets) gf.update_screen(ai_settings, screen, ship, alien, bullets)
def run_game(): # 初始化游戏并创建一个屏幕对象 pygame.init() ai_settings = Settings() # 创建一艘飞船 screen = pygame.display.set_mode( [ai_settings.screen_width, ai_settings.screen_height]) pygame.display.set_caption('Alient Invasion') ship = Ship(ai_settings, screen) # 创建一个用于存储子弹的编组 bullets = Group() # 开始游戏的主循环 while True: # 监视键盘和鼠标事 gf.check_events(ai_settings, screen, ship, bullets) ship.update() bullets.update() gf.update_screen(ai_settings, screen, ship, bullets)
def run_game(): # 初始化游戏并创建屏幕对象 pygame.init() ai_settings = Settings() scree = pygame.display.set_mode( (ai_settings.scree_width, ai_settings.scree_height)) pygame.display.set_caption("Alien Invasion") # 绘制飞船 ship = Ship(scree, ai_settings) # 创建子弹组 bullets = Group() # 开始游戏 while True: gf.check_events(ai_settings, scree, ship, bullets) ship.update() bullets.update() gf.update_bullet(bullets) gf.update_scree(ai_settings, scree, ship, bullets)
def run_game(): pygame.init() ai_settings = settings.Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") ship = sh.Ship(ai_settings, screen) alien1 = alien.Alien(ai_settings, screen) bullets = Group() aliens = Group() gf.create_fleet(ai_settings, screen, ship, aliens) while True: gf.check_events(ai_settings, screen, ship, bullets) ship.update() bullets.update() gf.update_bullets(bullets) gf.update_aliens(aliens) gf.update_screen(ai_settings, screen, ship, aliens, bullets)
def run_game(): pygame.init() pygame.display.set_caption("Alien Invasion") ai_setting = Setting() screen = pygame.display.set_mode( (ai_setting.screen_width, ai_setting.screen_height)) stats = Game_stats(ai_setting) play_button = Play_button(ai_setting, screen, "Play") sb = Scoreboard(ai_setting, screen, stats) ship = Ship(screen, ai_setting) aliens = Group() bullets = Group() gf.creat_fleet(ai_setting, screen, aliens, ship) while True: gf.check_events(ai_setting, screen, ship, bullets, play_button, aliens, stats, sb) if stats.game_active: ship.update() bullets.update() gf.update_bullets(bullets, aliens, ai_setting, screen, ship, sb, stats) gf.update_aliens(ai_setting, aliens, ship, stats, screen, bullets, sb) gf.update_screen(ai_setting, screen, ship, bullets, aliens, play_button, sb, stats)
def run_game(): pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") ship = Ship(ai_settings, screen) bullets = Group() while True: gf.check_events(ai_settings, screen, ship, bullets) ship.update() time.sleep(0.01) bullets.update() gf.update_screen(ai_settings, screen, ship, bullets)
def run_game(): # init game and create screen object pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") # Create an instance to store game statistics. stats = GameStats(ai_settings) sb = Scoreboard(ai_settings, screen, stats) # Make a ship. ship = Ship(ai_settings, screen) bullets = Group() aliens = Group() # Create the fleet of aliens. gf.create_fleet(ai_settings, screen, ship, aliens) # Make an alien. # Make the Play button. play_button = Button(ai_settings, screen, "Play") while True: gf.check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets) if stats.game_active: ship.update() gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets) gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens, bullets) bullets.update() # Get rid of bullets that have disappeared. for bullet in bullets.copy(): if bullet.rect.bottom <= 0: bullets.remove(bullet) gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button)
def start_window(): # start the game and make a screen object and settings for the game pygame.init() ai_settings = Settings() window = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_hieght)) pygame.display.set_caption("Inavders Return!") # spawn ship ship = Ship(ai_settings, window) # Store rounds in a group rounds = Group() # Game Main loop while True: gf.check_events(ai_settings, window, ship, rounds) ship.update() rounds.update() gf.update_rounds(rounds) gf.update_window(ai_settings, window, ship, rounds)
def init_game(): pygame.init() game_settings = Settings() screen = pygame.display.set_mode( (game_settings.screen_width, game_settings.screen_height)) ship = Ship(screen) bullets = Group() background = Background(screen) aliens = Group() stats = Stats(game_settings) g_f.create_fleet(game_settings, screen, aliens, ship) pygame.display.set_caption("Our first game") while True: g_f.check_events(game_settings, screen, ship, bullets) g_f.update_screen(background, ship, bullets, aliens, screen) ship.update() bullets.update() g_f.update_aliens(game_settings, aliens, stats, screen, ship, bullets) g_f.update_bullets(bullets, aliens)
def run_game(): # Инициализирует игру и создает объект экрана. pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") # Создание корабля ship = Ship(ai_settings, screen) # Создание группы для хранения пуль. bullets = Group() # Запуск основного цикла игры. while True: # Отслеживание событий клавиатуры и мыши. gf.check_events(ai_settings, screen, ship, bullets) ship.update() bullets.update() gf.update_bullets(bullets) gf.update_screen(ai_settings, screen, ship, bullets)
def run_game(): # Initialize game and create a screen object pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") # Make the Play button play_button = Button(ai_settings, screen, "Play") # Create an instance to store game stats and make a scoreboard stats = GameStats(ai_settings) sb = Scoreboard(ai_settings, screen, stats) # Set the background color bg_color = (230, 230, 230) # Make a ship, a group of bullets, and a group of aliens ship = Ship(ai_settings, screen) bullets = Group() aliens = Group() # Create the fleet of aliens. gf.create_fleet(ai_settings, screen, ship, aliens) # Start the main loop for the game while True: gf.check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets) # Watch for keyboard and mouse events if stats.game_active: ship.update() bullets.update() gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets) gf.update_aliens(ai_settings, stats, screen, sb, ship, aliens, bullets) gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button) # Update images on screen
def run_game(): pygame.init() screen = pygame.display.set_mode((1200, 800)) pygame.display.set_caption("坦克大战") bg_color = (0, 0, 0) tank = Tank(screen) bullets = Group() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: tank.moving_right = True elif event.key == pygame.K_LEFT: tank.moving_left = True elif event.key == pygame.K_UP: tank.moving_up = True elif event.key == pygame.K_DOWN: tank.moving_down = True elif event.key == pygame.K_SPACE: new_bullet = Bullet(screen, tank) bullets.add(new_bullet) elif event.type == pygame.KEYUP: if event.key == pygame.K_RIGHT: tank.moving_right = False elif event.key == pygame.K_LEFT: tank.moving_left = False elif event.key == pygame.K_UP: tank.moving_up = False elif event.key == pygame.K_DOWN: tank.moving_down = False tank.update() bullets.update() for bullet in bullets.copy(): if bullet.rect.bottom <= 0: bullets.remove(bullet) screen.fill(bg_color) for bullet in bullets.sprites(): bullet.draw_bullets() tank.blitme() pygame.display.flip()
def run_game(): # Initialize background settings for pygame functionality pygame.init() # Initialize settings object settings = Settings() # Initialize screen object of 1200x800 and add caption screen = pygame.display.set_mode((settings.screen_w, settings.screen_h)) pygame.display.set_caption("Alien Invasion") # Initialize ship ship = Ship(settings, screen) # Initialize alien and create fleet aliens = Group() gf.create_fleet(settings, screen, ship, aliens) # Create group for bullets bullets = Group() # Main loop for game # Surfaces are redrawn on every pass of our loop while True: # Check for events gf.check_events(screen, settings, ship, bullets) # Update ship ship.update(settings) # Update bullets bullets.update() # get rid of off-screen bullets gf.update_bullets(aliens, bullets) # Update aliens gf.update_aliens(settings, aliens) # Flip to new screen, ship position, etc. gf.update_screen(settings, screen, ship, bullets, aliens)
class evade(Microgame): def __init__(self): Microgame.__init__(self) self.e_icicles = [e_icicle(0), e_icicle(locals.HEIGHT + 70),e_icicle(locals.HEIGHT+100),e_icicle(locals.HEIGHT+10),e_icicle(100), e_icicle(100),e_icicle(700),e_icicle(300),e_icicle(500)] self.e_eskimo = eskimo() self.sprites = Group(self.e_eskimo, *self.e_icicles) def start(self): music.load(os.path.join("games", "evadeFull", "alt_song.wav")) music.play() def stop(self): music.stop() self.lose() def update(self, events): self.sprites.update() keys = pygame.key.get_pressed() if keys[K_q]: self.win() elif (keys[K_RIGHT] or keys[K_d]) and (keys[K_LEFT] or keys[K_a]): pass elif keys[K_LEFT] or keys[K_a]: self.e_eskimo.rect.x = max(self.e_eskimo.rect.x - 15, 0) elif keys[K_RIGHT] or keys[K_d]: self.e_eskimo.rect.x = min(locals.WIDTH -57, self.e_eskimo.rect.x + 15) for icicle in self.e_icicles: if self.e_eskimo.rect.colliderect(icicle.rect): music.stop() self.lose() def render(self, surface): surface.fill((0, 0, 0)) imgpathh = os.path.join("games", "evadeFull", "tile.png") test_image = pygame.image.load(imgpathh) surface.blit(test_image,(0,0)) self.sprites.draw(surface) def get_timelimit(self): return 15
class Shield(): def __init__(self, screen, ai_settings, ship): """A class that defines a picked up shield.""" self.screen = screen self.screen_rect = screen.get_rect() self.ai_settings = ai_settings self.ship = ship self.rect = pygame.Rect(0, 0, ship.rect.width + 2 * ai_settings.edge_width, ship.rect.height + 2 * ai_settings.edge_width) self.borders = Group() for edge_index in [0, 1, 3]: border = Border(self, edge_index) self.borders.add(border) self.strength_left = ai_settings.shield_strength self.color_change = [] for i in range(0, 3): self.color_change.append( int((ai_settings.edge_color[i] - ai_settings.bg_color[i]) / self.strength_left)) self.color_change = tuple(self.color_change) self.update() def shield_hit(self): """Decrease shield's strength once it's hit.""" self.strength_left -= 1 for b in range(0, len(self.borders)): color = [] for i in range(0, len(self.borders.sprites()[b].edge_color)): color.append(self.borders.sprites()[b].edge_color[i] - (self.color_change[i])) self.borders.sprites()[b].edge_color = tuple(color) def update(self): """Make the shield follow the ship.""" self.rect.center = self.ship.rect.center self.borders.update() def draw_shield(self): """Draw the edges of the shield.""" for border in self.borders: self.screen.fill(border.edge_color, border.rect)
def run_game(): #初始化游戏并创建一个对象 pygame.init() #设置屏幕宽高、名 ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") #创建一个用于存储游戏统计信息的实例,并创建记分牌 stats = GameStats(ai_settings) sb = Scoreboadr(ai_settings, screen, stats) #创建Play按钮 play_button = Button(ai_settings, screen, "Play") #创建一艘飞船、一个子弹编组、一个外星人编组 ship = Ship(ai_settings, screen) bullets = Group() aliens = Group() #创建外星人群 gf.create_fleet(ai_settings, screen, ship, aliens) #开始游戏的主循环 while True: #监视键盘和鼠标事件 gf.check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets) if stats.game_active: #每次循环都重绘屏幕 ship.update() bullets.update() gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets) gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens, bullets) gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button) #让最近绘制的屏幕可见 pygame.display.flip()
class Board: def __init__(self, width: int, height: int): super().__init__() self.width = width self.height = height self.players = Group() self.walls = Group() for w in range(width >> 1): for h in range(height >> 1): wall = Wall() wall.rect.x = PPM * (2 * w + 1) wall.rect.y = PPM * (2 * h + 1) self.walls.add(wall) def draw(self, canvas): self.walls.draw(canvas) self.players.draw(canvas) def update(self, dt): self.players.update(dt)
def run_game(): # Initialize game, settings and screen object. pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") # Make a ship ship = Ship(ai_settings, screen) # Make a group to store bullets in. bullets = Group() # Start the main loop for the game. while True: gf.check_events(ai_settings, screen, ship, bullets) ship.update() bullets.update() gf.update_bullets(bullets) gf.update_screen(ai_settings, screen, ship, bullets)
def run_game(): """Initalize game and create a screen object.""" pygame.init() game_settings = Settings() screen = pygame.display.set_mode((game_settings.screen_width, game_settings.screen_height)) pygame.display.set_caption("Alien Invasion") # Create an instance of to store game stats stats = GameStats(game_settings) score = Scoreboard(game_settings, screen, stats) # Make the play button play_button = Button(game_settings, screen, "Play") # create a ship my_ship = Ship(game_settings, screen) # Make a group to store bullets shellings = Group() roadman = Group() # Create alien fleet gf.create_fleet(game_settings, screen, roadman, my_ship) #Start the main loop for the game while True: gf.events(game_settings, my_ship, screen, shellings, stats, play_button, roadman, score) if stats.game_active: my_ship.update() gf.update_bullets(shellings, roadman, game_settings, screen, my_ship, stats, score) gf.update_aliens(game_settings, roadman, my_ship, stats, shellings, screen, score) gf.update_screen(game_settings, screen, my_ship, roadman, shellings, play_button, stats, score) shellings.update()
def run_game() -> object: """ Main module to run the game.""" # Initialize pygame, Settings and screen objects pygame.init() ai_settings = Settings() screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") # Create an instance to store game statistics and create a scoreboard. stats = GameStats(ai_settings) sb = Scoreboard(ai_settings, screen, stats) # Make the Play button. play_button = Button(screen, "Play") # Make a ship, group of bullets and group of aliens ship = Ship(ai_settings, screen) bullets = Group() aliens = Group() # Create a fleet of aliens. gf.create_fleet(ai_settings, screen, ship, aliens) # Starting main loop for the game while True: gf.check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets) if stats.game_active: bullets.update() gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets) gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens, bullets) ship.update() gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets,play_button)
def run_game(): pygame.init() ai_settings = Settings() screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") ship = Ship(ai_settings, screen) bullets = Group() while True: gf.check_events(ai_settings, screen, ship, bullets) ship.update() bullets.update() gf.update_screen(ai_settings, screen, ship, bullets) for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() screen.fill(ai_settings.bg_color) ship.blitme() pygame.display.flip() bullets.update() for bullet in bullets.copy(): if bullet.rect.bottom <= 0: bullets.remove(bullet) print(len(bullets))
class Game(Application): title = "Spaceships" screen_size = 800, 600 def __init__(self): Application.__init__(self) self.bounds = self.screen.get_rect() self.ships = Group() self.spawners = [ TieSpawner(2000, self.ships, self.bounds) ] def update(self): dt = self.clock.get_time() self.ships.update(dt) for spawner in self.spawners: spawner.update(dt) def draw(self, screen): screen.fill((0,0,0)) self.ships.draw(screen)
class InvadersGame: def __init__(self): self.game = Game() floorframe = Frame(self.game.screen, Rect(0, 542, MAX_X + 36, 596)) self.floor = TiledMap(self.game, floorframe) self.floor.fill_map('#', (25, 2)) self.player = Player(self.game) self.aliens = Group() self.create_aliens() self.shots = Group() self.alien_shots = Group() def create_aliens(self): for i in range(4): for j in range(20): direction = [LEFT, RIGHT][i % 2] alien = Alien(self.game, Vector(j * 32 + 32, i * 64), direction) self.aliens.add(alien) def shoot(self): shot = self.player.get_shot() self.shots.add(shot) def draw(self): self.game.screen.clear() self.player.draw() self.shots.draw(self.game.screen.display) self.alien_shots.draw(self.game.screen.display) self.aliens.draw(self.game.screen.display) self.floor.draw() def update(self): self.player.move() self.shots.update() self.alien_shots.update() self.aliens.update() for a in self.aliens: shot = a.get_shot() if shot: self.alien_shots.add(shot) self.draw() groupcollide(self.shots, self.aliens, True, True, collided=collide_mask) if spritecollideany(self.player, self.alien_shots, collided=collide_mask): self.game.exit() if not self.aliens: self.game.exit() def run(self): self.game.event_loop(figure_moves=self.player.set_direction, draw_func=self.update, keymap={K_SPACE: self.shoot}, delay=30)
class Fallgame(Microgame): def __init__(self): Microgame.__init__(self) self.ball=Ball() self.ball1=Group(self.ball) self.entities=Group() self.Sound=pygame.mixer.Sound(join('games','fall','ball.wav')) #self.entities=Group([self.fall]) self.timer=pygame.time.Clock() self.time=0 # TODO: Initialization code here def start(self): # TODO: Startup code here music.load(join('games','fall','fall.wav')) music.play() def stop(self): # TODO: Clean-up code here music.stop() def update(self, events): # TODO: Update code here self.time+=self.timer.tick() addg=Fall() adgroup=Group(addg) if self.time%1000<50: self.entities.add(adgroup) self.entities.update() self.ball1.update() collide=pygame.sprite.spritecollideany(self.ball,self.entities) for event in events: if event.type==KEYUP and event.key==K_q: self.lose() elif event.type ==KEYDOWN and event.key ==K_RIGHT: self.ball.velocity=(30,0) elif event.type==KEYUP and event.key==K_RIGHT: self.ball.velocity=(0,0) elif event.type==KEYDOWN and event.key==K_UP: self.ball.velocity=(0,-30) elif event.type==KEYUP and event.key==K_UP: self.ball.velocity=(0,0) elif event.type==KEYDOWN and event.key==K_DOWN: self.ball.velocity=(0,30) elif event.type==KEYUP and event.key==K_DOWN: self.ball.velocity=(0,0) elif event.type==KEYDOWN and event.key==K_LEFT: self.ball.velocity=(-30,0) elif event.type==KEYUP and event.key==K_LEFT: self.ball.velocity=(0,0) for event in events: if event.type==KEYUP and (event.key==K_UP or event.key==K_RIGHT or event.key==K_LEFT or event.key==K_DOWN): self.Sound.play() _, y_bot = self.ball.rect.bottomleft x_bot,_ = self.ball.rect.bottomright if collide: self.lose() '''if self.ball.rect.y <=0 or y_bot >= locals.HEIGHT: #self.lose() for event in events: if event.type ==KEYDOWN and event.key ==K_RIGHT: self.ball.velocity=(0,0) elif event.type==KEYUP and event.key ==K_RIGHT: self.ball.velocity=(0,0) elif event.type==KEYDOWN and event.key==K_LEFT: self.ball.velocity=(0,0) elif event.type==KEYUP and event.key==K_LEFT: self.ball.velocity=(0,0) elif self.ball.rect.x<=0 or x_bot>= locals.WIDTH: #self.lose() for event in events: if event.type==KEYDOWN and event.key==K_UP: self.ball.velocity=(0,0) elif event.type==KEYUP and event.key==K_UP: self.ball.velocity=(0,0) elif event.type==KEYDOWN and event.key==K_DOWN: self.ball.velocity=(0,0) elif event.type==KEYUP and event.key==K_DOWN: self.ball.velocity=(0,0)''' # TODO: Rendering code here def render(self, surface): surface.blit(background,(0,0)) self.ball1.draw(surface) self.entities.draw(surface) def get_timelimit(self): # TODO: Return the time limit of this game (in seconds, 0 <= s <= 15) return 20
class Gameboard(object): ''' classdocs ''' def __init__(self, surface, width, height, song_filename): ''' Constructor ''' #progressively increase; must end with 1 self.PROB_HEALTH = 0.4 self.PROB_KI = 0.7 self.PROB_SHIELD = 0.9 self.PROB_SWORD = 1.0 self.windowSurface = surface self.width = width self.height = height self.song_filename = song_filename board_size = (width, height) self.gameSurface = Surface(board_size) # This will be drawn every frame to the window song_file = open(song_filename) self.song_name = song_file.readline().strip() self.song_length = float(song_file.readline()) self.pixels_per_second = float(song_file.readline()) self.level_filename = song_file.readline().strip() self.music_filename = song_file.readline().strip() self.background_filename = song_file.readline().strip() self.pixel_offset = 0 self.last_frame_time = -1 self.frac_scroll = 0 # print "{0}[{1}] : {2}".format(self.song_name, self.song_length, self.pixels_per_second) # self.background_width = (self.pixels_per_second * self.song_length) + width self.background_width = width + 96 # Jank scroll edition! background_size = (self.background_width, height) self.backgroundSurface = Surface(background_size) self.__render_background() self.backgroundSurface.set_colorkey((0,0,0),pygame.RLEACCEL) #self.backgroundSurface.set_colorkey((217,62,245),pygame.RLEACCEL) #self.backgroundSurface.set_alpha(100,pygame.RLEACCEL) self.mainScreenBackground,self.mainScreenBackgroundRect = load_image_from_folder('backgrounds', self.background_filename) #self.backgroundSurface.blit(mainScreenBackground, (0,0)) #self.__render_background() possible_samurai_positions = [] for i in range(0, 6): possible_samurai_positions.append(PATH_HEIGHT * i + 15) self.samurai = Samurai(possible_samurai_positions) self.samurai_sprite_group = Group(self.samurai) self.bridge_group = OrderedUpdates() self.mine_group = OrderedUpdates() self.enemy_group = OrderedUpdates() self.attack_group = OrderedUpdates() self.healthpack_group = OrderedUpdates() self.ki_potion_group = OrderedUpdates() self.shield_group = OrderedUpdates() self.sword_group = OrderedUpdates() self.explosion_group = OrderedUpdates() # tempSprite = self.samurai_sprite_group.sprites() # tempRect = tempSprite[0].get_rect() # self.testSword = VerticalSlash(tempRect.centerx,tempRect.centery, self.remove_attack) # self.attack_group.add(self.testSword) if sys.platform == "win32": # On Windows, the best timer is time.clock() self.default_timer = time.clock else: # On most other platforms, the best timer is time.time() self.default_timer = time.time def draw(self): self.gameSurface.fill((0,0,0)) #self.gameSurface.fill((217,62,245)) origin = (0, 0) # this_scroll = 0 self.scroll_amount = 0 if self.last_frame_time > 0: cur_time = self.default_timer() self.gap_time = cur_time - self.last_frame_time # print "Pixels per second: {0}\nGap Time: {1}\nScrollAmount: {2}".format(self.pixels_per_second, self.gap_time, this_scroll) self.last_frame_time = cur_time else: self.gap_time = 0 self.last_frame_time = self.default_timer() this_scroll = self.pixels_per_second * self.gap_time self.frac_scroll += this_scroll if self.frac_scroll >= 1: self.scroll_amount = math.floor(self.frac_scroll) self.pixel_offset += self.scroll_amount # print "Now scrolling {0} pixel(s)".format(whole_part) self.frac_scroll -= self.scroll_amount if self.pixel_offset > 96: self.pixel_offset = self.pixel_offset - 96 if self.pixel_offset < 0: self.pixel_offset = 0 self.gameSurface.blit(self.mainScreenBackground, origin) window_rect = Rect(self.pixel_offset, 0, self.gameSurface.get_width(), self.gameSurface.get_height()) # print window_rect self.gameSurface.blit(self.backgroundSurface, origin, window_rect) #All other drawing self.bridge_group.update(self.scroll_amount) self.bridge_group.draw(self.gameSurface) self.mine_group.update(self.scroll_amount) self.mine_group.draw(self.gameSurface) self.enemy_group.update(self.scroll_amount) self.enemy_group.draw(self.gameSurface) self.samurai_sprite_group.update() self.samurai_sprite_group.draw(self.gameSurface) self.healthpack_group.update(self.scroll_amount) self.healthpack_group.draw(self.gameSurface) self.ki_potion_group.update(self.scroll_amount) self.ki_potion_group.draw(self.gameSurface) self.shield_group.update(self.scroll_amount) self.shield_group.draw(self.gameSurface) self.sword_group.update(self.scroll_amount) self.sword_group.draw(self.gameSurface) #self.testSword = VerticalSlash(400,400) #self.attack_group.add(self.testSword) self.attack_group.update() self.attack_group.draw(self.gameSurface) self.explosion_group.update() self.explosion_group.draw(self.gameSurface) # self.testSword.draw(self.gameSurface) for bridge in self.bridge_group.sprites(): if bridge.rect.left < 0: self.bridge_group.remove(bridge) #Annnnd blast it back to the screen window_origin = (0, 60) self.windowSurface.blit(self.gameSurface, window_origin) def add_bridge(self, bridge_num): # print "FAKE BRIDGE" new_bridge = Bridge(1101, bridge_num * PATH_HEIGHT + 39) self.bridge_group.add(new_bridge) def add_mine(self, string_num): # print "CREATE ZE LANDMINE" new_mine = Mine(1101, PATH_HEIGHT * string_num + 42) self.mine_group.add(new_mine) def add_powerup(self, string_num): r = random.random() if r < self.PROB_HEALTH: self.add_healthpack(string_num) elif r < self.PROB_KI: self.add_kiboost(string_num) elif r < self.PROB_SHIELD: self.add_shield(string_num) elif r < self.PROB_SWORD: self.add_sword(string_num) def add_healthpack(self, string_num): # print "such a healthy young man!" new_healthpack = Healthpack(1101, PATH_HEIGHT * string_num + 42) self.healthpack_group.add(new_healthpack) def add_shield(self, string_num): new_shield = Shield(1101, PATH_HEIGHT * string_num + 42) self.shield_group.add(new_shield) def add_sword(self, string_num): new_sword = MegaSword(1101, PATH_HEIGHT * string_num + 42) self.sword_group.add(new_sword) def add_kiboost(self, string_num): new_ki_potion = KiPotion(1101, PATH_HEIGHT * string_num + 42) self.ki_potion_group.add(new_ki_potion) def add_enemy(self, string_num): new_enemy = Enemy(1111, PATH_HEIGHT * string_num + 42) self.enemy_group.add(new_enemy) def add_male_groupie(self, string_num): new_enemy = MaleGroupie(1111, PATH_HEIGHT * string_num + 15) self.enemy_group.add(new_enemy) def add_lawyer(self, string_num): new_lawyer = Lawyer(1111, PATH_HEIGHT * string_num + 15) self.enemy_group.add(new_lawyer) def add_bodyguard(self, string_num): new_bodyguard = Bodyguard(1111, PATH_HEIGHT * string_num + 15) self.enemy_group.add(new_bodyguard) def remove_attack(self, attack): self.attack_group.remove(attack) def add_attack(self, attack): self.attack_group.add(attack) def add_explosion(self, y_val): new_explosion = Explosion(20, y_val, self.explosion_group) def __render_background(self): # Jank implementation that just uses that one sprite over and over again! # Jay's jank dirtBlockThingy is 96x48 pixels num_blocks = int(math.ceil(self.background_width / 96.0)) cur_width = 0 for bI in range(0, num_blocks): for hI in range(0, 6): my_location = (cur_width, (PATH_HEIGHT * hI + 35)) dp = DirtPath(my_location) # print "DirtPath at {0}".format(my_location) self.backgroundSurface.blit(dp.image, my_location) cur_width += 96
def main(): # initialze pygame pygame.init() screen = pygame.display.set_mode(SCREEN_SIZE) bounds = screen.get_rect() # initialize the game player = Player(bounds.center, bounds) player_grp = GroupSingle(player) enemies = Group() spawn_counter = 0 fast_spawn_counter = 0 score = 0 font = pygame.font.Font(None, 40) # game loop done = False clock = pygame.time.Clock() while not done: # input for event in pygame.event.get(): if event.type == QUIT: done = True elif event.type == KEYDOWN and event.key == K_ESCAPE: done = True elif event.type == MOUSEBUTTONDOWN and event.button == 1: player.shoot() elif event.type == KEYDOWN and event.key == K_SPACE and not player.alive(): player = Player(bounds.center, bounds) player_grp.add(player) score = 0 for enemy in enemies: enemy.kill() # same as enemies.empty() # update player_grp.update() player.bullets.update() enemies.update() # spawn enemies spawn_counter += 1 if spawn_counter >= 10: n = randrange(4) for i in range(n): x = randrange(bounds.width - Enemy.width) enemy = Enemy((x, 0), bounds) enemies.add(enemy) spawn_counter = 0 # fast spawn fast_spawn_counter += 1 if fast_spawn_counter >= 45: x = randrange(bounds.width - FastEnemy.width) enemy = FastEnemy((x, 0), bounds) enemies.add(enemy) fast_spawn_counter = 0 # collisions groupcollide(player_grp, enemies, True, False) for enemy in groupcollide(enemies, player.bullets, True, True): if player.alive(): score += 1 # draw screen.fill(BG_COLOR) player_grp.draw(screen) player.bullets.draw(screen) enemies.draw(screen) score_text = font.render("Score: %08d"%score, False, (255, 255, 255)) screen.blit(score_text, (5, 5)) if not player.alive(): gameover = font.render("Press Space to Respawn", False, (255, 255, 255)) rect = gameover.get_rect() rect.center = screen.get_rect().center screen.blit(gameover, rect) pygame.display.flip() clock.tick(30)
# input for game pressed = pygame.key.get_pressed() if pressed[K_LEFT]: ship.update(-8, 0) if pressed[K_RIGHT]: ship.update(8, 0) if pressed[K_UP]: ship.update(0, -8) if pressed[K_DOWN]: ship.update(0, 8) # update wasp baddies if move < 2: move += 1 else: enemies.update() move = 0 # update bullets for i in your_bullets: i.fire(1) your_bullets.draw(screen) for enemy in pygame.sprite.groupcollide(enemies, your_bullets, False, True): enemy.hurt(1) for i in enemy_bullets: i.fire(-1) enemy_bullets.draw(screen) if len(enemies) < 5 and unlimit == -1:
class Game(): def __init__(self): #setup pygame.init() pygame.font.init() self.font = pygame.font.Font(None,24) self.fontColor = (0,0,0) pygame.mixer.init() pygame.display.set_mode(SCREEN) pygame.display.set_caption('#ElJuegoDeLasJoincic') self.screen = pygame.display.get_surface() self._quit=False self.clock = pygame.time.Clock() self.controller= Controller() self.background = load_image("background.png") self.menu_background = load_image("menu_background.png") self.menu_iniciar = load_image("menu_iniciar.png") self.menu_salir = load_image("menu_salir.png") self.gameover = load_image("gameover.png") self.cursor = load_image("cursor.png") self.arrow = load_image("arrow.png") self.player = Player() self.group = Group() self.protocolo = Protocolo() self.group.add(self.player) self.groupOyentes = Group() self.groupTakitos = Group() self.groupHUD = Group() self.state= GAME_INIT def pause(self): pass def wait(self): pass def hayPuesto(self): for row in self.oyentes: for val in row: if val == 0: return True return False def init(self): self.screen.blit(self.menu_background,(0,0)) rect = self.screen.blit(self.menu_iniciar,(200,200)) if rect.collidepoint(self.controller.mouse.position): self.screen.blit(self.menu_iniciar,(200,200)) if self.controller.mouse.click: self.state = GAME_LOOP self.oyentes=[ [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0], ] self.level=1 self.initLevel(); rect = self.screen.blit(self.menu_salir,(200,260)) if rect.collidepoint(self.controller.mouse.position): self.screen.blit(self.menu_salir,(200,260)) if self.controller.mouse.click: sys.exit(0) def initLevel(self): count= (self.level - 1 )*2 + 4 self.oyentes=[ [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0], ] self.groupOyentes.empty() self.groupTakitos.empty() for i in range(count): if self.hayPuesto(): oyente=Oyente() self.groupOyentes.add(oyente) oyente.onScoreTick = self.comprobarScore while True: i = randrange(5) j = randrange(5) if self.oyentes[i][j]== 0: oyente.rect.x=160+(i*oyente.rect.w) oyente.rect.y=j*oyente.rect.h break self.time_next_level=time.time()+ 60 self.puntos=0 def comprobarScore(self, oyente): if oyente.state == OYENTE_DESPIERTO or \ oyente.state == OYENTE_DISTRAIDO or \ oyente.state == OYENTE_ABURRIDO: self.groupHUD.add(TextHUD(oyente.rect, "+1")) if oyente.state == OYENTE_DORMIDO: self.groupHUD.add(TextHUD(oyente.rect, "-1")) def loop(self): #input self.player.update(self) self.protocolo.update(self) for oyente in self.groupOyentes: oyente.update(self) for takito in self.groupTakitos: takito.update(self) self.groupHUD.update() #render self.screen.blit(self.background,(0,0)) self.screen.blit(self.protocolo.image, self.protocolo.rect) self.groupOyentes.draw(self.screen) self.groupTakitos.draw(self.screen) self.group.draw(self.screen) self.groupHUD.draw(self.screen) if self.player.state == PLAYER_AIM: image= pygame.transform.scale(self.arrow, ( self.arrow.get_width()+ int( MAX_DISTAN_FORCE*self.player.force) ,self.arrow.get_height() )) image= pygame.transform.rotate(image, self.player.arrow_angle) rect=image.get_rect() rect.centerx=self.player.rect.centerx rect.centery=self.player.rect.centery self.screen.blit(image, rect) delta_time=self.time_next_level - time.time() self.screen.blit( self.font.render("Faltan: %d : %d " % ( (delta_time/60) , delta_time % 60),True, self.fontColor ) , (15,15) ) self.screen.blit( self.font.render(" Nivel: %d " % self.level ,True, self.fontColor ) , (565,15) ) self.screen.blit( self.font.render(" Puntos: %d " % self.puntos ,True, self.fontColor ) , (365,15) ) if delta_time <= 0: count= len(self.groupOyentes) count_len=0 for sprite in self.groupOyentes: if sprite.state <= OYENTE_NORMAL: count_len+=1 if count_len >= count /2: self.level+=1 self.initLevel() else: self.state= GAME_END def end(self): self.screen.blit(self.gameover, (0,0)) def update(self): self.controller.update() self.screen = pygame.display.get_surface() if self.state <= GAME_PAUSE: self.pause() elif self.state <= GAME_INIT: self.init() elif self.state <= GAME_WAIT: self.wait() elif self.state <= GAME_LOOP: self.loop() elif self.state <= GAME_END: self.end() if self.player.state != PLAYER_AIM: self.screen.blit(self.cursor, self.controller.m.position) def go(self): while not self._quit: self.update() pygame.display.flip() self.clock.tick(TICKPERSEC)
class SpaceGame(Microgame): def __init__(self): Microgame.__init__(self) # TODO: Initialization code here self.count = 0 self.spaceship = Spaceship() self.bg = Background() self.planet = Planet() self.monster = Group(Monster()) self.earth = Group(EarthExp()) self.background = Group(self.bg) self.sprites = Group(self.planet, self.spaceship) self.is_win = False self.is_lose = False def generate_asteroid(self): if self.count == 10: if randint(0,1) == 0: self.sprites.add(Asteroid(-10, randint(0, locals.HEIGHT - 400), 1)) else: self.sprites.add(Asteroid(locals.WIDTH + 10, randint(0, locals.HEIGHT - 400), -1)) self.count = 0 else: self.count += 1 def start(self): # TODO: Startup code here music.load(join("games","space","music","space_song.ogg")) music.play() def stop(self): # TODO: Clean-up code here music.stop() def update(self, events): # TODO: Update code here self.background.update() self.sprites.update() #Make asteroids self.generate_asteroid() #Check if spaceship hits sides of screen x_ship_left, _ = self.spaceship.rect.bottomleft x_ship_right, _ = self.spaceship.rect.bottomright if x_ship_left <= 0: self.spaceship.x_velocity = 0 elif x_ship_right >= locals.WIDTH - 14: self.spaceship.x_velocity = 0 #Check if spaceship hits top/bottom of screen sectioned to movement _, y_ship_top = self.spaceship.rect.topleft _, y_ship_bottom = self.spaceship.rect.bottomleft if y_ship_top <= locals.HEIGHT - 300: self.spaceship.y_velocity = 0 elif y_ship_bottom >= locals.HEIGHT - 20: self.spaceship.y_velocity = 0 #Process user input for event in events: if event.type == KEYDOWN and event.key == K_LEFT: if x_ship_left > 0: self.spaceship.x_velocity -= VELOCITY_INC elif event.type == KEYUP and event.key == K_LEFT: self.spaceship.x_velocity = 0 elif event.type == KEYDOWN and event.key == K_RIGHT: if x_ship_right < locals.WIDTH - 14: self.spaceship.x_velocity += VELOCITY_INC elif event.type == KEYUP and event.key == K_RIGHT: self.spaceship.x_velocity = 0 elif event.type == KEYDOWN and event.key == K_UP: if y_ship_top > locals.HEIGHT - 300: self.spaceship.y_velocity -= VELOCITY_INC elif event.type == KEYUP and event.key == K_UP: self.spaceship.y_velocity = 0 elif event.type == KEYDOWN and event.key == K_DOWN: if y_ship_bottom < locals.HEIGHT - 20: self.spaceship.y_velocity += VELOCITY_INC elif event.type == KEYUP and event.key == K_DOWN: self.spaceship.y_velocity = 0 #music.load(join("games","space","music","Powerup7.wav")) #music.play() #Make win when spaceship hits planet if self.planet.rect.colliderect(self.spaceship.rect): sound_planet = pygame.mixer.Sound(join("games","space","music","Powerup.wav")) sound_planet.play() self.is_win = True for each in self.sprites.sprites(): if isinstance(each, Asteroid): if each.rect.colliderect(self.spaceship.rect): sound_asteroid = pygame.mixer.Sound(join("games","space","music","Explosion.wav")) sound_asteroid.play() self.is_lose = True #Creates win scree if self.is_win: self.sprites.empty() self.background.empty() self.sprites.add(Monster()) #Creates lose screen elif self.is_lose: self.sprites.empty() self.background.empty() self.sprites.add(EarthExp()) def render(self, surface): # TODO: Rendering code here surface.fill(Color(0, 0, 0)) self.background.draw(surface) self.sprites.draw(surface) def get_timelimit(self): # TODO: Return the time limit of this game (in seconds, 0 <= s <= 15) #raise NotImplementedError("get_timelimit") return 15
def main(): #initialize pygame pygame.init() screen = pygame.display.set_mode(SCREEN_SIZE) bounds = screen.get_rect() #initialize game player = Player(bounds.center, bounds) #sets starting position fir player robot = Robot((randrange(0,800),randrange(0,600)), bounds) player_grp = GroupSingle(player) #robot_grp = GroupSingle(robot) robot_grp = Group() robot_grp.add(Robot((randrange(0,800),randrange(0,600)), bounds)) robot_grp.add(Robot((randrange(0,800),randrange(0,600)), bounds)) robot_grp.add(Robot((randrange(0,800),randrange(0,600)), bounds)) meteors = Group() impacts = Group() score = 0 spawntime = 10 spawnticker = 0 font = pygame.font.Font(None,35) #game loop done = False clock = pygame.time.Clock() print "Loop Started" while not done: for event in pygame.event.get(): if event.type == QUIT: done = True elif event.type == KEYDOWN and event.key == K_ESCAPE: done = True elif event.type == KEYDOWN and event.key == K_SPACE: if player.carrying: player.drop() else: for robot in groupcollide(robot_grp, player_grp, False, False): player.grab(robot) score += 5 print "robot picked up" break #input #spawn meteors spawnticker += 1 if spawnticker >= spawntime: #print "spawned!" meteors.add(Meteor((randrange(0,800),randrange(0,600)),bounds, 90, "rock")) spawnticker = 0 #update meteors.update() ImpactGroup.impacts.update() player.update() #collisions coll = groupcollide(player_grp, ImpactGroup.impacts, False, False) for robot in coll: robot.damage(coll[robot][0]) coll = groupcollide(robot_grp, ImpactGroup.impacts, False, False) for robot in coll: robot.damage(coll[robot][0]) #draw screen.fill(BG_COLOR) robot_grp.draw(screen) ImpactGroup.impacts.draw(screen) meteors.draw(screen) player_grp.draw(screen) robot_grp.draw(screen) clock.tick(30) score_text = font.render("Score: %05d"%score, False, (255,255,255)) screen.blit(score_text, (5,5)) pygame.display.flip()
for e in event.get(): if e.type == QUIT: done = True elif e.type == KEYDOWN: if e.key == K_ESCAPE: done = True elif e.unicode == u'r': generation = randint(0,500) index = randint(0,10000) while not personat(generation, index): index += 1 describeperson(generation, index) elif e.type == MOUSEBUTTONDOWN and e.button == 1: for sprite in sprites: if sprite.rect.collidepoint(e.pos) and sprite.exists: generation = sprite.rect.left / 8 index = sprite.rect.top / 8 describeperson(generation, index) break sprites.update() sprites.clear(screen, background) sprites.draw(screen) display.flip() limit.tick(20)
class PongMicrogame(Microgame): ''' Simple Pong Microgame. An example Microgame. Single bounce Pong. Attributes: rect - the bounding box of the playfield ball - the ball of the microgame lbat - the left-hand bat of this microgame, ai-controlled rbat - the right-hand bat of this microgame, user-controlled sprites - the sprite group that contains the sprites of the game timeSinceWin - the time in (ms) when the player won the game, or 0 if the game has not been won yet ''' def __init__(self): Microgame.__init__(self) self.rect = Rect(0, 0, locals.WIDTH, locals.HEIGHT) speed = BALL_SPEED_BASE widthqrt = self.rect.width / 4 heightqrt = self.rect.height / 4 self.ball = Ball(self, 150, randint(heightqrt, heightqrt * 3), \ randint(speed, speed + BALL_SPEED_RANGE), \ choice([speed, -speed])) self.lbat = Bat(100, randint(heightqrt, heightqrt * 3), \ self.rect, self.ball, True) self.rbat = Bat(self.rect.width - 150, \ randint(heightqrt, heightqrt * 3), \ self.rect, self.ball) self.sprites = Group((self.ball, self.lbat, self.rbat)) self.timeSinceWin = 0 def start_win_countdown(self): ''' Starts the successful hit countdown --- once this is up, the player wins the game. ''' self.timeSinceWin = pygame.time.get_ticks() def start(self): music.load('games/pong/music.mp3') music.play(0, 0.5) def stop(self): music.stop() def update(self, events): time = pygame.time.get_ticks() if self.timeSinceWin > 0 and \ time > self.timeSinceWin + TIME_TO_WIN_AFTER_BOUNCE: self.win() self.sprites.update() for event in events: if event.type == KEYDOWN: if event.key == K_UP: self.rbat.direction = -1 elif event.key == K_DOWN: self.rbat.direction = 1 if event.type == KEYUP: if event.key == K_UP or event.key == K_DOWN: self.rbat.direction = 0 def render(self, surface): surface.fill(Color(0, 0, 0)) self.sprites.draw(surface) def get_timelimit(self): return 10
class Game(Application): def __init__(self): Application.__init__(self) self.screenRect = self.screen.get_rect() self.minDt = 200 self.enemyGroup = Group() self.enemyGroup.add(BasicEnemy(100,100,0,1,self.screenRect,80)) self.bulletGroup = Group() self.player = Player(self.screenRect) self.playerGroup = GroupSingle(self.player) self.playerWeaponType = 1 self.playerFired = False self.playerMoveX = 0 self.playerMoveY = 0 self.playerMoveFlag = False def handle_event(self,event): if event.type == MOUSEBUTTONUP and event.button == 1: self.playerFired = True if event.type == KEYDOWN: ## need to put in KEYUP to turn off the thing... if event.key == K_DOWN: self.playerMoveY = 1 self.playerMoveFlag = True if event.key == K_UP: self.playerMoveY = -1 self.playerMoveFlag = True if event.key == K_LEFT: self.playerMoveX = -1 self.playerMoveFlag = True if event.key == K_RIGHT: self.playerMoveX = 1 self.playerMoveFlag = True if event.key == K_SPACE: self.playerFired = True if event.type == KEYUP: if event.key == K_DOWN: self.playerMoveY = 0 self.playerMoveFlag = True if event.key == K_UP: self.playerMoveY = 0 self.playerMoveFlag = True if event.key == K_LEFT: self.playerMoveX = 0 self.playerMoveFlag = True if event.key == K_RIGHT: self.playerMoveX = 0 self.playerMoveFlag = True def update(self, screen): dt = min(self.minDt, self.clock.get_time()) self.enemyGroup.update(dt) if self.playerFired: self.bulletGroup.add(self.player.shoot(self.playerWeaponType)) self.playerFired = False ## need to validate holding down the key... if self.playerMoveFlag: self.player.setDirection(self.playerMoveX, self.playerMoveY) self.playerMoveFlag = False self.bulletGroup.update(dt) self.playerGroup.update(dt) pygame.sprite.groupcollide(self.enemyGroup, self.bulletGroup, True, True) def draw(self,screen): screen.fill((0,0,0)) self.playerGroup.draw(screen) self.enemyGroup.draw(screen) self.bulletGroup.draw(screen)