예제 #1
0
    def init(self):

        self.loadScore()
        self.__background = Background(
            self,
            self.__width,
            self.__height,
            fp=self.background_fp,
            animation_speed=self.__background_animation_speed)
        self.__background.focus_force()
        self.__background.bind(self.window_fullscreen_event,
                               self.changeFullscreenOption)
        self.__background.bind(self.window_start_event, self.start)
        self.__background.bind(self.window_exit_event, self.close)
        self.protocol("WM_DELETE_WINDOW", self.close)
        self.__background.pack()
        self.createMenuButtons()
        self.createTitleImage()
        self.__bird = Bird(self.__background,
                           self.gameOver,
                           self.__width,
                           self.__height,
                           fp=self.bird_fp,
                           event=self.bird_event,
                           descend_speed=self.__bird_descend_speed)
예제 #2
0
    def initialize_pygame(self):

        print("Initializing Pong game ...")

        pygame.mixer.pre_init(self.settings.sound_sample_rate, -16,
                              self.settings.sound_channels, 1024)
        pygame.mixer.init()
        pygame.init()

        self.clock = pygame.time.Clock()

        width = int(self.settings.screen_width * self.settings.screen_resize)
        height = int(self.settings.screen_height * self.settings.screen_resize)
        self.screen = pygame.display.set_mode((width, height))
        self.screen_rect = self.screen.get_rect()
        pygame.display.set_caption(self.settings.screen_title)

        self.background = Background(self.settings, self.screen)

        self.welcome_board = WelcomeBoard(self.settings, self.screen, self)

        self.scoreboard = Scoreboard(self.settings, self.screen, self)

        self.victory_board = VictoryBoard(self.settings, self.screen, self)

        self.ball = Ball(self.settings, self.screen)
        self.scoreboard.set_ball(self.ball)

        self.initialize_players()
예제 #3
0
    def start(self):
        pygame.init()

        self.stage = Stage(self, 1)
        self.screen = pygame.display.set_mode((800, 600))

        self.background = Background(self)
        self.background.load()

        self.player = Player(self)
        self.player.load()

        self.bullet = Bullet(self)
        self.bullet.load()

        self.enemies = Enemies(self)
        self.enemies.load()

        self.game_text = GameText(self)
        self.game_text.load()

        self.explosion = Explosion(self)
        self.explosion.load()

        self.caption = Caption(self)
        self.caption.load()

        self.score = Score(self)
        self.score.load()

        while self.running:
            self.screen.fill((0, 0, 0))
            self.background.show()
            self.handle_event()
예제 #4
0
 def criarCena(self):
     background = Background("caldron.jpg")
     background.position = (self.director.get_window_size()[0]/2,
                             self.director.get_window_size()[1]/2)
     background.fundo.opacity = 100
     cena = Scene(background, self )
     return cena
예제 #5
0
    def __init__(self, main):
        self.main = main
        self.highScores = []
        self.highScoreDisplays = []
        # populate the highscores and displays
        for i in range(0, 5):
            self.highScores.append(0)
            tScore = TextItem(400,
                              250 + i * 50,
                              400,
                              150,
                              [str(i + 1) + ': ' + str(self.highScores[i])],
                              showRect=False)
            self.highScoreDisplays.append(tScore)

        self.background_image = os.path.join('assets', 'startscreen',
                                             'night_sunset_gradient.png')
        self.background = Background(self.background_image)
        self.menuBtn = Button(500, 600, 200, 75, 'Menu')
        self.playerScoreDisplay = TextItem(400,
                                           100,
                                           400,
                                           150, [''],
                                           showRect=False,
                                           fontSize=72)
예제 #6
0
    def __init__(self, gsm):
        self.gsm = gsm
        self.background = Background(
            os.path.join("res", "PlayState", "background.png"))
        self.camera = Camera(self)
        self.HUD = HUD(self.gsm)
        # Key handling
        self.leftKeyDown = False
        self.rightKeyDown = False
        self.upKeyDown = False

        self.spriteSheet = SpriteSheet(
            os.path.join("res", "PlayState", "Spritesheet.png"), 1)

        # Holds all the objects in the game
        self.allObjectList = pygame.sprite.Group()
        self.activeObjectList = pygame.sprite.Group()
        self.terrainList = pygame.sprite.Group()
        self.interactableList = pygame.sprite.Group()
        self.enemyList = pygame.sprite.Group()
        self.enemyAIList = pygame.sprite.Group()
        self.player = None

        self.level = currentLevel  # Sets the current level
        self.loadLevel(self.level)  # Loads the level
예제 #7
0
class Game(object):
    def __init__(self):
        pygame.init()

        # Config
        self.max_fps = 40
        self.screen_length = int(GetSystemMetrics(1) * 0.75)
        self.screen_with = int(GetSystemMetrics(1) * 0.5)
        self.screen = pygame.display.set_mode(
            (self.screen_with, self.screen_length))
        self.clock = pygame.time.Clock()
        self.delta = 0.0
        pygame.display.set_caption("303 Polish Fighter Squadron")
        self.title_icon = pygame.image.load("title_icon.png")
        pygame.display.set_icon(self.title_icon)

        # Initialization
        self.player = Rocket(self)
        self.bullet = Bullets(self, self.player)
        self.enemy = Enemy(self, self.player, self.bullet)
        self.background = Background(self)
        print(self.screen_with, self.screen_length)

        while True:
            self.update()
            self.screen.fill((0, 0, 0))

            for event in pygame.event.get():
                if event.type == pygame.QUIT or event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                    sys.exit(0)

                if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                    self.bullet.shoot()

            # Ticking
            self.delta += self.clock.tick() / 1000.0
            while self.delta > 1 / self.max_fps:
                self.tick()
                self.delta -= 1 / self.max_fps

            # Drawing
            self.draw()
            pygame.display.flip()

    def update(self):
        self.screen_length = int(GetSystemMetrics(1) * 0.75)
        self.screen_with = int(GetSystemMetrics(1) * 0.5)

    def tick(self):
        self.background.tick()
        self.bullet.tick()
        self.player.tick()
        self.enemy.tick()

    def draw(self):
        self.background.draw()
        self.bullet.draw()
        self.player.draw()
        self.enemy.draw()
예제 #8
0
class Scoreboard(object):
    def __init__(self, main):
        self.main = main
        self.highScores = []
        self.highScoreDisplays = []
        # populate the highscores and displays
        for i in range(0, 5):
            self.highScores.append(0)
            tScore = TextItem(400,
                              250 + i * 50,
                              400,
                              150,
                              [str(i + 1) + ': ' + str(self.highScores[i])],
                              showRect=False)
            self.highScoreDisplays.append(tScore)

        self.background_image = os.path.join('assets', 'startscreen',
                                             'night_sunset_gradient.png')
        self.background = Background(self.background_image)
        self.menuBtn = Button(500, 600, 200, 75, 'Menu')
        self.playerScoreDisplay = TextItem(400,
                                           100,
                                           400,
                                           150, [''],
                                           showRect=False,
                                           fontSize=72)

    def listenForEvents(self):
        if 1 in pygame.mouse.get_pressed():
            if self.menuBtn.is_under(pygame.mouse.get_pos()):
                self.main.set_mode('menu')

    def renderScreen(self):
        self.background.draw(self.main.screen)
        self.menuBtn.draw(self.main.screen)
        self.playerScoreDisplay.draw(self.main.screen)
        for displays in self.highScoreDisplays:
            displays.draw(self.main.screen)

    def enter(self):
        print("entered Scoreboard")
        self.playerScoreDisplay.setText(
            ['You did it! Score: ' + self.main.score])
        # append the player score to highScores
        print self.highScores
        self.highScores.append(int(self.main.score))
        print self.highScores
        # sort highScore
        self.highScores.sort()
        print self.highScores
        # remove the minimum and display the rest in sorted order
        self.highScores.pop(0)
        print self.highScores
        for i in range(0, 5):
            self.highScoreDisplays[i].setText(
                [str(i + 1) + ': ' + str(self.highScores[5 - 1 - i])])
