def update_portals(self): """Check if portals need to be closed.""" portal_position = None if self.create_blue_portal: for portal in self.portals.sprites(): if portal.indicator == 0: portal.closing_portal = True else: portal_position = portal.position portal.other_portal = self.blue_bullet_position new_portal = Portal(screen=self.screen, image_list=self.sprite_sheet.blue_portal, position=self.blue_bullet_position, indicator=0, other_portal=portal_position) self.portals.add(new_portal) self.create_blue_portal = False if self.create_red_portal: for portal in self.portals.sprites(): if portal.indicator == 1: portal.closing_portal = True else: portal_position = portal.position portal.other_portal = self.red_bullet_position new_portal = Portal(screen=self.screen, image_list=self.sprite_sheet.red_portal, position=self.red_bullet_position, indicator=1, other_portal=portal_position) self.portals.add(new_portal) self.create_red_portal = False self.portals.update()
def __init__(self): pygame.init() self.screen = pygame.display.set_mode((716, 793 + 60)) pygame.display.set_caption("Pacman Portal") self.bricks = Group() self.shields = Group() self.powerpills = Group() self.qpills = Group() self.maze = Maze(self.screen, self.bricks, self.shields, self.powerpills, self.qpills, brickfile='square', mazefile='images/pacmanportalmaze.txt', shieldfile='shield', powerpill='powerpill') self.increase = False self.scoreboard = Scorebord(self.screen, self) self.pacman = Pacman(self.screen, self.scoreboard, self) self.play_button = Button(self.screen, "PLAY GAME", 80 / 100) self.score_button = Button(self.screen, "HIGH SCORES", 90 / 100) self.menu = Menu() self.audio = Audio() self.fruit = Fruit(self.screen) self.blinky = Blinky(self.screen, self.pacman, self.scoreboard) self.inky = Inky(self.screen, self.pacman, self.scoreboard) self.pinky = Pinky(self.screen, self.pacman, self.scoreboard) self.clyde = Clyde(self.screen, self.pacman, self.scoreboard) self.oportal = Portal('o', self.pacman) self.bportal = Portal('b', self.pacman) self.active = False self.pause = False
class MainView(QWidget): def __init__(self): QWidget.__init__(self) self._ui_model = None self._portal = Portal() self._main_splitter = MainSplitter() self._import_progress = ImportProgress() self._peak_meter = PeakMeter() v = QVBoxLayout() v.setContentsMargins(0, 0, 0, 0) v.addWidget(self._portal) v.addWidget(self._main_splitter) v.addWidget(self._import_progress) v.addWidget(self._peak_meter) self.setLayout(v) if not cmdline.get_experimental(): self._import_progress.hide() def set_ui_model(self, ui_model): self._ui_model = ui_model self._portal.set_ui_model(ui_model) self._main_splitter.set_ui_model(ui_model) self._import_progress.set_ui_model(ui_model) self._peak_meter.set_ui_model(ui_model) def unregister_updaters(self): self._peak_meter.unregister_updaters() self._import_progress.unregister_updaters() self._main_splitter.unregister_updaters() self._portal.unregister_updaters()
def __init__(self, settings, screen, stats, nodes, stars, update_score, red, pink, orange, blue): super(Pacman, self).__init__() self.screen = screen self.screen_rect = screen.get_rect() self.settings = settings self.stats = stats self.stars = stars self.nodes = nodes self.update_score = update_score self.node = nodes.nodeList[6] self.red = red self.pink = pink self.orange = orange self.blue = blue self.images = self.frames('right') self.timer = Timer(self.images, wait=50) self.image = self.images[self.timer.frame_index()] self.rect = self.image.get_rect() self.eat_star = pygame.mixer.Sound('music/pacman_chomp.wav') self.eat_super_star = pygame.mixer.Sound('music/pacman_eatfruit.wav') self.open_portal = False self.curr_portal = 0 self.portal_a = Portal(self.settings, self.screen, self.rect.x, self.rect.y, 'orange') self.portal_b = Portal(self.settings, self.screen, self.rect.x, self.rect.y, 'blue') self.portal_init = False self.portals = [self.portal_a, self.portal_b]
class App(object): def __init__(self, settings): self._actors_path = settings["actors_path"] self.app = None self.actors = None def startapp(self): self.app = Portal(__name__) self.app.config['SECRET_KEY'] = '3294038' self.app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False self.app.debug = True toolbar = DebugToolbarExtension(self.app) mainbp = Blueprint('mainpb', __name__) # Required by the portal self.app.config['PAGES_DIR'] = os.path.join(self.app.root_path, 'pages') self.app.register_blueprint(blueprint) admin = Admin(self.app, 'Portal Admin', template_mode='bootstrap3') admin.add_view(PortalFileAdmin(self.app.root_path, '/', name='Files')) conn = pymongo.MongoClient() db = conn.apitest admin.add_view(PeopleView(db.people, 'People')) self.actors = ActorsLoader(self._actors_path).load_actors() self.generate_routes() self.load_macros(mainbp) self.app.register_blueprint(blueprint) self.app.register_blueprint(mainbp) self.app.run(host='0.0.0.0') def getCallback(self, fn): def wrapper(*args, **kwargs): return fn(self.actors, *args, **kwargs) return wrapper def generate_routes(self): for ns_name in dir(self.actors): if ns_name.startswith("__"): continue ns = getattr(self.actors, ns_name) for obj_name in dir(ns): if obj_name.startswith("__"): continue obj = getattr(ns, obj_name) for method_name in dir(obj): if method_name.startswith("_") or method_name.startswith("__"): continue method = getattr(obj, method_name) self.app.add_url_rule("/"+'{namespace}/{object}/{method}'.format(namespace=ns_name, object=obj_name, method=method_name), method_name, self.getCallback(method)) def getCallback(self, fn): def wrapper(*args, **kwargs): return fn(self.actors, *args, **kwargs) return wrapper def load_macros(self, pb): MacrosLoader("portal/macros").load_macros(pb, self.actors)
def portal(result): res = [] res.append("=============================") res.append("1. Portal") portalSoup = request.makeGet("http://ufm.edu/Portal") por = Portal(portalSoup) portalArray = por.init() #print(portalArray) res = res + portalArray return res
def checkpacmanportals(settings, screen, blocks, portals, portal_bullet): if settings.portal_passed: for portal in portals.sprites(): portals.remove(portal) settings.active_portals = 0 settings.portal_passed = False for bullet in portal_bullet.sprites(): if checkobjectwallcollisions(bullet, blocks, settings): settings.active_portals += 1 if settings.active_portals != 3: portal = None if settings.active_portals == 1: portal = Portal(screen, 1) portal.draw_portal(bullet.colx - 3, bullet.coly - 3) elif settings.active_portals == 2: portal = Portal(screen, 2) portal.draw_portal(bullet.colx - 3, bullet.coly - 3) for block in blocks.sprites(): if (portal.rect.x + 3) == block.rect.x and ( portal.rect.y + 3) == block.rect.y: if settings.active_portals == 1: block.type = "blockp1" elif settings.active_portals == 2: block.type = "blockp2" portal_bullet.remove(bullet) portals.add(portal) else: settings.active_portals -= 1
def create_portals(self, wall): x1 = self.laser.rect.centerx - (self.laser.velocity.x * 13) y1 = self.laser.rect.centery - (self.laser.velocity.y * 13) x2, y2 = self.game.WIDTH - x1 - 2, y1 + 2 # create portals and open self.game.portals = [ Portal(self.game, x1, y1, ['g5452', 'g5520', 'g5627', 'g5402-4']), Portal(self.game, x2, y2, ['g5452', 'g5520', 'g5627', 'g5402-4']) ] for p in self.game.portals: if not p.isopen: p.open(self.game) self.game.portals[0].draw() self.game.portals[1].draw()
class Game: settings: Settings def __init__(self): pygame.init() self.settings = Settings() self.settings.reset() self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height)) self.intro = Intro(self.screen, self.settings) self.menu = Menu(self.screen, self.settings) pygame.display.set_caption("Pacman Portal") self.maze = Maze(self.screen, mazefile='pacmap.txt') self.pacman = Pacman(self.screen) self.dashboard = Dashboard(self.screen) self.portal_enter = Portal("Enter", self.screen, self.settings) self.portal_exit = Portal("Exit", self.screen, self.settings) scoresheet = open('scoresheet.txt', 'r') self.settings.score_high = int(scoresheet.read()) def __str__(self): return 'Game(Pacman Portal), maze=' + str(self.maze) + ')' def play(self): eloop = EventLoop(finished=False) while not eloop.finished: eloop.check_events(self.pacman, self.menu, self.portal_enter, self.portal_exit, self.settings) self.update_screen() def update_screen(self): self.screen.fill((0, 0, 0)) if self.settings.mode == "Game": self.maze.check_pac_conditions(self.pacman, self.settings, self.portal_enter, self.portal_exit) self.maze.blitme(self.settings) self.pacman.blitme(self.settings) self.dashboard.blitme(self.settings) self.portal_enter.blitme() self.portal_exit.blitme() elif self.settings.mode == "Menu": self.menu.blitme() pass elif self.settings.mode == "Intro": self.intro.blitme() pygame.display.flip()
def test_portal(): res = [] res.append("=============================") res.append("1. Portal") portalSoup = request.makeGet("http://ufm.edu/Portal") por = Portal(portalSoup) return res
def run_game(): pygame.init() pygame.display.set_caption("Portal") user32 = ctypes.windll.user32 screenSize = (user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)) screen = pygame.display.set_mode((screenSize), pygame.FULLSCREEN) settings = Settings(screenSize) settings.g_speed = settings.g_speed / 65 portais = Group() portal_inicial = Portal(settings, screen, None) portais.add(portal_inicial) ball = Ball(settings, screen) while True: check_events(ball) ball.update() screen.fill(settings.bg_color) for portal in portais: portal.check_collision(settings, screen, ball, portais) portal.draw_portal() pygame.draw.line(screen, (255, 255, 255), [0, settings.bottom], [settings.screen_width, settings.bottom], 5) ball.draw_ball() pygame.display.flip()
def new(self): self.all_sprites = pg.sprite.Group() self.platforms = pg.sprite.Group() self.saws = pg.sprite.Group() plts_conf, plr_conf, saw_conf, fl_saw_conf, prtl_conf = self.create_level( levels.level1) self.player = Player(*plr_conf, self) self.all_sprites.add(self.player) for plt in plts_conf: p = Platform(*plt) self.all_sprites.add(p) self.platforms.add(p) for saw in saw_conf: s = Saw(*saw) self.all_sprites.add(s) self.saws.add(s) for fl_saw in fl_saw_conf: s = FlyingSaw(*fl_saw, self.platforms) self.all_sprites.add(s) self.saws.add(s) self.portal = Portal(*prtl_conf) self.all_sprites.add(self.portal) self.run()
def fire_orange_portal(self): if not self.orange_active: port_loc = self.pac_man.find_portal_spot() self.oport = Portal(self.screen, 'orange') self.oport.rect.centerx = port_loc[0] self.oport.rect.centery = port_loc[1] self.active_ports.add(self.oport) self.orange_active = True
def enter(): global guy, bg, wall, map, death, portal, clear, deathcount deathcount = 0 guy = Guy() portal = Portal() map = create_map() bg = Background() death = Death() clear = Clear() guy.set_bg(bg) bg.set_guy(guy) death.set_bg(bg) death.set_guy(guy) clear.set_bg(bg) clear.set_guy(guy) portal.set_bg(bg) for wall in map: wall.set_bg(bg)
def __init__(self): pygame.init() self.settings = Settings() self.settings.reset() self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height)) self.intro = Intro(self.screen, self.settings) self.menu = Menu(self.screen, self.settings) pygame.display.set_caption("Pacman Portal") self.maze = Maze(self.screen, mazefile='pacmap.txt') self.pacman = Pacman(self.screen) self.dashboard = Dashboard(self.screen) self.portal_enter = Portal("Enter", self.screen, self.settings) self.portal_exit = Portal("Exit", self.screen, self.settings) scoresheet = open('scoresheet.txt', 'r') self.settings.score_high = int(scoresheet.read())
def __init__(self): pygame.init() # declares all and sets classes, data, groups self.pac = Group() self.points = Group() self.pills = Group() self.fruits = Group() self.ghosts = Group() self.delay = 0 self.count = 0 self.timer = random.randint(3000, 5001) self.timer2 = 4500 self.settings = Settings() self.stats = GameStats(self.settings) self.screen = pygame.display.set_mode( (self.settings.screen_width, self.settings.screen_height)) pygame.display.set_caption("Pacman Portal") self.point = Point(self.screen, self.settings) self.maze = Maze(self.screen, self.settings, self.pac, self.points, self.pills, self.fruits, mazefile='images/maze.txt', brickfile='square') self.portal = Portal(self.screen, self.settings) self.pacman = Pacman(self.screen, self.settings, self.maze, self.portal, self.stats) self.sb = Scoreboard(self.settings, self.screen, self.stats, self.maze, self.portal) self.play_button = Startup(self.screen, self.settings, 'Play') self.score_button = HighScores(self.screen, "High Scores", self.settings) self.back_button = HighScores(self.screen, "Back (B)", self.settings)
def get_portal(self): if self.curr_portal == 0: portal_color = 'orange' self.portal_a = Portal(self.settings, self.screen, self.rect.x, self.rect.y, portal_color) self.portals.insert(0, self.portal_a) self.portal_a.open(self) self.portal_a.blitme() self.portal_a.image_rect.centerx = self.rect.centerx + 20 self.portal_a.image_rect.centery = self.rect.centery self.curr_portal += 1 self.portal_init = True else: portal_color = 'blue' self.portal_b = Portal(self.settings, self.screen, self.rect.x, self.rect.y, portal_color) self.portals.insert(1, self.portal_b) self.portal_b.open(self) self.portal_b.blitme() self.portal_b.image_rect.centerx = self.rect.centerx + 20 self.portal_b.image_rect.centery = self.rect.centery self.curr_portal = 0 self.portal_init = True
def _add_random_artifact(self, context, brick): if context.portal is None: if random() <= 1 / len(context.bricks): context.portal = Portal(brick.y, brick.x) return if random() <= 0.1: context.artifacts.append(Life(brick.y, brick.x)) return if random() <= 0.3: context.artifacts.append(SuperBombArtifact(brick.y, brick.x)) return if random() <= 0.3: context.artifacts.append(Point(brick.y, brick.x)) return if random() <= 0.4: context.monsters.append(Monster(context.board, context.user, 1, brick.y, brick.x)) return
def __init__(self): QWidget.__init__(self) self._ui_model = None self._portal = Portal() self._main_splitter = MainSplitter() self._import_progress = ImportProgress() self._peak_meter = PeakMeter() v = QVBoxLayout() v.setContentsMargins(0, 0, 0, 0) v.addWidget(self._portal) v.addWidget(self._main_splitter) v.addWidget(self._import_progress) v.addWidget(self._peak_meter) self.setLayout(v) if not cmdline.get_experimental(): self._import_progress.hide()
def readFile(screen, blocks, shield, powerpills, portal): file = open("images/otherpacmanportalmaze.txt", "r") contents = file.read() line = '' all_lines = [] for chars in contents: if chars != '\n': line += chars else: all_lines.append(line) line = '' i = 0 j = 0 for rows in all_lines: for chars in rows: if chars == 'X': new = Blocks(screen) new.rect.x, new.rect.y = 13 * i, 13 * j blocks.add(new) elif chars == 'd': thepowerpill = Powerpills(screen) thepowerpill.rect.x, thepowerpill.rect.y = 13 * i, 13 * j powerpills.add(thepowerpill) elif chars == 'o': theshield = Shield(screen) theshield.rect.x, theshield.rect.y = 13 * i, 13 * j shield.add(theshield) # This is where the horizontal portal is supposed to be elif chars == 'h': pass # Vertical portal? elif chars == 'P': theportal = Portal(screen) theportal.rect.x, theportal.rect.y = 13 * i, 13 * j portal.add(theportal) pass i += 1 i = 0 j += 1
def startapp(self): self.app = Portal(__name__) self.app.config['SECRET_KEY'] = '3294038' self.app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False self.app.debug = True toolbar = DebugToolbarExtension(self.app) mainbp = Blueprint('mainpb', __name__) # Required by the portal self.app.config['PAGES_DIR'] = os.path.join(self.app.root_path, 'pages') self.app.register_blueprint(blueprint) admin = Admin(self.app, 'Portal Admin', template_mode='bootstrap3') admin.add_view(PortalFileAdmin(self.app.root_path, '/', name='Files')) conn = pymongo.MongoClient() db = conn.apitest admin.add_view(PeopleView(db.people, 'People')) self.actors = ActorsLoader(self._actors_path).load_actors() self.generate_routes() self.load_macros(mainbp) self.app.register_blueprint(blueprint) self.app.register_blueprint(mainbp) self.app.run(host='0.0.0.0')
def new(self): # Создание нового уровня self.all_sprites = pg.sprite.Group( ) # Создание группы для всех спрайтов self.platforms = pg.sprite.Group() # Создание группы для платформ self.saws = pg.sprite.Group() # Создание группы для пил # Взятие двумерного кортежа настроек платформ и кортежа настроек игрока plts_conf, sws_cong, fl_sws_conf, plr_conf, prtl_conf = self.create_level( levels.level1) self.player = Player( *plr_conf, self ) # Создание игрока раскрыв кортеж настроек игрока и передав ссылку на игру self.all_sprites.add(self.player) # Добавление игрока в группу for plt in plts_conf: # Для каждого кортежа настроек в двумерном кортеже p = Platform( *plt ) # Создаем платформу по координатам раскрывая кортеж настроек # Добавляем платформу в группы self.all_sprites.add(p) self.platforms.add(p) for saw in sws_cong: # Для каждого кортежа настроек в двумерном кортеже s = Saw( *saw) # Создаем пилу по координатам раскрывая кортеж настроек # Добавляем платформу в группы self.all_sprites.add(s) self.saws.add(s) for saw in fl_sws_conf: # Для каждого кортежа настроек в двумерном кортеже s = FlyingSaw(*saw, self.platforms) # Создание летающей пилы # Добавляем летающую пилу в группы self.all_sprites.add(s) self.saws.add(s) self.portal = Portal(*prtl_conf) self.all_sprites.add(self.portal) self.run() # Запускаем уровень
import json from portal import Portal from api_ckan import obter_metadados_datasets ##################################################################### ########## Lendo todos os portais do arquivo portals.json ########### ##################################################################### lstPortals = [] portalsFile = "portals.json" with open(portalsFile, 'r') as json_file: data = json.load(json_file) for p in data: portal = Portal() portal.setCity(p["city"]) portal.setUrl(p["url"]) portal.setCoord(p["coord"]) portal.setCategorization(p["categorization"]) portal.setPlatform(p["platform"]) portal.setCategories(p['categories']) lstPortals.append(portal) #################################################################### ###### Obtendo portais que utilizam o CKAN como plataforma ######### #################################################################### ckan_portals = [] for portal in lstPortals:
import os from flask import request, current_app, render_template, abort from flask_debugtoolbar import DebugToolbarExtension from flask.ext.admin import Admin from portal import blueprint, Page, Portal from portal.editing import PortalFileAdmin app = Portal(__name__) app.config['SECRET_KEY'] = '3294038' app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False app.debug = True toolbar = DebugToolbarExtension(app) # Required by the portal app.config['PAGES_DIR'] = os.path.join(app.root_path, 'pages') app.register_blueprint(blueprint) admin = Admin(app, 'Portal Admin', template_mode='bootstrap3') admin.add_view(PortalFileAdmin(app.root_path, '/', name='Files')) print "portal running on port 5000" app.run()
class Game: BLACK = (0, 0, 0) def __init__(self): pygame.init() self.screen = pygame.display.set_mode((716, 793 + 60)) pygame.display.set_caption("Pacman Portal") self.bricks = Group() self.shields = Group() self.powerpills = Group() self.qpills = Group() self.maze = Maze(self.screen, self.bricks, self.shields, self.powerpills, self.qpills, brickfile='square', mazefile='images/pacmanportalmaze.txt', shieldfile='shield', powerpill='powerpill') self.increase = False self.scoreboard = Scorebord(self.screen, self) self.pacman = Pacman(self.screen, self.scoreboard, self) self.play_button = Button(self.screen, "PLAY GAME", 80 / 100) self.score_button = Button(self.screen, "HIGH SCORES", 90 / 100) self.menu = Menu() self.audio = Audio() self.fruit = Fruit(self.screen) self.blinky = Blinky(self.screen, self.pacman, self.scoreboard) self.inky = Inky(self.screen, self.pacman, self.scoreboard) self.pinky = Pinky(self.screen, self.pacman, self.scoreboard) self.clyde = Clyde(self.screen, self.pacman, self.scoreboard) self.oportal = Portal('o', self.pacman) self.bportal = Portal('b', self.pacman) self.active = False self.pause = False def __str__(self): return 'Game(Pacman Portal), maze=' + str(self.maze) + ')' def play(self): while True: pygame.time.Clock().tick(1800) func.check_events(self.pacman, self.score_button, self.menu, self.play_button, self, self.bportal, self.oportal, self.screen, self.maze, self.audio) self.update_screen() if self.active: func.check_collisions(self.pacman, self.bricks, self.shields, self.powerpills, self.scoreboard, self.blinky, self.pinky, self.inky, self.clyde, self.qpills, self.fruit, self.audio) self.pacman.update(self.oportal, self.bportal, self.audio) if not self.pause: self.fruit.update() self.blinky.update(self.oportal, self.bportal) self.inky.update(self.oportal, self.bportal) self.pinky.update(self.oportal, self.bportal) self.clyde.update(self.oportal, self.bportal) self.scoreboard.update_score(self) if self.increase: self.pacman.reset() self.inky.reset() self.clyde.reset() self.pinky.reset() self.fruit.reset() self.blinky.reset() self.maze.build() self.increase = False if self.scoreboard.lives == 0: self.active = False def update_screen(self): self.screen.fill(Game.BLACK) if self.active: self.maze.blitme(self.screen) self.scoreboard.show_score() self.pacman.blitme() self.blinky.blitme() self.inky.blitme() self.pinky.blitme() self.clyde.blitme() self.oportal.blitme(self.screen) self.bportal.blitme(self.screen) self.fruit.blitme() elif not self.menu.show_scores: self.menu.main(self.play_button, self.score_button, self.screen) else: self.menu.scores(self.score_button, self.screen) pygame.display.flip()
import os import time from portal import Portal portal = Portal( os.getenv("PORTAL_URL"), os.getenv("PORTAL_ID_ECHO"), os.getenv("PORTAL_TOKEN_ECHO") ) @portal.on_request() def on_request(data): print(data) time.sleep(5) return {"title": data, "description": "Echo portal, made with <3 by breq!"} portal.run()
score_table = HighScoreTable(screen) # used to control fps clock = pygame.time.Clock() # max fps MAX_PFS = 30 # game intro object intro = GameIntro(screen, play_button, high_score_button, ai_settings) score_board = Scoreboard(ai_settings, screen, stats, score_table) fruit = Fruit(0, 0, 19, 19, pac.maze, screen, stats, pac) portal = Portal(screen, pac, pac.rect.x, pac.rect.y, 32, 32, os.getcwd() + '/images/invis_portal.png') fire = False def gameloop(): # temporary fix for variables will create classes and clean the code global fire while not stats.game_exit: # debugging # print(str(pac.rect.x) + ", " + str(pac.rect.y)) # print(pac.stats.score) # print(pac.stats.pacman_left) while stats.game_over or stats.intro: time.sleep(0.01)
class Pacman(Sprite): def __init__(self, settings, screen, stats, nodes, stars, update_score, red, pink, orange, blue): super(Pacman, self).__init__() self.screen = screen self.screen_rect = screen.get_rect() self.settings = settings self.stats = stats self.stars = stars self.nodes = nodes self.update_score = update_score self.node = nodes.nodeList[6] self.red = red self.pink = pink self.orange = orange self.blue = blue self.images = self.frames('right') self.timer = Timer(self.images, wait=50) self.image = self.images[self.timer.frame_index()] self.rect = self.image.get_rect() self.eat_star = pygame.mixer.Sound('music/pacman_chomp.wav') self.eat_super_star = pygame.mixer.Sound('music/pacman_eatfruit.wav') self.open_portal = False self.curr_portal = 0 self.portal_a = Portal(self.settings, self.screen, self.rect.x, self.rect.y, 'orange') self.portal_b = Portal(self.settings, self.screen, self.rect.x, self.rect.y, 'blue') self.portal_init = False self.portals = [self.portal_a, self.portal_b] def game_active(self): self.images = self.frames('right') self.timer = Timer(self.images, wait=50) self.image = self.images[self.timer.frame_index()] self.node = self.nodes.nodeList[6] self.rect.centerx = self.setPosition().x self.rect.centery = self.setPosition().y self.center = float(self.rect.centerx) self.top = self.rect.centery self.moving_right = False self.moving_left = False self.moving_up = False self.moving_down = False self.target = self.node self.direction = None def setPosition(self): position = self.node.position.copy() return position def frames(self, direction): images = [] path = 'images/pacman/' + direction for file_name in os.listdir(path): pacman = pygame.image.load(path + os.sep + file_name) images.append(pacman) return images def get_portal(self): if self.curr_portal == 0: portal_color = 'orange' self.portal_a = Portal(self.settings, self.screen, self.rect.x, self.rect.y, portal_color) self.portals.insert(0, self.portal_a) self.portal_a.open(self) self.portal_a.blitme() self.portal_a.image_rect.centerx = self.rect.centerx + 20 self.portal_a.image_rect.centery = self.rect.centery self.curr_portal += 1 self.portal_init = True else: portal_color = 'blue' self.portal_b = Portal(self.settings, self.screen, self.rect.x, self.rect.y, portal_color) self.portals.insert(1, self.portal_b) self.portal_b.open(self) self.portal_b.blitme() self.portal_b.image_rect.centerx = self.rect.centerx + 20 self.portal_b.image_rect.centery = self.rect.centery self.curr_portal = 0 self.portal_init = True def update(self): if self.open_portal: self.get_portal() if self.stats.lost_life: if self.image == self.last_frame: self.stats.lost_life = False self.images = self.frames('right') self.timer = Timer(self.images, wait=50) self.game_active() self.blue.pacman_hit = False self.blue.game_active() self.rect.centerx = self.lastx self.image = self.images[self.timer.frame_index()] self.prev = self.node if self.node is not None and not self.stats.lost_life: if self.portal_init: self.portal() if self.moving_right and self.node.column < self.nodes.num_columns: self.node = self.nodes.get_path_node(self.nodes.settings.right, self.node.row, self.node.column + 1, self.nodes.nodeList) self.direction = self.settings.right self.moving_right = False self.images = self.frames('right') if self.moving_left and self.node.column > 0: self.node = self.nodes.get_path_node(self.nodes.settings.left, self.node.row, self.node.column - 1, self.nodes.nodeList) self.direction = self.settings.left self.moving_left = False self.images = self.frames('left') if self.moving_up and self.node.row > 0: self.node = self.nodes.get_path_node(self.nodes.settings.up, self.node.row - 1, self.node.column, self.nodes.nodeList) self.direction = self.settings.up self.moving_up = False self.images = self.frames('up') if self.moving_down and self.node.row < self.nodes.num_rows: self.node = self.nodes.get_path_node(self.nodes.settings.down, self.node.row + 1, self.node.column, self.nodes.nodeList) self.direction = self.settings.down self.moving_down = False self.images = self.frames('down') if self.node is None: self.node = self.prev self.rect.centerx = self.setPosition().x self.rect.centery = self.setPosition().y self.check_pacman_ghost_collisions() self.check_pacman_pill_collisions() def blitme(self): self.screen.blit(self.image, self.rect) def check_pacman_pill_collisions(self): self_group = Group() self_group.add(self) collisions = pygame.sprite.groupcollide(self_group, self.stars.star_group, False, True) if collisions: for star in collisions.values(): self.stats.score += self.settings.star_score self.update_score.prep_score_title() pygame.mixer.Sound.play(self.eat_star) self.update_score.check_high_score() super_collisions = pygame.sprite.groupcollide(self_group, self.stars.ss_group, False, True) if super_collisions: for super_star in super_collisions.values(): self.stats.score += self.settings.super_star_score self.update_score.prep_score_title() pygame.mixer.Sound.stop(self.eat_star) pygame.mixer.Sound.play(self.eat_super_star) self.blue.in_danger = True self.blue.danger() self.pink.in_danger = True self.pink.danger() self.red.in_danger = True self.red.danger() self.orange.in_danger = True self.orange.danger() self.update_score.check_high_score() def check_pacman_ghost_collisions(self): blue_col = pygame.sprite.collide_rect(self, self.blue) if blue_col: if self.blue.in_danger: self.blue.retreat() self.settings.ghost_score *= 2 self.stats.score += self.settings.ghost_score self.update_score.prep_score_title() pygame.mixer.Sound.stop(self.eat_star) eat_ghost = pygame.mixer.Sound('music/pacman_eatghost.wav') pygame.mixer.Sound.play(eat_ghost) else: self.images = self.frames('death') self.last_frame = self.images[len(self.images) - 1] self.timer = Timer(self.images, wait=30) self.lastx = self.rect.centerx self.stats.lives_left -= 1 self.stats.lost_life = True pygame.mixer.Sound.stop(self.eat_star) die = pygame.mixer.Sound('music/pacman_death.wav') pygame.mixer.Sound.play(die) self.update_score.prep_lives() pink_col = pygame.sprite.collide_rect(self, self.pink) if pink_col: if self.pink.in_danger: self.pink.retreat() self.settings.ghost_score *= 2 self.stats.score += self.settings.ghost_score self.update_score.prep_score_title() pygame.mixer.Sound.stop(self.eat_star) eat_ghost = pygame.mixer.Sound('music/pacman_eatghost.wav') pygame.mixer.Sound.play(eat_ghost) else: self.images = self.frames('death') self.last_frame = self.images[len(self.images) - 1] self.timer = Timer(self.images, wait=30) self.lastx = self.rect.centerx self.stats.lives_left -= 1 self.stats.lost_life = True pygame.mixer.Sound.stop(self.eat_star) die = pygame.mixer.Sound('music/pacman_death.wav') pygame.mixer.Sound.play(die) self.update_score.prep_lives() self.update_score.check_high_score() red_col = pygame.sprite.collide_rect(self, self.red) if red_col: if self.red.in_danger: self.red.retreat() self.settings.ghost_score *= 2 self.stats.score += self.settings.ghost_score self.update_score.prep_score_title() pygame.mixer.Sound.stop(self.eat_star) eat_ghost = pygame.mixer.Sound('music/pacman_eatghost.wav') pygame.mixer.Sound.play(eat_ghost) else: self.images = self.frames('death') self.last_frame = self.images[len(self.images) - 1] self.timer = Timer(self.images, wait=30) self.lastx = self.rect.centerx self.stats.lives_left -= 1 self.stats.lost_life = True pygame.mixer.Sound.stop(self.eat_star) die = pygame.mixer.Sound('music/pacman_death.wav') pygame.mixer.Sound.play(die) self.update_score.prep_lives() orange_col = pygame.sprite.collide_rect(self, self.orange) if orange_col: if self.orange.in_danger: self.orange.retreat() self.settings.ghost_score *= 2 self.stats.score += self.settings.ghost_score self.update_score.prep_score_title() pygame.mixer.Sound.stop(self.eat_star) eat_ghost = pygame.mixer.Sound('music/pacman_eatghost.wav') pygame.mixer.Sound.play(eat_ghost) else: self.images = self.frames('death') self.last_frame = self.images[len(self.images) - 1] self.timer = Timer(self.images, wait=30) self.lastx = self.rect.centerx self.stats.lives_left -= 1 self.stats.lost_life = True pygame.mixer.Sound.stop(self.eat_star) die = pygame.mixer.Sound('music/pacman_death.wav') pygame.mixer.Sound.play(die) self.update_score.prep_lives() self.update_score.check_high_score() if self.stats.lives_left < 0: self.stats.game_over = True self.update_score.check_high_score() self.game_active() self.blue.game_active() self.pink.game_active() self.orange.game_active() self.stats.game_active = False self.stats.reset_stats() pygame.mouse.set_visible(True) def portal(self): self.portal_a.attempt_transport(self, self) self.portal_b.attempt_transport(self, self)
def readPortalsFromJsonFile(portalsFile, platform=None): lstPortals = [] with open(portalsFile, 'r') as json_file: data = json.load(json_file) for p in data: portal = Portal() portal.setCity(p["city"]) portal.setUrl(p["url"]) portal.setCoord(p["coord"]) portal.setCategorization(p["categorization"]) portal.setPlatform(p["platform"]) portal.setCategories(p['categories']) lstPortals.append(portal) if platform is None: return lstPortals platform_portals = [] for portal in lstPortals: if (portal.getPlatform() == platform): platform_portals.append(portal) return platform_portals
class Game: """Runs the game""" def __init__(self): pygame.init() # declares all and sets classes, data, groups self.pac = Group() self.points = Group() self.pills = Group() self.fruits = Group() self.ghosts = Group() self.delay = 0 self.count = 0 self.timer = random.randint(3000, 5001) self.timer2 = 4500 self.settings = Settings() self.stats = GameStats(self.settings) self.screen = pygame.display.set_mode( (self.settings.screen_width, self.settings.screen_height)) pygame.display.set_caption("Pacman Portal") self.point = Point(self.screen, self.settings) self.maze = Maze(self.screen, self.settings, self.pac, self.points, self.pills, self.fruits, mazefile='images/maze.txt', brickfile='square') self.portal = Portal(self.screen, self.settings) self.pacman = Pacman(self.screen, self.settings, self.maze, self.portal, self.stats) self.sb = Scoreboard(self.settings, self.screen, self.stats, self.maze, self.portal) self.play_button = Startup(self.screen, self.settings, 'Play') self.score_button = HighScores(self.screen, "High Scores", self.settings) self.back_button = HighScores(self.screen, "Back (B)", self.settings) def __str__(self): return 'Game(Pacman Portal), maze=' + str(self.maze) + ')' def play(self): # Starts the game eloop = EventLoop(self.screen, self.settings, self.play_button, self.score_button, self.maze, self.stats, self.sb, self.pacman, self.pac, self.ghosts, self.points, self.pills, self.fruits, self.portal, finished=False) # loops while not finished while not eloop.finished: # Check events eloop.check_events() if self.stats.game_active: # spawns fruits at random times if self.delay == self.timer: self.maze.create_fruit(self.stats.fruit_count) if self.stats.fruit_count >= 3: self.stats.fruit_count = 0 else: self.stats.fruit_count += 1 self.delay = 0 self.timer = random.randint(3000, 5001) else: self.delay += 1 # deletes fruit after a period of time if self.count == self.timer2: self.fruits.empty() self.count = 0 else: self.count += 1 # updates sprites self.pac.update() self.ghosts.update() self.portal.update() # Checks for collision eloop.check_collisions() self.update_screen() def update_screen(self): """Updates what is on the screen""" self.screen.fill(self.settings.bg_color) # displays statrup screen if not self.stats.game_active and not self.stats.score_screen_active: self.play_button.draw_button() self.score_button.draw_button() # displays score screen if score button is pressed if not self.stats.game_active and self.stats.score_screen_active: self.sb.draw_score_screen() self.back_button.draw_back() # Main game starts if active if self.stats.game_active: self.maze.blitme() self.pac.draw(self.screen) self.points.draw(self.screen) self.pills.draw(self.screen) self.fruits.draw(self.screen) self.ghosts.draw(self.screen) if not self.settings.play_once: self.settings.ghost.play(-1) self.settings.play_once = True self.sb.show_score() pygame.display.flip()
def __init__(self): pg.init() # Initialize pygame self.BG_COLOR = (0, 0, 0) # Set background to black self.screen = pg.display.set_mode( (Game.WIDTH, Game.HEIGHT)) # Set window dimensions pg.display.set_caption('Pac-Man') # Set name of the game # ****************** # *** Animations *** # ****************** self.CLOCK = pg.time.Clock() # Universal animation clock self.img_index = Timer(3) # Pac-man Animations self.last_img_index = self.img_index.frame_index() self.enemy_img_index = Timer(2) # Enemy Animations self.last_enemy_img_index = self.enemy_img_index.frame_index() self.enemy_scatter_index = TimerDual(2, 4) self.sprite_store = SpriteStore() # Instance for retrieving sprites portal_sprites = [] # Portal Animations for sprite in self.sprite_store.portal: # Fill list with unscaled images portal_sprites.append(pg.transform.scale(sprite, (20, 20))) self.portal_img_index = Timer(6) # ******************** # *** Game Objects *** # ******************** self.graph = Graph(self) # Graph (Map) obj self.pacman = Pacman(self, self.sprite_store.pacman, self.graph) # Pac-man obj self.portal1 = Portal(self, portal_sprites) # Portal One obj self.portal2 = Portal(self, portal_sprites) # Portal Two obj self.portals = [self.portal1, self.portal2] # List of Portal obj's self.blinky = Enemy(self, self.sprite_store.blinky, self.graph) # 1. Blinky obj (Enemy00) self.pinky = Enemy(self, self.sprite_store.pinky, self.graph) # 2. Pinky obj (Enemy01) self.clyde = Enemy(self, self.sprite_store.clyde, self.graph) # 3. Clyde obj (Enemy02) self.inkey = Enemy(self, self.sprite_store.inkey, self.graph) # 4. Inkey obj (Enemy03) self.enemies = [] # List of Enemy obj's self.enemies.append(self.blinky) # Add enemies to list self.enemies.append(self.pinky) self.enemies.append(self.clyde) self.enemies.append(self.inkey) self.bg = Background('images/map.png', (0, 60)) # Background Image obj self.small_logo = self.sprite_store.get_small_logo() self.big_logo = self.sprite_store.get_bigger_logo() # ********************** # *** Initialization *** # ********************** self.pacman.rect.centerx = self.graph.nodes[ 65].x # Set Pac-man to node 65 self.pacman.rect.centery = self.graph.nodes[65].y self.pacman.adj_node = self.graph.nodes[65] self.initialize_enemies() self.pellets = Group() for pellet in self.graph.pellets: self.pellets.add(pellet) self.score = 0 self.high_score = 0 self.win = False self.last_key = None # Last key the user inputted self.start_screen = True self.initial_start = True self.is_paused = False self.game_over = False self.new_life = False self.has_game_started = False # buttons self.play_button = True self.play_button_rect = None self.hs_show = False self.hs_button = True self.hs_button_rect = None self.back_button = False self.back_button_rect = None self.last_flip = pg.time.get_ticks() self.show = True self.debug_game_state() # define the RGB value for white, # green, blue colour . self.white = (255, 255, 255) self.green = (0, 255, 0) self.blue = (0, 0, 128) # ************************ # ********* U.I. ********* # ************************ self.pac_life_icon = self.sprite_store.pac_life self.cherry_icon = self.sprite_store.fruits[0] self.sound_icon = pg.image.load(r'images/sound_icon.png') self.load_high_score() # Load high scores # ************************ # ******** Sounds ******** # ************************ pg.mixer.init() # If you want more channels, change 8 to a desired number. 8 is the default number of channel pg.mixer.set_num_channels(8) self.voice = pg.mixer.Channel(5) self.portal = pg.mixer.Channel(6) # This is the sound channel self.eating_sound = pg.mixer.Sound('sounds/chomp.wav') self.death_sound = pg.mixer.Sound('sounds/pacman_death.wav') self.beginning_music = pg.mixer.Sound('sounds/beginning.wav') self.portal_shoot = pg.mixer.Sound('sounds/portal_shoot.wav') self.tp_sound = pg.mixer.Sound('sounds/tp.wav') self.eat_ghost_sound = pg.mixer.Sound('sounds/pacman_eat_ghost.wav') pg.mixer.music.load('sounds/pkmn_trainer_victory_cut_for_loop.wav') spac_imgs = self.sprite_store.get_pacman_sprites( ) # L indices -- 0, 1, 2 // R indices -- 0, 3, 4 self.starter_pacman = [] for img in spac_imgs: self.starter_pacman.append(pg.transform.scale(img, (48, 48))) self.starter_pacman_rect = self.starter_pacman[0].get_rect() self.starter_pacman_rect.centerx = -48 self.starter_pacman_rect.centery = 430 # ALL GHOSTS: L indices -- 4, 5 // R indices -- 0, 1 sblinky_imgs = self.sprite_store.get_blinky_sprites() self.starter_blinky = [] for img in sblinky_imgs: self.starter_blinky.append(pg.transform.scale(img, (48, 48))) self.starter_blinky_rect = self.starter_blinky[0].get_rect() self.starter_blinky_rect.centerx = -144 self.starter_blinky_rect.centery = 430 spinky_imgs = self.sprite_store.get_pinky_sprites() self.starter_pinky = [] for img in spinky_imgs: self.starter_pinky.append(pg.transform.scale(img, (48, 48))) self.starter_pinky_rect = self.starter_pinky[0].get_rect() self.starter_pinky_rect.centerx = -199 self.starter_pinky_rect.centery = 430 sclyde_imgs = self.sprite_store.get_clyde_sprites() self.starter_clyde = [] for img in sclyde_imgs: self.starter_clyde.append(pg.transform.scale(img, (48, 48))) self.starter_clyde_rect = self.starter_clyde[0].get_rect() self.starter_clyde_rect.centerx = -254 self.starter_clyde_rect.centery = 430 sinkey_imgs = self.sprite_store.get_inkey_sprites() self.starter_inkey = [] for img in sinkey_imgs: self.starter_inkey.append(pg.transform.scale(img, (48, 48))) self.starter_inkey_rect = self.starter_inkey[0].get_rect() self.starter_inkey_rect.centerx = -309 self.starter_inkey_rect.centery = 430 running_away = self.sprite_store.get_ghost_running_away_sprites() self.starter_running_away = [] for img in running_away: self.starter_running_away.append(pg.transform.scale(img, (48, 48))) self.starter_entities = [] self.starter_entities.append( [self.starter_blinky, self.starter_blinky_rect]) self.starter_entities.append( [self.starter_pinky, self.starter_pinky_rect]) self.starter_entities.append( [self.starter_clyde, self.starter_clyde_rect]) self.starter_entities.append( [self.starter_inkey, self.starter_inkey_rect]) self.starter_right = True
class Game: WIDTH = 450 # Width of game window HEIGHT = 600 # Height of game window HS_FILE = 'images/high_score.txt' # Initialize (Game) class def __init__(self): pg.init() # Initialize pygame self.BG_COLOR = (0, 0, 0) # Set background to black self.screen = pg.display.set_mode( (Game.WIDTH, Game.HEIGHT)) # Set window dimensions pg.display.set_caption('Pac-Man') # Set name of the game # ****************** # *** Animations *** # ****************** self.CLOCK = pg.time.Clock() # Universal animation clock self.img_index = Timer(3) # Pac-man Animations self.last_img_index = self.img_index.frame_index() self.enemy_img_index = Timer(2) # Enemy Animations self.last_enemy_img_index = self.enemy_img_index.frame_index() self.enemy_scatter_index = TimerDual(2, 4) self.sprite_store = SpriteStore() # Instance for retrieving sprites portal_sprites = [] # Portal Animations for sprite in self.sprite_store.portal: # Fill list with unscaled images portal_sprites.append(pg.transform.scale(sprite, (20, 20))) self.portal_img_index = Timer(6) # ******************** # *** Game Objects *** # ******************** self.graph = Graph(self) # Graph (Map) obj self.pacman = Pacman(self, self.sprite_store.pacman, self.graph) # Pac-man obj self.portal1 = Portal(self, portal_sprites) # Portal One obj self.portal2 = Portal(self, portal_sprites) # Portal Two obj self.portals = [self.portal1, self.portal2] # List of Portal obj's self.blinky = Enemy(self, self.sprite_store.blinky, self.graph) # 1. Blinky obj (Enemy00) self.pinky = Enemy(self, self.sprite_store.pinky, self.graph) # 2. Pinky obj (Enemy01) self.clyde = Enemy(self, self.sprite_store.clyde, self.graph) # 3. Clyde obj (Enemy02) self.inkey = Enemy(self, self.sprite_store.inkey, self.graph) # 4. Inkey obj (Enemy03) self.enemies = [] # List of Enemy obj's self.enemies.append(self.blinky) # Add enemies to list self.enemies.append(self.pinky) self.enemies.append(self.clyde) self.enemies.append(self.inkey) self.bg = Background('images/map.png', (0, 60)) # Background Image obj self.small_logo = self.sprite_store.get_small_logo() self.big_logo = self.sprite_store.get_bigger_logo() # ********************** # *** Initialization *** # ********************** self.pacman.rect.centerx = self.graph.nodes[ 65].x # Set Pac-man to node 65 self.pacman.rect.centery = self.graph.nodes[65].y self.pacman.adj_node = self.graph.nodes[65] self.initialize_enemies() self.pellets = Group() for pellet in self.graph.pellets: self.pellets.add(pellet) self.score = 0 self.high_score = 0 self.win = False self.last_key = None # Last key the user inputted self.start_screen = True self.initial_start = True self.is_paused = False self.game_over = False self.new_life = False self.has_game_started = False # buttons self.play_button = True self.play_button_rect = None self.hs_show = False self.hs_button = True self.hs_button_rect = None self.back_button = False self.back_button_rect = None self.last_flip = pg.time.get_ticks() self.show = True self.debug_game_state() # define the RGB value for white, # green, blue colour . self.white = (255, 255, 255) self.green = (0, 255, 0) self.blue = (0, 0, 128) # ************************ # ********* U.I. ********* # ************************ self.pac_life_icon = self.sprite_store.pac_life self.cherry_icon = self.sprite_store.fruits[0] self.sound_icon = pg.image.load(r'images/sound_icon.png') self.load_high_score() # Load high scores # ************************ # ******** Sounds ******** # ************************ pg.mixer.init() # If you want more channels, change 8 to a desired number. 8 is the default number of channel pg.mixer.set_num_channels(8) self.voice = pg.mixer.Channel(5) self.portal = pg.mixer.Channel(6) # This is the sound channel self.eating_sound = pg.mixer.Sound('sounds/chomp.wav') self.death_sound = pg.mixer.Sound('sounds/pacman_death.wav') self.beginning_music = pg.mixer.Sound('sounds/beginning.wav') self.portal_shoot = pg.mixer.Sound('sounds/portal_shoot.wav') self.tp_sound = pg.mixer.Sound('sounds/tp.wav') self.eat_ghost_sound = pg.mixer.Sound('sounds/pacman_eat_ghost.wav') pg.mixer.music.load('sounds/pkmn_trainer_victory_cut_for_loop.wav') spac_imgs = self.sprite_store.get_pacman_sprites( ) # L indices -- 0, 1, 2 // R indices -- 0, 3, 4 self.starter_pacman = [] for img in spac_imgs: self.starter_pacman.append(pg.transform.scale(img, (48, 48))) self.starter_pacman_rect = self.starter_pacman[0].get_rect() self.starter_pacman_rect.centerx = -48 self.starter_pacman_rect.centery = 430 # ALL GHOSTS: L indices -- 4, 5 // R indices -- 0, 1 sblinky_imgs = self.sprite_store.get_blinky_sprites() self.starter_blinky = [] for img in sblinky_imgs: self.starter_blinky.append(pg.transform.scale(img, (48, 48))) self.starter_blinky_rect = self.starter_blinky[0].get_rect() self.starter_blinky_rect.centerx = -144 self.starter_blinky_rect.centery = 430 spinky_imgs = self.sprite_store.get_pinky_sprites() self.starter_pinky = [] for img in spinky_imgs: self.starter_pinky.append(pg.transform.scale(img, (48, 48))) self.starter_pinky_rect = self.starter_pinky[0].get_rect() self.starter_pinky_rect.centerx = -199 self.starter_pinky_rect.centery = 430 sclyde_imgs = self.sprite_store.get_clyde_sprites() self.starter_clyde = [] for img in sclyde_imgs: self.starter_clyde.append(pg.transform.scale(img, (48, 48))) self.starter_clyde_rect = self.starter_clyde[0].get_rect() self.starter_clyde_rect.centerx = -254 self.starter_clyde_rect.centery = 430 sinkey_imgs = self.sprite_store.get_inkey_sprites() self.starter_inkey = [] for img in sinkey_imgs: self.starter_inkey.append(pg.transform.scale(img, (48, 48))) self.starter_inkey_rect = self.starter_inkey[0].get_rect() self.starter_inkey_rect.centerx = -309 self.starter_inkey_rect.centery = 430 running_away = self.sprite_store.get_ghost_running_away_sprites() self.starter_running_away = [] for img in running_away: self.starter_running_away.append(pg.transform.scale(img, (48, 48))) self.starter_entities = [] self.starter_entities.append( [self.starter_blinky, self.starter_blinky_rect]) self.starter_entities.append( [self.starter_pinky, self.starter_pinky_rect]) self.starter_entities.append( [self.starter_clyde, self.starter_clyde_rect]) self.starter_entities.append( [self.starter_inkey, self.starter_inkey_rect]) self.starter_right = True def load_high_score(self): # load high score self.dir = path.dirname(__file__) with open(path.join(self.dir, self.HS_FILE), 'r') as f: try: self.high_score = int(f.read()) except: self.high_score = 0 def display_sprites(self): # DIRECTION INDICES # for pacman pr_ind = (0, 3, 4) pl_ind = (0, 1, 2) # for ghosts l_running_ind = (2, 3) gr_ind = (0, 1) if self.starter_pacman_rect.right < -200: self.starter_right = True # go right because too far left self.starter_pacman_rect.centerx = -48 self.starter_blinky_rect.centerx = -144 self.starter_pinky_rect.centerx = -199 self.starter_clyde_rect.centerx = -254 self.starter_inkey_rect.centerx = -309 if self.starter_inkey_rect.left >= (self.WIDTH + 200): self.starter_right = False # go left because too far right self.starter_inkey_rect.centerx = self.WIDTH + 48 self.starter_clyde_rect.centerx = self.WIDTH + 103 self.starter_pinky_rect.centerx = self.WIDTH + 158 self.starter_blinky_rect.centerx = self.WIDTH + 213 self.starter_pacman_rect.centerx = self.WIDTH + 309 if self.starter_right: self.screen.blit( self.starter_pacman[pr_ind[self.img_index.frame_index()]], self.starter_pacman_rect) for entity in self.starter_entities: self.screen.blit( entity[0][gr_ind[self.enemy_img_index.frame_index()]], entity[1]) self.starter_pacman_rect.centerx += 2 for entity in self.starter_entities: entity[1].centerx += 2 if not self.starter_right: self.screen.blit( self.starter_pacman[pl_ind[self.img_index.frame_index()]], self.starter_pacman_rect) for entity in self.starter_entities: self.screen.blit( self.starter_running_away[l_running_ind[ self.enemy_img_index.frame_index()]], entity[1]) self.starter_pacman_rect.centerx -= 2 for entity in self.starter_entities: entity[1].centerx -= 2 def display_introduction(self): pr_ind = (0, 3, 4) gr_ind = (0, 1) font = pg.font.Font('Gameplay.ttf', 20) # X -- 113, 338 # Y -- 150, 350 # blinky bimg_rect = copy.deepcopy(self.starter_blinky_rect) bimg_rect.centerx = 170 bimg_rect.centery = 245 blinky_text = font.render('Blinky', True, (255, 0, 0)) # 255 0 0 -- red btext_rect = blinky_text.get_rect() btext_rect.centerx = bimg_rect.left - 50 btext_rect.centery = bimg_rect.centery self.screen.blit( self.starter_blinky[gr_ind[self.enemy_img_index.frame_index()]], bimg_rect) self.screen.blit(blinky_text, btext_rect) # pinky pimg_rect = copy.deepcopy(self.starter_pinky_rect) pimg_rect.centerx = 281 pimg_rect.centery = 245 pinky_text = font.render('Pinky', True, (255, 153, 255)) # 255 153 255 -- pink ptext_rect = pinky_text.get_rect() ptext_rect.centerx = pimg_rect.right + 50 ptext_rect.centery = pimg_rect.centery self.screen.blit( self.starter_pinky[gr_ind[self.enemy_img_index.frame_index()]], pimg_rect) self.screen.blit(pinky_text, ptext_rect) # clyde cimg_rect = copy.deepcopy(self.starter_clyde_rect) cimg_rect.centerx = 170 cimg_rect.centery = 320 clyde_text = font.render('Clyde', True, (255, 204, 0)) # 255 204, 0 -- clyde color ctext_rect = clyde_text.get_rect() ctext_rect.centerx = cimg_rect.left - 50 ctext_rect.centery = cimg_rect.centery self.screen.blit( self.starter_clyde[gr_ind[self.enemy_img_index.frame_index()]], cimg_rect) self.screen.blit(clyde_text, ctext_rect) # inky iimg_rect = copy.deepcopy(self.starter_pinky_rect) iimg_rect.centerx = 281 iimg_rect.centery = 320 inkey_text = font.render('Inkey', True, (0, 255, 255)) # 0 255 255 -- inkey color itext_rect = inkey_text.get_rect() itext_rect.centerx = iimg_rect.right + 50 itext_rect.centery = iimg_rect.centery self.screen.blit( self.starter_inkey[gr_ind[self.enemy_img_index.frame_index()]], iimg_rect) self.screen.blit(inkey_text, itext_rect) # Contains main game loops def play(self): pg.mixer.music.stop() while self.start_screen: flip_time = 250 # blink prompt every 500 ms self.process_events() # CLICK HERE to start the game font = pg.font.Font('Gameplay.ttf', 25) play_game_prompt = font.render('PLAY', True, self.white) self.play_button_rect = play_game_prompt.get_rect() self.play_button_rect.center = ((self.WIDTH // 2), 475) hs_prompt = font.render('High Score', True, self.white) self.hs_button_rect = hs_prompt.get_rect() self.hs_button_rect.center = ((self.WIDTH // 2), 525) hs = font.render(str(self.high_score), True, self.white) hs_rect = self.play_button_rect back_prompt = font.render('Back', True, self.white) self.back_button_rect = back_prompt.get_rect() self.back_button_rect.center = ((self.WIDTH // 2), 525) font = pg.font.Font('Gameplay.ttf', 10) credit = font.render('Project by David Guido and Joshua Maranan', True, self.white) credit_rect = credit.get_rect() credit_rect.center = ((self.WIDTH // 2), (self.HEIGHT - 20)) time_since = abs(self.last_flip - pg.time.get_ticks()) if time_since >= flip_time: self.show = not self.show self.last_flip = pg.time.get_ticks() self.screen.fill(self.BG_COLOR) # Set background color to black self.display_sprites() self.display_introduction() self.screen.blit(self.big_logo, (0, 0)) # w = 450, h = 200 if self.show and self.play_button: self.screen.blit(play_game_prompt, self.play_button_rect) if self.hs_button: self.screen.blit(hs_prompt, self.hs_button_rect) if self.back_button: self.screen.blit(back_prompt, self.back_button_rect) if self.hs_show: self.screen.blit(hs, hs_rect) self.screen.blit(credit, credit_rect) pg.display.update() self.beginning_music.play() start_ticks = pg.time.get_ticks() # starter tick while not self.has_game_started: seconds = (pg.time.get_ticks() - start_ticks) / 1000 # calculate how many seconds self.process_events() # Get user input self.update() # Update this (Game) instance self.graph.update() # Update (Graph) instance self.pacman.update() # Update (Pac-man) instance self.ui_update() for enemy in self.enemies: # Update (Enemy) instances enemy.update() pg.display.update( ) # Tell game engine to update this games display if seconds > 5.5: # if more than 10 seconds close the game self.has_game_started = True self.initial_start = False while not self.win and not self.game_over \ and not self.is_paused and not self.new_life: #if self.pacman.moving: #self.eating_sound.set_volume(.4) #self.voice.play(self.eating_sound) self.process_events() # Get user input self.update() # Update this (Game) instance self.graph.update() # Update (Graph) instance self.pacman.update() # Update (Pac-man) instance self.ui_update() for enemy in self.enemies: # Update (Enemy) instances enemy.update() pg.display.update( ) # Tell game engine to update this games display if not self.is_paused: self.CLOCK.tick(60) # Limit display rate if self.game_over: self.show_game_over() self.beginning_music.play() self.play() elif self.new_life: self.reset_map() self.last_key = 'stop' if self.win: pg.mixer.music.play(-1) self.display_win() def display_win(self): # Save high score if self.score > self.high_score: self.high_score = self.score with open(path.join(self.dir, self.HS_FILE), 'w') as f: f.write(str(self.high_score)) # Texts font = pg.font.Font('Gameplay.ttf', 32) restart_font = pg.font.Font('Gameplay.ttf', 12) text = font.render('You Win!', True, (205, 204, 0), self.blue) restart_text = restart_font.render('Press R to restart.', True, (205, 204, 0), self.blue) textRect = text.get_rect() restart_text_rect = restart_text.get_rect() textRect.center = (self.WIDTH // 2, self.HEIGHT // 2) restart_text_rect.center = (self.WIDTH // 2, (self.HEIGHT // 2) + 50) while self.win: self.screen.blit(text, textRect) self.screen.blit(restart_text, restart_text_rect) for event in pg.event.get(): if event.type == pg.QUIT: pg.quit() quit() elif event.type == pg.KEYDOWN: if event.key == pg.K_r: self.__init__() self.has_game_started = False self.play() pg.display.update() self.CLOCK.tick(15) def ui_update(self): # Logo self.screen.blit(self.small_logo, (0, 0)) # Fruit self.screen.blit(self.graph.fruits[self.graph.fruit_index], (self.WIDTH - 80, self.HEIGHT - 28)) # Texts font = pg.font.Font('freesansbold.ttf', 16) high_score_label = font.render('HIGH SCORE', True, self.white) high_score_text = font.render(str(self.high_score), True, self.white) one_up_label = font.render('1UP', True, self.white) current_score_text = font.render(str(self.score), True, self.white) text_rect00 = high_score_label.get_rect() text_rect01 = high_score_text.get_rect() text_rect02 = one_up_label.get_rect() text_rect03 = current_score_text.get_rect() text_rect00.center = ((self.WIDTH // 2) - 5, 20) text_rect01.center = ((self.WIDTH // 2) - 5, 40) text_rect02.center = ((self.WIDTH // 2) + 100, 20) text_rect03.center = ((self.WIDTH // 2) + 100, 40) self.screen.blit(high_score_label, text_rect00) self.screen.blit(high_score_text, text_rect01) self.screen.blit(current_score_text, text_rect03) # blinking 1UP flip_time = 250 # blink 1UP every 250 ms time_since = abs(self.last_flip - pg.time.get_ticks()) if time_since >= flip_time: self.show = not self.show self.last_flip = pg.time.get_ticks() if self.show: self.screen.blit(one_up_label, text_rect02) # Sound icon self.screen.blit(self.sound_icon, (self.WIDTH - 50, 20)) # Pac lives if self.pacman.lives == 3: self.screen.blit(self.pac_life_icon, (10, self.HEIGHT - 28)) self.screen.blit(self.pac_life_icon, (35, self.HEIGHT - 28)) elif self.pacman.lives == 2: self.screen.blit(self.pac_life_icon, (10, self.HEIGHT - 28)) def reinit(self): self.pacman = Pacman(self, self.sprite_store.pacman, self.graph) # Pac-man obj self.blinky = Enemy(self, self.sprite_store.blinky, self.graph) # 1. Blinky obj (Enemy00) self.pinky = Enemy(self, self.sprite_store.pinky, self.graph) # 2. Pinky obj (Enemy01) self.clyde = Enemy(self, self.sprite_store.clyde, self.graph) # 3. Clyde obj (Enemy02) self.inkey = Enemy(self, self.sprite_store.inkey, self.graph) # 4. Inkey obj (Enemy03) self.enemies = [] # List of Enemy obj's self.enemies.append(self.blinky) # Add enemies to list self.enemies.append(self.pinky) self.enemies.append(self.clyde) self.enemies.append(self.inkey) self.pacman.rect.centerx = self.graph.nodes[ 65].x # Set Pac-man to node 65 self.pacman.rect.centery = self.graph.nodes[65].y self.pacman.adj_node = self.graph.nodes[65] self.initialize_enemies() def reset_map(self): temp = self.pacman.lives self.reinit() self.pacman.lives = temp self.new_life = False delay = 2000 # delay is 2 seconds after resetting start = pg.time.get_ticks() while abs(start - pg.time.get_ticks() ) <= delay: # reset screen and wait 2 seconds self.process_events() # Get user input self.update() # Update this (Game) instance self.graph.update() # Update (Graph) instance self.pacman.update() # Update (Pac-man) instance self.ui_update() for enemy in self.enemies: # Update (Enemy) instances enemy.update() pg.display.update( ) # Tell game engine to update this games display self.has_game_started = True # restart the game def show_game_over(self): # Save high score if self.score > self.high_score: self.high_score = self.score with open(path.join(self.dir, self.HS_FILE), 'w') as f: f.write(str(self.high_score)) # Texts font = pg.font.Font('Gameplay.ttf', 32) restart_font = pg.font.Font('Gameplay.ttf', 12) text = font.render('Game Over', True, self.green, self.blue) restart_text = restart_font.render('Press R to restart.', True, self.green, self.blue) textRect = text.get_rect() restart_text_rect = restart_text.get_rect() textRect.center = (self.WIDTH // 2, self.HEIGHT // 2) restart_text_rect.center = (self.WIDTH // 2, (self.HEIGHT // 2) + 50) while self.game_over: self.screen.blit(text, textRect) self.screen.blit(restart_text, restart_text_rect) for event in pg.event.get(): if event.type == pg.QUIT: pg.quit() quit() elif event.type == pg.KEYDOWN: if event.key == pg.K_r: self.__init__() self.has_game_started = False pg.display.update() self.CLOCK.tick(15) def un_pause(self): self.is_paused = False print('game is un-paused') def pause(self): self.is_paused = True print('game is paused') # create a font object. # 1st parameter is the font file # which is present in pygame. # 2nd parameter is size of the font font = pg.font.Font('freesansbold.ttf', 32) # create a text suface object, # on which text is drawn on it. text = font.render('Paused', True, self.green, self.blue) # create a rectangular object for the # text surface object textRect = text.get_rect() # set the center of the rectangular object. textRect.center = (self.WIDTH // 2, self.HEIGHT // 2) while self.is_paused: # copying the text surface object # to the display surface object # at the center coordinate. self.screen.blit(text, textRect) for event in pg.event.get(): if event.type == pg.QUIT: pg.quit() quit() elif event.type == pg.KEYDOWN: if event.key == pg.K_p: self.un_pause() pg.display.update() self.CLOCK.tick(15) # Set 'Last Key' to user input def process_events(self): for event in pg.event.get(): if event.type == pg.QUIT: sys.exit() # elif event.type == pg.KEYDOWN and not self.has_game_started: # allows for ENTER to start game # if event.key == pg.K_RETURN: # self.start_screen = False elif event.type == pg.MOUSEBUTTONDOWN and not self.has_game_started: x, y = event.pos if self.play_button_rect.collidepoint(x, y): self.start_screen = False elif self.hs_button_rect.collidepoint(x, y) and self.hs_button: self.play_button = False self.hs_button = False self.hs_show = True self.back_button = True elif self.back_button_rect.collidepoint( x, y) and self.back_button: self.play_button = True self.hs_button = True self.hs_show = False self.back_button = False elif event.type == pg.KEYDOWN and self.has_game_started: if event.key == pg.K_p: self.pause() elif event.key == pg.K_LEFT: self.last_key = 'left' elif event.key == pg.K_RIGHT: self.last_key = 'right' elif event.key == pg.K_UP: self.last_key = 'up' elif event.key == pg.K_DOWN: self.last_key = 'down' elif event.key == pg.K_z: self.portal1.fire() elif event.key == pg.K_x: self.portal2.fire() # Update the single (Game) instance def update(self): self.screen.fill(self.BG_COLOR) # Set background color to black self.screen.blit( self.bg.image, self.bg.rect) # Set game background to the maze background image self.portal1.update() # Update portals self.portal2.update() def initialize_enemies(self): self.blinky.rect.centerx = self.graph.nodes[69].x self.blinky.rect.centery = self.graph.nodes[69].y self.blinky.current_node = self.graph.nodes[69] self.blinky.adj_node = self.graph.nodes[24] shortest_path = self.graph.get_shortest_path(self.blinky.current_node, self.pacman.current_node) if len(shortest_path) > 0: self.blinky.adj_node = shortest_path[0].node self.blinky.next_node = shortest_path[len(shortest_path) - 1].node # = self.graph.get_adj_path(self.blinky.current_node, self.blinky.direction)[0] self.pinky.rect.centerx = self.graph.nodes[67].x self.pinky.rect.centery = self.graph.nodes[67].y self.pinky.current_node = self.graph.nodes[67] self.pinky.adj_node = self.graph.nodes[68] shortest_path = self.graph.get_shortest_path(self.pinky.current_node, self.pacman.current_node) if len(shortest_path) > 0: self.pinky.adj_node = shortest_path[0].node self.pinky.next_node = shortest_path[len(shortest_path) - 1].node self.clyde.rect.centerx = self.graph.nodes[68].x self.clyde.rect.centery = self.graph.nodes[68].y self.clyde.current_node = self.graph.nodes[68] self.clyde.adj_node = self.graph.nodes[67] shortest_path = self.graph.get_shortest_path(self.clyde.current_node, self.pacman.current_node) if len(shortest_path) > 0: self.clyde.adj_node = shortest_path[0].node self.clyde.next_node = shortest_path[len(shortest_path) - 1].node self.inkey.rect.centerx = self.graph.nodes[ 66].x # Set Inkey to his special starting node self.inkey.rect.centery = self.graph.nodes[66].y self.inkey.current_node = self.graph.nodes[66] self.inkey.adj_node = self.graph.nodes[67] shortest_path = self.graph.get_shortest_path(self.inkey.current_node, self.pacman.current_node) if len(shortest_path) > 0: self.inkey.adj_node = shortest_path[0].node self.inkey.next_node = shortest_path[len(shortest_path) - 1].node # Print application information to the console def debug_game_state(self): print()
def Game(): pygame.init() gamesettings = Settings() screen = pygame.display.set_mode( (gamesettings.screen_width, gamesettings.screen_height)) pygame.display.set_caption("Pacman Portal") # Start screen showgamestats = GameStats(screen, gamesettings) startScreen = StartScreen(screen, gamesettings, showgamestats) # Grouping blocks and pellets and ghosts blocks = Group() powerpills = Group() shield = Group() portals = Group() ghosts = Group() intersections = Group() fruit = Fruit(screen) thepacman = Pacman(screen, gamesettings) # Making the ghosts redghost = Ghosts(screen, "red") cyanghost = Ghosts(screen, "cyan") orangeghost = Ghosts(screen, "orange") pinkghost = Ghosts(screen, "pink") ghosts.add(redghost) ghosts.add(cyanghost) ghosts.add(orangeghost) ghosts.add(pinkghost) # Making the two portals orange = Portal(screen, "orange") blue = Portal(screen, "blue") portals.add(orange) portals.add(blue) startScreen.makeScreen(screen, gamesettings) fruit.fruitReset() gf.readFile(screen, blocks, shield, powerpills, intersections) frames = 0 # for the victory fanfare and death animation # play intro chime playIntro = True screen.fill(BLACK) while True: if (gamesettings.game_active): pygame.time.Clock().tick(120) #120 fps lock screen.fill(BLACK) showgamestats.blitstats() gf.check_events(thepacman, powerpills, gamesettings, orange, blue) gf.check_collision(thepacman, blocks, powerpills, shield, ghosts, intersections, showgamestats, gamesettings, fruit, orange, blue) for block in blocks: block.blitblocks() for theshield in shield: theshield.blitshield() for pill in powerpills: pill.blitpowerpills() for portal in portals: portal.blitportal() for ghost in ghosts: ghost.blitghosts() ghost.update() if (ghost.DEAD): ghost.playRetreatSound() elif (ghost.afraid): ghost.playAfraidSound( ) # if ghosts are afraid, loop their sound for intersection in intersections: intersection.blit() fruit.blitfruit() thepacman.blitpacman() thepacman.update() if (len(powerpills) == 0): gamesettings.game_active = False gamesettings.victory_fanfare = True if (playIntro and pygame.time.get_ticks() % 200 <= 50): mixer.Channel(2).play( pygame.mixer.Sound('sounds/pacman_beginning.wav')) pygame.time.wait(4500) playIntro = False elif (gamesettings.victory_fanfare): if (frames <= 120): for block in blocks: block.color = ((255, 255, 255)) block.blitblocks() elif (frames <= 240): for block in blocks: block.color = ((0, 0, 255)) block.blitblocks() elif (frames <= 360): for block in blocks: block.color = ((255, 255, 255)) block.blitblocks() elif (frames <= 480): for block in blocks: block.color = ((0, 0, 255)) block.blitblocks() else: gamesettings.game_active = True gamesettings.victory_fanfare = False thepacman.resetPosition() for ghost in ghosts: ghost.resetPosition() ghost.speed += 1 showgamestats.level += 1 fruit.fruitReset() gf.readFile(screen, blocks, shield, powerpills, intersections) frames = 0 pygame.time.wait(1000) frames += 1 elif (thepacman.DEAD): thepacman.deathAnimation(frames) frames += 1 if (frames > 600): gamesettings.game_active = True thepacman.DEAD = False thepacman.resetPosition() for ghost in ghosts: ghost.resetPosition() frames = 0 pygame.time.wait(1000) if (showgamestats.num_lives < 0): #reset game and save score screen.fill(BLACK) pygame.time.wait(2000) gamesettings.game_active = False thepacman.resetPosition() for ghost in ghosts: ghost.resetPosition() ghost.speed = 1 showgamestats.num_lives = 3 showgamestats.save_hs_to_file() showgamestats.score = 0 showgamestats.level = 1 fruit.fruitReset() playIntro = True # reset the chime gf.readFile(screen, blocks, shield, powerpills, intersections) startScreen.makeScreen(screen, gamesettings) pygame.display.flip()
def __init__(self, screen, mazefile, stats, clock): self.screen = screen self.stats = stats self.clock = clock self.radio = pygame.mixer self.radio.init() self.filename = mazefile with open(self.filename, 'r') as f: self.rows = f.readlines() self.maze_obj = [] size = Maze.BRICK_SIZE self.brick = Image(screen, 'brick', size, size) self.default_ports = pygame.sprite.Group() self.def_port_list = [] self.lport = Portal(self.screen, 'blue') self.rport = Portal(self.screen, 'orange') self.pac_dots = pygame.sprite.Group() self.pac_dot = Pacdot(screen, pygame.image.load('images/pacdot.png')) self.pac_dot.image = pygame.transform.scale(self.pac_dot.image, (8, 8)) self.power_dots = pygame.sprite.Group() self.power = Pacdot(screen, pygame.image.load('images/pacdot.png')) self.power.image = pygame.transform.scale(self.power.image, (15, 15)) self.shield = Image(screen, 'shield', size, size) self.pac_man = Pacman(screen, self) self.blinky = Ghost(screen, self, 'blinky') self.pinky = Ghost(screen, self, 'pinky') self.inky = Ghost(screen, self, 'inky') self.clyde = Ghost(screen, self, 'clyde') self.ghosts = pygame.sprite.Group() self.fruit = None self.fruits = pygame.sprite.Group() self.deltax = self.deltay = Maze.BRICK_SIZE # used for menu purposes self.title = None self.title_rect = None self.start_button = None self.scores_button = None # end of menu items # used for sounds self.intro = self.radio.Sound('sounds/intro.wav') self.ambient = self.radio.Sound('sounds/ambient.wav') self.eatdot = self.radio.Sound('sounds/eatdot.wav') self.eatghost = self.radio.Sound('sounds/eatghost.wav') self.powersound = self.radio.Sound('sounds/power.wav') self.death = self.radio.Sound('sounds/death.wav') self.gameover = self.radio.Sound('sounds/gameover.wav') self.ambient_playing = False self.power_playing = False # end of sounds self.lives_counter = pygame.sprite.Group() self.lives_sprites = [] self.active_ports = pygame.sprite.Group() self.bport = None self.oport = None self.blue_active = False self.orange_active = False self.build()