Ejemplo n.º 1
0
        def start_game(self):
            try:

                if self.reRun:
                    if self.death_text != None:
                        self.Scen.removeItem(self.death_text)
                        self.death_text = None
                    if self.win_text != None:
                        self.Scen.removeItem(self.win_text)
                        self.win_text = None
                    self.test_player.setY(-60)
                    self.test_player = Player(self.player_specs)
                    self.backGround = Background(-1, -1, self.window_width + 1,
                                                 self.window_height + 1)
                    self.skyObject = self.backGround.skyObj
                    self.bottom_lava = Lava(-1, self.window_height - 50,
                                            self.window_width + 1, 51)
                    self.test_platform = Platform(0, 300,
                                                  self.window_width - 100, 40)
                    self.test_platform_2 = Platform(self.window_width - 50,
                                                    320, 100, 35)
                    self.init_game_screen()
                    self.completion = 0
                    self.goal_added = False

                self.view.setScene(self.scene)

                self.game_timer.start(10)
            except Exception as r:
                print('JJJJJJJJ')
Ejemplo n.º 2
0
class Interaction:
    def __init__(self, dimensions, kbd):  #,pearl, carol):
        self.lastFrameTime = time.time()
        self.dimensions = dimensions
        # self.perl = pearl
        # self.carol = carol
        self.back = Bg(dimensions)
        self.fish = School(30, (CANVAS_WIDTH, CANVAS_HEIGHT))
        self.player = Player(dimensions)
        self.keyboard = kbd

    def update(self):
        if self.player.inBounds():
            if self.keyboard.right:
                self.player.addVel(Vector(1, 0))
            elif self.keyboard.left:
                self.player.addVel(Vector(-1, 0))
        else:
            self.player.set()

    def draw(self, canvas):
        self.update()
        self.player.update()

        delta = time.time() - self.lastFrameTime
        self.lastFrameTime = time.time()
        self.back.draw(canvas)
        # self.carol.draw_canvas(canvas)
        # self.perl.draw_canvas(canvas)
        self.fish.draw(canvas, delta)
        self.player.draw(canvas)
Ejemplo n.º 3
0
def start_screen(screen):
    prompts = [
        "save some people", "solve global warming", "put out some fires",
        "save the cat on that tree"
    ]
    chosen_prompt = random.choice(prompts)

    picture_path = r'Images/screen.png'
    background = Background(screen, picture_path, speed=0.35, repeat=True)

    game_name = Message(screen, "Fire Pew Pew", (250, 0, 0), 100, size='big')
    start_prompt = Message(screen, f"Press 'SPACE' to {chosen_prompt}",
                           (250, 0, 0), -200)

    clock = pygame.time.Clock()

    interval = 0
    while True:
        for event in pygame.event.get():
            full_quit(event)

            if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                return

        background.update()
        game_name.show_message()
        interval = show_start_prompt(interval, start_prompt)

        pygame.display.flip()
        clock.tick(140)
Ejemplo n.º 4
0
    def __init__(self):
        BLACK = 0, 0, 0
        screenSize = (1024, 768)

        pygame.init()
        mainScreen = pygame.display.set_mode(screenSize)
        background = Background("images/TestMap.png", "DevMap", screenSize)
        player = background.player
        tilesX, tilesY = background.tileMap.shape

        while (True):
            for event in pygame.event.get():
                if event.type == pygame.QUIT: sys.exit()
                if event.type == pygame.KEYDOWN:
                    playerX, playerY = player.position
                    if event.key == pygame.K_UP:
                        if 0 <= playerY - 1: background.move(player, (0, -1))
                    if event.key == pygame.K_DOWN:
                        if playerY + 1 < tilesY:
                            background.move(player, (0, 1))
                    if event.key == pygame.K_RIGHT:
                        if playerX + 1 < tilesX:
                            background.move(player, (1, 0))
                    if event.key == pygame.K_LEFT:
                        if 0 <= playerX - 1: background.move(player, (-1, 0))

            mainScreen.fill(BLACK)
            mainScreen.blit(
                pygame.transform.scale(background.image, screenSize),
                background.rect)
            mainScreen.blit(player.image, player.rect)
            for npc in background.characterArray:
                mainScreen.blit(npc.image, npc.rect)

            pygame.display.flip()
    def __init__(self):
        with open("conf/filepaths.yaml") as filepath_config:
            self.conf = yaml.safe_load(filepath_config)
        self.sheet_stuff = utils.load_json(self.conf["CHARACTER_STATS_PATH"])
        self.all_items = utils.load_json(self.conf["ITEM_PATH"])
        self.clss = PlayerClass(
            self.sheet_stuff["saving_throws"],
            utils.load_json(self.conf["ITEM_PATH"]),
            *utils.select_random_from_json(self.conf["PLAYER_CLASS_PATH"]),
        )
        self.stats = sheet_maths.generate_stats()
        self.race = Race(
            *utils.select_random_from_json(self.conf["RACES_PATH"]))
        self.finalise_stats()
        self.mods = sheet_maths.generate_mods(self.stats)
        self.saves = sheet_maths.generate_saves(self.mods, self.clss.saves,
                                                self.clss.proficiency_bonus)
        self.weapons = self.finalise_weapons()
        self.bg = Background(
            *utils.select_random_from_json(self.conf["BACKGROUND_PATH"]))
        self.final_languages = self.select_languages()

        self.final_profs = self.select_profs()
        self.final_skills = self.select_skills()
        self.ac = self.finalise_ac()
        if "Perception" in self.final_skills:
            self.pp = self.mods["WISmod"] + self.clss.proficiency_bonus + 10
        else:
            self.pp = self.mods["WISmod"] + 10
Ejemplo n.º 6
0
 def backgroundChanged(self, dummyDeferredResult, dummyOldName, newName):
     """if the wanted background changed, apply the change now"""
     centralWidget = self.centralWidget()
     if centralWidget:
         self.background = Background(newName)
         self.background.setPalette(centralWidget)
         centralWidget.setAutoFillBackground(True)
Ejemplo n.º 7
0
 def __init__(self, width, height):
     self.mWidth = width
     self.mHeight = height
     self.mBackground = Background(width, height)
     self.mBall = Ball(width, height)
     self.mBars = []
     self.mBars.append(Bar(width, height))
     self.mBars[0].evolve()
     self.mScore = 0
     self.mGameStart = False
     self.mEZGame = False
     self.mEZText = Text("EZ MODE", self.mWidth / 2, 40)
     self.mGameStartTextTop = Text("Press 'W' to flap", self.mWidth / 2,
                                   self.mHeight / 3)
     self.mGameStartTextBot = Text("Press 'E' for EZ Mode", self.mWidth / 2,
                                   self.mHeight / 3 + 35)
     self.mScoreText = Text(str(self.mScore), self.mWidth / 10 - 20,
                            self.mHeight / 10 - 20)
     self.mGameOverTextTop = Text("GAME OVER NERD", self.mWidth / 2,
                                  self.mHeight / 3)
     self.mGameOverTextBot = Text("Press 'A' to play again",
                                  self.mWidth / 2, self.mHeight / 3 + 35)
     self.mGameOver = False
     self.mFlapSound = Sound("sounds/flap.wav")
     self.mPipeSound = Sound("sounds/pipe_sound.wav")
     self.mHitSound = Sound("sounds/hit.wav")
     self.mThemeSong = Sound("sounds/theme_song.wav")
     self.mThemePlaying = False
     self.mThemeSong.setVolume(.5)
     self.mWings = 0
     return
Ejemplo n.º 8
0
    def __init__(self):

        # sound buffer size decrease
        pygame.mixer.pre_init(44100, -16, 1, 512)
        pygame.init()
        pygame.mixer.init()
        pygame.display.set_caption("Space Shooter")
        self.screen = pygame.display.set_mode(
            (config.WIDTH, config.HEIGHT), pygame.HWSURFACE | pygame.DOUBLEBUF)
        self.clock = pygame.time.Clock()

        self.background = Background()

        self.init_explosion_images()

        self.score = 0
        self.power_up_rate = 0.9  # default value: 0.9

        # Float_Texts
        self.score_textes = []
        self.shield_bonus_textes = []

        # Sound init
        self.sound_handler = Sound_Handler()
        self.sound_laser = self.sound_handler.sounds["laser"][1]
        pygame.mixer.music.load(config.background_music)
        pygame.mixer.music.play(loops=-1)

        # Loop continuing conditions
        self.running = True
        self.gameover = True

        # Hiding cursor
        pygame.mouse.set_visible(False)