예제 #9
0
    def __init__(self):
        pygame.init()
        self.size = self.width, self.height = 900, 444
        self.screen = pygame.display.set_mode(self.size)

        self.player = Player(self, "mario")
        self.bg = Background(self, self.player)

        go = LoopingCall(self.ticker)
        go.start(0.01)
        reactor.run()
예제 #10
0
def start():
    director.set_depth_test()
    background = Background("halloween.jpg")
    background.position = (director.get_window_size()[0] / 2,
                           director.get_window_size()[1] / 2)

    firelayer = FireManager(director.get_window_size()[0], 250)
    menulayer = MultiplexLayer(MenuPrincipal(), OptionMenu(), CreditsLayer())

    scene = Scene(background, menulayer, firelayer)

    return scene
예제 #11
0
 def __init__(self, main):
     self.main = main
     self.buttons = []
     self.background_image = os.path.join('assets', 'startscreen', 'night_sunset_gradient.png')
     self.background = Background(self.background_image)
     self.tutImage = Background('assets/tutorial-images/tut1.jpg',self.main.hcenter - 400, 50)
     self.menuBtn = Button(500, 750, 200, 75, 'Menu')
     self.backBtn = Button(300, 650, 200,75, 'Back')
     self.nextBtn = Button(700, 650, 200, 75, 'Next')
     self.currentScreen = 1
     # Help screen buttons
     self.buttons.append(self.menuBtn)
     self.buttons.append(self.nextBtn)
     self.buttons.append(self.backBtn)
예제 #12
0
    def init(self):
        """
        Método para iniciar o programa em si, criando toda a parte gráfica inicial do jogo
        """

        # self.createMenuButtons()
        self.loadScore()

        # Cria o plano de fundo do jogo
        self.__background = Background(
            self,
            self.__width,
            self.__height,
            fp=self.background_fp,
            animation_speed=self.__background_animation_speed,
        )

        # Foca o plano de fundo para que seja possível definir os eventos
        self.__background.focus_force()
        # Define evento para trocar o modo de janela para "fullscreen" ou "window"
        self.__background.bind(self.window_fullscreen_event,
                               self.changeFullscreenOption)
        # Define evento para começar o jogo
        self.__background.bind(self.window_start_event, self.start)
        # Define evento para sair do jogo
        self.__background.bind(self.window_exit_event, self.close)

        # Define um método caso o usuário feche a janela do jogo
        self.protocol("WM_DELETE_WINDOW", self.close)

        # Empacota o objeto background
        self.__background.pack()

        # Cria os botões do menu do jogo
        self.createMenuButtons()

        # Cria imagem do título do jogo
        self.createTitleImage()

        # Cria um pássaro inicial no jogo
        self.__bird = Bird(
            self.__background,
            self.gameOver,
            self.__width,
            self.__height,
            fp=self.bird_fp,
            event=self.bird_event,
            descend_speed=self.__bird_descend_speed,
        )
예제 #13
0
    def __init__(self,screenSize):
        self.buttons = []
        self.background_image = os.path.join('assets', 'startscreen', 'night_sunset_gradient.png')
        self.background = Background(self.background_image)
        self.tutImage = Background('assets/tutorial-images/tut1.jpg',(0.05)*screenSize[0], .05*screenSize[1])
        self.menuBtn = Button(.41*screenSize[0], .83*screenSize[1], .16*screenSize[0], .08*screenSize[1], 'Menu')
        self.backBtn = Button(.25*screenSize[0], .72*screenSize[1], .16*screenSize[0],.08*screenSize[1], 'Back')
        self.nextBtn = Button(.58*screenSize[0], .72*screenSize[1], .16*screenSize[0], .08*screenSize[1], 'Next')
        self.currentScreen = 1
        # Help screen buttons
        self.buttons.append(self.menuBtn)
        self.buttons.append(self.nextBtn)
        self.buttons.append(self.backBtn)

        self.EVENT_MENU =[]
예제 #14
0
파일: World.py 프로젝트: MWojnar/GMTK2
 def __init__(self, mainSurface, width, height):
     self.roomWidth = width
     self.roomHeight = height
     self.screenWidth = width
     self.screenHeight = height
     self.assetLoader = AssetLoader(self)
     self.mainSurface = mainSurface
     self.background = Background()
     self.level = 1
     self.cursor = Cursor(self)
     self.loadMenu()
     self.events = []
     self.fullscreen = False
     self.alreadyClicked = False
     pygame.mixer.music.play(-1)
예제 #15
0
def main():

    background = Background(20)

    terrain = Tunnel()
    terrain.build()

    pygame.init()

    win_size = (1200, 900)
    pygame.display.set_mode(
        win_size, pygame.DOUBLEBUF | pygame.OPENGL | pygame.RESIZABLE)

    gluPerspective(60, (win_size[0] / win_size[1]), 0.9, 600)
    glTranslate(0, terrain.radius - 20, -560)
    glEnable(GL_DEPTH_TEST)

    clock = pygame.time.Clock()
    exit_flag = False

    while not exit_flag:
        clock.tick(60)
        for eve in pygame.event.get():
            if eve.type == pygame.QUIT:
                exit_flag = True

        keys = pygame.key.get_pressed()
        if keys[pygame.K_d]:
            terrain.rotate(-1)
            background.rotate(-1, math.pi / terrain.sides_num / 2)
        if keys[pygame.K_a]:
            terrain.rotate(1)
            background.rotate(1, math.pi / terrain.sides_num / 2)
        if keys[pygame.K_ESCAPE]:
            exit_flag = True

        background.move()

        terrain.clear()
        terrain.move()
        terrain.collision()

        # glRotatef(1, 0, 0, int(2 * mat.pi))
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        background.draw()
        terrain.draw()
        pygame.display.flip()
예제 #16
0
파일: Level.py 프로젝트: span/taxrunner
    def __init__(self, game):
        self.finished = False
        self.sprites = pygame.sprite.Group()
        self.surface = game.surface
        self.speed = game.speed
        self.surface_rect = self.surface.get_rect()
        self.center = (self.surface_rect.width / 2, self.surface_rect.height / 2)
        self.background = Background(self.speed)
        self.heightfactor = 0
        self.x = 0
        self.y = 0

        for i in range(0, self.bricks):
            self.x = i * Brick.width
            if i % 4 == 0:
                self.x += Brick.width / 2
                if self.heightfactor == 4:
                    self.heightfactor -= 2
                else:
                    self.heightfactor += 1
            self.y = self.start_pos_y - (50 * self.heightfactor)
            brick = Brick(self.x, self.y, self.speed, self.bricks)
            self.sprites.add(brick)
            
        self.green_cash = Cash(self.surface_rect.width, self.y - 70, self.speed, 'green')    
        self.receipt = Cash(self.surface_rect.width, self.y - 50, self.speed * 1.5, 'receipt')
        self.sprites.add(self.green_cash)
        self.sprites.add(self.receipt)
        self.player = Player(self.start_pos_x, 0, self.speed)
        self.taxman = TaxMan(50, 100, self.speed)
        self.sprites.add(self.taxman)
