Ejemplo n.º 1
0
class MyTestCase(unittest.TestCase):
    past_url_testing = ["https://i.redd.it/eqhlkjhh1p151.jpg"]
    bg_valid_ratio_hires = background.Background(
        "https://i.redd.it/eqhlkjhh1p151.jpg", 'wallpaper')
    bg_invalid_url = background.Background(
        "https://i.redd.it/eqhlkjhh1p151.test", "test")
    bg_invalid_ratio = background.Background(
        "https://cdnb.artstation.com/p/assets/images/images/026/905/135/large/kotakan-kinokonoyamanoshiro20200520-1000.jpg?1590054349",
        "ImaginaryCastles")
    bg_clipped_ratio = background.Background(
        "https://cdna.artstation.com/p/assets/images/images/026/798/234/large/z-4-zero-.jpg",
        'ImaginaryCastles')

    def test_0_pull_image_from_reddit(self):
        self.assertEqual(True, self.bg_valid_ratio_hires.get_image_from_url())
        self.assertEqual(False, self.bg_invalid_url.get_image_from_url())
        self.assertEqual(True, self.bg_invalid_ratio.get_image_from_url())
        self.assertEqual(True, self.bg_clipped_ratio.get_image_from_url())

    def test_1_is_aspect_ratio_valid(self):
        self.bg_valid_ratio_hires.get_dimensions()
        self.bg_invalid_ratio.get_dimensions()
        self.bg_clipped_ratio.get_dimensions()
        self.assertEqual(False, self.bg_valid_ratio_hires.is_ratio_invalid())
        self.assertEqual(True, self.bg_invalid_ratio.is_ratio_invalid())
        self.assertEqual(False, self.bg_clipped_ratio.is_ratio_invalid())

    def test_2_is_image_duplicated(self):
        self.assertEqual(
            True,
            self.bg_valid_ratio_hires.is_image_duped(self.past_url_testing))
        self.assertEqual(
            False, self.bg_clipped_ratio.is_image_duped(self.past_url_testing))

    def test_3_saving_image_to_file(self):
        self.bg_valid_ratio_hires.save_image_to_file()
        self.assertEqual(
            True, os.path.isfile(self.bg_valid_ratio_hires.image_file_path))

    def test_4_set_image_background(self):
        # Should only fail for non-Windows OS but cannot unit test this
        self.assertEqual(True, self.bg_valid_ratio_hires.change_background())

    def test_x_add_favourite(self):
        pass

    def test_x_skip_current_image(self):
        pass
Ejemplo n.º 2
0
def game(stats):
    '''Get the level of the game, user's name...etc'''
    playerName = stats["name"]
    difficulty = stats["level"]
    screen = pygame.display.set_mode((800, 800))
    backScreen = background.Background("sampleCode/str1.jpg", screen)
    done = False
    clock = pygame.time.Clock()
    backScreen.display()

    while not done:

        clock.tick(60)  # at most 60FPS

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RIGHT:
                    backScreen.changeToSpeed(10)
                if event.key == pygame.K_LEFT:
                    backScreen.changeToSpeed(-10)
            else:
                backScreen.changeToSpeed(0)

        backScreen.move()
        backScreen.display()
        pygame.display.update()
Ejemplo n.º 3
0
    def __init__(self):
        self.__index = 0

        self.STAGE = []
        self.BACKGROUND = background.Background()

        self.AddToStage(self.BACKGROUND, "Background")

        STAGE_WIDTH, STAGE_HEIGHT = pygame.display.get_surface().get_size()

        TEXTOA = dat.GetWord("presentacion parte 1")
        TEXTOB = dat.GetWord("presentacion parte 2")

        self.LETRASA = autors.autorEffect(
            TEXTOA,
            (STAGE_WIDTH / 2 - len(TEXTOA) * 10, STAGE_HEIGHT / 2 - 15))
        self.LETRASB = autors.autorEffect(
            TEXTOB,
            (STAGE_WIDTH / 2 - len(TEXTOB) * 10, STAGE_HEIGHT / 2 + 15))

        self.AddToStage(self.LETRASA, "Autors A")
        self.AddToStage(self.LETRASB, "Autors B")

        self.LETRASA.StartMove()

        self.phrase = "Authors"
        self.auxiliarA = 0

        self.__ACTION = MenuActions.NOSET

        self.subMenus = []
        self.__started = False
        self.__waitToUnclock = 0