Ejemplo n.º 9
0
def OnMessageStatus(Message, Status):
    B = Background()
    Marker = ' ';
    if Message.IsEditable:
        Marker = '* ';
    if (Status == 'RECEIVED' or Status == 'SENT'):
        mP = rePlay.match(Message.Body)
        mV = reViel.match(Message.Body)
        if (mP):
            Message.Chat.SendMessage('Aber ich hab keine Lust '+mP.group(1)+' zu spielen.')
        elif (mV and Message.IsEditable):
            def repViel(m):
                print "repViel"
                x = re.sub("viel viel", "viel viel viel", m.Body)
                print "attempted viel viel replacement: " + x
                m.Body = x
            print "found viel viel"
            for i in range(7):
                print i
                B.runLater(2*i, lambda m: repViel(m), {'m':Message})
        elif (Message.Body == 'xyzzy'):
                B.runLater(2, lambda m: m.Chat.SendMessage(m.Body+"?"), {'m':Message})
        elif (Message.Body == '===='):
            Message.Chat.SendMessage('. \n\n\n\n----------------------------\n\n\n\n\n ... sooo weit bin ich noch nicht.')
    if Status == 'RECEIVED':
        print(Message.FromDisplayName + ': ' + Message.Body);
    elif Status == 'SENT':
        print('Myself:' + Marker + Message.Body);
    else:
        print(Message.FromDisplayName + '(' + Message.FromHandle + ')' + Status + ':' + Marker + Message.Body);