예제 #17
0
    def main(self):
        # 1)  #init
        pygame.init()
        pygame.key.set_repeat(25, 25)
        self.slowmotion = 100
        # self.screen = screen
        self.size = self.width, self.height = 640, 480
        self.black = 0, 0, 0
        self.counter = 0
        #screen size
        self.screen = pygame.display.set_mode(self.size)
        #create game clock
        #self.clock = pygame.time.Clock()

        #2) set up game objects
        self.level = 1
        self.hearts = 5
        self.fire_count = 0
        self.health_pickup_array = []
        self.laser_array = []
        self.enemies_spawned = False
        self.enemy_array = []
        self.enemy_laser_array = []
        self.player = Player(self)
        self.background = Background(self)
        self.healthbar = Healthbar(self)
        self.gameover = GameOver(self)
        self.cat = Sushi_Cat(self)
        self.octoking = OctoKing(self)
        self.item = Item(self)
    def check(rect: pygame.Rect, speed: int, dir: Helpers.Direction) -> bool:
        if dir == Helpers.Direction.UP:
            tile = Background.checkTile(rect.left, rect.top - speed)
        elif dir == Helpers.Direction.RIGHT:
            tile = Background.checkTile(rect.right + speed, rect.top)
        elif dir == Helpers.Direction.DOWN:
            tile = Background.checkTile(rect.left, rect.bottom + speed)
        elif dir == Helpers.Direction.LEFT:
            tile = Background.checkTile(rect.left - speed, rect.top)

        if tile == Background.ROCK:
            return False
        elif tile == Background.SPACE:
            return False
        else:
            return True
예제 #19
0
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((1280, 800))
        self.area = self.screen.get_rect()
        self.walls = Wall.gather_walls()

        self.my_clock = pygame.time.Clock()     # Utility object

        self.background = Background()          # Objects we put on screen
        self.character = Character(self.area)

        self.all_but_background = PgGroup((self.character, self.walls))

        self.monsters = Monster.spawn_monsters(self.character, self.walls, ((ChampionMeleeMonster, 15), (Monster, 30),
                                                                            (RangeMonster, 25)))

        # So we can call each monster's attack method.
        self.monster_group = PgGroup(self.monsters)

        # Used to update everything to screen.
        self.all_sprites = PgGroup((self.character, self.monsters, self.background, self.walls))

        # Used to draw. We separate background so we can ensure it gets pictured before other things.
        self.all_but_background.add(self.monsters)

        self.time_test = False # Changed things in while loop so need to recreate timetest.
        self.time_dict = {'drawmove': 0, 'abilitydraw': 0, 'eventloop': 0, 'attacks': 0, 'collisions': 0,
                          'move': 0, 'clear/recover': 0, 'drawbars': 0}
        self.loop_counter = 0

        self.find_key = {K_LSHIFT: 0, K_SPACE: 1, LEFT: 2, RIGHT: 3}
예제 #20
0
def run_game():

    # Inicializa o jogo e cria um objeto na tela
    pygame.init()
    pygame.mixer.init()

    # Inicializa uma instancia de Settings():
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption(ai_settings.game_name)
    ship = Ship(ai_settings, screen)
    bullets = Group()
    aliens = Group()
    stats = GameStats(ai_settings)

    sb = Scoreboard(ai_settings, screen, stats)
    bg = Background(screen)

    sound_playing = ai_settings.play_music()
    alien = Alien(ai_settings, screen)
    # Cria botao play
    play_button = Button(ai_settings, screen, 'Play')

    # Cria um frota de alienigenas

    gf.create_fleet(ai_settings, screen, ship, aliens)

    # Inicia o laco principal do jogo

    while True:
        gf.check_events(ai_settings, screen, stats, sb, play_button, ship,
                        aliens, bullets)

        # importa as funcoes do modulo game_functions
        #space_scrolling
        if stats.game_active:
            sound_playing
            ship.update()
            bullets.update()
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                              bullets)
            gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens,
                             bullets)
            bg.update()
        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets,
                         play_button, bg)
예제 #21
0
파일: Game.py 프로젝트: nekocoder/Vault
    def __init__(self, main):
        self.main = main
        self.buttons = []
        self.gameScreenUI = []
        self.currentAnswers = []
        self.level_loaded = False
        self.last_mousepressed = []
        self.levelWon = False
        self.failed_rocket = os.path.join('assets', 'rocket_down.png')
        self.launching_rocket = os.path.join('assets', 'rocket_launch.png')
        self.background_image = os.path.join('assets','Background.png')
        self.background = Background(self.background_image)
        self.background_rocket = Background(self.launching_rocket, 800, 675 - (self.main.currentLevel * 100))
        print 'currentLevel is ' + str(self.main.currentLevel)

        # Game playing screen buttons
        self.emptyBtn = Button(750, 725, 200, 75, 'Reset', (206, 148, 73), (109, 78, 38))
        self.menuBtn = Button(950, 725, 250, 75, 'Back to Menu', (202, 198, 82), (85, 83, 34))
        self.doneBtn = Button(915, 625, 250, 75, 'Check Answer', (7,208,226), (4,111,121))
        self.buttons.append(self.menuBtn)
        self.buttons.append(self.emptyBtn)
        self.buttons.append(self.doneBtn)

        # Game screen text elements
        self.scoreDisplay = TextItem(700, 0, 200, 75, ['Score: '], showRect = False)
        self.levelDisplay = TextItem(900, 0, 300, 75, ['Current Level: '], showRect = False)
        self.goalDisplay = TextItem(950, 240, 177, 60, ['Fill to: '], textColor= (255,255,255), showRect = False)
        self.feedback_width = 600
        self.feedback_height = 200
        self.feedback_x = (self.main.width / 2) - (self.feedback_width / 2)
        self.feedback_y = (self.main.height / 2) - (self.feedback_height / 2)
        self.gameScreenUI.append(self.goalDisplay)
        self.gameScreenUI.append(self.scoreDisplay)
        self.gameScreenUI.append(self.levelDisplay)
        self.winScreen = TextItem(self.feedback_x, self.feedback_y, self.feedback_width, self.feedback_height, ['Nice Job!', 'Click here to go on!'], (84, 194, 92), (39, 90, 43), True, Background(self.launching_rocket, self.feedback_x, self.feedback_y, self.feedback_width / 2, 100))
        self.winScreen.close()
        self.loseScreen = TextItem(self.feedback_x, self.feedback_y, self.feedback_width, self.feedback_height, ['Oops, that\'s not quite right.', 'Click here and try again.'], (209, 72, 72), (96, 33, 33), True, Background(self.failed_rocket, self.feedback_x, self.feedback_y, self.feedback_width / 2, 100))
        self.loseScreen.close()

        # Game screen elements
        self.goalContainer = Container(950, 300, 0, 1, 177, 259, False)
        self.goalFill = 1.0 #temporary goal fill amount #the number you are aiming for

        # Timer Bonus
        self.timer = 0;
        self.secondsTillNoBonus = 10; 
예제 #22
0
 def __init__(self):
     self._running = True
     self._display_surf = None
     self._enemyTimer = 0
     self._ENEMYSPAWNTIME = Helpers.FPS * 2
     self._player = Player()
     self._entities = pygame.sprite.Group()
     self._entities.add(self._player)
     self._mobs = pygame.sprite.Group()
     self._bullets = pygame.sprite.Group()
     self._background = Background()
     self._clock = None
     self._paused = False
     try:
         self._opening.isAlive()
     except AttributeError:
         self._opening = Opening()