Ejemplo n.º 4
0
def enter():
    global player, cars, coins, info, fires, player_data, bg, start_time, wav_lev, collision_check_thread, is_over
    player = Player()

    fires = []
    info = Info()
    coins = []
    cars = []

    lev = player.car.level

    global NUM_CAR
    NUM_CAR = (garage_state.garage.difficulty + 1) * 20
    for i in range(NUM_CAR):
        #내 차보다 최대 2레벨 높은것만 나오도록
        cars.append(
            Car(random.randrange(0,
                                 lev + 2 if lev + 2 < MAX_LEV else MAX_LEV)))
    bg = background.Background()

    global bgm, gameover_bgm, get_coin_bgm
    bgm = pico2d.load_music('res/sound/bgm.mp3')
    gameover_bgm = pico2d.load_wav('res/sound/dead.wav')
    get_coin_bgm = pico2d.load_wav('res/sound/coin.wav')
    bgm.set_volume(64)
    gameover_bgm.set_volume(64)
    get_coin_bgm.set_volume(64)
    bgm.repeat_play()

    wav_lev = 1
    is_over = False
    collision_check1 = threading.Thread(target=collides_car)
    collision_check1.start()
    collision_check2 = threading.Thread(target=collides_bullet)
    collision_check2.start()
Ejemplo n.º 5
0
	def __init__(self):
		"""Initialize the game, and create game resources."""
		pygame.init()
		self.settings = settings.Settings()

		# Start game in an inactive state.
		self.game_active = False

		self.screen = pygame.display.set_mode(
			(self.settings.screen_width, self.settings.screen_height)
		)
		# self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
		# self.settings.screen_width = self.screen.get_rect().width
		# self.settings.screen_height = self.screen.get_rect().height

		pygame.display.set_caption("Alien Invasion")

		# Create an instance to store game statistics and create a scoreboard.
		self.stats = game_stats.GameStats(self)
		self.sb = scoreboard.Scoreboard(self)

		self.ship = ship.Ship(self)
		self.background = background.Background(self)
		self.bullets = pygame.sprite.Group()
		self.aliens = pygame.sprite.Group()

		self._create_fleet()

		# Make the Play button.
		self.play_button = button.Button(self, "Play")
Ejemplo n.º 6
0
def enter():
    global hero, menu, back, st_num, finish, mt, current_time, time_score, rank_image, show_rank, scores, ss, MAX_STAGE, dragon_time, DRAGON, mainbgm
    dragon_time = 0
    DRAGON = []
    current_time = get_time()
    show_rank = False
    time_score = 0.0
    st_num = 1
    MAX_STAGE = 6
    finish = False
    mt = 0
    menu = Menu()
    hero = genji.Genji()
    scores = []
    ss = []
    loadScores()

    enemy.enemys.append(enemy.Robot(500, 250))
    enemy.enemys.append(enemy.Robot(800, 350))
    enemy.enemys.append(enemy.Robot(950, 200))
    back = background.Background()
    if rank_image == None:
        rank_image = load_image('랭킹.png')
        mainbgm = load_music('Hanamura.mp3')
        mainbgm.set_volume(128)
    mainbgm.repeat_play()
Ejemplo n.º 7
0
def enter():
    global back, player, dalls
    global LKeyco, RKeyco
    global dallcount, count, remain_dall
    global stage, stage_set
    global font, playTime
    global totalpoint
    global music, hit_S
    music = LoadRe.sound.play_bgm
    music.repeat_play()
    hit_S = LoadRe.sound.hit_sound
    playTime = 0
    totalpoint = 0
    font = load_font('ENCR10B.TTF', 70)
    stage = 0
    stage_set = LoadStage.Stage()
    dallcount = stage_set.Getdallcount(stage)
    remain_dall = dallcount
    count = 0
    RKeyco, LKeyco = 0, 0
    back = background.Background()
    player = Player.Ragna()
    player.x = 300
    dalls = [Dall.dall() for i in range(dallcount)]
    j = 0
    print(dallcount)
    for dall in dalls:
        stage_set.SetStage(j, stage, dall)
        j += 1