Ejemplo n.º 10
0
    def __init__(self):
        """constructor"""
        pygame.init()

        self.screen_width = 1300
        self.screen_height = 700
        pygame.display.set_caption('FloppyBird')
        self.screen = pygame.display.set_mode(
            (self.screen_width, self.screen_height))

        self.run = True
        self.jump = False
        self.debug = False

        self.pipegroup = pygame.sprite.Group()

        self.clock = pygame.time.Clock()
        self.bird = Bird(self.screen)
        self.background = Background(self.screen, self.screen_width)
        self.font = pygame.font.Font('freesansbold.ttf', 32)
        self.points = 0
        self.score = self.font.render(str(self.points), True, (0, 0, 0))
        self.score_rect = self.score.get_rect()
        self.score_rect.center = (self.screen_width // 2, 50)

        self.bird_grav = 4
        self.bird_max_grav = 8
        self.bird_jump_height = 15
        # pygame.display.set_icon(pygame.image.load())
        self.flopdabird()
Ejemplo n.º 11
0
 def __init__(self):
     self._running = True
     self.screen = pygame.display.set_mode((self.W, self.H))
     pygame.display.set_caption('Lovag')
     self.bg = Background(self.W, self.H, self.sizeFaktorX, self.sizeFaktorY)
     self.kn = Knight(self.W, self.H, self.sizeFaktorX, self.sizeFaktorY)
     self.clock = None
Ejemplo n.º 12
0
def main():
    os.environ['SDL_VIDEO_CENTERED'] = '1'

    pygame.init()

    pygame.display.set_caption('pyarcanoid')
    pygame.display.set_icon(pygame.image.load('assets/brick.png'))
    screen = pygame.display.set_mode(
        [settings.SCREEN_WIDTH, settings.SCREEN_HEIGHT])
    pygame_clock = pygame.time.Clock()

    background = Background(screen)
    game_controller = GameController(screen)

    running = True
    while running:
        pygame_clock.tick(60)
        screen.fill([0, 0, 0])
        background.update()
        game_controller.update()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    game_controller.pause = not game_controller.pause

        pygame.display.flip()

    pygame.quit()
Ejemplo n.º 13
0
def enter():
    global player, life, scoreLabel
    bg = Background()
    game_world.add_object(bg, game_world.layer_bg)
    player = Player()
    game_world.add_object(player, game_world.layer_player)
    life = Life()

    bg.target = player

    label = ui.Label("Score: 0", 35, get_canvas_height() - 55, 45, ui.FONT_2)
    label.color = (255, 127, 127)
    ui.labels.append(label)
    scoreLabel = label

    global highscore
    highscore = Highscore()

    global music_bg, wav_bomb, wav_item
    music_bg = load_music('background.mp3')
    wav_bomb = load_wav('explosion.wav')
    wav_item = load_wav('item.wav')

    game_world.isPaused = isPaused

    ready_game()

    global gameOverImage
    gameOverImage = load_image('game_over.png')
Ejemplo n.º 14
0
class Rules(object):
    """menu of the game"""
    def __init__(self, width, height):
        self.initAttr(width, height);

    def loadResource(self):
        self.headMark = pygame.image.load(getFilePath("separators.png"))

    def initAttr(self, width, height):
        self.width, self.height = width, height
        self.loadResource()
        self.background = Background((width, height))
        # 规则文字开始的位置
        offLine = 100
        offSet = 50
        self.content = []
        for content in RULES_CONTENT[0 : -1]:
            offLine += offSet
            self.content.append(Label(RULES_CONTENT_FONTS, content, (50, offLine), headMark = self.headMark))
        self.returnButton = TextButton(RULES_EXIT_FONTS, RULES_CONTENT[-1], (offSet, self.height - offSet), (255, 255, 255))

    def draw(self, screen):
        self.background.draw(screen)
        [content.draw(screen) for content in self.content]
        self.returnButton.draw(screen)
        pygame.display.flip()

    def clickListener(self):
        if (pygame.mouse.get_pressed()[0]):
            mousePos = pygame.mouse.get_pos()
            if self.returnButton.rect.collidepoint(mousePos):
                return STATE.menu
        return STATE.rules
Ejemplo n.º 15
0
class Settings(State, ScreenHandler):
    def __init__(self):
        super(Settings, self).__init__()
        #self.__sizetextures()
        self.gameobjects = []
        self.background_left = Background(config.width / 2, config.height)
        self.background_right = Background(config.width / 2, config.height)

    def update(self, dt):
        pass
        #width, height = self.screen.get_size()

    def isdone(self):
        return False

    def resize(self):
        pass
        #self.__sizetextures()

    def __sizetextures(self):
        width, height = self.screen.get_size()
        self.left_back_screen = self.back_screen.subsurface(
            0, 0, width / 2, height)
        self.right_back_screen = self.back_screen.subsurface(
            width / 2, 0, width / 2, height)
        self.background_left.resize_textures(width / 2, height)
        self.background_right.resize_textures(width / 2, height)
Ejemplo n.º 16
0
    def init_model(self):
        # 创建实例对象
        # 地图背景实例
        self.background = Background(0, 0, self.window, self.bg_image_path)
        # 敌机对象实例
        self.enemy1 = Enemy(random.randint(120,
                                           WINDOW_WIDTH - 120), 0, self.window,
                            "res/img-plane_%d.png" % random.randint(1, 7))
        self.enemy2 = Enemy(random.randint(120, WINDOW_WIDTH - 120),
                            random.randint(0, WINDOW_HEIGHT - 68), self.window,
                            "res/img-plane_%d.png" % random.randint(1, 7))
        self.enemy3 = Enemy(random.randint(120, WINDOW_WIDTH - 120),
                            random.randint(0, WINDOW_HEIGHT - 68), self.window,
                            "res/img-plane_%d.png" % random.randint(1, 7))
        self.enemy4 = Enemy(random.randint(120, WINDOW_WIDTH - 120),
                            random.randint(0, WINDOW_HEIGHT - 68), self.window,
                            "res/img-plane_%d.png" % random.randint(1, 7))
        self.enemy5 = Enemy(random.randint(120, WINDOW_WIDTH - 120),
                            random.randint(0, WINDOW_HEIGHT - 68), self.window,
                            "res/img-plane_%d.png" % random.randint(1, 7))
        self.enemy6 = Enemy(random.randint(120, WINDOW_WIDTH - 120),
                            random.randint(0, WINDOW_HEIGHT - 68), self.window,
                            "res/img-plane_%d.png" % random.randint(1, 7))
        global enemy_lis
        enemy_lis = [
            self.enemy1, self.enemy2, self.enemy3, self.enemy4, self.enemy5,
            self.enemy6
        ]
        self.enemy_lis = enemy_lis

        # 玩家飞机实例
        self.player = Plane(196, 660, self.window, self.hero_image_path,
                            self.enemy_lis)
Ejemplo n.º 17
0
def enter():
    gfw.world.init([
        'background', 'bullet', 'save', 'platform', 'spike', 'player', 'clear'
    ])

    global background, clear, bgm, victory, player, victory_time, play_bgm, play_clear

    play_bgm = 0
    play_clear = 0
    victory_time = 0

    player = Player()
    player.pos = 335, get_canvas_height()
    player.state = 5
    player.action = 1
    gfw.world.add(gfw.layer.player, player)

    background = Background('ending.png', player)
    gfw.world.add(gfw.layer.background, background)

    clear = Background('game_clear.png', player)
    clear.ch = 200
    clear.draw_pos = 0, 200

    stage_gen.load(game_object.resBM('../ending.txt'), True)
Ejemplo n.º 18
0
 def __init__(self):
     self.background = Background()
     self.shot = Fire()
     self.senary = Senary()
     self.trilha = pygame.mixer.Sound("sound\\trilha.wav")
     self.tiro = pygame.mixer.Sound('sound\\tiro.wav')
     self.porrada = pygame.mixer.Sound('sound\\porrada.wav')
     self.morreu = pygame.mixer.Sound('sound\\morreu.wav')
     self.trilha.play(-1)
     self.img = pygame.Surface((80,120))
     self.img = pygame.image.load('img\\joao1.png')
     self.imgS = pygame.image.load('img\\joao2.png')
     self.imgC = pygame.image.load('img\\joao1c.png')
     self.imgSC = pygame.image.load('img\\joao2c.png')
     self.img.set_colorkey((10,255,0),0)
     self.img.set_alpha(255,0)
     self.img2 = pygame.Surface((80,120))
     self.img2.set_colorkey((10,255,0),0)
     self.img2.set_alpha(255,0)
     self.pos = pygame.Rect((120,320,80,120))
     self.jump = 0
     self.jump_h = 11
     self.life = 5
     self.face = 1
     self.x = 0
     self.contx = 0
     self.step = 1
     self.score = 0
     self.moveActivedJump = 1 
     draw(self.img,(self.pos.left,self.pos.top))
     self.background.sky()
     self.drawLife()
Ejemplo n.º 19
0
	def _background(self):
		if self.__background is None:
			self.__background = pygame.Surface(self._screen().get_size())
			self.__background = self.__background.convert()
			bg = Background(self.__background)
			bg.fill()
		return self.__background
Ejemplo n.º 20
0
    def __init__(self, int_screen, filename=''):
        if not filename:
            filename = str(CFG().start_level)

        with open(path.join(CFG().path_levels, filename), 'r') as file:
            level = loads(file.read())

        self.int_screen = int_screen
        self.timer = 0
        self.enemies = Group()
        self.enemy_hold = False
        self.show_name = False

        self.starting = True
        self.ending = False

        self.text = Text(int_screen, CFG().font_main, 16, (255, 255, 255))

        self.layout = level['layout']
        self.background = Background(self.int_screen, GFX().background[level['background']],
                                     type=level['background_type'],
                                     use_stars=level['stars'],
                                     lenght=len(self.layout))
        self.story = Story(level['prestory'], level['poststory'], self.int_screen)
        self.next_level = level['nextlevel']
        self.name = level['name']
        self.music = level['music']
Ejemplo n.º 21
0
    def setup(self):
        """
        set up the initial conditions of the level
        """
        self.level += 1

        self.in_diolouge = False
        self.near_npc = None
        self.diolouge = None
        self.show_correct = False
        self.show_incorrect = False
        self.show_level = True
        self.lives = 3

        # Sprite lists
        self.list_of_sprite_lists = []
        self.player_list = None
        self.barrier_list = None
        self.npc_list = None
        self.hazard_list = None
        self.objective_list = None
        self.player = None
        self.objective = None

        self.list_of_backgrounds = []
        self.background1 = Background(0)
        self.background1.texture = arcade.load_texture(
            "Images/Game_Background.png")
        self.list_of_backgrounds.append(self.background1)
        self.background2 = Background(1 * BACKGROUND_WIDTH)
        self.background2.texture = arcade.load_texture(
            "Images/Game_Background_Flipped.png")
        self.list_of_backgrounds.append(self.background2)
        self.background3 = Background(2 * BACKGROUND_WIDTH)
        self.background3.texture = arcade.load_texture(
            "Images/Game_Background.png")
        self.list_of_backgrounds.append(self.background3)

        # Initialize the sprite lists and add them to the list of sprite lists
        self.player_list = arcade.SpriteList()
        self.barrier_list = arcade.SpriteList()
        self.wall_list = arcade.SpriteList()
        self.npc_list = arcade.SpriteList()
        self.hazard_list = arcade.SpriteList()
        self.objective_list = arcade.SpriteList()
        self.list_of_sprite_lists.append(self.player_list)
        self.list_of_sprite_lists.append(self.wall_list)
        self.list_of_sprite_lists.append(self.npc_list)
        self.list_of_sprite_lists.append(self.hazard_list)
        self.list_of_sprite_lists.append(self.objective_list)

        self.createMap(LEVEL_TEMPLATES[self.level])

        self.physics_engine = PhysicsEngine(
            self.player,
            GRAVITY,
            FRICTION,
            DRAG,
            max_move_speed=PLAYER_MAX_MOVEMENT_SPEED)
Ejemplo n.º 22
0
    def loop(self):

        # criando pessoas
        self.create_person()

        self.infecteds.draw(self.screen)
        self.healthy.draw(self.screen)

        clock = pygame.time.Clock()

        chart_report = pygame.sprite.RenderPlain(ChartReport())

        while self.run:

            # criando o fundo
            self.background = Background()
            self.background.draw()

            # Manipulando eventos
            self.handle_events()

            # Atualiza Elementos
            self.healthy.update()
            self.infecteds.update()
            self.after_sick.update()

            collision = pygame.sprite.groupcollide(self.healthy,
                                                   self.infecteds, False,
                                                   False)

            # verifico se houve encontro entre pessoas
            # saudáveis e pessoas contaminadas
            for p in collision:
                if p.get_status() == StatusHealth.healthy:
                    p.set_status(StatusHealth.contaminated)
                    p.draw()
                    self.healthy.remove(p)
                    self.infecteds.add(p)

            # verifico se alguém que estava doente
            # se recuperou ou morreu
            for p in self.infecteds:
                if p.get_status() in [
                        StatusHealth.recovered, StatusHealth.dead
                ]:
                    self.infecteds.remove(p)
                    self.after_sick.add(p)

            # desenho as pessoas em suas novas posicoes e status
            self.infecteds.draw(self.screen)
            self.healthy.draw(self.screen)
            self.after_sick.draw(self.screen)

            # atualizo graficos
            chart_report.update()
            chart_report.draw(self.screen)
            pygame.display.flip()

            clock.tick(20)
Ejemplo n.º 23
0
def check_background_top_edge(ai_settings, screen, backgrounds):
	"""检查背景图顶端是否过了边缘"""
	for background in backgrounds.sprites():
		if background.rect.top == 0:
			background = Background(ai_settings, screen)
			background.y = 0 - background.rect.height
			background.rect.y = background.y
			backgrounds.add(background)	
Ejemplo n.º 24
0
 def initElement(self):
     # 背景
     self.background = Background((self.width, self.height))
     backgroundColor = GAME["GAME_BACKGROUND_COLOR"]
     self.background.setColor(backgroundColor)
     # 返回按钮
     self.returnButton = TextButton(GAME["RETURN_BUTTON_FONTS"],
                                    GAME["RETURN_BUTTON_CONTENT"], (30, 30))
Ejemplo n.º 25
0
class World:
    def __init__(self, app):
        self.app = app
        self.enemy_list = []
        self.width = 640
        self.height = 480
        self.player = Player(self, 225, 85, 15, 15)
        self.background = Background(self, pygame.image.load('assets/background_image.png'))
        self.door = Door(self,self.background, 0, 150)
        self.door_2 = Door(self,self.background,0,50)
        self.npc = None
        self.protectable_item = ProtectableItem(self,app,150,150, 'assets/cake.png')
        self.score_display = ScoreDisplay(self)
        window_size = SCREEN_WIDTH, SCREEN_HEIGHT = 320,240
        self.screen = pygame.display.set_mode(window_size,RESIZABLE)
        self.surface = pygame.Surface(self.screen.get_size())
        self.surface = self.surface.convert()
        self.fpsClock=pygame.time.Clock()


    def update(self):
        self.player.update()
        self.player.Interacting(self.npc)
        if self.door.check_door_touching(self.player):
            for enemy_number in range(0,1):
                PlayerAttacker(self, 50, 50,  pygame.image.load('assets/demon1.png'))
                itemAttacker(self, 10, 10,  pygame.image.load('assets/demon1.png'))



        #self.door.check_door_touching(self.player)
        self.player.Interacting(self.npc)
        for this_enemy in self.enemy_list:
            this_enemy.update()
        if self.npc != None:
            self.npc.update()

    def draw(self):
        self.surface.fill((0, 0, 0)) # clear screen (Paint it all white)
        self.background.draw(self.surface)
        self.player.draw(self.surface)
        self.protectable_item.draw(self.surface)
        self.score_display.draw()
        if self.npc != None:
            self.npc.draw(self.surface)
        for this_enemy in self.enemy_list:
            this_enemy.draw(self.surface)
            this_enemy.draw(self.surface)
        self.door.draw(self.surface)

        self.screen.blit(self.surface, (0,0)) # this might be what was missing
        pygame.display.update() #  Actually do all the stuff? (Not actually sure what this does... but I think it should be called at the end of the drawing step)
        FPS = 30
        self.fpsClock.tick(FPS)

    def change_location(self, background_image):
        self.background.change_image(background_image)
        self.npc = NonPlayer(self, pygame.image.load('assets/npc_32x32.png'))
Ejemplo n.º 26
0
    def __init__(self, settings, screen, clock, containers, fonts):
        """Initialise the setting page's layout and UI elements."""

        self.ui_manager = gui.UIManager(settings.screen_size)

        # shared state with main menu
        self.settings = settings
        self.screen = screen
        self.clock = clock
        self.background = Background(settings, screen)
        self.containers = containers

        color = pygame.Color(249, 126, 5)
        # render text labels, not drawn yet. These are non-pygame_gui.
        self.labels = {
            'title':
            fonts['large'].render('Settings', color)[0],
            #'rows': fonts['small'].render('Number of rows:', color)[0],
            'rows':
            fonts['small'].render('Board size:', color)[0],
            #'cols': fonts['small'].render('Number of columns:', color)[0],
            'coins':
            fonts['small'].render('Number of coins needed to win:', color)[0],
        }

        # slightly magical, but not tied to program logic: purely for layout
        self.input_size = (0.5 * screen.get_width(), 50)
        self.input_vspace = 50
        self.input_col_ratio = 0.8

        # initialise "settings menu"-specific element layout
        self.input_rects = self.init_input_rects()

        # create menu elements, these will be drawn every frame
        # for n_rows, n_cols, and connect_num allow numbers 1 to 99,
        # 0 will lead to no-op when saved
        self.rows_input = gui.elements.ui_text_entry_line.UITextEntryLine(
            relative_rect=self.input_rects['rows'][1], manager=self.ui_manager)
        self.rows_input.set_allowed_characters('numbers')
        self.rows_input.set_text_length_limit(limit=2)
        self.rows_input.set_text(str(settings.n_rows))

        self.coins_input = gui.elements.ui_text_entry_line.UITextEntryLine(
            relative_rect=self.input_rects['coins'][1],
            manager=self.ui_manager)
        self.coins_input.set_allowed_characters('numbers')
        self.coins_input.set_text_length_limit(limit=2)
        self.coins_input.set_text(str(settings.connect_num))

        self.save_button = gui.elements.UIButton(
            relative_rect=containers['bottomleft'],
            text='Save changes',
            manager=self.ui_manager)

        self.back_button = gui.elements.UIButton(
            relative_rect=containers['bottomright'],
            text='Back to menu',
            manager=self.ui_manager)
Ejemplo n.º 27
0
    def reset(self):
        self.y_offset = 0
        self.player = Player(self)
        self.walls = Walls(self)
        self.slice = Slice(self)
        self.enemies = [
            TutorialEnemy(self, y=c.WINDOW_HEIGHT / 2, x=c.MIDDLE_X)
        ]
        self.enemies[0].angle = 0
        self.update_enemies(0, [])
        self.particles = []
        self.text_particles = []
        self.background = Background(self)
        self.player.velocity = (100, 600)
        self.aiming = False
        self.aimingness = 0

        self.score_yoff = 50
        self.score_size = 40
        self.target_score_size = 40
        self.score_bumped = True

        self.shade = pygame.Surface(c.WINDOW_SIZE)
        self.shade.fill(c.BLACK)
        self.shade.set_alpha(0)

        self.shade_2 = pygame.Surface(c.WINDOW_SIZE)
        self.shade.fill(c.BLACK)
        self.shade_2.set_alpha(0)

        self.shade_3 = pygame.Surface(c.WINDOW_SIZE)
        self.shade.fill(c.BLACK)
        self.shade_3.set_alpha(255)

        self.flare = pygame.Surface(c.WINDOW_SIZE)
        self.flare.fill((255, 226, 140))
        self.flare.set_alpha(0)
        self.flare_alpha = 0

        self.multiplier = 1

        self.queue_reset = False

        self.game_end = False

        self.retry_button.visible = False
        self.submit_button.visible = False
        self.closing = False
        self.freeze_surf = None

        for button in self.buttons:
            button.disabled = False

        self.error_message = ""
        self.tutorial = True
        self.tutorial_offset = 0
Ejemplo n.º 28
0
    def setup(self):
        """Set up the game"""
        # set the default state
        self.state_change = False
        self.state = GameStates.MAIN_MENU

        # setup the background
        self.background = Background()
        self.background.center_x = SCREEN_WIDTH / 2
        self.background.center_y = SCREEN_HEIGHT / 2

        # setup the main menu
        self.main_menu = MainMenu()
        self.main_menu.center_x = SCREEN_WIDTH / 2
        self.main_menu.center_y = SCREEN_HEIGHT / 2

        # setup the pause menu
        self.pause_menu = PauseMenu()
        self.pause_menu.center_x = SCREEN_WIDTH / 2
        self.pause_menu.center_y = SCREEN_HEIGHT / 2

        # setup the game over screen
        self.game_over_screen = GameOverMenu()
        self.game_over_screen.center_x = SCREEN_WIDTH / 2
        self.game_over_screen.center_y = SCREEN_HEIGHT / 2

        # setup the highscores
        self.load_scores()

        # setup the scoreboard
        self.score_board = ScoreBoard()
        self.score_board.center_x = SCREEN_WIDTH / 2
        self.score_board.center_y = SCREEN_HEIGHT / 2

        # setup the player
        self.player = Player()
        self.player.center_x = SCREEN_WIDTH / 2
        self.player.center_y = SCREEN_HEIGHT / 2

        # setup the creatures
        self.all_creature_sprites_list = arcade.SpriteList()
        for i in range(self.current_creature_amount):
            rand = random.randint(1, 2)
            if rand == 1:
                creature = Moth()
            elif rand == 2:
                creature = Bug()
            creature.setup()
            self.all_creature_sprites_list.append(creature)

        # setup the obstacles
        self.all_obstacle_sprite_list = arcade.SpriteList()
        for i in range(MAX_OBSTACLE_COUNT):
            obstacle = Obstacle()
            obstacle.setup()
            self.all_obstacle_sprite_list.append(obstacle)
Ejemplo n.º 29
0
 def __init__(self, width, height):
     pygame.init()
     self._surface = pygame.display.set_mode((width, height))
     self._surface.fill((255., 255., 255.))
     self._bgr = Background(width, height)
     self._player = Player([width / 2., height - 100.], [0., 0.])
     self._effects = []  # e.g. bullets, explosions, power-ups, etc
     self._units = [self._player]  # 'physical' objects, e.g. can collide
     self._width = width
     self._height = height
Ejemplo n.º 30
0
class TestSort(unittest.TestCase):
    def setUp(self):
        r_file = File()
        self.bg = Background(r_file.ruleData[0])

    def testCkChagne(self):
        self.assertFalse(self.bg.ckChange())

    def testBg_move(self):
        self.assertTrue(self.bg.bg_move())
    def __init__(self):
        self._running = True
        self.clock = None

        # Select a world (EARTH, JUPITER, MOON):
        self.current_world = self.worlds[0]

        self.background = Background(640, 400)
        self.hero = Hero(self.current_world, self.background.boundaries)
        self.enemy = Enemy(self.hero, self.background)
Ejemplo n.º 32
0
    def __create_sprites(self):

        # 创建背景精灵和精灵组
        bg1 = Background(False)
        bg2 = Background(True)
        self.back_group = pygame.sprite.Group(bg1, bg2)
        # 创建敌机的精灵组
        self.enemy_group = pygame.sprite.Group()
        # 创建英雄精灵和精灵组
        self.hero = Hero()
        self.hero_group = pygame.sprite.Group(self.hero)
Ejemplo n.º 33
0
    def __init__(self):
        super().__init__()
        """
        set all initial conditions to null values to clear the way for a new game
        """
        self.level = -1
        self.questions_wrong = 0
        self.counter = 0
        self.in_diolouge = False
        self.near_npc = None
        self.diolouge = None
        self.show_correct = False
        self.show_incorrect = False
        self.show_level = False

        self.list_of_backgrounds = []
        self.background1 = Background(0)
        self.background1.texture = arcade.load_texture(
            "Images/Game_Background.png")
        self.list_of_backgrounds.append(self.background1)
        self.background2 = Background(1 * BACKGROUND_WIDTH)
        self.background2.texture = arcade.load_texture(
            "Images/Game_Background_Flipped.png")
        self.list_of_backgrounds.append(self.background2)
        self.background3 = Background(2 * BACKGROUND_WIDTH)
        self.background3.texture = arcade.load_texture(
            "Images/Game_Background.png")
        self.list_of_backgrounds.append(self.background3)

        # Sprite lists
        self.list_of_sprite_lists = []
        self.player_list = None
        self.barrier_list = None
        self.npc_list = None
        self.hazard_list = None
        self.objective_list = None
        self.player = None
        self.objective = None

        # For background music
        self.music_player = None
        self.music = None

        # Textures
        self.diolouge_box_texture = arcade.load_texture("Images/text_box.png")

        # Keyboard keys
        self.left_pressed = False
        self.right_pressed = False
        self.up_pressed = False
        self.down_pressed = False
        self.interact_pressed = False

        self.playSong()
Ejemplo n.º 34
0
 def backgroundChanged(self, dummyDeferredResult, dummyOldName, newName):
     """if the wanted background changed, apply the change now"""
     centralWidget = self.centralWidget()
     if centralWidget:
         self.background = Background(newName)
         self.background.setPalette(centralWidget)
         centralWidget.setAutoFillBackground(True)
Ejemplo n.º 35
0
 def entities(self):
     self.label = pyglet.text.Label('Hello, world',
                                    font_name = 'Times New Roman',
                                    font_size = 36,
                                    x = self.width/2, y = self.height/2,
                                    anchor_x = 'center', anchor_y = 'center')
     self.panel = Panel((self.width,self.height))
     self.background = Background((self.width,self.height),self.panel.size)
     self.background.pos = [self.mapsize[0] / 2, self.mapsize[1] / 2]
     self.background.populate()
     self.bgcheck = 1
     self.player = player.Player((self.width,self.height),self.panel.size)
     self.player.name = self.name
     self.player.idnum = self.idnum
     self.player.location[0] = self.startsystem
     self.spritelist = [self.player.sprite]
     self.visible_size = (self.background.x,self.background.y)
     self.systemdict = MakeSystemDict("data/systems/systems.list",self.player.pos,self.center,self.visible_size)
     self.systemdict.get(self.startsystem.name).update(self.startsystem)
     self.systemdict.get(self.startsystem.name).active = 1
     self.system = self.systemdict.get(self.startsystem.name)
     self.selectedsystem = None
     self.activesystem = self.system.name
     self.linkdict = MakeLinks(self.systemdict)
     print "LINKDICT: " + str(self.linkdict)
     self.menudialogue = MenuDialogue((self.width,self.height))
     self.optionsdialogue = OptionsDialogue((self.width,self.height))
     self.controlsdialogue = ControlsDialogue((self.width,self.height))
     self.dockdialogue = DockDialogue((self.width,self.height))           
     self.mapdialogue = MapDialogue((self.width, self.height))
     self.mapdialogue.active = self.activesystem
Ejemplo n.º 36
0
    def promptUserForPin():
        userHasAccess = True

        # Set the background
        background = Background.createBackground()
        if background is not None:
            background.show()

        # Prompt the user to enter the pin
        numberpad = NumberPad.createNumberPad()
        numberpad.doModal()

        # Remove the background if we had one
        if background is not None:
            background.close()
            del background

        # Get the code that the user entered
        enteredPin = numberpad.getPin()
        del numberpad

        # Check to see if the pin entered is correct
        if Settings.isPinCorrect(enteredPin):
            log("PinSentry: Pin entered Correctly")
            userHasAccess = True
            # Check if we are allowed to cache the pin level
            PinSentry.setCachedPinLevel(1)
        else:
            log("PinSentry: Incorrect Pin Value Entered")
            userHasAccess = False

        return userHasAccess
Ejemplo n.º 37
0
 def open(self):
     init_analysis(self.main_window)
     self.main_window.analysis_next_btn.setEnabled(True)
     if self.source.media == 'file':
         self.source.base_name = get_base_file(self.file) 
         self.source.analysis_frames = cv2.VideoCapture(self.file)
     if self.source.media == 'camera':
         init_analysis_camera(self.main_window)
         print("Setting analysis frames for camera")
         # release camera resource for analysis
         self.source.setup_frames.release()
         self.source.analysis_frames = cv2.VideoCapture(config['camera'])
     # images folder
     directory = 'images/' + self.source.base_name
     create_dir(directory) 
     self.get_video()
     if self.source.media == 'file':
         self.setup.load_video(self.video.id)
     self.background = Background(self.source) 
     self.background.get_db(self.video.id)
     self.source.background = self.background
     self.polygon = Polygon(self.source, self.setup) 
     self.polygon.get_points(self.video.id)
     self.polygon.draw_setup(self.background.frame, self.polygon.points)
     self.source.polygon = self.polygon
     self.play = Play(self.source, self.setup)
     self.play.run_analysis()
     # set location
     self.location.set_location(self.video.address_id)
     # play
     self.click_analysis_play_btn()
Ejemplo n.º 38
0
 def initElement(self):
     # 背景
     self.background = Background((self.width, self.height))
     backgroundColor = GAME["GAME_BACKGROUND_COLOR"]
     self.background.setColor(backgroundColor)
     # 返回按钮
     self.returnButton = TextButton(GAME["RETURN_BUTTON_FONTS"], GAME["RETURN_BUTTON_CONTENT"], (30, 30))
Ejemplo n.º 39
0
    def __init__(self, dt=0.1, auto_dt=False):
        """
        Class constructor
        """

        self.background = Background()
        # check width and height
        ret, cap = self.background.capture.read()
        height, width, channels = np.array(cap).shape

        self.render = vtk.vtkRenderer()
        self.render.SetLayer(2)

        # self.camera = vtk.vtkCamera()
        # self.camera.SetPosition(-10, 0, 0)
        # self.camera.SetFocalPoint(0, 0, 0)
        # self.render.SetActiveCamera(self.camera)
        # self.render.ResetCamera()

        self.render_window = vtk.vtkRenderWindow()
        self.render_window.SetNumberOfLayers(3)
        self.render_window.SetSize(width, height)
        self.render_window.AddRenderer(self.background.render)
        self.render_window.AddRenderer(self.render)

        self.t = 0
        self.dt = dt
        self.auto_dt = auto_dt

        self.actors = []
Ejemplo n.º 40
0
    def __init__(self, parent, rows=1, cols=7):
        super(Gtk.DrawingArea, self).__init__()

        self.par = parent
        self.num_rows = rows
        self.num_columns = cols
        self.background = Background(rows, cols)

        self.padding = 1.5
        self.font = "Courier"
        self.font_size = 12
        self.font_color = (0.35, 0.31, 0.24)
        self.link_color = (0, 0, 255, 0.5)  # default blue link color
        self.today_cell = (None, None)
        self.selected_task = None
        self.faded_cells = []
        self.cells = []
        self.labels = None
        self.label_height = self.font_size
        self.overflow_links = []

        self.connect("draw", self.draw)

        # drag-and-drop signals and events
        self.add_events(Gdk.EventMask.BUTTON_PRESS_MASK
                        | Gdk.EventMask.BUTTON_RELEASE_MASK
                        | Gdk.EventMask.BUTTON1_MOTION_MASK
                        | Gdk.EventMask.POINTER_MOTION_MASK)
Ejemplo n.º 41
0
 def __init__(self):
     self.background = Background()
     self.shot = Fire()
     self.senary = Senary()
     self.trilha = pygame.mixer.Sound(os.path.join("sound","trilha.wav"))
     self.tiro = pygame.mixer.Sound(os.path.join("sound",'tiro.wav'))
     self.porrada = pygame.mixer.Sound(os.path.join("sound",'porrada.wav'))
     self.morreu = pygame.mixer.Sound(os.path.join("sound",'morreu.wav'))
     self.trilha.play(-1)
     self.img = pygame.Surface((80,120))
     self.img = pygame.image.load(os.path.join("img",'joao1.png'))
     self.imgS = pygame.image.load(os.path.join("img",'joao2.png'))
     self.imgC = pygame.image.load(os.path.join("img",'joao1c.png'))
     self.imgSC = pygame.image.load(os.path.join("img",'joao2c.png'))
     self.img.set_colorkey((10,255,0),0)
     self.img.set_alpha(255,0)
     self.img2 = pygame.Surface((80,120))
     self.img2.set_colorkey((10,255,0),0)
     self.img2.set_alpha(255,0)
     self.pos = pygame.Rect((120,320,80,120))
     self.jump = 0
     self.jump_h = 11
     self.life = 5
     self.face = 1
     self.x = 0
     self.contx = 0
     self.step = 1
     self.score = 0
     self.moveActivedJump = 1 
     draw(self.img,(self.pos.left,self.pos.top))
     self.background.sky()
     self.drawLife()
Ejemplo n.º 42
0
Archivo: game.py Proyecto: Nebual/spad
	def __init__(self, *args, **kwargs):
		super(GameWindow, self).__init__(*args, **kwargs)
		
		self.mainBatch = pyglet.graphics.Batch() #"Misc" drawables
		self.hudBatch = pyglet.graphics.Batch() #Drawn after everything

		self.background = Background()
		self.playerShip = physicalobject.Player(x=0, y=0)
				
		
		self.push_handlers(self.playerShip.keyHandler)

		self.paused = False
		self.camera = Vector(0,0)

		#Basically targetting either 1920x1080 (and 1920x1200) at 1, or 1366x768 ish at 0.5
		self.uiScale = 1
		if self.width < 1400 or self.height < 800: self.uiScale = 0.5
		
		self.hud = hud.HUD(window=self, batch=self.hudBatch)
		
		self.currentSystem = solarsystem.SolarSystem(x=0, y=0, seed=0)
		self.currentSystem.ships.append(self.playerShip)
		components.init()
	
		pyglet.clock.schedule_interval(self.update, 1/60.0)
Ejemplo n.º 43
0
    def __init__(self, file_name):
        pygame.init()
        self.display_surf = pygame.display.set_mode((WINDOW_SIZE_X, WINDOW_SIZE_Y), 0, 32)
        pygame.display.set_caption("Dinosaurs Evolved")

        self.change = False  # Used to see if the board needs to be redrawn
        self.down_keys = Set()  # The keys that the user is currently holding down
        self.player = Player()
        self.background = Background(file_name)
        self.loop()
Ejemplo n.º 44
0
class TheApp(cocos.layer.Layer):
    # If you want that your layer receives events
    # you must set this variable to 'True',
    # otherwise it won't receive any event.
    is_event_handler = True

    def __init__(self):
        super(TheApp, self).__init__()

        self.image = pyglet.resource.image('terrain_4.png')
        self._background = Background()
        self._objects = []
        enemy = Enemy()
        self._objects.append(enemy)
        self._player = Player()
        self._objects.append(self._player)
        # call the "step" method every frame when the layer is active
        self.schedule(self.step)

    def on_enter(self):
        super(TheApp, self).on_enter()
        self._background.init()
        for ob in self._objects:
            ob.init()

    def draw(self):
        super(TheApp, self).draw()
        self._background.draw()
        for ob in self._objects:
            ob.draw()

    def step(self, dt):
        for ob in self._objects:
            ob.update(dt)

    def on_key_press(self, symbol, modifiers):
        if symbol == key.RIGHT:
            self._player.setXVelocity(10)
        if symbol == key.LEFT:
            self._player.setXVelocity(-10)

    def on_key_release(self, key, modifiers):
        self._player.setXVelocity(0)
Ejemplo n.º 45
0
    def __init__(self, cols=7):
        super(Header, self).__init__()
        self.labels = []
        self.background = Background(1, cols)
        self.sidebar = 0
        self.font = "Courier"
        self.font_size = 12
        self.font_color = (0.35, 0.31, 0.24)
        self.highlight_cell = (None, None)

        self.connect("draw", self.draw)
Ejemplo n.º 46
0
    def initialise(self):
        """this function is called when the program starts.
           it initializes everything it needs, then runs in
           a loop until the function returns."""
        #Initialize Everything
        pygame.init()
        self.screen = pygame.display.set_mode((640, 480))
        pygame.display.set_caption('VacuumFire')
        pygame.mouse.set_visible(0)
        #icon
        icon, foo = utils.load_image('icon.png')
        pygame.display.set_icon(icon)

        self.game_paused = False
        #sounds
        self.sounds = {};
        self.sounds['music'] = utils.load_sound('archivo.ogg')
        self.sounds['warning'] = utils.load_sound('warning.wav')
        self.sounds['powerup'] = utils.load_sound('powerup.wav')
        self.sounds['music'].play()
        #Create The Backgound
        self.background = Background(self.screen.get_size())
        #game variables
        self.score = 0
        #Display The Background
        self.screen.blit(self.background, (0, 0))
        pygame.display.flip()


        #The player's ship
        self.ship = Ship()
        #The player's ship
        self.lifemeter = LifeMeter()
        self.player    = pygame.sprite.RenderPlain((self.ship))
        #group that stores all enemies
        self.enemies    = pygame.sprite.Group()
        #group that stores all powerups
        self.powerups    = pygame.sprite.Group()
        #group that stores all the lasers the player shoots
        self.fire        = pygame.sprite.Group()
        #group for information sprites in the screen, should be rendered the last one
        self.hud         = pygame.sprite.Group()
        self.explosions  = pygame.sprite.Group()
        self.hud.add(self.lifemeter)
        #The level
        self.level = Stage('level_1')
        self.font = utils.load_font('4114blasterc.ttf', 36)


        self.clock = pygame.time.Clock()

        self.game_started = False
        self.game_finished = False
Ejemplo n.º 47
0
    def __init__(self):
        super(TheApp, self).__init__()

        self.image = pyglet.resource.image('terrain_4.png')
        self._background = Background()
        self._objects = []
        enemy = Enemy()
        self._objects.append(enemy)
        self._player = Player()
        self._objects.append(self._player)
        # call the "step" method every frame when the layer is active
        self.schedule(self.step)
Ejemplo n.º 48
0
 def initAttr(self, width, height):
     self.width, self.height = width, height
     self.loadResource()
     self.background = Background((width, height))
     # 规则文字开始的位置
     offLine = 100
     offSet = 50
     self.content = []
     for content in RULES_CONTENT[0 : -1]:
         offLine += offSet
         self.content.append(Label(RULES_CONTENT_FONTS, content, (50, offLine), headMark = self.headMark))
     self.returnButton = TextButton(RULES_EXIT_FONTS, RULES_CONTENT[-1], (offSet, self.height - offSet), (255, 255, 255))
Ejemplo n.º 49
0
def main():

    open_canvas()

    global background, score, timer, burger, character_list
    global running
    global current_time, frame_time
    background = Background()
    score = Score()
    timer = Timer()
    character_list = [Character() for i in range(nCharacter)]
    burger.draw()

    running = True
    current_time = get_time()

    while running:
        frame_time = get_frame_time()
        handle_events()
        for character in character_list:
            character.update(frame_time)

        clear_canvas()
        background.draw()
        score.draw()
        score.update(value)
        timer.draw()
        timer.update(time_value)
        for character in character_list:
            character.draw()
            character.draw_bb()
        burger.draw()

        update_canvas()




    close_canvas()
Ejemplo n.º 50
0
    def setUp(self):
        """fill the selector"""

        #The lineEdit widget holds our background path, but the user does
        # not manipulate it directly
        self.kcfg_backgroundName.hide()

        self.backgroundNameList.currentRowChanged.connect(self.backgroundRowChanged)
        self.kcfg_backgroundName.textChanged.connect(self.backgroundNameChanged)
        self.backgroundList = Background.backgroundsAvailable()
        for aset in self.backgroundList:
            self.backgroundNameList.addItem(aset.name)
        self.kcfg_backgroundName.setText(common.PREF.backgroundName)
Ejemplo n.º 51
0
 def open(self):
     self.source.base_name = get_base_file(self.file) 
     # background folder
     directory = 'backgrounds/' + self.source.base_name
     create_dir(directory) 
     init_setup_new(self.main_window)
     self.source.setup_frames = cv2.VideoCapture(self.file)
     self.get_data()
     self.populate_setup()
     self.address_window = AddressWindow(self, self.main_window)
     self.polygon = Polygon(self, self.source)
     self.draw_status = False
     self.play = Play(self.source, self)
     self.play.run_setup()
     self.background = Background(self.source)
Ejemplo n.º 52
0
    def initAttr(self, width, height):
        self.justClicked = SETLEVEL["JUST_CLICKED"]
        # 默认 level
        self.loadResouce()
        self.setArrow()
        self.setLevel()

        self.background = Background((self.width, self.height))

        titleOffTop = 150

        self.titleText = CenteredText(SETLEVEL["TITLE_FONTS"], SETLEVEL["TITLE_CONTENT"], (self.width / 2, titleOffTop))

        offSet = 50
        self.beginButton = TextButton(SETLEVEL["BEGIN_FONTS"], SETLEVEL["BEGIN_CONTENT"], (self.width - offSet, self.height - offSet), (255, 255, 255))
        self.returnButton = TextButton(SETLEVEL["EXIT_FONTS"], SETLEVEL["EXIT_CONTENT"], (offSet, self.height - offSet), (255, 255, 255))
Ejemplo n.º 53
0
 def __init__(self, PCs = [], NPCs = []):
   self.delay = 30 # duration of animation frames in milliseconds
   screen = pygame.display.get_surface()
   self.ring = pygame.rect.Rect(0, 0, 600, 300) # combat circle
   self.ring.centerx = screen.get_width() / 2
   self.ring.bottom = screen.get_height()
   self.background = Background('graphics/All_Gizah_Pyramids-cropped.jpg')
   self.setPlayerCharacters(PCs)
   self.setNonPlayerCharacters(NPCs)
   self.quit = False
   self.escape = Button('escape')
   rect = self.escape.rect
   rect.bottom = screen.get_height() - 20
   rect.left = 20
   self.heal = pygame.image.load("graphics/heal.png").convert_alpha()
   self.attack = pygame.image.load("graphics/attack.png").convert_alpha()
Ejemplo n.º 54
0
 def camera(self):
     print("Camera in setup")
     # background folder
     directory = 'backgrounds/' + self.source.base_name
     create_dir(directory) 
     self.status = True
     init_setup_new(self.main_window)
     self.source.setup_frames = cv2.VideoCapture(config['camera'])
     self.get_data()
     self.populate_setup()
     self.address_window = AddressWindow(self, self.main_window)
     self.polygon = Polygon(self, self.source)
     self.draw_status = False
     self.play = Play(self.source, self)
     self.play.run_setup()
     self.background = Background(self.source)
Ejemplo n.º 55
0
 def __init__(self):
     """
     Initialize the game
     """
     pygame.init()
     self.screen = pygame.display.set_mode(consts.RESOLUTION)
     pygame.event.set_allowed([pygame.QUIT, pygame.KEYDOWN, pygame.KEYUP])
     # Blit background
     self.background = Background((0, 0))
     # TODO avoid acting on sprite and do actions on group?
     self.player = player.Player({
         'tilesGroup': 'new',
         'x': 400,
         'y': 300
     })
     self.background.setMainSprite(self.player)
     self.init_joystick()
Ejemplo n.º 56
0
 def __init__(self, **kw):
     super(RootWidget, self).__init__(**kw)
     self.level = 1
     self.seconds = 0
     self.combo = 1
     self.score = 0
     self.hits = 0
     self.cons = 0
     self.rainboxes = [Rainbox(pos=(-500, 0)) for i in range(10)]
     self.powerup = Powerup()
     self.miniball = Rainball(size=(60, 60), name='mini')
     self.miniball.speed = 20
     self.maxiball = Rainball(size=(120, 120), name='maxi', element='stone')
     self.background = Background(size=Window.size)
     self.target_l = Image(source='img/target_l.zip', size=(60, 60))
     self.lbl_fps = Label(pos=(Window.width -100, 0))
     self.lbl_level = PopLabel(
         pos=(100, Window.height-100),
         font_name='font/Mouser.ttf')
     self.lbl_hits = PopLabel(
         pos=(100, Window.height-140),
         font_name='font/Mouser.ttf')
     self.lbl_combo = PopLabel(
         pos=(100, Window.height-180),
         font_name='font/Mouser.ttf')
     self.lbl_score = PopLabel(
         pos=(100, Window.height-220),
         font_name='font/Mouser.ttf')
     self.add_widget(self.background, canvas='before')
     self.add_widget(self.target_l)
     self.add_widget(self.miniball)
     self.add_widget(self.maxiball)
     self.add_widget(self.lbl_fps)
     self.add_widget(self.lbl_level)
     self.add_widget(self.lbl_hits)
     self.add_widget(self.lbl_combo)
     self.add_widget(self.lbl_score)
     self.add_widget(self.powerup)
     for i in range(10):
         self.add_widget(self.rainboxes[i])
     self._keyboard = Window.request_keyboard(
         self._keyboard_closed, self, 'text')
     self._keyboard.bind(on_key_down=self._on_key_down)
     sounds['music'].loop = True
     sounds['music'].play()
     Clock.schedule_interval(self.update, 1/60.)
Ejemplo n.º 57
0
    def __init__(self, joystickList, screenSize, initialPath):

        self.screenSize = screenSize
        self.joystickList = joystickList
        self.font = pygame.font.SysFont("arial", 16)
        self.pauseGame = False
        self.gameOver = False
        self.playerInDeadZone = False
        self.totalElapsedTime = 0

        self.background = Background(self.screenSize, initialPath)

        x = self.background.levelMaker.startXPosition
        y = self.background.levelMaker.startYPosition

        if len(self.joystickList) == 2 and self.joystickList != None:
            self.player1  = Player(self.joystickList[1], ProjectileMotion(), FreeFall(15), StoryBoard2(), x, y)
            self.player2 = Player(self.joystickList[0], ProjectileMotion(), FreeFall(15), StoryBoard2(), x, y) #-----------------#
        else:
            self.player1 = Player(self.joystickList[0], ProjectileMotion(), FreeFall(15), StoryBoard2(), x, y)
            self.player2 = Player(self.joystickList[0], ProjectileMotion(), FreeFall(15), StoryBoard2(), x, y) #-----------------#
        self.player1.id = "p1"
        self.player2.id = "p2"
        
        self.player1.companero = self.player2
        self.player2.companero = self.player1

        # Flecha guia (para ubicar a otro player
        self.compassImageUp   = pygame.image.load("blocks//arrowUp.png").convert_alpha()
        self.compassImageDown = pygame.image.load("blocks//arrowDown.png").convert_alpha()
        self.compassImageRight = pygame.image.load("blocks//arrowRight.png").convert_alpha()
        self.compassImageLeft = pygame.image.load("blocks//arrowLeft.png").convert_alpha()
        self.compass = pygame.sprite.Sprite()
        self.compass.image = self.compassImageUp
        self.verticalCompassNeeded  = False
        self.horizontalCompassNeeded = False
        self.P1horizontalCompassNeeded = False
Ejemplo n.º 58
0
Archivo: game.py Proyecto: owad/thegame
 def __init__(self):
     self.cfg = config.Config(file('config.ini'))
     self.game_start_time = time.time()
     self.game_speed = self.cfg.init_game_speed
     self.play_time = 0
     self.game_score = 0
     self.player_name = ''
     
     self.fps = self.cfg.fps
     pygame.init()
     try:
         if sys.argv[1] == 'fullscreen':
             info = pygame.display.Info()
             self.window_size = (info.current_w, info.current_h)
             pygame.display.set_mode(self.window_size, pygame.FULLSCREEN)
     except:
         self.window_size = (640, 480)
     self.screen = pygame.display.set_mode(self.window_size)
     self.clock = pygame.time.Clock()
     
     self.obstacles = Obstacles(self.screen, self.window_size)
     self.obstacles.gen_obstacles(1)
     self.player = Player(self.screen, self.window_size)
     self.bg = Background(self.screen)
Ejemplo n.º 59
0
    def promptUserForPin(requiredLevel=1):
        userHasAccess = True

        # Set the background
        background = Background.createBackground()
        if background is not None:
            background.show()

        # Prompt the user to enter the pin
        numberpad = NumberPad.createNumberPad()
        numberpad.doModal()

        # Remove the background if we had one
        if background is not None:
            background.close()
            del background

        # Get the code that the user entered
        enteredPin = numberpad.getPin()
        del numberpad

        # Find out what level this pin gives access to
        # This will be the highest level
        pinMatchLevel = Settings.getSecurityLevelForPin(enteredPin)

        # Check to see if the pin entered is correct
        if pinMatchLevel >= requiredLevel:
            log("PinSentry: Pin entered correctly for security level %d" % pinMatchLevel)
            userHasAccess = True
            # Check if we are allowed to cache the pin level
            PinSentry.setCachedPinLevel(pinMatchLevel)
        else:
            log("PinSentry: Incorrect Pin Value Entered, required level %d entered level %d" % (requiredLevel, pinMatchLevel))
            userHasAccess = False

        return userHasAccess
Ejemplo n.º 60
0
Archivo: game.py Proyecto: owad/thegame
class Game:
    
    def __init__(self):
        self.cfg = config.Config(file('config.ini'))
        self.game_start_time = time.time()
        self.game_speed = self.cfg.init_game_speed
        self.play_time = 0
        self.game_score = 0
        self.player_name = ''
        
        self.fps = self.cfg.fps
        pygame.init()
        try:
            if sys.argv[1] == 'fullscreen':
                info = pygame.display.Info()
                self.window_size = (info.current_w, info.current_h)
                pygame.display.set_mode(self.window_size, pygame.FULLSCREEN)
        except:
            self.window_size = (640, 480)
        self.screen = pygame.display.set_mode(self.window_size)
        self.clock = pygame.time.Clock()
        
        self.obstacles = Obstacles(self.screen, self.window_size)
        self.obstacles.gen_obstacles(1)
        self.player = Player(self.screen, self.window_size)
        self.bg = Background(self.screen)
    
    def display_text(self, text, x=None, y=None, font_size=40):
        myfont = pygame.font.SysFont("Arial Bold", font_size)
        label = myfont.render(text, 1, (255, 255, 255))
        if not x:
            x = self.window_size[0] / 2 - label.get_width() / 2
        if not y:
            y = self.window_size[1] / 3
        self.screen.blit(label, (x, y))
        return label

    def game_over(self):
        self.display_text('GAME OVER', None, 50)
        self.display_text("your score is %s" % self.game_score, None, 80)
        
    def game_score_display(self):
        self.play_time = time.time() - self.game_start_time
        self.display_text("Score: %s" % str(self.game_score), 10, 10)
    
    def game_score_save(self, key_index=None):
        if len(self.player_name) < 3:
            if key_index != None and key_index > 96 and key_index < 123:
                self.player_name += chr(key_index)
            self.display_text('Type your initials: %s' % self.player_name, None, 120, 30)
        elif len(self.player_name) == 3:
            writer = csv.writer(open('scores.txt', 'ab'))
            writer.writerow([self.player_name, self.game_score])
            self.player_name += '-1'
        elif int(self.player_name[-1:]) == 1:
            self.player_name = 'abc2'
            reader = csv.reader(open('scores.txt', 'rb'))
            scores = []
            for row in reader:
                scores.append((row[0], row[1]))
            scores.sort(None, operator.itemgetter(1), True)
            writer = csv.writer(open('scores.txt', 'wb'))
            writer.writerows(scores[:5])
        else:
            self.game_score_board()
            
    def game_score_board(self):
        reader = csv.reader(open('scores.txt', 'rb'))
        y = 120
        self.display_text("Top scores", None, y, 30)
        y = 150
        for row in reader:
            self.display_text('%s %s' % (row[0].upper(), row[1]), None, y, 30)
            y += 30
    
    def game_speedup(self, speedup=1):
        self.game_speed += speedup
    
    def draw(self, hide_scores=False):
        self.bg.draw()
        self.obstacles.draw()
        self.player.draw()
        if not hide_scores:
            self.game_score_display()
    
    def main(self):
        done = False
        stop = False
        gameover = False
        speedup_counter = self.fps
        while done == False:
            if not gameover:
                if self.player.hit_obstacle(self.obstacles.collection):
                    gameover = True
            key_index = None
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    done = True
                if event.type == pygame.KEYUP:
                    if event.key == pygame.K_ESCAPE:
                        done = True
                    if gameover:
                        key_index = event.key
                self.player.keyboard_move(event)
            self.player.mouse_move()
            
            self.obstacles.up(self.game_speed)
            if speedup_counter > 0:
                speedup_counter -= 1
            else:
                if int(self.play_time) % 5 == 0 and self.play_time != 0:
                    self.game_speedup()
                    if len(self.obstacles.collection) < self.cfg.max_obstacles:
                        self.obstacles.one_more()
                speedup_counter = self.fps
            if not stop:
                self.clock.tick(self.fps)
            
            self.draw(gameover)
            
            if gameover:
                self.game_over()
                self.game_score_save(key_index)
                stop = True
            else: 
                self.game_score += 1
            
            pygame.display.flip()
            self.clock.tick(self.fps)