예제 #23
0
def enter():
    hide_cursor()
    global start_select, cursor, background, big_start, small_start
    start_select = False
    cursor = Cursor()
    background = Background()
    big_start = Big_start()
    small_start = Small_start()
    game_world.add_object(cursor, 0)
예제 #24
0
    def __init__(self, connection, character):
        self.connection = connection
        self.character = character

        # initialize the game space
        pygame.init()
        self.size = self.width, self.height = 900, 444
        self.screen = pygame.display.set_mode(self.size)

        self.player = Player(self, self.character)
        self.enemy = Enemy(self, self.character)
        self.bg = Background(self, self.player)

        self.clock = pygame.time.Clock()

        self.received = [450, 365, 450, 365]
        self.p1 = [450, 365]
        self.p2 = [450, 365]
예제 #25
0
class Scoreboard(object):
	
	def __init__(self, main):
		self.main = main;
		self.highScores = [];
		self.highScoreDisplays = [];
		# populate the highscores and displays
		for i in range(0, 5):
			self.highScores.append(0);
			tScore = TextItem(400, 250 + i * 50, 400, 150, [str(i+1)+': ' + str(self.highScores[i])], showRect = False);
			self.highScoreDisplays.append(tScore);

		self.background_image = os.path.join('assets', 'startscreen', 'night_sunset_gradient.png');
		self.background = Background(self.background_image);
		self.menuBtn = Button(500, 600, 200, 75, 'Menu');
		self.playerScoreDisplay = TextItem(400, 100, 400, 150, [''], showRect = False, fontSize = 72);

	def listenForEvents(self):
		if 1 in pygame.mouse.get_pressed():
			if self.menuBtn.is_under(pygame.mouse.get_pos()):
				self.main.set_mode('menu');

	def renderScreen(self):
		self.background.draw(self.main.screen);
		self.menuBtn.draw(self.main.screen);
		self.playerScoreDisplay.draw(self.main.screen);
		for displays in self.highScoreDisplays:
			displays.draw(self.main.screen);

	def enter(self):
		print("entered Scoreboard");
		self.playerScoreDisplay.setText(['You did it! Score: ' + self.main.score]);
		# append the player score to highScores
		print self.highScores
		self.highScores.append(int(self.main.score));
		print self.highScores
		# sort highScore
		self.highScores.sort();
		print self.highScores
		# remove the minimum and display the rest in sorted order
		self.highScores.pop(0);
		print self.highScores
		for i in range(0, 5):
			self.highScoreDisplays[i].setText([str(i+1)+': ' + str(self.highScores[5 - 1 - i])])
예제 #26
0
def enter_level3():
    bgImage = simplegui.load_image("https://i.imgur.com/AljXcD9.png")
    global bg, treeImg, tree1, tree2, interaction
    bg = Background(bgImage, Vector((bgImage.get_width()/2, bgImage.get_height()/2)), DISPLAYW)
    treeImg = simplegui.load_image("https://i.imgur.com/354gDYv.png")
    tree1 = Tree(treeImg, 0 + treeImg.get_height() / 2, DISPLAYW)
    tree2 = Tree(treeImg, DISPLAYH - treeImg.get_height() / 2, DISPLAYW)
    interaction = Interaction(userCar, userCar2, kbd, [tree1, tree2], w1, w2, obstacles, bombs, papaya, twoPlayer)
    interaction.passBack(bg)
    enterWelcomeScreen()