Ejemplo n.º 8
0
    def initUI(self):
        self.resize(560, 700)
        self.center()
        self.setWindowTitle('Teris')

        nextLabel = QLabel('下一个方块:', self)
        nextLabel.setFont(QFont("Roman times", 16, QFont.Bold))
        nextLabel.move((self.backWidth + 3) * self.blockSize, 30)

        scoreLabel = QLabel('当前得分:', self)
        scoreLabel.setFont(QFont("Roman times", 16, QFont.Bold))
        scoreLabel.move((self.backWidth + 3) * self.blockSize, 230)

        self.scoreNumber = QLCDNumber(self)
        self.scoreNumber.move((self.backWidth + 3) * self.blockSize, 260)
        self.scoreNumber.setSegmentStyle(QLCDNumber.Flat)
        self.scoreNumber.setStyleSheet(
            "font-size: 30px; color: red; border: 1px solid black; height: 100px; width: 100px;"
        )

        self.timer = QBasicTimer()
        self.background = bg.Background(self.backWidth, self.backHeight,
                                        self.blockSize, self.blockOffset)
        self.productShape()
        self.startHandler()
        self.show()
Ejemplo n.º 9
0
def run_game(window, surface):
    clock = pygame.time.Clock()
    game_bg = background.Background(surface)
    game = Game(surface)

    running = True
    while running:
        clock.tick()
        pygame.time.delay(10)  ## apparently this helps with inputs
        game_bg.draw()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:  # what happens when X is pressed
                running = False
            if event.type == pygame.KEYDOWN:
                game.press_key(event.key)

            if event.type == pygame.MOUSEMOTION:  # keeps track of mouse coords
                mouse_x, mouse_y = event.pos
                game.move_mouse(mouse_x, mouse_y)

            if event.type == pygame.MOUSEBUTTONDOWN:
                game.click_mouse()

        game.tick()
        game.draw()

        window.blit(surface, (0, 0))
        pygame.display.update()
    pygame.quit()
Ejemplo n.º 10
0
def main():
    pygame.init()
    gamedisplay = pygame.display.set_mode((840, 650))
    print("#testing driver car model#")
    test_driver = driver.Driver(0, 0)

    print("#right input test#")
    test_driver.moveRight()
    assert test_driver.x == 5

    print('#zero input test#')
    assert test_driver.x == 5

    print('#left input test#')
    test_driver.moveLeft()
    assert test_driver.x == 0

    print("#testing traffic model#")
    test_traffic = traffic.Traffic(0)

    print('#speedup test#')
    oldspeed = test_traffic.randomspeed
    test_traffic.speedup()
    assert test_traffic.randomspeed > oldspeed

    print('#slowdown test#')
    oldspeed = test_traffic.randomspeed
    test_traffic.slowdown()
    assert test_traffic.randomspeed < oldspeed

    print('#reset test#')
    test_traffic.reset()
    assert test_traffic.y >= -2000 and test_traffic.y <= -500

    print('#drive test#')
    test_traffic.drive()
    assert test_traffic.y >= -2000 and test_traffic.y <= -500

    print('#testing gameSetup model#')
    test_gameSetup = gameSetup.GameSetup()

    print('#game screen test#')
    test_gameSetup.setup()
    assert test_gameSetup.display_width == 840

    print('#testing background model#')
    test_background = background.Background()

    print('#testing reset#')
    test_background.reset()
    assert test_background.y == -650

    print('#testing speedup#')
    test_background.speedup()
    assert test_background.speed <= 5

    print('#testing slowdown#')
    test_background.slowdown()
    assert test_background.speed >= 2
Ejemplo n.º 11
0
    def test_part_one(self):
        "Test part one example of Background object"

        # 1. Create Background object from text
        myobj = background.Background(text=aoc_19.from_text(PART_ONE_TEXT))

        # 2. Check the part one result
        self.assertEqual(myobj.part_one(verbose=False), PART_ONE_RESULT)
