def __init__(self): pygame.mixer.init() pygame.init() self.screen = pygame.display.set_mode(screen_size, 0, 32) self.background = None #self.Fill_Back() pygame.display.set_caption('Pacman Remake') pygame.display.set_icon(icon) self.clock = pygame.time.Clock() pygame.mixer.music.load('Pac-man theme 1.mp3') #pygame.mixer.music.set_volume(0.25) pygame.mixer.music.play(-1, 0.0) self.pellet_count = 0 self.fruit = None self.text = Group_Text() self.count_time = 0 self.time = 0 self.besttime = 0 self.pause = Pause(True) self.level = Level() self.end_game = False self.chase_music = pygame.mixer.Sound("chase_theme_2.wav") self.switch_music = False self.switch_time = 0 self.quit = False
def __init__(self): """Initialize the game, and create game resources """ pygame.init() self.settings = Settings() self.screen = pygame.display.set_mode( (self.settings.screen_width, self.settings.screen_height)) #self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) #self.settings.screen_width = self.screen.get_rect().width #self.settings.screen_height = self.screen.get_rect().height self.caption = "J'y-rens Alien Invasion 1.0" pygame.display.set_caption(self.caption) #Create an instance to store game statistics. # and create a scoreboar. self.stats = GameStats(self) self.sb = Scoreboard(self) self.ship = Ship(self) #bullet groups self.bullets = pygame.sprite.Group() #Alien Groups self.aliens = pygame.sprite.Group() # create fleet of aliens self._create_fleet() #Make the Play Button. self.play_button = Button(self, "Play") self.pause_button = Pause(self, "Pause")
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_button = Button(ai_settings, screen, 0, 1) pause_button = Pause(ai_settings, screen, "Pause") ship = Ship(ai_settings, screen) bullets = Group() aliens = Group() gf.create_fleet(ai_settings, screen, ship, aliens) stats = GameStats(ai_settings) sb = Scoreboard(ai_settings, screen, stats) while True: gf.check_events(ai_settings, screen, stats, sb, play_button, pause_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) gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button, 1, pause_button)
def switch_button(self): for button in self.all_buttons: if button.action == 3: # bouton pause self.all_buttons.remove(button) self.all_buttons.add(Play(self)) if button.action == 4: # bouton play self.all_buttons.remove(button) self.all_buttons.add(Pause(self))
def initialize(self): self.player = Tabby(0, 0) self.hud = Hud() self.pause = Pause() self.title = TitleScreen() self.camera = Camera(self.player.sprite) self.cameratarget = self.player self.entities.append(self.player) #player should always be the first in the list
def __init__(self): """Initialize the game and create game ressources """ pygame.init() self.settings = Settings() self.screen = pygame.display.set_mode( (self.settings.screen_width,self.settings.screen_height)) pygame.display.set_caption("J'y-rens Target Shoot 1.0") #Set the clock and time click self.clock = pygame.time.Clock() self.dt = 0 # create an instance of the game stats class self.stats = GameStats(self) #Create an instance of the scoreboard class self.sb = Scoreboard(self) # Create an instance of the class ship self.ship = Ship(self) #create a list of bullets that hit the rectangle self.bullets_hit_rectangle = [] # create an instance of the class rectangle self.rectangle = Rectangle(self) # create an instance of the group bullets self.bullets = pygame.sprite.Group() # create an instance of the button self.play_button= Button(self,"Play") # create an instance of the pause Button self.pause_button = Pause(self,"Pause")
def change_mode(self, mode, args=None): self.mode = mode print("Changing mode...") if self.mode == 'Line Follower': print("Creating Line Follower...") self.thread = LineFollower(self.change_mode) self.thread.start() elif self.mode == 'Manual Control': print("Starting manual control...") self.thread = ManualControl(args) print("Manual control started") elif self.mode == 'Forest Crawler': print("Creating Forest Crawler...") self.thread = ForestCrawler(self.change_mode) self.thread.start() elif self.mode == 'Cube Carrier': print("Creating Cube Carrier...") self.thread = CubeCarrier(self.change_mode) self.thread.start() elif self.mode == 'Disc Traveler': print("Creating Disc Traveler...") self.thread = DiscTraveler(self.change_mode) self.thread.start() elif self.mode == 'Slope Searcher': print("Creating Slope Searcher...") self.thread = SlopeSearcher(self.change_mode) self.thread.start() elif self.mode == 'Battle Mode': print("Creating Battle Mode...") self.thread = BattleMode(self.change_mode) print("FOOBAR") self.thread.start() elif self.mode == 'Pause': print("Pausing...") self.thread = Pause() self.thread.start() elif self.mode == 'Stop': print("Stop")
def __init__(self, screen: pygame.Surface, data: dict, settings: dict, display: dict): """ une classe de jeu d'échecs Parameters ---------- screen : pygame.Surface la surface de jeu data : dict le dictionnaire des couleurs settings : dict les réglages de l'ia display : dict les réglages des graphiques """ self.pause = False # pour mettre le jeu en pause self.new_start = 0.0 # le temps pour redémarer les chronos après la pause self.running = True # le jeu tourne self.clock = Clock(-1, 0) # pour avoir la durée de la partie self.screen = screen self.data = data self.settings = settings self.display = display self.board = Board() self.playerB = Human(B, self) # joueur avec les pièces blanches self.playerN = Ai(N, self) # joueur avec les pièces noires self.cur_player = self.playerB self.score = self.board.get_score(self.board.board) self.all_scores = [self.score] self.all_moves = [] # str self.suggested = [(-11, -11), (-11, -11)] self.all_buttons = pygame.sprite.Group() self.all_buttons.add(Help(self)) self.all_buttons.add(Pause(self))
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 = Scoreboard(ai_settings,screen,stats) # 创建按钮 play_button = Button(ai_settings,screen,"Play") pause_button = Pause(ai_settings,screen,"Pause") # 创建一艘飞船、一个子弹编组和一个外星人编组 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,pause_button, ship,aliens,bullets) if stats.game_active and not stats.pause_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) gf.update_screen(ai_settings,screen,stats,sb,ship,aliens,bullets, play_button,pause_button)
def __init__(self,gamestate,score,ammo): # Konfuguracja random.seed() #inicjalizaja pygame.init() self.SCREEN_SIZE = (1280, 720) # grafiki dopasowane do tego self.screen = pygame.display.set_mode(self.SCREEN_SIZE) self.tps_clock = pygame.time.Clock() self.tps_delta = 0.0 self.shot = 0.0 self.supertime = -2 self.player = Player(self) self.aliens = [] self.opp = 10 self.bullets = [] self.alienbulets = [] self.lives = Lives(self) self.lives_number = 3 self.score = Score(self) self.score_number = 0 + score self.ammo = Ammo(self) self.walls = [] self.gameover = GameOver(self) self.gamestate = gamestate self.ammo_number = ammo + 5 self.nextlevel = NextLevel(self) self.tps_max = 300.0 self.superalien = [] self.tooClose = False self.pauseSign = Pause(self) self.pause = 1 for i in range(0,self.opp): self.aliens.append(Alien(self, i * 100 + 100, 100,self.gamestate-1)) self.aliens.append(Alien(self, i * 100 + 100, 150,self.gamestate-1)) self.aliens.append(Alien(self, i * 100 + 100, 200,self.gamestate-1)) self.aliens.append(Alien(self, i * 100 + 100, 250,self.gamestate-1)) self.aliens.append(Alien(self, i * 100 + 100, 300,self.gamestate-1)) self.aliens.append(Alien(self, i * 100 + 100, 350,self.gamestate-1)) self.rand_opp = 6*self.opp for i in range(0,5): self.walls.append(Wall(self,80+i*340)) channel_game = pygame.mixer.Channel(1) channel_game2 = pygame.mixer.Channel(2) channel_game3 = pygame.mixer.Channel(3) self.background = pygame.image.load("tlo3.jpg") self.text = open("score").readline() while self.gamestate !=0: if self.rand_opp != 0: los = random.randrange(self.rand_opp) else: los = 0 # obsługa zdarzen for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN and event.key == pygame.K_p: self.pause *= -1 elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE and self.ammo_number != 0: self.bullets.append(Bullet(self,self.player.pos[0]+23,self.player.pos[1])) channel_game3.play(pygame.mixer.Sound("mygun.wav")) channel_game3.set_volume(0.5) elif (self.lives_number == 0 or self.ammo_number <= 0 or self.tooClose == True) and event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN: self.gamestate = 0 elif len(self.aliens) == 0 and event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN: self.gamestate += 1 Game(self.gamestate,self.score_number,self.ammo_number) self.text = open("score").readline() self.gamestate = 0 elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE and self.pause == -1: self.gamestate = 0 elif event.type == pygame.KEYDOWN and event.key == pygame.K_p and self.pause == -1: self.pause *= -1 #ticking self.tps_delta += self.tps_clock.tick() / 1000.0 self.shot += self.tps_clock.tick()+0.000000003*(self.gamestate-1) / 1.0 self.supertime += self.tps_clock.tick() / 1.0 while self.tps_delta > 1 / self.tps_max: self.tick() self.tps_delta -= 1 / self.tps_max while(self.shot >= 0.001 / self.tps_max and len(self.aliens)!=0 and (self.lives_number != 0 and self.ammo_number > 0) and self.tooClose == False and self.pause == 1): self.shot = 0 channel_game.play(pygame.mixer.Sound("shot.wav")) channel_game.set_volume(0.5) self.alienbulets.append(AlienBullet(self,self.aliens[los].x,self.aliens[los].y)) while self.supertime >= 0.001 / self.tps_max: self.supertime = -2 if(len(self.superalien)==0 and self.tooClose == False and self.lives_number !=0 and self.ammo_number > 0 and self.pause == 1): self.superalien.append(SuperAlien(self)) channel_game2.play(pygame.mixer.Sound("supersound.wav")) channel_game2.set_volume(0.3) #rendering self.screen.fill((0, 0, 0)) self.screen.blit(self.background, (0, 0)) self.draw() pygame.display.flip()
class Game(object): def __init__(self,gamestate,score,ammo): # Konfuguracja random.seed() #inicjalizaja pygame.init() self.SCREEN_SIZE = (1280, 720) # grafiki dopasowane do tego self.screen = pygame.display.set_mode(self.SCREEN_SIZE) self.tps_clock = pygame.time.Clock() self.tps_delta = 0.0 self.shot = 0.0 self.supertime = -2 self.player = Player(self) self.aliens = [] self.opp = 10 self.bullets = [] self.alienbulets = [] self.lives = Lives(self) self.lives_number = 3 self.score = Score(self) self.score_number = 0 + score self.ammo = Ammo(self) self.walls = [] self.gameover = GameOver(self) self.gamestate = gamestate self.ammo_number = ammo + 5 self.nextlevel = NextLevel(self) self.tps_max = 300.0 self.superalien = [] self.tooClose = False self.pauseSign = Pause(self) self.pause = 1 for i in range(0,self.opp): self.aliens.append(Alien(self, i * 100 + 100, 100,self.gamestate-1)) self.aliens.append(Alien(self, i * 100 + 100, 150,self.gamestate-1)) self.aliens.append(Alien(self, i * 100 + 100, 200,self.gamestate-1)) self.aliens.append(Alien(self, i * 100 + 100, 250,self.gamestate-1)) self.aliens.append(Alien(self, i * 100 + 100, 300,self.gamestate-1)) self.aliens.append(Alien(self, i * 100 + 100, 350,self.gamestate-1)) self.rand_opp = 6*self.opp for i in range(0,5): self.walls.append(Wall(self,80+i*340)) channel_game = pygame.mixer.Channel(1) channel_game2 = pygame.mixer.Channel(2) channel_game3 = pygame.mixer.Channel(3) self.background = pygame.image.load("tlo3.jpg") self.text = open("score").readline() while self.gamestate !=0: if self.rand_opp != 0: los = random.randrange(self.rand_opp) else: los = 0 # obsługa zdarzen for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN and event.key == pygame.K_p: self.pause *= -1 elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE and self.ammo_number != 0: self.bullets.append(Bullet(self,self.player.pos[0]+23,self.player.pos[1])) channel_game3.play(pygame.mixer.Sound("mygun.wav")) channel_game3.set_volume(0.5) elif (self.lives_number == 0 or self.ammo_number <= 0 or self.tooClose == True) and event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN: self.gamestate = 0 elif len(self.aliens) == 0 and event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN: self.gamestate += 1 Game(self.gamestate,self.score_number,self.ammo_number) self.text = open("score").readline() self.gamestate = 0 elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE and self.pause == -1: self.gamestate = 0 elif event.type == pygame.KEYDOWN and event.key == pygame.K_p and self.pause == -1: self.pause *= -1 #ticking self.tps_delta += self.tps_clock.tick() / 1000.0 self.shot += self.tps_clock.tick()+0.000000003*(self.gamestate-1) / 1.0 self.supertime += self.tps_clock.tick() / 1.0 while self.tps_delta > 1 / self.tps_max: self.tick() self.tps_delta -= 1 / self.tps_max while(self.shot >= 0.001 / self.tps_max and len(self.aliens)!=0 and (self.lives_number != 0 and self.ammo_number > 0) and self.tooClose == False and self.pause == 1): self.shot = 0 channel_game.play(pygame.mixer.Sound("shot.wav")) channel_game.set_volume(0.5) self.alienbulets.append(AlienBullet(self,self.aliens[los].x,self.aliens[los].y)) while self.supertime >= 0.001 / self.tps_max: self.supertime = -2 if(len(self.superalien)==0 and self.tooClose == False and self.lives_number !=0 and self.ammo_number > 0 and self.pause == 1): self.superalien.append(SuperAlien(self)) channel_game2.play(pygame.mixer.Sound("supersound.wav")) channel_game2.set_volume(0.3) #rendering self.screen.fill((0, 0, 0)) self.screen.blit(self.background, (0, 0)) self.draw() pygame.display.flip() def tick(self): if (self.lives_number != 0 and self.ammo_number > 0 and len(self.aliens) !=0 and self.tooClose == False and self.pause == 1): self.edge = False self.player.tick() for i in range(0,len(self.aliens)): self.aliens[i].move() if (self.aliens[i].x >= self.SCREEN_SIZE[0]-50) or (self.aliens[i].x <= 0): self.edge = True if self.edge: for i in range(0, len(self.aliens)): if self.aliens[i].x >= self.SCREEN_SIZE[0]-100: for j in range(0, len(self.aliens)): self.aliens[j].x -= 3 elif self.aliens[i].x < 50: for j in range(0, len(self.aliens)): self.aliens[j].x += 3 self.aliens[i].shiftDown() self.edge = False if (self.aliens[i].y > 600 ): self.tooClose = True for i in range(0,len(self.bullets)): self.bullets[i].tick() for i in range(0,len(self.alienbulets)): self.alienbulets[i].tick() for i in range(0,len(self.superalien)): self.superalien[i].move() def draw(self): self.player.draw() self.lives.draw(self.lives_number) self.score.draw(self.score_number) self.ammo.draw(self.ammo_number) for i in range(0,len(self.walls)-1): self.walls[i].draw() for i in range(0,len(self.bullets)): self.bullets[i].draw() for j in range(0, len(self.aliens)): if(self.bullets[i].hits(self.aliens[j])): self.aliens[j].destroy() self.bullets[i].destroy() self.score_number +=10 #self.ammo_number += 1 for j in range(0, len(self.walls)): if (self.bullets[i].hits_wall(self.walls[j])): self.bullets[i].destroy() self.ammo_number -=1 if (self.walls[j].state > 0): self.walls[j].state -= 1 else: self.walls[j].destroy() for j in range(0,len(self.superalien)): if(self.bullets[i].hits_super(self.superalien[j])): self.superalien[j].destroy() self.bullets[i].destroy() self.score_number +=100 self.ammo_number += 5 if(self.bullets[i].y <= 0): self.bullets[i].destroy() self.ammo_number -= 1 for i in range(0,len(self.aliens)): self.aliens[i].draw() for i in range(len(self.bullets)-1,-1,-1): if(self.bullets[i].toDestroy): self.bullets.pop(i) for i in range(len(self.aliens)-1,-1,-1): if(self.aliens[i].toDestroy): self.aliens.pop(i) self.rand_opp -= 1 for i in range(len(self.walls)-1,-1,-1): if(self.walls[i].toDestroy): self.walls.pop(i) for i in range(len(self.alienbulets)-1,-1,-1): if(self.alienbulets[i].toDestroy): self.alienbulets.pop(i) for i in range(len(self.superalien)-1,-1,-1): if(self.superalien[i].toDestroy): self.superalien.pop(i) for i in range(0,len(self.superalien)): self.superalien[i].draw() if self.superalien[i].x < -65: self.superalien[i].destroy() for i in range(0,len(self.alienbulets)): self.alienbulets[i].draw() if(self.alienbulets[i].hits(self.player) and len(self.aliens) != 0): self.alienbulets[i].destroy() self.lives_number -= 1 self.ammo_number -= 4*(self.gamestate) self.score_number -= 100 for j in range(0,len(self.walls)): if(self.alienbulets[i].hits_wall(self.walls[j])): self.alienbulets[i].destroy() if(self.walls[j].state>0): self.walls[j].state -=1 else: self.walls[j].destroy() if (self.alienbulets[i].y >= 720): self.alienbulets[i].destroy() if self.lives_number == 0 or self.ammo_number <= 0 or self.tooClose: self.gameover.draw() if len(self.aliens) == 0: self.nextlevel.draw() if self.pause == -1: self.pauseSign.draw() if(self.score_number > int(self.text)): self.cel = open("score", "w") self.cel.write(self.text.replace(self.text,str(self.score_number))) self.cel.close()
class RobotService(rpyc.Service): mode = None thread = None def exposed_change_mode(self, mode, args=None): print("Mode change command: " + mode) if self.mode == mode: return if self.thread is not None: if self.mode != 'Manual Control': self.mode = mode self.thread.stop() self.thread.join() else: self.thread.stop_direction(self.thread.direction) self.change_mode(mode, args) def exposed_start_direction(self, direction): if self.mode == 'Manual Control': print(direction) self.thread.start_direction(direction) def exposed_stop_direction(self, direction): if self.mode == 'Manual Control': self.thread.stop_direction(direction) def change_mode(self, mode, args=None): self.mode = mode print("Changing mode...") if self.mode == 'Line Follower': print("Creating Line Follower...") self.thread = LineFollower(self.change_mode) self.thread.start() elif self.mode == 'Manual Control': print("Starting manual control...") self.thread = ManualControl(args) print("Manual control started") elif self.mode == 'Forest Crawler': print("Creating Forest Crawler...") self.thread = ForestCrawler(self.change_mode) self.thread.start() elif self.mode == 'Cube Carrier': print("Creating Cube Carrier...") self.thread = CubeCarrier(self.change_mode) self.thread.start() elif self.mode == 'Disc Traveler': print("Creating Disc Traveler...") self.thread = DiscTraveler(self.change_mode) self.thread.start() elif self.mode == 'Slope Searcher': print("Creating Slope Searcher...") self.thread = SlopeSearcher(self.change_mode) self.thread.start() elif self.mode == 'Battle Mode': print("Creating Battle Mode...") self.thread = BattleMode(self.change_mode) print("FOOBAR") self.thread.start() elif self.mode == 'Pause': print("Pausing...") self.thread = Pause() self.thread.start() elif self.mode == 'Stop': print("Stop")
class TargetPractice: """A class to manage all the assets and the game behavior """ def __init__(self): """Initialize the game and create game ressources """ pygame.init() self.settings = Settings() self.screen = pygame.display.set_mode( (self.settings.screen_width,self.settings.screen_height)) pygame.display.set_caption("J'y-rens Target Shoot 1.0") #Set the clock and time click self.clock = pygame.time.Clock() self.dt = 0 # create an instance of the game stats class self.stats = GameStats(self) #Create an instance of the scoreboard class self.sb = Scoreboard(self) # Create an instance of the class ship self.ship = Ship(self) #create a list of bullets that hit the rectangle self.bullets_hit_rectangle = [] # create an instance of the class rectangle self.rectangle = Rectangle(self) # create an instance of the group bullets self.bullets = pygame.sprite.Group() # create an instance of the button self.play_button= Button(self,"Play") # create an instance of the pause Button self.pause_button = Pause(self,"Pause") def run_game(self): """Start the main loop of the game """ while True : # watch for keyboard events self._check_events() if self.stats.game_active: # start the timer on the screen self.start_timer() #update the ship position self.ship.update() # update the position of the bullet self._update_bullets() #update the rectangle self._update_rectangle() # Update aliens self._update_screen() def _check_events(self): """Respond to keyboard events """ for event in pygame.event.get(): if event.type == pygame.QUIT: # store the highest score before quiting self.write_high_score_to_folder() sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pygame.KEYUP: self._check_keyup_events(event) elif event.type == pygame.MOUSEBUTTONDOWN: mouse_pos = pygame.mouse.get_pos() self._check_play_button(mouse_pos) self._check_pause_button(mouse_pos) def _check_pause_button(self, mouse_pos): """Lock the game when the player cliks the pause button """ button_clicked = self.pause_button.rect.collidepoint(mouse_pos) if button_clicked and self.stats.game_active: # pause the game . self.stats.game_active = False def _check_play_button(self, mouse_pos): """Check the play button """ button_clicked = self.play_button.button_rect.collidepoint(mouse_pos) if button_clicked and not self.stats.game_active: # Reset the game settings self.settings.initialize_dynamic_settings() # starts the game when the player clicks play and the game is inactive if self.stats.chances_left == 0 and self.sb.time == 0 or self.stats.score == 0: # Restart the game when the time is 0 seconds # and all the chances are gone self._start_game() self.stats.game_active = True self.sb.prep_score() self.sb.prep_level() self.sb.prep_timer() self.sb.prep_chances_left() def start_timer(self): """Start the timer when the game starts """ self.stats.timer -= self.dt if self.stats.timer <= 0 : sleep(1) self.stats.resets_timer() self.sb.prep_timer() self.dt = self.clock.tick(200) / 1000 # / 1000 to convert to seconds. def _start_game(self): """Start the game """ # set the game to active state self.stats.game_active = True # reset the stats self.stats.reset_stats() # set the timer back to zero self.stats.resets_timer() # Empty the bullets self.bullets.empty() # center the ship and the rectangle self.rectangle.center_rectangle() self.ship.center_ship() def _check_keydown_events(self,event): """Respond to keydown events """ if event.key == pygame.K_UP: self.ship.moving_up = True elif event.key == pygame.K_DOWN: self.ship.moving_down = True elif event.key == pygame.K_q: self.write_high_score_to_folder() sys.exit() elif event.key == pygame.K_SPACE: self._fire_bullets() elif event.key == pygame.K_p or pygame.K_KP_ENTER: if not self.stats.game_active: self._start_game() def write_high_score_to_folder(self): """write High score to folder""" with open(self.stats.filename, 'w') as f: json.dump(self.stats.high_score, f) def _fire_bullets(self): """Draws bullet on the screen """ if len(self.bullets) <= self.settings.bullets_allowed: new_bullet = Bullet(self) self.bullets.add(new_bullet) se.bullet_sound.play() def _update_bullets(self): """Update the position of the bullets """ self.bullets.update() for bullet in self.bullets.copy(): if bullet.rect.x >= self.settings.screen_width: self.bullets.remove(bullet) # check bullets and rectangle collisions and update bullets self._check_bullet_rectangle_collision() def _check_bullet_rectangle_collision(self): """Respond to bullets and rectangle collision """ bullet = pygame.sprite.spritecollideany( self.rectangle ,self.bullets) if bullet and self.stats.timer > 0: self.bullets_hit_rectangle.append(bullet) self.stats.score += self.settings.rectangle_points self.sb.prep_score() self.sb.check_high_score() # detect that the rectangle has been hit # and start a new level self._rectangle_hit() self.start_new_level() elif self.sb.time == 0 and not self.bullets_hit_rectangle : self._rectangle_not_hit() def start_new_level(self): """Start a new level if the rectangle has been hit """ self.settings.increase_speed() self.sb.prep_level() def _check_keyup_events(self,event): """Respond to keyup events """ if event.key == pygame.K_UP: self.ship.moving_up = False elif event.key == pygame.K_DOWN: self.ship.moving_down = False def _change_movement_direction(self): """change the movememnt direction of the rectangle """ self.settings.movement_direction *= -1 def _check_rectangle_edges(self): """check rectangle edges and change the movement direction """ if self.rectangle.check_edges(): self._change_movement_direction() def _update_rectangle(self): """Update rectangle position before""" self._check_rectangle_edges() self.rectangle.update() def _rectangle_not_hit(self): """Respond when the rectangle has not been hit and the timer has reached 0 """ if self.stats.chances_left > 0: #Decrement the number of chances self.stats.chances_left -=1 self.sb.prep_chances_left() se.miss_sound.play() self.bullets.empty() # Center the rectangle self.rectangle.center_rectangle() # resets timer to its initial value self.stats.resets_timer() sleep(0.5) else: self.end_of_game() def _rectangle_hit(self): """Respond when the rectangle is hit """ if self.stats.chances_left >= 0: # Empty the bullets_hit_rectangle list self.bullets_hit_rectangle = [] #Increment the level and empty the bullets self.stats.level +=1 se.level_increase_sound.play() self.bullets.empty() # resets the bullets to its orginal 15 seconds self.stats.resets_timer() # center the rectangle self.rectangle.center_rectangle() sleep(1) else: self.end_of_game() def end_of_game(self): """Play end of game sound """ sleep(2) se.end_of_game_sound.play() self.stats.game_active = False def _update_screen(self): """Update the screen anytime an item position is modified on the screen """ self.screen.fill(self.settings.bg_color) #Draw the ship of the screen self.ship.blitme() #Draw the rectangle to the screen self.rectangle.draw_rectangle() # Draw bullets on the screen for bullet in self.bullets.sprites(): bullet.draw_bullet() #Draw the score button self.sb.show_score() #Draw the play button if the game is not active if not self.stats.game_active: self.play_button.draw_button() else: self.pause_button.draw_button() pygame.display.flip()
def run(): conditions = getConditions() op = Pause() for condition in conditions: op.clickMyWechat(condition['id']) try: # 进行前置操作 op.auto_ad_before(condition['operate']) for i in range(0, 500): i += 1 try: try: op.auto_ad(condition['operate']) print('=======================' + condition['operate'] + '成功=======================') except Exception: pass # 判断是否跳出循环 if op.validate_xpath(): break except Exception: continue op.wait_text("小程序广告") op.find_link_text("小程序广告") time.sleep(1) # 进行前置操作 op.auto_ad_before(condition['operate']) for i in range(0, 500): i += 1 try: try: op.auto_ad(condition['operate']) print('=======================' + condition['operate'] + '成功=======================') except Exception: pass # 判断是否跳出循环 if op.validate_xpath(): break except Exception: continue except Exception: continue #定义循环结束页面 print('=======================处理完成=======================')
class Engine(object): def __init__(self): self.music = None ika.SetCaption('%s - Mannux' % ika.GetCaption()) video.clear() print >> fonts.big.center(), 'Loading . . .' ika.Video.ShowPage() self.window = Window() self.seconds = 0 self.minutes = 0 self.hours = 0 self.ticks = 0 self.time = '' self.flags = {'notloaded': True, 'shiplanded': False} self.curmap = '' # Not loading a map at this time. self.loading = False # Temporary Things, erased on each mapswitch. self.background_things = [] self.foreground_things = [] # Permanent Things, never erased (not currently used.) self.permanent_things = [] self.fields = [] self.entities = [] self.effects = [] self.add_list = [] self.kill_list = [] self.addeffect_list = [] self.killeffect_list = [] self.messages = [] # Current layer. self.cur_secret = None self.cur_terrain = None #for splash/water effects, mostly # List of layers in map. self.secret_layers = [] self.terrain_layers = [] try: ika.Map.Switch('amap.ika-map') except ImportError: # Probably should do something here. pass self.automap = automap.AutoMap() self.automap.load_automap() #self.meta = ika.Map.GetMetaData() # DO NOT PUT RUN HERE # If run is put here, the engine object is never returned. self.lights=True #lights activated self.lightcanvas=ika.Canvas(320,240) #should use xres and yres self.lightcanvas.Clear(ika.RGB(255,255,255,255)) self.circleimage = ika.Image('%s/circle_gradient.png' % config.image_path) self.circle = ika.Canvas('%s/circle_gradient.png' % config.image_path) self.bigcircle = ika.Canvas('%s/circle320.png' % config.image_path) self.smallcircle = ika.Canvas('%s/circle32.png' % config.image_path) def GetFlag(self, key): return self.flags.get(key, False) def SetFlag(self, key, value): self.flags[key] = value def GetLayers(self): """Creates a listing for all secret/terrain layers.""" s_layers = [] #secret t_layers = [] #terrain lname = '' for l in range(ika.Map.layercount): #complex line for grabbing all layers that start with the word secret :) lname = ika.Map.GetLayerName(l) if lname[:6].lower() == "secret": s_layers.append([l, 0, 255]) elif lname in ("Lava", "Acid", "Water"): #add more later, possibly.. #get the layer height and scroll through it to find where it starts #terrain layers #for i in range(ika.Map.GetLayerProperties(l)[2]): # if ika.Map.GetTile(0, i, l): #find where the layer actually begins... may need to change later t_layers.append( ( lname, l ) ) #name, layer # print "Terrain Detected. Type: " + lname + " "+str(l) #break self.secret_layers = s_layers self.terrain_layers = t_layers self.cur_secret = None self.cur_terrain = None # #Grab terrain layer. # tlayer = ika.Map.layercount - 1 # name = ika.Map.GetLayerName(tlayer) # #Check the last layer's name to see if it's a terrain type. # if name in ("Lava", "Acid", "Water") or name[:4] == "Wind": # print "Terrain Detected. Type: " + name # for i in range(ika.Map.GetLayerProperties(tlayer)[2]): # if ika.Map.GetObs(0, i, tlayer): # ty = i # break # self.cur_terrain = (name, tlayer, ty * 16) # else: # self.cur_terrain = None def initialize(self): self.player = Tabby(0, 0) self.hud = Hud() self.pause = Pause() self.title = TitleScreen() self.camera = Camera(self.player.sprite) self.cameratarget = self.player self.entities.append(self.player) #player should always be the first in the list def newgame(self): self.load('%s/default.save' % config.save_path) def loadgame(self, f='%s/savegame.save' % config.save_path): try: #sf = file(f) #close(f) self.load(f) except: self.newgame() def Run(self): self.title.show() self.newgame() #only comment out if not showing title self.hud.resize() self.automap.update_room() time = ika.GetTime() done = False self.music = ika.Music('%s/00_-_zaril_-_close_to_the_core.xm' % config.music_path) self.music.loop = True self.music.Play() while not done: t = ika.GetTime() while t > time: # Uncomment for slow motion. #ika.Delay(2) self.tick() time += 1 time = ika.GetTime() self.update_time() self.camera.update() self.draw() print >> fonts.one(0, 40), 'FPS:', ika.GetFrameRate() #for i, e in enumerate(self.entities): # print >> fonts.one(0, 50 + 10*i), 'sprite', e.sprite ika.Input.Update() if controls.pause.Pressed(): self.pause.menu() ika.Input.Unpress() # Make sure the engine doesn't have to play 'catchup'. time = ika.GetTime() #screenshot key if False: #controls.confirm.Pressed(): #screenshot #self.text('This is a textbox.') ika.Input.Unpress() time = ika.GetTime() c = ika.Video.GrabCanvas(0, 0, ika.Video.xres, ika.Video.yres) c2 = ika.Image(c) c2.Blit(0, 0) c.Save('blah1.png') ika.Video.ShowPage() def draw(self): for thing in self.background_things: thing.draw() #if self.background: # ika.Video.Blit(self.background, 0, 0) for i in range(ika.Map.layercount): ika.Map.Render(i) for ent in self.entities: if ent.layer == i and ent.visible: ent.draw() #inefficient as it loops through each entity multiple times depending on # of layers, but works for now... #if performance becomes an issue will refactor to multiple lists per layer. for eff in self.effects: if eff.layer == i and eff.visible: eff.draw() #for special effects, may behave differntly for entities so putting them here instead. #video.clear(ika.RGB(0, 255, 0)) #ika.Map.Render() for thing in self.foreground_things: try: thing.draw() except AttributeError: # This is retarded. pass if self.lights: #lightmap check #self.lightcanvas.Clear() p=self.player x=int(p.x + p.width/2 - ika.Map.xwin)# - 320 y=int(p.y + p.height/2 - ika.Map.ywin)# - 240 #print >> fonts.tiny(0,80), 'x: '+str(x) #print >> fonts.tiny(0,90), 'y: '+str(y) #self.bigcircle.Blit(self.lightcanvas, 0, 0, ika.AddBlend) #self.smallcircle.Blit(self.lightcanvas, x-10, y-80, ika.AddBlend) #if controls.confirm.Pressed(): # self.lightcanvas.Save("test.png") #self.lightcanvas.Blit(self.image, x , y, ika.RGB(255, 255, 255, self.opacity), ika.SubtractBlend) #img=ika.Image(self.lightcanvas) #ika.Video.DrawRect(0,0,319,219,ika.RGB(0,0,64,128), ika.SubtractBlend) #ika.Video.TintBlit(img, 0,0, ika.RGB(255,255,255,128), ika.AddBlend) #the one that always works #ika.Video.DrawEllipse(x+160, y+160, 50, 40, ika.RGB(100,100,100,128), 1, ika.AddBlend) #ika.Video.TintBlit(img, 0 , 0, ika.RGB(255, 255, 255, 128)) #ika.Video.TintBlit(img, 0 , 0) self.hud.draw() x = 10 y = 230 for m in self.messages: print >> fonts.one(x, y), m.text y -= 10 #font.Print(0, 80, self.meta['testing']) #font.Print(240, 0, 'xwin: %s' % ika.Map.xwin) #font.Print(240, 10, 'ywin: %s' % ika.Map.ywin) #font.Print(240, 30, 'vx: %s' % self.player.vx) #font.Print(240, 40, 'floor: %s' % self.player.floor) #font.Print(10, 60, 'x: %s' % self.player.x) #font.Print(10, 70, 'y: %s' % self.player.y) #font.Print(10, 80, 'slope: %s' % self.player.in_slope) #font.Print(10, 90, 'floor: %s' % self.player.floor) #font.Print(10, 100, 'jumps: %s' % self.player.jump_count) #font.Print(10, 70, 'vy: %s' % self.player.vy) #font.Print(10, 80, self.player.msg) #font.Print(10, 80, str(ika.Input.joysticks[0].axes[0].Position())) #font.Print(10, 80, str(len(entities))) #x = int(self.player.x + self.player.sprite.hotwidth / 2 + # self.player.vx) #y = int(self.player.y + self.player.sprite.hotheight - 1 + # self.player.vy) #tx = x / 16 #ty = y / 16 #ika.Video.DrawPixel(x - ika.Map.xwin, y - ika.Map.ywin, # color.white) #ika.Video.DrawRect(tx * 16 - ika.Map.xwin, ty * 16 - ika.Map.ywin, # tx * 16 + 16 - ika.Map.xwin, # ty * 16 + 16 - ika.Map.ywin, # ika.RGB(255, 0, 0, 128), True) #font.Print(240, 40, str(self.player.right_wall)) #main engine processing def tick(self): self.UpdateTerrain() for thing in self.background_things: try: thing.update() except AttributeError: pass for thing in self.foreground_things: try: thing.update() except AttributeError: pass for entity in self.add_list: self.entities.append(entity) self.add_list = [] for effect in self.addeffect_list: self.effects.append(effect) self.addeffect_list = [] for entity in self.entities: if entity.active: entity.update() for effect in self.effects: if effect.active: effect.update() for entity in self.kill_list: self.entities.remove(entity) self.kill_list = [] for effect in self.killeffect_list: self.effects.remove(effect) self.killeffect_list = [] for f in self.fields: if f.test(self.player) and not f.runnable: f.fire() mlist = [] for m in self.messages: m.duration -= 1 if m.duration <= 0: mlist.append(m) for m in mlist: self.messages.remove(m) self.ticks += 1 def map_switch(self, x, y, m, direction=0, fadeout=True, fadein=True, scroll=False): # Update the current map. self.curmap = m m = 'maps/%s' % m if fadeout: self.FadeOut(16) video.clear() # Destroy entities. for e in self.entities[:]: if e is not self.player: e._destroy() for e in self.effects[:]: e._destroy() self.background_things = [] self.foreground_things = [] self.player.x = x self.player.y = y ika.Map.Switch(m) self.automap.update_room() self.camera.reset_borders() self.camera.update() self.player.layer = ika.Map.FindLayerByName('Walls') self.player.sprite.layer = self.player.layer moduleName = m[:m.rfind('.')].replace('/', '.') mapModule = __import__(moduleName, globals(), locals(), ['']) self.readZones(mapModule) self.GetLayers() #if True: #check for flag for lighting... eventually.. # self.foreground_things.append(fog.Darkness()) video.clear() if fadein: self.FadeIn(16) def GameOver(self): t = ika.GetTime() while True: self.draw() a = min(100, ika.GetTime() - t) if a == 100: print >> fonts.big.center(), 'G A M E O V E R' video.clear(ika.RGB(10, 10, 10, a)) ika.Video.ShowPage() ika.Input.Update() if controls.confirm.Pressed() or \ controls.cancel.Pressed(): break t = ika.GetTime() while True: self.draw() a = min(255, ika.GetTime() - t + 100) video.clear(ika.RGB(10, 10, 10, a)) ika.Video.ShowPage() ika.Input.Update() if a == 255: break ika.Exit('') def update_time(self): while self.ticks >= 100: self.ticks -= 100 self.seconds += 1 while self.seconds >= 60: self.seconds -= 60 self.minutes += 1 while self.minutes >= 60: self.minutes -= 60 self.hours += 1 self.time = '%01d:%02d:%02d' % (self.hours, self.minutes, self.seconds) def UpdateTerrain(self): #Updates terrain layer. For water effects, currently. should be part of Tabby herself... for l in self.terrain_layers: name, layer = l #going in if ika.Map.GetTile(int(self.player.x+1) / 16, int(self.player.y + 31) / 16, layer): if self.player.cur_terrain == None: self.AddEntity(Splash(int(self.player.x - 12), int(self.player.y), name.lower(), layer)) self.player.cur_terrain = name #globals()[name + "Terrain"](self, self.player) else: #jumping out if self.player.cur_terrain: #should include regular entities too... self.AddEntity(Splash(int(self.player.x - 12), int(self.player.y), name.lower(), layer)) self.player.cur_terrain = None #def UpdateTerrain(self): # # if self.cur_terrain: # name, l = self.cur_terrain # # #jumping out # if ika.Map.GetTile(0, int(self.player.y + 31) / 16, layer): # if self.player.cur_terrain == None: # self.AddEntity(Splash(self.player.x, self.player.y, name.lower(), layer=l )) # self.player.cur_terrain = name # # #globals()[name + "Terrain"](self, self.player) # else: #going in # if self.player.cur_terrain: #should include regular entities too... # self.AddEntity(Splash(self.player.x+self.player.vx, self.player.y, name.lower())) # self.player.cur_terrain = None def text(self, txt): #ooold code... done = 0 state = 0 h = 0 arrow = ika.Image('%s/arrow.png' % config.image_path) lines = wrap(txt, 360, fonts.big) scrolling = 1 scroll = [0] * len(lines) current = 0 offset = 0 t = ika.GetTime() while not done: #ika.Map.Render() self.draw() while t == ika.GetTime(): pass for i in range(ika.GetTime() - t): for entity in self.entities: entity.update() if state == 0: h += 2 if state == 1 and scrolling == 1: scroll[current + offset] += 1 if state == 2: h -= 2 t = ika.GetTime() if state == 0: if h >= 40: h = 40 state = 1 self.window.resize(h * 8, h) else: self.window.resize(h * 8, h) self.window.draw(168 - h * 4, 200 - h / 2) if state == 1: self.window.draw(8, 180) for i in range(len(lines[offset:])): print >> fonts.big(20, 190 + 12 * i), lines[i + offset][:scroll[i + offset]] if scroll[current + offset] >= \ len(lines[current + offset]): if current + offset < len(lines) - 1: current += 1 else: scrolling = 0 if current == 7: scrolling = 0 # Put blinking arrow or whatever here. if ika.GetTime() % 50 < 40: ika.Video.Blit(arrow, 192, 280 + ika.GetTime() % 50 / 10) if state == 2: if h <= 0: done = True else: self.window.resize(h * 8, h) self.window.draw(168 - h * 4, 200 - h / 2) print >> fonts.one(0, 0), 'lines:', '%s' ika.Video.ShowPage() ika.Input.Update() if ika.Input.keyboard['RETURN'].Pressed() and state == 1 and \ scrolling == 0: ika.Input.Unpress() if current + offset < len(lines) - 1: scrolling = 1 offset += 7 current = 0 else: state = 2 def addField(self, field): assert field not in self.fields self.fields.append(field) def destroyField(self, field): self.fields.remove(field) def readZones(self, mapModule): """Read all the zones on the map, and create fields.""" self.fields = [] for layer in range(ika.Map.layercount): zones = ika.Map.GetZones(layer) for x, y, w, h, script in zones: self.addField(Field((x, y, w, h), layer, mapModule.__dict__[script], str(script))) def FadeOut(self, time=50): video.fade_out(time, draw=self.draw, draw_after=self.hud.draw) def FadeIn(self, time=50): video.fade_in(time, draw=self.draw, draw_after=self.hud.draw) def SavePrompt(self, heal=True): if heal: self.player.dhp = self.player.maxhp self.player.dmp = self.player.maxmp selected = 0 while not controls.confirm.Pressed(): self.player.update() self.draw() Window(150, 0).draw(52, 60) print >> fonts.one(68, 80), 'Do you want to save?' x = 100 y = 98 for i, option in enumerate(['Yes', 'No']): f = [fonts.five, fonts.three][i == selected] print >> f(x, y), option x += 100 self.hud.draw() #ika.Video.DrawRect(80 + 110 * selected, 92, 120 + 110 * selected, # 108, ika.RGB(128, 192, 128)) ika.Video.ShowPage() ika.Input.Update() if controls.left.Pressed(): sound.play('Menu') selected -= 1 if selected < 0: selected = 1 if controls.right.Pressed(): sound.play('Menu') selected += 1 if selected > 1: selected = 0 #for c in controls.control_list: # c.Release() if selected == 0: self.Save() return True return False #saving incomplete, does not save map data def Save(self, filename='%s/savegame.save' % config.save_path): flagnode = parser.Node('flags') for key, value in self.flags.iteritems(): flagnode.append(parser.Node(key).append(value)) #mapnode = parser.Node('amap') #for n in self.automap.amap: # mapnode.append(n) foo = (parser.Node('mannux-save') .append(parser.Node('version').append(1)) .append(parser.Node('map').append(self.curmap)) .append(parser.Node('hp').append(self.player.maxhp)) #always save with full health .append(parser.Node('maxhp').append(self.player.maxhp)) .append(parser.Node('mp').append(self.player.maxmp)) .append(parser.Node('maxmp').append(self.player.maxmp)) .append(flagnode) .append(parser.Node('amap1').append(str(self.automap.amap))) ) print >> open(filename, 'wt'), foo self.messages.append(Message("Game saved", 300)) #for some reason misses some flags.. def load(self, filename='%s/default.save' % config.save_path): self.loading = True d = parser.load(filename) self.curmap = d['mannux-save'].get('map') self.player.hp = int(d['mannux-save'].get('hp')) self.player.maxhp = int(d['mannux-save'].get('maxhp')) self.player.mp = int(d['mannux-save'].get('mp')) self.player.maxmp = int(d['mannux-save'].get('maxmp')) self.flags = d['mannux-save']['flags'].todict() a = d['mannux-save'].get('amap1') print 'testing: ' print d['mannux-save'].get('map') print d['mannux-save'].get('amap1') #print a #if 'amap1' in d['mannux-save']: # print 'yes!' # a = d['mannux-save']['amap1'] # b = '' # for c in a: # b+=str(c) # print "Load test:" # # test = eval(b) # self.automap.amap = test #else: # print 'wtf!' #b = d['mannux-save']['amap'] #self.automap.amap = [] #i=0 #for y in range(50): #need to change so it's not just 50x50... # for x in range(50): #self.automap.amap.append(a[i]) #for i in a: # ika.Log('i: '+str(i)) # i+=1 #for i in d['mannux-save']['amap']: # self.automap.amap.append(i) self.hud.resize() #print self.curmap self.map_switch(0, 0, self.curmap, fadeout=False) self.loading = False def AddEntity(self, ent): self.add_list.append(ent) def RemoveEntity(self, ent): self.kill_list.append(ent) def AddEffect(self, effect): self.addeffect_list.append(effect) def RemoveEffect(self, effect): self.killeffect_list.append(effect)
class AlienInvasion: """Overall class to manage game assets and behavior.""" def __init__(self): """Initialize the game, and create game resources """ pygame.init() self.settings = Settings() self.screen = pygame.display.set_mode( (self.settings.screen_width, self.settings.screen_height)) #self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) #self.settings.screen_width = self.screen.get_rect().width #self.settings.screen_height = self.screen.get_rect().height self.caption = "J'y-rens Alien Invasion 1.0" pygame.display.set_caption(self.caption) #Create an instance to store game statistics. # and create a scoreboar. self.stats = GameStats(self) self.sb = Scoreboard(self) self.ship = Ship(self) #bullet groups self.bullets = pygame.sprite.Group() #Alien Groups self.aliens = pygame.sprite.Group() # create fleet of aliens self._create_fleet() #Make the Play Button. self.play_button = Button(self, "Play") self.pause_button = Pause(self, "Pause") def run_game(self): """Start the main loop for the game.""" while True: #Watch for keyboard and mouse events. self._check_events() if self.stats.game_active and self.caption == "J'y-rens Alien Invasion 1.0": # Update the ship position self.ship.update() # Update bullets and get rid of old bullets self._update_bullets() #Update the position of each Alien self._update_aliens() # Redraw the screen during each pass through the loop and flip to the new screen. self._update_screen() def _check_events(self): """ Respond to keypresses and mouse events """ for event in pygame.event.get(): if event.type == pygame.QUIT: self.write_high_score_to_folder() sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pygame.KEYUP: self._check_keyup_events(event) elif event.type == pygame.MOUSEBUTTONDOWN: mouse_pos = pygame.mouse.get_pos() self._check_play_button(mouse_pos) self._check_pause_button(mouse_pos) def _check_pause_button(self, mouse_pos): """Lock the game when the player cliks the pause button """ button_clicked = self.pause_button.rect.collidepoint(mouse_pos) if button_clicked and self.stats.game_active: # Reset the game settings. self.stats.game_active = False #self.play_button.draw_button() def _check_play_button(self, mouse_pos): """Starts a new game when the player clicks Play """ button_clicked = self.play_button.rect.collidepoint(mouse_pos) if button_clicked and not self.stats.game_active: # Reset the game settings. self.settings.initialize_dynamic_settings() # starts the game when the player clicks play and the game is inactive if self.stats.score == 0: self._start_game() self.stats.game_active = True self.sb.prep_score() self.sb.prep_level() self.sb.prep_ships() def _check_keydown_events(self, event): """ Respond to keypresses """ if event.key == pygame.K_RIGHT: #Move the ship to the right self.ship.moving_right = True elif event.key == pygame.K_LEFT: #Move the ship to the left self.ship.moving_left = True elif event.key == pygame.K_q: self.write_high_score_to_folder() sys.exit() elif event.key == pygame.K_SPACE: self._fire_bullet() elif event.key == pygame.K_p or pygame.K_KP_ENTER: if not self.stats.game_active: self._start_game() def write_high_score_to_folder(self): """write High score to folder""" with open(self.stats.filename, 'w') as f: json.dump(self.stats.high_score, f) def _start_game(self): """Start the game when the player presses the button""" # Reset the game statistics. self.stats.reset_stats() self.stats.game_active = True # Get rid of any remaining aliens and bullets self.aliens.empty() self.bullets.empty() #Create a new fleet and center the ship. self._create_fleet() self.ship.center_ship() # Hide the mouse cursor. pygame.mouse.set_visible(True) def _check_keyup_events(self, event): """ Respond to key releases """ if event.key == pygame.K_RIGHT: self.ship.moving_right = False elif event.key == pygame.K_LEFT: self.ship.moving_left = False def _fire_bullet(self): """Create a new bullet and add it to the bullets group.""" if len(self.bullets) < self.settings.bullets_allowed: new_bullet = Bullet(self) self.bullets.add(new_bullet) se.bullet_sound.play() def _update_bullets(self): """Update position of bullets and get rid of old bullets """ # update the bullets self.bullets.update() # Get rid of old bullets that have disappeared for bullet in self.bullets.copy(): if bullet.rect.bottom <= 0: self.bullets.remove(bullet) # Check for any bullets that have hit aliens. # If so , get rid of the alien and the bullet. self._check_bullet_allien_collisions() def _check_bullet_allien_collisions(self): """ Respond to bullet alien collisions """ # Remove any bullets an allien that have collided collisions = pygame.sprite.groupcollide(self.bullets, self.aliens, True, True) if collisions: for aliens in collisions.values(): self.stats.score += self.settings.alien_points * len(aliens) self.sb.prep_score() self.sb.check_high_score() se.alien_sound.play() if not self.aliens: # Destroy existing bullets and create new fleet self.start_new_level() def start_new_level(self): """Start a new level if aliens have been destroyed """ self.bullets.empty() self._create_fleet() self.settings.increase_speed() # Increase level. self.stats.level += 1 self.sb.prep_level() def _create_fleet(self): """ Create fleet of Aliens """ # create an Alien and find the number of aliens in a row # Spacing between each alien is equal to one alien width alien = Alien(self) alien_width = alien.rect.width alien_height = alien.rect.height # Determine the number columns that fit the aliens on the screen available_space_x = self.settings.screen_width - (2 * alien_width) number_aliens_x = available_space_x // (2 * alien_width) # Determine the number of rows that fit the Alien on the screen ship_height = self.ship.rect.height available_space_y = (self.settings.screen_height - (3 * alien_height) - ship_height) number_rows = available_space_y // (2 * alien_height) # create the full feet of aliens for row_number in range(number_rows): for alien_number in range(number_aliens_x): self._create_alien(alien_number, row_number) def _create_alien(self, alien_number, row_number): """ Create an Instance of an Alien """ #Create an alien and place it in the row . alien = Alien(self) alien_width = alien.rect.width alien_height = alien.rect.height alien.x = alien_width + 2 * alien_width * alien_number alien.y = alien_height + 2 * alien_height * row_number alien.rect.x = alien.x alien.rect.y = alien.y self.aliens.add(alien) def _check_fleet_edges(self): """Respond Appropriatly if any aliens have reached the edge """ for alien in self.aliens.sprites(): if alien.check_edges(): self._change_fleet_direction() break def _change_fleet_direction(self): """Drop the entire fleet and change the fleet's direction """ for alien in self.aliens.sprites(): alien.rect.y += self.settings.fleet_drop_speed self.settings.fleet_direction *= -1 def _ship_hit(self): """Respond to the ship being hit by an alien """ if self.stats.ships_left > 0: se.ship_hit_sound.play() # Decrement ships_left and update scoreboard self.stats.ships_left -= 1 self.sb.prep_ships() # Get rid of any remaning aliens and bullets self.aliens.empty() self.bullets.empty() #Create a new fleet and center the ship self._create_fleet() self.ship.center_ship() # Pause. sleep(0.5) else: self.stats.game_active = False pygame.mouse.set_visible(True) def _check_aliens_bottom(self): """Check if aliens have reached the bottom of the screen """ screen_rect = self.screen.get_rect() for alien in self.aliens.sprites(): if alien.rect.bottom >= screen_rect.bottom: # Treat it the same way as if a ship got hit self._ship_hit() break def _update_aliens(self): """Update the positions of all aliens in the fleet """ self._check_fleet_edges() self.aliens.update() # Look for alien-ship collisions . if pygame.sprite.spritecollideany(self.ship, self.aliens): self._ship_hit() #Look for aliens hitting the bottom of the screen self._check_aliens_bottom() def _update_screen(self): """ Update images on the screen, and flip to the new screen.""" self.screen.fill(self.settings.bg_color) self.ship.blitme() # Make the most recently drawn screen visible. for bullet in self.bullets.sprites(): bullet.draw_bullet() self.aliens.draw(self.screen) # Draw the score information self.sb.show_score() # Draw the play button if the game is inactive if not self.stats.game_active: self.play_button.draw_button() else: self.pause_button.draw_button() pygame.display.flip()
def play(self): state = constants.STATE_START score_board = Score(location=(constants.WINDOW_WIDTH - 30, 20)) play_button = Play( location=(int((constants.WINDOW_WIDTH - constants.PLAY_WIDTH) / 2), int((constants.WINDOW_HEIGHT - constants.PLAY_HEIGHT) / 2))) pause_button = Pause(location=(20, 20)) welcome_message = Welcome(location=( int((constants.WINDOW_WIDTH - constants.MESSAGE_WIDTH) / 2), int((constants.WINDOW_HEIGHT - constants.MESSAGE_HEIGHT) / 2))) gameover_message = GameOver(location=( int((constants.WINDOW_WIDTH - constants.GAMEOVER_WIDTH) / 2), int((constants.WINDOW_HEIGHT - constants.GAMEOVER_HEIGHT) / 3))) collided = False done = False while not done: for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked close done = True # Flag that we are done so we exit this loop elif event.type == pygame.KEYDOWN: if state == constants.STATE_START: if event.key == pygame.K_SPACE: state = constants.STATE_RUN self.nb_games += 1 if self.nb_games > 1: self.reset() elif state == constants.STATE_RUN: if event.key == pygame.K_SPACE: self.agent.flap() elif event.key == pygame.K_ESCAPE: state = constants.STATE_PAUSE elif state == constants.STATE_PAUSE: if event.key == pygame.K_SPACE: if collided: state = constants.STATE_RUN self.nb_games += 1 if self.nb_games > 1: self.reset() else: self.agent.resume(fps=self.fps) state = constants.STATE_RUN elif event.type == pygame.MOUSEBUTTONDOWN: mouse_pos = event.pos # gets mouse position if state == constants.STATE_RUN: if pause_button.rect.collidepoint(mouse_pos): state = constants.STATE_PAUSE else: self.agent.flap() elif state == constants.STATE_START and welcome_message.rect.collidepoint( mouse_pos): state = constants.STATE_RUN self.nb_games += 1 if self.nb_games > 1: self.reset() elif state == constants.STATE_PAUSE: if gameover_message.rect.collidepoint(mouse_pos): state = constants.STATE_START collided = False elif play_button.rect.collidepoint(mouse_pos): self.agent.resume(fps=self.fps) state = constants.STATE_RUN if state == constants.STATE_START: self.redraw_screen(move=False) self.screen.blit(welcome_message.image, welcome_message.rect) elif state == constants.STATE_RUN: out_of_bounds = self.agent.move() self.meter_counts[1] += constants.SPEED if self.meter_counts[1] - self.meter_counts[ 0] > constants.PIPE_WIDTH: self.meter_counts[0] = self.meter_counts[1] self.update_pipes() collided, _ = self.check_collision() collided = collided or out_of_bounds if collided: state = constants.STATE_PAUSE score_board.update(score=self.score) self.redraw_screen() self.screen.blit(pause_button.image, pause_button.rect) self.screen.blit(score_board.surface, score_board.rect) elif state == constants.STATE_PAUSE: self.redraw_screen(move=False) if collided: self.screen.blit(gameover_message.image, gameover_message.rect) else: self.screen.blit(play_button.image, play_button.rect) # Limit the number of frames per second fps = self.fps if state == constants.STATE_RUN else int(self.fps / 2) self.clock.tick(fps) # Go ahead and update the screen with what we've drawn. pygame.display.flip() # Be IDLE friendly. If you forget this line, the program will 'hang' # on exit. pygame.quit()
class GameControl2(object): def __init__(self): pygame.mixer.init() pygame.init() self.screen = pygame.display.set_mode(screen_size, 0, 32) self.background = None #self.Fill_Back() pygame.display.set_caption('Pacman Remake') pygame.display.set_icon(icon) self.clock = pygame.time.Clock() pygame.mixer.music.load('Pac-man theme 1.mp3') #pygame.mixer.music.set_volume(0.25) pygame.mixer.music.play(-1, 0.0) self.pellet_count = 0 self.fruit = None self.text = Group_Text() self.count_time = 0 self.time = 0 self.besttime = 0 self.pause = Pause(True) self.level = Level() self.end_game = False self.chase_music = pygame.mixer.Sound("chase_theme_2.wav") self.switch_music = False self.switch_time = 0 self.quit = False #self.pac = pygame.transform.scale(pacr, (20, 22)) #self.clock.tick(30) #def Fill_Back(self): # self.background = pygame.surface.Surface(screen_size).convert() # self.background.fill(black) def eat_pellets(self): pellet = self.pacman.eatPellets(self.pellets.pelletList) if (pellet): self.pellet_count += 1 if (self.pellet_count == 50 or self.pellet_count == 140) and self.fruit is None: self.fruit = Fruit(self.Nodes) self.pellets.pelletList.remove(pellet) if (len(self.pellets.pelletList) == 0): #if (self.pellet_count == 10): #debug mode (check next lvl immediately) self.ghosts.hide() self.pacman.visible = False self.pacman.lives = 0 self.pause.start(3, "dead") if pellet.name == "powerpellet": self.ghosts.reset_points() self.ghosts.fright() self.chase_music.stop() self.chase_music.play() pygame.mixer.music.pause() self.switch_music = True self.switch_time = 0 def eat_ghost(self): ghost = self.pacman.Ghosteat(self.ghosts) if ghost is not None: if ghost.mode[ghost.modeCount].name == "FRIGHT": self.switch_time -= 1 self.text.Create_Temptxt(ghost.points, ghost.location.x - 10, ghost.location.y) self.ghosts.up_points() ghost.spawnMode(speed=2) self.pause.start(1) self.pacman.visible = False ghost.visible = False elif ghost.mode[ghost.modeCount].name != "SPAWN": self.pacman.lives -= 1 self.ghosts.hide() self.pause.start(3, "dead") def start_game(self): #pass self.level.current_lvl = 0 maze = self.level.new_lvl() self.Nodes = Group_Nodes(maze[0]) self.pellets = PelletGroups(maze[1]) self.pacman = Pacman(self.Nodes) self.ghosts = Group_Ghosts(self.Nodes) self.pellet_count = 0 self.fruit = None self.pause.force(True) self.pause.pauseType = None self.end_game = False self.text.Reset_Color(self.besttime) self.time = 0 self.count_time = 0 self.text.Ready() def next_lvl(self): self.level.current_lvl += 1 maze = self.level.new_lvl() self.Nodes = Group_Nodes(maze[0]) self.pellets = PelletGroups(maze[1]) self.pacman.initial_location() self.ghosts = Group_Ghosts(self.Nodes) self.pellet_count = 0 self.fruit = None self.pause.force(True) self.screen.fill(black) pygame.display.update() time.sleep(0.8) self.text.Ready() def restart_lvl(self): self.pacman.initial_location() self.ghosts = Group_Ghosts(self.Nodes) self.fruit = None self.pause.force(True) self.text.Ready() def Time_Check(self, t): self.count_time += t if (int(self.count_time) - self.time == 1): self.time = int(self.count_time) def update(self): t = self.clock.tick(60) / 1000 if self.end_game == False: if self.switch_music == True: self.switch_time += t if self.switch_time >= 7: pygame.mixer.music.unpause() self.switch_time = 0 self.switch_music = False #self.pacman.update() if self.pause.check_pause == False: self.Time_Check(t) if self.fruit is not None: self.fruit.update(t) self.pacman.update(t) self.ghosts.update(t, self.pacman) if self.pause.pauseType == "finish": self.clear_lvl() elif self.pause.pauseType == "dead": self.resolve_restart_lvl() self.eat_pellets() self.ghosts.check_release(self.pellet_count) self.check_fruit() self.eat_ghost() self.pause.update(t) self.pellets.update(t) self.text.update(t) self.checkEvents() self.text.Update_Time(self.time) if self.time > self.besttime: self.besttime = self.time self.text.Update_Besttime(self.besttime) self.redraw(t) def resolve_clear_lvl(self): self.level.next_lvl() self.pause.pauseType = None def resolve_restart_lvl(self): if self.pacman.lives == 0: self.end_game = True self.pacman.visible = False self.text.GameOver() else: self.restart_lvl() self.pause.pauseType = None def check_fruit(self): if self.fruit is not None: if self.pacman.eatFruit(self.fruit) is not None: self.text.Create_Temptxt(self.fruit.points, self.fruit.location.x - 10, self.fruit.location.y) self.fruit = None elif self.fruit.disappear == True: self.fruit = None def checkEvents(self): for event in pygame.event.get(): if event.type == QUIT: pygame.quit() exit() elif event.type == KEYDOWN: if event.key == K_SPACE: if self.end_game == True: self.start_game() else: self.pause.player() if self.pause.check_pause == True: self.text.Pause() else: self.text.Hide_All() elif event.key == K_ESCAPE: self.quit = True #elif event.type == KEYUP: # self.pacman.pressed = False def redraw(self, t): self.screen.fill(black) #for i in range(game_rows): # for j in range(game_cols): # pygame.draw.rect(self.screen, blue,(Tile_Width *(j+0.8) , Tile_Height * (i+0.8), 9, 9)) self.Nodes.refresh(self.screen) self.pellets.draw(self.screen) if self.fruit is not None: self.fruit.draw(self.screen) self.pacman.draw(self.screen) self.pacman.draw_lives(self.screen) self.ghosts.draw(self.screen, t) self.text.draw(self.screen) pygame.display.update()