예제 #27
0
 def __init__(self):
     Tk.__init__(self)
     self.setOptions()
     if all([self.window_width, self.window_height]):
         self.__width = self.window_width
         self.__height = self.window_height
     else:
         self.__width = self.winfo_screenwidth()
         self.__height = self.winfo_screenheight()
     self.title(self.window_name)
     self.geometry("{}x{}".format(self.__width, self.__height))
     self.resizable(*self.window_rz)
     self.attributes("-fullscreen", self.window_fullscreen)
     self["bg"] = "black"
     for file in self.images_fp:
         if not os.path.exists(file):
             raise FileNotFoundError(
                 "The following file was not found:\n{}".format(file))
     self.__startButton_image = Background.getPhotoImage(
         image_path=self.startButton_fp,
         width=(self.__width // 100) * self.button_width,
         height=(self.__height // 100) * self.button_height,
         closeAfter=True)[0]
     self.__exitButton_image = Background.getPhotoImage(
         image_path=self.exitButton_fp,
         width=(self.__width // 100) * self.button_width,
         height=(self.__height // 100) * self.button_height,
         closeAfter=True)[0]
     self.__title_image = Background.getPhotoImage(
         image_path=self.title_fp,
         width=(self.__width // 100) * self.title_width,
         height=(self.__height // 100) * self.title_height,
         closeAfter=True)[0]
     self.__scoreboard_image = Background.getPhotoImage(
         image_path=self.scoreboard_fp,
         width=(self.__width // 100) * self.scoreboard_width,
         height=(self.__height // 100) * self.scoreboard_height,
         closeAfter=True)[0]
     self.__background_animation_speed //= self.__width / 100
     self.__background_animation_speed = int(
         self.__background_animation_speed)
     self.__bird_descend_speed //= self.__height / 100
     self.__bird_descend_speed = int(self.__bird_descend_speed)
예제 #28
0
 def __init__(
         self,
         height=144,
         noteSpeed=9.0,  # songNo=73, difficulty=Difficulty.expert,
         interval=3,
         audio_state=True,
         real_music=False,
         seed=None):
     self.const = ConstPara(height=height, noteSpeed=noteSpeed)
     self.screen = pygame.display.set_mode(self.const.size,
                                           flags=0,
                                           depth=24)  # window size
     self.bg = Background(self.const)
     # self.s_c = SongChart(songNo=songNo, difficulty=difficulty)
     self.seed = seed
     # if isinstance(self.seed, int):
     #    random.seed(self.seed)
     self._e = EnvMap(random.randint(8, 12) * 1000)
     j, self.pydub_bgm = self._e.get_chart_song()
     # e.save_and_play()
     self.ng = NoteBarGroup(j, self.const)
     self.in_time_music = real_music  # play music? default is false
     # assert not self.in_time_music
     self.playing = False
     self.delta_t = 15.5 / 1000.
     self.interval = interval
     self.audio_state = audio_state
     # for agent
     self.info = {}
     self.rec_surface = self.screen.subsurface(
         (math.ceil(self.const.width * .43), self.const.height / 2,
          math.ceil(self.const.width * (1 - 2 * .43)),
          self.const.height / 2))
     self.playTime = random.randint(0, 16) / 1000.
     self.judge = SimpleJudgement(self.ng.basic_notes, self.ng.notes_hit)
     # self.pydub_bgm = pydub.AudioSegment.from_mp3(self.s_c.songPath)
     self.obs = [
         0 for _ in range(self.interval + (1 if self.audio_state else 0))
     ]  # screen*3, audio segment
     # self.songNo = songNo
     # print(j)
     self.music_file = None  # for test
예제 #29
0
    def __init__(self):
        pygame.init()
        self.size = self.width, self.height = 1920 // 2, 1080 // 2
        self.screen = pygame.display.set_mode(self.size)

        self.player = Player()
        self.bg = Background()

        go = LoopingCall(self.ticker)
        go.start(0.01)
        reactor.run()
예제 #30
0
    def reset(self):
        self.shakeScreen = resources.screen
        self.screen = self.shakeScreen.copy()
        resources.screen_copied = self.screen
        self.background = Background(self.screen)
        self.screenShaker = ScreenShaker()

        self.OPACITY = 250

        self.activeRegions = {}
        self.allPackages = {}
        self.allPackageNames = []
        self.allShields = []
        self.messages = []

        self.MAX_SHIP_HP = 100
        self.shipHp = 100
        self.MAX_SHIP_POWER = 1000
        self.ship_power = 1000
        self.ship_reload = 0
        self.SHIP_MAX_PROGRESS = 2000
        self.ship_progress = 0
        self.night_opacity = self.OPACITY

        #self.cannon_accuracy = 3

        self.console = Console.Console(self.screen)
        self.addMessage(
            "Once upon a time, there was a woman named Wax Chug da Gwad. She had a solar powered ship. However, she was far from home and the solar panels sucked. And tentacle monsters appeared. Help Wax Chug get home."
        )

        resources.time = Time()
        self.time = resources.time
        #tells Time to call "toggleDay" when 6:00 happens
        self.time.setToggleDayListener(self, '6:00')
        self.day = False
        self.night = resources.all_sprites["night.png"]

        self.monsterList = MonsterList()

        self.initializePackages()
예제 #31
0
def enter():
    global cursor, background, sad, happy, selected_character
    cursor = Cursor()
    background = Background()
    sad = Choose_sadness300()
    happy = Choose_happiness300()
    selected_character = 'none'

    game_world.add_object(background, 0)
    game_world.add_object(happy, 1)
    game_world.add_object(sad, 1)
    game_world.add_object(cursor, 2)
예제 #32
0
class GameSpace:
    def __init__(self):
        pygame.init()
        self.size = self.width, self.height = 900, 444
        self.screen = pygame.display.set_mode(self.size)

        self.player = Player(self, "mario")
        self.bg = Background(self, self.player)

        go = LoopingCall(self.ticker)
        go.start(0.01)
        reactor.run()

    def ticker(self):
        pygame.event.get()
        self.player.tick()
        self.bg.tick()

        self.screen.fill((0, 0, 0))  # black
        self.screen.blit(self.bg.image, self.bg.rect)
        self.screen.blit(self.player.image, self.player.rect)
        pygame.display.flip()
예제 #33
0
	def __init__(self, main):
		self.main = main;
		self.highScores = [];
		self.highScoreDisplays = [];
		# populate the highscores and displays
		for i in range(0, 5):
			self.highScores.append(0);
			tScore = TextItem(400, 250 + i * 50, 400, 150, [str(i+1)+': ' + str(self.highScores[i])], showRect = False);
			self.highScoreDisplays.append(tScore);

		self.background_image = os.path.join('assets', 'startscreen', 'night_sunset_gradient.png');
		self.background = Background(self.background_image);
		self.menuBtn = Button(500, 600, 200, 75, 'Menu');
		self.playerScoreDisplay = TextItem(400, 100, 400, 150, [''], showRect = False, fontSize = 72);
예제 #34
0
파일: Screen.py 프로젝트: sifirib/no_clue
 def __init__(self, name, sizes, background_image, background_music,
              caption, icon):
     self.name = name
     self.x = self.y = 0
     self.width = sizes[0]
     self.height = sizes[1]
     self.screen = pygame.display.set_mode((self.width, self.height))
     self.background_image = background_image
     self.background = Background(self.screen)
     self.y2 = self.height  #self.background_image.get_height()
     self.x2 = self.width  #self.background_image.get_width()
     self.background_music = background_music
     self.caption = caption
     self.icon = icon
예제 #35
0
    def __init__(self):
        # Create the SpriteGroups for the platforms, enemies, and portal.
        self.platform_list = pygame.sprite.Group()
        self.enemy_list = pygame.sprite.Group()
        self.damaged_enemy_list = pygame.sprite.Group()
        # We make a portal list, even though there's only one portal per level, because it's a lot easier
        # to draw a SpriteGroup than a single Sprite.
        self.portal_list = pygame.sprite.Group()

        # Set the background.
        self.background = Background("Assets/background.png", -1600, -2000)

        # How far this world has been scrolled left/right and up/down. (Because the world moves offscreen,
        # we shift in the opposite direction from the player.)
        self.world_shift_x = 0
        self.world_shift_y = 0
예제 #36
0
def enter():
    global background, smallReplay, smallExit, bigReplay, bigExit, chooseExit, chooseReplay, cursor, crying, score
    background = Background()
    smallReplay = SmallReplay()
    smallExit = SmallExit()
    bigReplay = BigReplay()
    bigExit = BigExit()
    chooseExit = False
    chooseReplay = False
    cursor = Cursor()
    crying = Crying()
    score = Score()
    score.score = main_state.number.score
    game_world.clear()
    game_world.add_object(crying, 0)
    game_world.add_object(score, 0)
    game_world.add_object(cursor, 1)
예제 #37
0
    def reset(self):
        self.shakeScreen = resources.screen
        self.screen = self.shakeScreen.copy()
        resources.screen_copied = self.screen
        self.background = Background(self.screen)
        self.screenShaker = ScreenShaker()
        
        self.OPACITY = 250
        
        self.activeRegions = {}
        self.allPackages = {}
        self.allPackageNames = []
        self.allShields = []
        self.messages = []

        self.MAX_SHIP_HP = 100
        self.shipHp = 100
        self.MAX_SHIP_POWER = 1000
        self.ship_power = 1000
        self.ship_reload = 0
        self.SHIP_MAX_PROGRESS = 2000
        self.ship_progress = 0
        self.night_opacity = self.OPACITY

        #self.cannon_accuracy = 3
        
        self.console = Console.Console(self.screen)
        self.addMessage("Once upon a time, there was a woman named Wax Chug da Gwad. She had a solar powered ship. However, she was far from home and the solar panels sucked. And tentacle monsters appeared. Help Wax Chug get home.")
        
        resources.time = Time()
        self.time = resources.time
        #tells Time to call "toggleDay" when 6:00 happens
        self.time.setToggleDayListener(self, '6:00')
        self.day = False
        self.night = resources.all_sprites["night.png"]

        self.monsterList = MonsterList()

        self.initializePackages()
예제 #38
0
class Help(object):

    def __init__(self, main):
        self.main = main
        self.buttons = []
        self.background_image = os.path.join('assets', 'startscreen', 'night_sunset_gradient.png')
        self.background = Background(self.background_image)
        self.tutImage = Background('assets/tutorial-images/tut1.jpg',self.main.hcenter - 400, 50)
        self.menuBtn = Button(500, 750, 200, 75, 'Menu')
        self.backBtn = Button(300, 650, 200,75, 'Back')
        self.nextBtn = Button(700, 650, 200, 75, 'Next')
        self.currentScreen = 1
        # Help screen buttons
        self.buttons.append(self.menuBtn)
        self.buttons.append(self.nextBtn)
        self.buttons.append(self.backBtn)


    def listenForEvents(self):
        if 1 in pygame.mouse.get_pressed():
            #Help state buttos
            for button in self.buttons:
                if button.is_under(pygame.mouse.get_pos()):
                    print 'You clicked the ' + button.text + ' button'
                    if button == self.menuBtn:
                        self.main.set_mode('menu')
                    if button == self.nextBtn:
                        if self.currentScreen < 6:
                            self.currentScreen+=1
                            print(self.currentScreen)
                            filepath = 'assets/tutorial-images/tut'+str(self.currentScreen)+'.jpg'
                            print 'here'
                            self.tutImage.image = pygame.image.load(filepath)
                            self.tutImage.filename = filepath
                        else:
                            self.currentScreen = 6
                    elif button == self.backBtn:
                        self.currentScreen-=1
                        if self.currentScreen >= 1:
                            filepath = 'assets/tutorial-images/tut'+str(self.currentScreen)+'.jpg'
                            print 'here'
                            self.tutImage.image = pygame.image.load(filepath)
                            self.tutImage.filename = filepath
                        else:
                            self.currentScreen = 1
                            filepath = 'assets/tutorial-images/tut'+str(self.currentScreen)+'.jpg'
                            print 'here'
                            self.tutImage.image = pygame.image.load(filepath)
                            self.tutImage.filename = filepath

                    
                  

    def renderScreen(self):
        self.background.draw(self.main.screen)
        self.tutImage.draw(self.main.screen)
        if(self.currentScreen == 1):
            for button in self.buttons:
                if button != self.backBtn:
                    button.draw(self.main.screen)
        elif(self.currentScreen == 7):
            for button in self.buttons:
                if button != self.nextBtn:
                    button.draw(self.main.screen)
        else:
            for button in self.buttons:
                button.draw(self.main.screen)



    def enter(self):
        print("entered help screen")
예제 #39
0
파일: Game.py 프로젝트: nekocoder/Vault
class Game(object):

    def __init__(self, main):
        self.main = main
        self.buttons = []
        self.gameScreenUI = []
        self.currentAnswers = []
        self.level_loaded = False
        self.last_mousepressed = []
        self.levelWon = False
        self.failed_rocket = os.path.join('assets', 'rocket_down.png')
        self.launching_rocket = os.path.join('assets', 'rocket_launch.png')
        self.background_image = os.path.join('assets','Background.png')
        self.background = Background(self.background_image)
        self.background_rocket = Background(self.launching_rocket, 800, 675 - (self.main.currentLevel * 100))
        print 'currentLevel is ' + str(self.main.currentLevel)

        # Game playing screen buttons
        self.emptyBtn = Button(750, 725, 200, 75, 'Reset', (206, 148, 73), (109, 78, 38))
        self.menuBtn = Button(950, 725, 250, 75, 'Back to Menu', (202, 198, 82), (85, 83, 34))
        self.doneBtn = Button(915, 625, 250, 75, 'Check Answer', (7,208,226), (4,111,121))
        self.buttons.append(self.menuBtn)
        self.buttons.append(self.emptyBtn)
        self.buttons.append(self.doneBtn)

        # Game screen text elements
        self.scoreDisplay = TextItem(700, 0, 200, 75, ['Score: '], showRect = False)
        self.levelDisplay = TextItem(900, 0, 300, 75, ['Current Level: '], showRect = False)
        self.goalDisplay = TextItem(950, 240, 177, 60, ['Fill to: '], textColor= (255,255,255), showRect = False)
        self.feedback_width = 600
        self.feedback_height = 200
        self.feedback_x = (self.main.width / 2) - (self.feedback_width / 2)
        self.feedback_y = (self.main.height / 2) - (self.feedback_height / 2)
        self.gameScreenUI.append(self.goalDisplay)
        self.gameScreenUI.append(self.scoreDisplay)
        self.gameScreenUI.append(self.levelDisplay)
        self.winScreen = TextItem(self.feedback_x, self.feedback_y, self.feedback_width, self.feedback_height, ['Nice Job!', 'Click here to go on!'], (84, 194, 92), (39, 90, 43), True, Background(self.launching_rocket, self.feedback_x, self.feedback_y, self.feedback_width / 2, 100))
        self.winScreen.close()
        self.loseScreen = TextItem(self.feedback_x, self.feedback_y, self.feedback_width, self.feedback_height, ['Oops, that\'s not quite right.', 'Click here and try again.'], (209, 72, 72), (96, 33, 33), True, Background(self.failed_rocket, self.feedback_x, self.feedback_y, self.feedback_width / 2, 100))
        self.loseScreen.close()

        # Game screen elements
        self.goalContainer = Container(950, 300, 0, 1, 177, 259, False)
        self.goalFill = 1.0 #temporary goal fill amount #the number you are aiming for

        # Timer Bonus
        self.timer = 0;
        self.secondsTillNoBonus = 10; 
        

    def listenForEvents(self):
        if self.level_loaded and 1 in pygame.mouse.get_pressed()\
            and not (1 in self.last_mousepressed):
            for answer in self.currentAnswers:
                if answer.is_under(pygame.mouse.get_pos()):
                    print 'You clicked the ' + answer.text + ' answer'
                    answer.selected = not answer.selected
                    if answer.selected:
                        self.goalContainer.fill(self.goalContainer.filled+answer.filled)
                    else:
                        self.goalContainer.fill(self.goalContainer.filled-answer.filled)

            if self.winScreen.drawing == True and self.winScreen.is_under(pygame.mouse.get_pos()):
                self.winScreen.close()
                if(self.checkLevelExists(self.main.currentLevel + 1)):
                    self.main.currentLevel += 1
                    self.main.set_mode('play')
                else:
                    self.main.currentLevel = 0
                    self.main.set_mode('menu')
            if self.loseScreen.drawing == True and self.loseScreen.is_under(pygame.mouse.get_pos()):
                # close lose screen.
                self.loseScreen.close()

            #Play state buttons
            for button in self.buttons:
                if button.is_under(pygame.mouse.get_pos()):
                    print 'You clicked the ' + button.text + ' button'

                    #Menu button
                    if button == self.menuBtn:
                        self.main.set_mode('menu')

                    #Empty button
                    elif button == self.emptyBtn:
                        for answer in self.currentAnswers:
                            answer.selected = False
                        self.goalContainer.fill(0.0)

                    #Done button
                    #Evaluate the answer.
                    #Scores are increased with timer bonus
                    elif button == self.doneBtn:
                        if self.evaluateAnswer():
                            if self.levelWon != True:
                                self.winScreen.open()
                                self.levelWon = True
                                addition = 50;
                                timerBonus = self.timer + self.secondsTillNoBonus * 1000 - pygame.time.get_ticks();
                                if timerBonus < 0:
                                    timerBonus = 0;
                                #add the normalized timer bonus to addition of scores
                                addition += ( timerBonus / float( self.secondsTillNoBonus * 1000 ) ) * addition;
                                self.main.score = str(int(self.main.score) + int(addition))
                        else:
                            self.loseScreen.open()
                            print 'WRONG ANSWER'
        self.last_mousepressed = pygame.mouse.get_pressed()


    def renderScreen(self):
        self.main.screen.fill((206, 156, 60))
        self.background.draw(self.main.screen)
        self.background_rocket.draw(self.main.screen)
        self.goalContainer.draw(self.main.screen)
        for button in self.buttons:
            button.draw(self.main.screen)
        for answer in self.currentAnswers:
            answer.draw(self.main.screen)
        for item in self.gameScreenUI:
            item.draw(self.main.screen)
            if(self.winScreen.drawing == True):
                self.winScreen.draw(self.main.screen)
            if(self.loseScreen.drawing == True):
                self.loseScreen.draw(self.main.screen)
        if not self.level_loaded:
            self.main.screen.fill((0, 0, 0))



    #Load the level-th JSON file in the levels folder
    def loadLevel(self, level):
        print 'loading level'
        load_file = str(level) + '.json'
        path = os.path.join('assets/levels', load_file)
        try:
            with open(path) as level_file:
                level_data = json.load(level_file)
                self.currentAnswers = []
                self.arrangeAnswers(level_data["options"], 3, 75, 125, 225, 375)
                answer = level_data["answer"].split("/")
                self.goalFill = float(answer[0])/float(answer[1])
                self.goalDisplay.setText(["Fill to: "+answer[0]+"/"+answer[1]])
                print self.goalFill
                level_file.close()
                self.level_loaded = True
                self.background_rocket.y = 600 - (self.main.currentLevel * 50)
                self.levelDisplay.setText(["Current Level: " + str(self.main.currentLevel + 1)])
                self.scoreDisplay.setText((["Score: " + str(self.main.score)]))
        except IOError:
            new_game = open(path, 'w')
            new_game.close()

    def checkLevelExists(self, level):
        return os.path.exists(os.path.join('assets/levels', str(level) + '.json'))

    #Arrange passed-in answers array in a grid with sensible default options
    def arrangeAnswers(self, answers, perRow = 3, base_x = 100, \
                       base_y = 50, h_spacing = 200, v_spacing = 350):
        #Starting our counter variables at 1 to avoid an additional if block 
        #(because we can never divide by 0 this way)
        counter = 1
        currentRow = 1
        posInCurrentRow = -1 #Initialize current row position to -1 
                             #so first answer isn't offset incorrectly
        for answer in answers:
            answer = answer.split("/")#get numerator and denominator
            if(counter > currentRow * perRow):
                currentRow = currentRow + 1
                posInCurrentRow = 0
            else:
                posInCurrentRow = posInCurrentRow + 1
            answer_x = base_x + (h_spacing * posInCurrentRow)
            answer_y = base_y + ((currentRow - 1) * v_spacing)
            temp = Container(answer_x, answer_y, int(answer[0]), int(answer[1]))
            self.currentAnswers.append(temp)
            counter = counter + 1


    #Compare the main container's current filled percentage with the goal filled percentage
    def evaluateAnswer(self):
        #later we should have a more solid way to deal with float errors
        print str(round(self.goalContainer.filled, 5))+" == "+str(round(self.goalFill, 5))
        print round(self.goalContainer.filled, 5) == round(self.goalFill, 5)
        return round(self.goalContainer.filled, 5) == round(self.goalFill, 5)


    def enter(self):
        print("entered play state")
        self.levelWon = False
        self.loadLevel(self.main.currentLevel)
        self.goalContainer.fill(0)
        self.timer = pygame.time.get_ticks();
예제 #40
0
파일: Level.py 프로젝트: span/taxrunner
class Level():
    
    start_pos_y  = 600
    start_pos_x = 600
    bricks = 24
    
    # Loads and initiates the level
    def __init__(self, game):
        self.finished = False
        self.sprites = pygame.sprite.Group()
        self.surface = game.surface
        self.speed = game.speed
        self.surface_rect = self.surface.get_rect()
        self.center = (self.surface_rect.width / 2, self.surface_rect.height / 2)
        self.background = Background(self.speed)
        self.heightfactor = 0
        self.x = 0
        self.y = 0

        for i in range(0, self.bricks):
            self.x = i * Brick.width
            if i % 4 == 0:
                self.x += Brick.width / 2
                if self.heightfactor == 4:
                    self.heightfactor -= 2
                else:
                    self.heightfactor += 1
            self.y = self.start_pos_y - (50 * self.heightfactor)
            brick = Brick(self.x, self.y, self.speed, self.bricks)
            self.sprites.add(brick)
            
        self.green_cash = Cash(self.surface_rect.width, self.y - 70, self.speed, 'green')    
        self.receipt = Cash(self.surface_rect.width, self.y - 50, self.speed * 1.5, 'receipt')
        self.sprites.add(self.green_cash)
        self.sprites.add(self.receipt)
        self.player = Player(self.start_pos_x, 0, self.speed)
        self.taxman = TaxMan(50, 100, self.speed)
        self.sprites.add(self.taxman)
      
    # Updates the sprite positions 
    def update(self, up):
        self.background.update()
        self.sprites.update(self.surface)
        self.player.update(up)
        self.player.collide(self.sprites, self.surface)

        if self.player.rect.y > self.surface_rect.height:
            self.player.state = 'busted'
    
    # Draws the sprites  
    def draw(self):
        self.background.draw(self.surface)
        self.sprites.draw(self.surface)
        self.player.draw(self.surface)
        
        # If we hit some cash during the update phase, draw cash info to screen
        if self.receipt.state == 'collect':
            self.surface.blit(self.receipt.text, self.center)
        if self.green_cash.state == 'collect':
            self.surface.blit(self.green_cash.text, self.center)
        
    def get_score(self):
        return self.player.score.get_score()
    
    while not start:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RETURN or event.key == pygame.K_SPACE:
                    start = True
                    

        screen.blit(bgImage, bgRect)
        pygame.display.flip()
        clock.tick(60)

    st = time.time()
    bg = Background()
    score = Score(0,(12.5,12.5))
    #Start the Game
    while start and player.living:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            #Controls for player
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_w or event.key == pygame.K_UP:
                    player.direction("up")
                    
                if event.key == pygame.K_s or event.key == pygame.K_DOWN:
                    player.direction("down")
            
                if event.key == pygame.K_d or event.key == pygame.K_RIGHT:
예제 #42
0
class SceneHelp(SceneBasic):

    def __init__(self,screenSize):
        self.buttons = []
        self.background_image = os.path.join('assets', 'startscreen', 'night_sunset_gradient.png')
        self.background = Background(self.background_image)
        self.tutImage = Background('assets/tutorial-images/tut1.jpg',(0.05)*screenSize[0], .05*screenSize[1])
        self.menuBtn = Button(.41*screenSize[0], .83*screenSize[1], .16*screenSize[0], .08*screenSize[1], 'Menu')
        self.backBtn = Button(.25*screenSize[0], .72*screenSize[1], .16*screenSize[0],.08*screenSize[1], 'Back')
        self.nextBtn = Button(.58*screenSize[0], .72*screenSize[1], .16*screenSize[0], .08*screenSize[1], 'Next')
        self.currentScreen = 1
        # Help screen buttons
        self.buttons.append(self.menuBtn)
        self.buttons.append(self.nextBtn)
        self.buttons.append(self.backBtn)

        self.EVENT_MENU =[]
    
    def registerEvent_menu(self,e):self.EVENT_MENU.append(e)

    def listenForEvents(self):
        if 1 in pygame.mouse.get_pressed():
            #Help state buttos
            for button in self.buttons:
                if button.is_under(pygame.mouse.get_pos()):
                    print 'You clicked the ' + button.text + ' button'
                    if button == self.menuBtn:
                        self.helperRaiseEvent(self.EVENT_MENU)

                    if button == self.nextBtn:
                        if self.currentScreen < 6:
                            self.currentScreen+=1
                            print(self.currentScreen)
                            filepath = 'assets/tutorial-images/tut'+str(self.currentScreen)+'.jpg'
                            print 'here'
                            self.tutImage.image = pygame.image.load(filepath)
                            self.tutImage.filename = filepath
                        else:
                            self.currentScreen = 6
                    elif button == self.backBtn:
                        self.currentScreen-=1
                        if self.currentScreen >= 1:
                            filepath = 'assets/tutorial-images/tut'+str(self.currentScreen)+'.jpg'
                            print 'here'
                            self.tutImage.image = pygame.image.load(filepath)
                            self.tutImage.filename = filepath
                        else:
                            self.currentScreen = 1
                            filepath = 'assets/tutorial-images/tut'+str(self.currentScreen)+'.jpg'
                            print 'here'
                            self.tutImage.image = pygame.image.load(filepath)
                            self.tutImage.filename = filepath

                    
                  

    def renderScreen(self,screen):
        self.background.draw(screen)
        self.tutImage.draw(screen)
        if(self.currentScreen == 1):
            for button in self.buttons:
                if button != self.backBtn:
                    button.draw(screen)
        elif(self.currentScreen == 7):
            for button in self.buttons:
                if button != self.nextBtn:
                    button.draw(screen)
        else:
            for button in self.buttons:
                button.draw(screen)



    def EVENT_SCENE_START(self):
        print("entered help screen")
예제 #43
0
from ShaderTypes import ShaderTypes

counter = [None]*5
counter[0] = 0

DISPLAY = pi3d.Display.create(frames_per_second=30)

ShaderTypes()

mykeys = pi3d.Keyboard()

perspectiveCamera = pi3d.Camera(is_3d=True)
ortographicCamera = pi3d.Camera(is_3d=False)

box = GeometryTypeSimpleCube(perspectiveCamera)
background = Background(perspectiveCamera)

animation_state = AnimationState()
midground = Midground()

writeState = 0 # waiting / sliding in / blink-in / showing / blinkout / sliding out
startSlideInMs = 0
startBlinkInMS = 0
startShowInMS = 0
startBlinkOutMS = 0
startSlideOutMS = 0

while DISPLAY.loop_running():

  animation_state.updateTimeAndFrameCount()
  if (animation_state.frameCount % 10) == 0:
예제 #44
0
class Game:
    def reset(self):
        self.shakeScreen = resources.screen
        self.screen = self.shakeScreen.copy()
        resources.screen_copied = self.screen
        self.background = Background(self.screen)
        self.screenShaker = ScreenShaker()
        
        self.OPACITY = 250
        
        self.activeRegions = {}
        self.allPackages = {}
        self.allPackageNames = []
        self.allShields = []
        self.messages = []

        self.MAX_SHIP_HP = 100
        self.shipHp = 100
        self.MAX_SHIP_POWER = 1000
        self.ship_power = 1000
        self.ship_reload = 0
        self.SHIP_MAX_PROGRESS = 2000
        self.ship_progress = 0
        self.night_opacity = self.OPACITY

        #self.cannon_accuracy = 3
        
        self.console = Console.Console(self.screen)
        self.addMessage("Once upon a time, there was a woman named Wax Chug da Gwad. She had a solar powered ship. However, she was far from home and the solar panels sucked. And tentacle monsters appeared. Help Wax Chug get home.")
        
        resources.time = Time()
        self.time = resources.time
        #tells Time to call "toggleDay" when 6:00 happens
        self.time.setToggleDayListener(self, '6:00')
        self.day = False
        self.night = resources.all_sprites["night.png"]

        self.monsterList = MonsterList()

        self.initializePackages()

    def __init__(self):
        self.reset()

    def addPackage(self, name, compType, position):
        package = CompartmentPackage(self.screen, compType, position)
        self.allPackages[name] = package
        self.activeRegions[package.get_corners()] = name
        self.allPackageNames.append(name)
        if compType == "shield":
            self.allShields.append(name)

    def initializePackages(self):

        self.addPackage("Weapon 2", "weapon", (708, 470))
        self.addPackage("Weapon", "weapon", (588, 470))
        self.addPackage("Health", "health", (468, 500))
        self.addPackage("Shield 2", "shield", (228, 500))
        self.addPackage("Shield", "shield", (348, 500))
        self.addPackage("Engine", "engine", (108, 500))
        self.addPackage("Light", "light", (443, 375))

    def click(self, position):
        for region in self.activeRegions:
            x = position[0]
            y = position[1]
            if x < region[0][0]:
                continue
            if x > region[1][0]:
                continue
            if y < region[0][1]:
                continue
            if y > region[1][1]:
                continue
            name = self.activeRegions[region]
            #print(name+" selected :)")
            self.allPackages[name].compartment.toggleSelect()
            break
    
    def addMessage(self, customText, event=None):
        if event != None:
            self.messages.append(event[0], event[1], event[2], customText)
        else:
            self.messages.append([None, None, "Flavor", customText])
    
    def update(self):
        self.background.update()
        self.background.draw()
    
    
    
        # update stuff
        self.time.update()
        self.console.get_message(self.messages)
        
        if self.day:
            if (self.ship_power < self.MAX_SHIP_POWER):
                self.ship_power += 5.5
                if self.ship_power > self.MAX_SHIP_POWER:
                    self.ship_power = self.MAX_SHIP_POWER

        for name in self.allPackages:
            self.allPackages[name].update(name)

        self.night.set_alpha(self.night_opacity)

        self.monsterList.update()
        
        if self.ship_progress >= self.SHIP_MAX_PROGRESS:
            resources.state = "WIN"
            resources.sound_manager.playSound('win.ogg')

        elif self.shipHp <= 0:
            resources.state = "LOSE"
            resources.sound_manager.playSound('lose.ogg')

        # draw stuff
        for p in self.allPackages:
            if p != "Light":
                self.allPackages[p].draw()

        self.monsterList.draw()
        self.allPackages["Light"].draw()

        if self.ship_progress == self.SHIP_MAX_PROGRESS/2:
            self.addMessage("You're halfway home... You can do this.")
        
        if self.ship_power >= self.MAX_SHIP_POWER/2 -5 and self.ship_power <= self.MAX_SHIP_POWER/2 + 5:
            self.messages.append([None, None, "Flavor", "Your power is getting low. Be careful!"])
        
        self.console.draw()
        
        self.screenShaker.update()
        self.shakeScreen.blit(self.screen, self.screenShaker.getValue())

    def toggleDay(self):
        self.day = not self.day
        #if self.day:
         #   self.cannon_accuracy = 1
        #else:
        #    self.cannon_accuracy = 3
        #print("DAY" if self.day else "NIGHT")


    def enemyAttack(self, dmg):
        resources.sound_manager.playSound('tentacle.ogg')

        for shieldName in self.allShields:
            if self.allPackages[shieldName].compartment.active:
                self.screenShaker.shake()
                self.allPackages[shieldName].attacked(dmg* 3)
                self.affectShipHp(-dmg/3)
                for comp in self.allPackages:
                    if self.allPackages[comp].compartment.active == False and not self.allPackages[comp].compartment.currentlyDisabled:
                        self.allPackages[comp].compartment.currentlyDisabled = True
                        comp_type = self.allPackages[comp].compartment.compType
                        first_letter = comp_type[0].upper()
                        self.addMessage(first_letter + comp_type[1:] + " has been disabled.")
                return

        self.screenShaker.shake(6, 2000)

        if self.shipHp < self.MAX_SHIP_HP/2:
            self.addMessage("Your ship is in critical health.")

        self.affectShipHp(-dmg * 2)

         
        for name in self.allPackages:
            dmg += random.randint(-5, 5)
            self.allPackages[name].attacked(dmg)

        for comp in self.allPackages:
            if self.allPackages[comp].compartment.active == False and not self.allPackages[comp].compartment.currentlyDisabled:
                self.allPackages[comp].compartment.currentlyDisabled = True
                comp_type = self.allPackages[comp].compartment.compType
                first_letter = comp_type[0].upper()

                self.addMessage(first_letter + comp_type[1:] + " has been disabled.")
                
    def affectShipHp(self, value):
        self.shipHp += value
        self.shipHp = max(self.shipHp, 0)
        self.shipHp = min(self.MAX_SHIP_HP, self.shipHp)
        if self.shipHp <= 0:
            pass
            #print("You died")

    def cannonAttack(self, dmg):
        self.monsterList.attackOldestMonster(dmg)