Ejemplo n.º 12
0
def main(paramfile,verbose):
    
    Ini = inifile.IniFile(paramfile)
    if(verbose>0):
        Ini.Dump()

    section = "OUTPUT"
    root = Ini.ReadString(section,"root")
    
    # fiducial cosmology
    BG = background.Background(verbose=verbose)
    section = "COSMOLOGY"
    paramsfid = np.array([Ini.ReadFloat(section,"ob"),Ini.ReadFloat(section,"odm"),Ini.ReadFloat(section,"ode"),
                          Ini.ReadFloat(section,"nnu"),Ini.ReadFloat(section,"mnu")])
    BG.SetParams(paramsfid)

    # clumpiness
    section = "NBODY"
    path = Ini.ReadString(section,"clumpiness")
    if(verbose>0):
        print("\n# cluminess (ignored when intype==2)")
        # clumz is ln(B) as function of ln(1+z) constructed from a lookup table of "z B(z)".
    try:
        tab = np.loadtxt(path)
        clumz = interpolate.make_interp_spline(np.log(1+tab[:,0]),np.log(1+tab[:,1]))
        if(verbose>0):
            print(" cluminess factor is read from ",path)
    except:
        if(verbose>0):
            print(" table file for clumpiness factor is missing; cluminess is ignored:")
        clumz = lambda x:0

    # energy deposition
    DE = deposition.Deposit(verbose=verbose)
    section = "DEPOSITION"
    DE.SetParams(Ini.ReadString(section,"epspath"),Ini.ReadInt("INJECTION","intype"))
    DE.Calcfc(BG.dtauda,clumz)

    # injection spectrum phythia
    INJ = injection.Injection(verbose=verbose)
    section = "INJECTION"
    mspec = 5
    INJ.SetParams(DE.intype,Ini.ReadFloat(section,"mass"),Ini.ReadInt(section,"mult"),Ini.ReadInt(section,"mode"),
                  Ini.ReadBoolean(section,"use_prec"),DE.nerg*mspec,DE.erg[0]*const.eV/const.GeV,DE.erg[DE.nerg-1]*const.eV/const.GeV)
    INJ.SetRate(Ini.ReadFloat(section,"sigmav") if INJ.intype==1 else Ini.ReadFloat(section,"gamma"))
    INJ.GetBinnedNumber()

    # IGM evolution
    TH = therm.Therm(verbose=verbose)
    TH.SetParams(root)
    TH.IntegEnergy(DE,INJ)
    TH.ThermInput(BG,DE,INJ)
    TH.EvolveTspin(BG,DE,INJ)

    #for EDGES???
    if(verbose>0):
        print(INJ.mass,INJ.sigmav/const.cm**3,TH.dT21cm_edges)
    return TH.dT21cm_edges
Ejemplo n.º 13
0
    def test_part_two(self):
        "Test part two example of Background object"

        # 1. Create Background object from text
        myobj = background.Background(part2=True,
                                      text=aoc_19.from_text(PART_TWO_TEXT))

        # 2. Check the part two result
        self.assertEqual(myobj.part_two(verbose=False), PART_TWO_RESULT)
Ejemplo n.º 14
0
    def init_entities(self):
        self.diver = diver.Diver(
            (self.dimensions[0] / 2, self.dimensions[1] / 2))
        self.bg = background.Background(self.dimensions)
        self.rocks = rock.Rock(self.dimensions)

        rock.create_rocks(self.rocks)

        self.entities = [self.bg, self.diver, self.rocks]
Ejemplo n.º 15
0
    def __init__(self, parent=None):
        QMainWindow.__init__(self)

        self.setWindowTitle("てきすとえでぃたー")

        self.text_area = TextArea(self)
        self.setCentralWidget(self.text_area)

        self.bg = background.Background(self)
        self.text_area.set_background(self.bg)
def enter():
    global sky_stage1, stage1, background1, count_pause_time_image, hp_ui, score_ui, first_background1, first_background2, first_background3
    stage1 = load_image("image\\stage_1.png")
    sky_stage1 = load_image("image\\stage_sky_1.png")
    background1 = load_image("image\\stage_background_1.png")

    count_pause_time_image = load_image("image\\count_pause_time_.png")
    first_background1 = background.Background(350)
    first_background2 = background.Background(1100)
    first_background3 = background.Background(1850)
    static_object_init(first_background1, 0)
    static_object_init(first_background2, 0)
    static_object_init(first_background3, 0)
    static_object_init(stage1, 0)
    static_object_init(background1, 0)

    static_object_init(count_pause_time_image, 1)
    hp_ui = HP.HP()
    score_ui = score.score()
    static_object_init(hp_ui, 1)
    static_object_init(score_ui, 1)
Ejemplo n.º 17
0
 def __init__(self, details):
     self.name = details["name"]
     self.slug = details["id"]
     self.song = details["song"]
     self.laps = details["laps"]
     self.backgrounds = map(
         lambda bg: b.Background(bg["id"], bg["speed"], bg["scale"], bg[
             "convert"]), details["backgrounds"])
     self.palettes = details["colours"]
     self.finished = False
     self.segments = []
     self.competitors = []
Ejemplo n.º 18
0
    def test_empty_init(self):
        "Test the default Background creation"

        # 1. Create default Background object
        myobj = background.Background()

        # 2. Make sure it has the default values
        self.assertEqual(myobj.part2, False)
        self.assertEqual(myobj.text, None)
        self.assertEqual(myobj.pc_reg, None)
        self.assertEqual(myobj.program, None)
        self.assertEqual(myobj.regs, None)
        self.assertEqual(myobj.pc, None)
Ejemplo n.º 19
0
def enter():
    global backgrounds, paths, obstacles, line, cookie, select_cookie, timer, jelly_line, jelly_file
    global button, score_font, score_font_back, coin_image, jelly_image, obs_sound

    backgrounds = background.Background()
    game_world.add_object(backgrounds, 0)

    if scene_lobby.select_cookie == 1:
        cookie = cookie_brave.Brave()
        cookie.newPosition(200, 70 + 115)
    elif scene_lobby.select_cookie == 2:
        cookie = cookie_bright.Bright()
        cookie.newPosition(200, 70 + 115)
    game_world.add_object(cookie, 2)

    obstacle_init()

    jelly_init()

    for item in jellies:
        game_world.add_object(item, 1)
        item.initialize()

    paths = [path.Path(n) for n in range(2)]
    for i in paths:
        game_world.add_object(i, 0)

    game_world.add_object(scene_lobby.life_num, 2)

    timer = 0

    scene_lobby.bgm = load_music('sound/Cookie Run Ovenbreak - Theme Song Breakout 1.mp3')
    scene_lobby.bgm.get_volume()
    scene_lobby.bgm.repeat_play()

    button = ui.UI()
    game_world.add_object(button, 2)

    if score_font == None:
        score_font = load_font('font/Maplestory Light.ttf', 20)

    if coin_image == None:
        coin_image = load_image('resource/Cookie Skill Effects and Jellies/jelly/silver coin.png')
    if jelly_image == None:
        jelly_image = load_image('resource/Cookie Skill Effects and Jellies/jelly/simple jelly.png')

    if obs_sound == None:
        obs_sound = load_wav('sound/effect sound/g_obs1.wav')
    obs_sound.set_volume(60)

    cookie.score = 0
Ejemplo n.º 20
0
 def __init__(self):
     pygame.init()
     self.score = 0
     self.scoreText = pygame.font.Font("Minecraft.ttf", 30)
     self.timeText = pygame.font.Font("Minecraft.ttf", 30)
     self.width = 1000
     self.height = 700
     self.screen = pygame.display.set_mode((self.width, self.height))
     self.background = pygame.Surface(self.screen.get_size())
     self.background = self.background.convert()
     self.screen.fill((200,200,200)) # Values can be changed as needed. Example values
     self.bg = background.Background(self.screen, 0, 375)
     self.ship1Y = random.randint(340, 375)
     self.ship2Y = random.randint(375, 385)
     self.ship3Y = random.randint(385, 395)
     self.ship1 = ships.Ship(self.screen, 0, self.ship1Y)
     self.ship2 = ships.Ship(self.screen, -50, self.ship2Y)
     self.ship3 = ships.Ship(self.screen, -80, self.ship3Y) 
     self.scope = scope.Scope(self.screen)
     self.linev = scope.Scope(self.screen)
     self.lineh = scope.Scope(self.screen)
     self.P1 = (500, 700)
     self.dx = 0
     self.dy = 0
     self.torpedo = None
     self.ship1Speed = random.randint(1,3)
     self.ship2Speed = random.randint(1,3)
     self.ship3Speed = random.randint(1,3)
     self.explosionLocX = None
     self.explosionLocY = None
     self.explosion = None
     self.LENGTHOFGAME = 90
     self.time = 90
     self.boVoiceCounter = 0
     self.explodeSound = pygame.mixer.Sound("explode.wav")
     self.torpedoSound = pygame.mixer.Sound("torpedoMove.wav")
     self.voiceSink = pygame.mixer.Sound("ShipDestroyed1.wav")
     #self.voiceShoot = pygame.mixer.Sound("")
     self.voicePowerPlus = pygame.mixer.Sound("HavePower.wav")
     self.voicePowerGone = pygame.mixer.Sound("NoPower.wav")
     #self.voiceTorp = pygame.mixer.Sound("Torpedo1.wav")
     self.cooldown = 300
     self.voiceCounter = 0
     self.voiceTorpedo = pygame.mixer.Sound("firingTorpedo.wav")
     self.channel1 = pygame.mixer.Channel(0)
     self.channel2 = pygame.mixer.Channel(1)
     self.channel3 = pygame.mixer.Channel(2)
     self.channel4 = pygame.mixer.Channel(3)
     self.channel5 = pygame.mixer.Channel(4)
Ejemplo n.º 21
0
def part_two(args, input_lines):
    "Process part two of the puzzle"

    # 1. Create the puzzle solver
    solver = background.Background(part2=True, text=input_lines)

    # 2. Determine the solution for part two
    solution = solver.part_two(verbose=args.verbose, limit=args.limit)
    if solution is None:
        print("There is no solution")
    else:
        print("The solution for part two is %s" % (solution))

    # 3. Return result
    return solution is not None
Ejemplo n.º 22
0
    def test_text_init(self):
        "Test the Background object creation from text"

        # 1. Create Background object from text
        myobj = background.Background(text=aoc_19.from_text(EXAMPLE_TEXT))

        # 2. Make sure it has the expected values
        self.assertEqual(myobj.part2, False)
        self.assertEqual(len(myobj.text), 8)
        self.assertEqual(myobj.pc_reg, 0)
        self.assertEqual(len(myobj.program), 7)
        self.assertEqual(myobj.program[0], ['seti', 5, 0, 1])
        self.assertEqual(myobj.program[1], ['seti', 6, 0, 2])
        self.assertEqual(myobj.program[2], ['addi', 0, 1, 0])
        self.assertEqual(myobj.program[6], ['seti', 9, 0, 5])
        self.assertEqual(myobj.regs, None)
        self.assertEqual(myobj.pc, None)

        # 3. Step through the program
        myobj.reset()
        self.assertEqual(len(myobj.regs), 6)
        self.assertEqual(myobj.regs, [0, 0, 0, 0, 0, 0])
        self.assertEqual(myobj.pc, 0)
        self.assertEqual(myobj.step(), True)
        self.assertEqual(myobj.regs, [0, 5, 0, 0, 0, 0])
        self.assertEqual(myobj.pc, 1)
        self.assertEqual(myobj.step(), True)
        self.assertEqual(myobj.regs, [1, 5, 6, 0, 0, 0])
        self.assertEqual(myobj.pc, 2)
        self.assertEqual(myobj.step(), True)
        self.assertEqual(myobj.regs, [3, 5, 6, 0, 0, 0])
        self.assertEqual(myobj.pc, 4)
        self.assertEqual(myobj.step(), True)
        self.assertEqual(myobj.regs, [5, 5, 6, 0, 0, 0])
        self.assertEqual(myobj.pc, 6)
        self.assertEqual(myobj.step(), True)
        self.assertEqual(myobj.regs, [6, 5, 6, 0, 0, 9])
        self.assertEqual(myobj.pc, 7)
        self.assertEqual(myobj.step(), False)
        self.assertEqual(myobj.regs, [6, 5, 6, 0, 0, 9])
        self.assertEqual(myobj.pc, 7)

        # 4. Run the program
        myobj.run()
        self.assertEqual(myobj.pc, 7)
        self.assertEqual(myobj.regs, [6, 5, 6, 0, 0, 9])
Ejemplo n.º 23
0
	def new(self, tileSize, width, height):
		"""
		Creates a new map of the given width, height, and tile dimentions
		@type tileSize: int
		@param tileSize: size of a tile in pixels
		@type width: int
		@param width: width of map in tiles
		@type height: int
		@param height: height of map in tiles
		"""
		self.close()
		self.__map = tilemap.TileMap.createMap(tileSize, width, height)
		self.__world = blazeworld.BlazeWorld()
		self.__background = background.Background()
		self.__selectedLayer = len(self.__map.layers) - 1
		for listener in self.__listeners:
			listener.listenFileOpened()
			listener.listenSelectLayer(self.__selectedLayer)
Ejemplo n.º 24
0
 def __init__(self, window_name, window_size=(900, 600)):
     self.window_name = window_name
     self.window_size = window_size
     self.window = pygame.display.set_mode(window_size, pygame.DOUBLEBUF,
                                           32)
     self.screen = pygame.Surface(window_size, pygame.SRCALPHA, 32)
     pygame.display.set_caption(self.window_name)
     self.g_renderer = renderer.Render(self.screen)
     player = horse.Horse(pygame.Rect(200, 460, 0, 0))
     back = background.Background()
     self.g_renderer.register_object(back, player)
     self.handle = eventHandler.EventHandler(player)
     self.audio_manager = audioManager.AudioManager()
     self.audio_manager.register_music(
         "assets/audio/car-racing-computer-game_WM.ogg")
     self.audio_manager.play_music()
     self.audio_manager.register_sound("assets/audio/gallop.ogg", "gallop")
     player.audio_manager = self.audio_manager
     return
Ejemplo n.º 25
0
	def open(self, fileName):
		"""
		Opens a file
		@type fileName: str
		@param fileName: the path of the file to open
		@rtype: str
		@return: Returns a string saying why the file could not be opened, or
		    None
		"""
		# Only one map can be used at a time
		self.close()
		self.__fileName = fileName
		if fileName is not None and os.path.exists(fileName):
			try:
				self.__background, self.__world, self.__map = levelio.read(
					fileName)
			except datafiles.FileNotFoundError as e:
				self.__fileName = None
				return str(e)
			except levelio.LoadError as e:
				self.__fileName = None
				return str(e)

			if self.__background is None:
				# Create an empty one
				self.__background = background.Background()

			if self.__world is None:
				# Same here
				self.__world = blazeworld.BlazeWorld()

			for index, fileName in enumerate(self.__map.images):
				for listener in self.__listeners:
					listener.listenAddTileSet(fileName)
			for listener in self.__listeners:
				listener.listenFileOpened()
				listener.listenSelectLayer(self.__selectedLayer)
			return None
		else:
			self.__fileName = None
			return "Could not find the file \"%s\"" % fileName
Ejemplo n.º 26
0
	def readd(self, dictionary):
		"""
		@type dictionary: {}
		@param dictionary: dictionary parsed from JSON describing the background
		@rtype: background.Background
		@return: the parsed background
		"""
		bg = background.Background()

		if "bgColor" in dictionary:
			try:
				bgColor = int(dictionary["bgColor"][1:], 16)
			except ValueError:
				log.error("Invalid background color specified.")
				bgColor = 0x00000000
		else:
			bgColor = 0x00000000
			log.error("No background color specified. Defaulting to Black.")
		color = graphics.RGBA()
		color.fromU32(bgColor)
		bg.setBGColor(color)

		if "parallaxes" in dictionary:
			parallaxList = []
			for parallax in dictionary["parallaxes"]:
				p, index = self.__readParallax(parallax)
				if index == -1: # index not specified
					parallaxList.append(p)
				else:
					while(index + 1 > len(parallaxList)):
						parallaxList.append(None)
					parallaxList[index] = p
			if None in parallaxList:
				log.warning("Parallax indicies are not consecutive. Maybe something's missing?")
			newList = [i for i in parallaxList if i != None]
			bg.setParallaxes(newList)
		else:
			log.info("No parallaxes specified")

		return bg
def get_redd_imgs(settings):
    sub = settings["SUBREDDITS"][random.randint(
        0,
        len(settings["SUBREDDITS"]) - 1)]
    print("Grabbing from", sub)

    bgs = []
    reddit = praw.Reddit(
        client_id="R1QneAltTJA0aw",
        client_secret="",
        user_agent=
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:78.0) Gecko/20100101 Firefox/78.0"
    )
    try:
        for submission in reddit.subreddit(sub).top(time_filter='all'):
            if submission:
                bg = background.Background(submission.url, sub)
                bgs.append(bg)
    except prawcore.exceptions.ResponseException:
        print("401 HTTP Timeout. Trying again.")
        get_redd_imgs(settings)
    return bgs
Ejemplo n.º 28
0
    def __init__(self):
        #Run the game window setup
        self.game = gameSetup.GameSetup()
        self.game.setup()

        #Initialize all needed objects
        self.gamedisplay = self.game.gamedisplay
        self.drivercar = driver.Driver(500, 400)
        self.background = background.Background()
        self.mainmenu = mainMenuLoop.TitleScreen(self.gamedisplay)
        self.crashmenu = crashMenuLoop.CrashMenuLoop(self.gamedisplay)
        self.lane1 = traffic.Traffic(110)
        self.lane2 = traffic.Traffic(230)
        self.lane3 = traffic.Traffic(370)
        self.lane4 = traffic.Traffic(500)
        self.slowfont = pygame.font.SysFont("monospace", 30)
        self.scorefont = pygame.font.SysFont("monospace", 20)
        self.dodged = 0

        pygame.mixer.music.load("assets/race_music.mp3")

        #Group the lane objects together
        self.lanegroup = pygame.sprite.Group(self.lane1, self.lane2,
                                             self.lane3, self.lane4)
Ejemplo n.º 29
0
 def __init__(self, width, height, fps):
     pygame.font.init()
     game_mouse.Game.__init__(self, "Flappy Bird",
                              width,
                              height,
                              fps)
     self.state = 'Main Menu'
     self.main_menu =  main_menu.Main_Menu(width, height)
     self.end_menu = end_menu.End_Menu(width, height)
     self.pause = pause_menu.Pause_Menu(width, height)
     self.barriers = barriers.Barriers(height, width)
     self.bird = bird.Bird(width, height)
     self.score = score.Score(width, height)
     self.scores_menu = displayscoresmenu.ScoresMenu(width, height)
     self.background = background.Background(height, width)
     self.music = { "state" : "",
                    "songs" : ["sounds/palm-beach.wav",
                               "sounds/chubby-cat.wav",
                               "sounds/the-awakening.wav"],
                     "current" : ""}
     self.instruction_menu = instruction_menu.InstructionMenu(width, height)
     self.bugs = []
     self.bug = bug.Bug
     return
Ejemplo n.º 30
0
 def __init__(
         self,
         capture_link="https://imageserver.webcamera.pl/rec/hotel-senacki-krakow/latest.mp4",
         box_min_area=800,
         blur_size=15,
         min_threshold=10,
         frames_to_work=10,
         average_alfa=0.1):
     """
     :param capture_link: link to the stream (0 is for local camera)
     :param box_min_area: minimal box area
     :param blur_size: size of the blur, the bigger the larger boxes will be detected
     :param min_threshold:
     :param frames_to_work: frames to start detecting move
     :param average_alfa: change of the background speed, between 0 and 1.
     """
     self.background = bg.Background(frames_to_work, average_alfa)
     self.captureStream = cv2.VideoCapture(capture_link)
     self.box_min_area = box_min_area
     self.blur_shape = (blur_size, blur_size)
     self.min_threshold = min_threshold
     self.state = States.Normal
     self.mask = Mask()
     self.defaults = (box_min_area, blur_size, min_threshold, average_alfa)