예제 #1
0
def init_level(next_level):
    global selected_tile, log_label, hero, the_map, all_monsters, life_label, weapon_label, level_label, bullets_controller, blood_controller, should_add_handlers, level, map_batch, main_batch
    main_batch  = pyglet.graphics.Batch()
    map_batch   = pyglet.graphics.Batch()
    level = next_level
    current_level = mapcreator.generate_map("../maps/level"+str(level)+".png")
    selected_tile = (0,0)
    log_label = pyglet.text.Label(text=log,x=10,y=585, batch=main_batch)
    if not hero:
        hero = player.Player(batch=main_batch)
    else:
        hero.batch = main_batch
    the_map     = maps.Map(hero, current_level, level, map_batch)
    hero.x      = the_map.center[0]
    hero.y      = the_map.center[1]
    all_monsters= mapmonster.MapMonster(the_map)

    life_label  = pyglet.text.Label(color=(255,255,0,255), x=10,y=20, batch=main_batch, multiline=True, width=200)
    life_label.text = 'Health ' + str(hero.lif) + '%'

    weapon_label= pyglet.text.Label(color=(255,255,0,255), x=790, y=10, batch=main_batch, anchor_x="right")
    weapon_label.text = 'Weapon 1 : Bow(2-10) 5/5'

    level_label = pyglet.text.Label(x=790, y=585, anchor_x="right",text="Floor "+str(level), batch=main_batch)

    bullets_controller.clear_bullets()
    blood_controller.clear()
    game_window.push_handlers(the_map)
    game_window.push_handlers(the_map.key_handler)
    should_add_handlers = False
예제 #2
0
    def generate_world(self, world_type='Generic'):

        self.maptype = random.choice(['FOREST', 'GRASSLAND', 'VALLEY'])

        if self.maptype == 'FOREST':
            self.game_map = maps.Map(size=[300, 300])
            self.game_map.vegetation.randomize('pareto', 4)
            self.game_map.elevation.randomize('pareto', 5)
            self.game_map.elevation.diffuse(10)
        elif self.maptype == 'GRASSLAND':
            self.game_map = maps.Map(size=[300, 300])
            self.game_map.vegetation.randomize('pareto', 5)
            self.game_map.elevation.randomize('pareto', 5)
            self.game_map.elevation.diffuse(10)
        else:  #VALLEY
            self.game_map = maps.Map(size=[500, 200])
            self.game_map.vegetation.randomize('pareto', 2)
            self.game_map.elevation.randomize('pareto', 5)
            for i in range(0, 15):
                p1 = [random.randint(0, 199), random.randint(20, 480)]
                p2 = [random.randint(0, 199), random.randint(20, 480)]
                p1[0] *= pow(p1[1] / 500., 3)
                p2[0] = 199 - p2[0] * pow(p2[1] / 500., 3)
                print p1, p2
                self.game_map.elevation.data[p1[1], p1[0]] = random.randint(
                    10000, 20000) * p1[1] / 500.
                self.game_map.elevation.data[p2[1], p2[0]] = random.randint(
                    10000, 20000) * p2[1] / 500.
            for i in range(50):
                self.game_map.elevation.diffuse(5)
            self.game_map.elevation.data *= 100 / self.game_map.elevation.data.max(
            )

        treeline = 20
        self.game_map.vegetation.bloom(treeline - self.game_map.elevation.data)

        self.mapscreen = mapgui.MapScreen(name='Home Map')
        globalvars.root.screen_manager.add_widget(self.mapscreen)
        self.mapscreen.ids['mapimg'].process_map(self.game_map)

        for i in range(0, 12):
            g = goblin.Goblin(self.game_map)
            if i == 0: g.wealth = 100
            self.mapscreen.ids['mapimg'].add_widget(g.image())

        globalvars.root.screen_manager.current = self.mapscreen.name
예제 #3
0
    def __init__(self):

        pygame.init()

        self.score = 0
        self.holescore = 10
        self.map_s = pygame.sprite.Group()
        self.player_s = pygame.sprite.Group()
        self.path_s = pygame.sprite.Group()
        self.hole_s = pygame.sprite.Group()
        self.range_s = pygame.sprite.Group()
        self.sensor_s = pygame.sprite.Group()
        self.animation_count = 0

        self.screen = pygame.display.set_mode((1800, 1000))
        for r in range(20):
            self.hole = holes.Holes()
            self.hole.add(self.hole_s)

        self.clock = pygame.time.Clock()
        self.CENTER_X = int(pygame.display.Info().current_w / 2)
        self.CENTER_Y = int(pygame.display.Info().current_h / 2)
        self.running = True
        self.car = player.Player()
        self.cam = camera.Camera()
        self.robrange = roborange.RoRange()
        self.current_map = maps.Map()
        self.path = path.Path()

        # Sensoren erstellen
        if USE_SENSORS:
            self.sensor1 = sensors.Sensor(0)
            self.sensor2 = sensors.Sensor(30)
            self.sensor3 = sensors.Sensor(150)
            self.sensor4 = sensors.Sensor(180)
            self.sensor5 = sensors.Sensor(210)
            self.sensor6 = sensors.Sensor(330)
            self.sensor_s.add(self.sensor1)
            self.sensor_s.add(self.sensor2)
            self.sensor_s.add(self.sensor3)
            self.sensor_s.add(self.sensor4)
            self.sensor_s.add(self.sensor5)
            self.sensor_s.add(self.sensor6)

        self.map_s.add(self.current_map)
        self.player_s.add(self.car)
        self.range_s.add(self.robrange)
        self.path_s.add(self.path)


        pygame.display.set_caption('RoboSimAI')
        pygame.mouse.set_visible(True)
        self.font = pygame.font.Font(None, 24)

        self.background = pygame.Surface(self.screen.get_size())

        self.background.fill((210, 210, 250))
예제 #4
0
def change_map(map_s, maps, type):
    map_s.empty()
    maps.map_files.clear()
    for tile_num in range(0, len(maps.map_tile[type])):
        maps.map_files.append(load_image(maps.map_tile[type][tile_num], False))
    for x in range(0, 10):
        for y in range(0, 10):
            map_s.add(
                maps.Map(maps.map_1[x][y], x * 1000, y * 1000,
                         maps.map_1_rot[x][y]))
    def test_equal(self):
        with open("resources/MxM_unseen_1.map", 'rb') as f:
            buf = structure_tools.Buffer(f.read())

        m = maps.Map().from_buffer(buf)
        m.unpack()
        m.directory.unpack()

        buf2 = structure_tools.Buffer()
        m.serialize_to_buffer(buf2)

        self.assertEqual(buf.getvalue(), buf2.getvalue())
예제 #6
0
    def testbfs():
        print('BFS Test')
        print('Loading map...', end='')
        m = maps.Map('../src/maps/dungeon')
        print('done')

        print('Loading problem...', end='')
        prob = MapProblem(m, (1, 6), (15, 1))
        print(' done')

        print('Solving...')
        return bf_search(prob, True)
예제 #7
0
 def __init__(self):
     args = self.parse_command_line_arguments()
     self.screen = pygame.display.set_mode((args.width, args.height))
     self.screen_rect = self.screen.get_rect()
     pygame.display.set_caption("Place Pictures")
     pygame.key.set_repeat(100, 100)
     self.map = maps.Map(self)
     self.map.create_map(2000, 2000, 0, 0, 0)
     self.gui = gui.Gui(self)
     self.pictures = pictures.Pictures(self)
     self.mouse = mouse.Mouse()
     self.savegame = savegame.Savegame(self)
     pygame.display.flip()
예제 #8
0
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((SCREEN_W, SCREEN_H))
        pygame.display.set_caption("Flapper")
        self.clock = pygame.time.Clock()

        self.score = 0
        self.scorefont = pygame.font.SysFont("Arial", 40)
        self.scoretext = self.scorefont.render("SKOOR: " + str(self.score),
                                               True, WHITE)

        self.hero = player.Player(19 * BLOCK_SIZE, 6 * BLOCK_SIZE)
        self.tilemap = maps.Map()
예제 #9
0
def get_screen(window):
    thing = tde.Screen(window)
    bottom_bar = tde.Rectangle(main.WIDTH / 2, BOTTOM_BAR_HEIGHT / 2,
                               main.WIDTH, BOTTOM_BAR_HEIGHT)
    bottom_bar.attach(thing)
    top_bar = tde.Rectangle(main.WIDTH / 2, main.HEIGHT - (TOP_BAR_HEIGHT / 2),
                            main.WIDTH, TOP_BAR_HEIGHT)
    top_bar.attach(thing)
    play_map = maps.Map(thing, tilesets.Fields())
    overlay_button = PlayButton(PLAY_BUTTON_COLOUR, thing, PLAY_BUTTON_X,
                                PLAY_BUTTON_Y, PLAY_BUTTON_WIDTH,
                                PLAY_BUTTON_HEIGHT, PLAY_BUTTON_TEXT,
                                PLAY_BUTTON_TEXT_FONT, PLAY_BUTTON_TEXT_SIZE,
                                PLAY_BUTTON_TEXT_COLOUR)
    return thing
예제 #10
0
    def testdfs():
        print('DFS Test')
        print('Loading map...', end='')
        m = maps.Map('../src/maps/dungeon')
        print('done')

        print('Loading problem...', end='')
        start = (1, 6)
        end = (15, 1)
        prob = MapProblem(m, start, end)
        print(' done')

        print('Solving:\nStart', start, '\nEnd', end, '\n')
        return df_search(
            prob, [MoveDir.UP, MoveDir.DOWN, MoveDir.LEFT, MoveDir.RIGHT],
            True)
예제 #11
0
def menu():
    clock = pygame.time.Clock()
    running = True
    cam = camera.Camera()
    #create sprite groups.
    map_s = pygame.sprite.Group()
    #generate tiles
    for tile_num in range(0, len(maps.map_tile)):
        maps.map_files.append(load_image(maps.map_tile[tile_num], False))
    for x in range(0, 5):
        for y in range(0, 6):
            map_s.add(maps.Map(maps.map_2[x][y], x * 450, y * 450))
    while running:
        map_s.update(cam.x, cam.y)
        map_s.draw(screen)
        clock.tick(64)
예제 #12
0
    def test_dump(self):
        with open("resources/MxM_unseen_1.map", 'rb') as f:
            buf = structure_tools.Buffer(f.read())

        m = maps.Map().from_buffer(buf)
        m.unpack()
        m.directory.unpack()

        import tempfile

        dir = tempfile.TemporaryDirectory()

        path = dir.name

        m.dump_to_folder(path)

        dir.cleanup()
예제 #13
0
    def testids():
        print('IDFS Test')
        print('Loading map...', end='')
        m = maps.Map('../src/maps/dungeon')
        print('done')

        print('Loading problem...', end='')
        start = (0, 9)
        end = (15, 1)
        prob = MapProblem(m, start, end)
        print(' done')

        print('Solving:\nStart', start, '\nEnd', end)
        return id_search(
            prob,
            [MoveDir.RIGHT, MoveDir.UP, MoveDir.LEFT, MoveDir.DOWN],
            1,
            1,
        )
예제 #14
0
    def testas():
        print('RBFS Test')
        print('Loading map...', end='')
        m = maps.Map('../src/maps/mission2')
        print('done')

        cost = {
            Terrain.MOUNTAIN: None,
            Terrain.LAND: 1,
            Terrain.WATER: 2,
            Terrain.SAND: 3,
            Terrain.FOREST: 4
        }

        print('Loading problem...', end='')
        start = (0, 10)
        end = (4, 5)
        prob = MapProblem(m, start, end, cost)
        print(' done')

        print('Solving:\nStart', start, '\nEnd', end)
        return astar_search(prob)
예제 #15
0
    def test_structures(self):
        files = [
            "resources/" + f for f in os.listdir("resources/")
            if f.endswith(".map")
        ]

        # import compression
        # compression.COMPRESSION = compression.BlastDecompression()

        for file in files:
            # print("reading file: {}".format(file))
            with open(file, 'rb') as f:
                data = f.read()

            # print("parsing file")
            buf = structure_tools.Buffer(data)
            m = maps.Map().from_buffer(buf)

            # print("verifying file")
            m.unpack()
            m.directory.unpack()

            # print("checking no data is left")
            self.assertEqual(buf.remaining(), 0)
예제 #16
0
x_old = car.x
y_old = car.y
##the old position for speed measurements

##read the maps and draw
for tile_num in range(0, len(maps.map_tile)):

    #add submap idx to array
    maps.map_files.append(load_image(maps.map_tile[tile_num], False))

for x in range(0, 7):

    for y in range(0, 20):

        #add submap to mapgroup
        map_s.add(maps.Map(maps.map_1[x][y], x * 1000, y * 1000))

##read the maps and draw

###main loop process

while True:
    ##system event
    for event in pygame.event.get():

        # quit for windows
        if event.type == QUIT:

            pygame.quit()

            sys.exit()
예제 #17
0
파일: BBB.py 프로젝트: JohnIler2/git
    Tiles.Tile("a group of locals toobing down the river", 1, "YouTubers",
               "Beta video tape"))

#These are the filler scenario tiles.  Don't put items here.  You can do it separately when the GenerateMap() code is called  You can put events here.
JohnRiverFluffTiles.append(
    Tiles.Tile("locals shouting at you from the river's edge", 0, "Locals",
               ""))
JohnRiverFluffTiles.append(Tiles.Tile("blue water", 0, "", ""))
JohnRiverFluffTiles.append(Tiles.Tile("open water", 0, "", ""))
JohnRiverFluffTiles.append(Tiles.Tile("slightly, murky water", 0, "", ""))
#Generate the scenario map!
JohnRiverMap = GenerateMap(1, 20, JohnRiverTiles, JohnRiverFluffTiles,
                           JohnRiverAvailableItems)
#ToDo:Need this in everyone's code!
#Setup the default map
JohnRiverMap = Maps.Map(JohnRiverMap, 1, 20,
                        "The river bank is too steep to exit here!")
MasterListOfItems += JohnRiverMap.GetItems()
#Manually add a few items I will control in the scenario
MasterListOfItems.append("a tasty burger")
MasterListOfItems.append("fried green tomatoes")
MasterListOfItems.append("a Babble Fish")
MasterListOfItems.append("a vial of crude oil")
#    **************************  River specific code end  **************************

#shell code (or copy the above river code to start your scenario)
#Map=[]
BayMap = []
BayTiles = []
BayFluffTiles = []
#(uncomment after you build tiles) - BayMap=GenerateMap(Len,Width,BayTiles,BayFluffTiles,AvailableItems)
예제 #18
0
    def __init__(self):
        metadata = {'render.modes': ['human']}
        pygame.init()

        self.action_space = spaces.Discrete(5)
        low = np.array([
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0
        ])
        high = np.array([
            4000, 4000, 360, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000,
            4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000,
            4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000,
            4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000,
            4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000,
            4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000,
            4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000,
            4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000,
            4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000,
            4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000,
            4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000,
            4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000,
            4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000,
            4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000,
            4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000,
            4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000,
            4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000,
            4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000,
            4000, 4000, 4000, 4000, 4000
        ])

        self.observation_space = spaces.Box(low, high, dtype=np.float32)

        self.score = 0
        self.stepscore = 0
        self.stepcount = 0
        self.holescore = 12

        self.map_s = pygame.sprite.Group()
        self.player_s = pygame.sprite.Group()
        self.path_s = pygame.sprite.Group()
        self.hole_s = pygame.sprite.Group()
        self.range_s = pygame.sprite.Group()

        self.animation_count = 0

        self.screen = pygame.display.set_mode((1800, 1000))

        self.clock = pygame.time.Clock()
        self.CENTER_X = int(pygame.display.Info().current_w / 2)
        self.CENTER_Y = int(pygame.display.Info().current_h / 2)
        self.running = True
        self.car = player.Player()
        self.cam = camera.Camera()
        self.robrange = roborange.RoRange()
        self.current_map = maps.Map()
        self.path = path.Path()

        # create new holes
        for r in range(100):
            hole = holes.Holes()
            hole.add(self.hole_s)

        # create list of hole coordinates and IR´s
        self.holestate = []
        for hole in self.hole_s:
            self.holestate.append(hole.x)
            self.holestate.append(hole.y)

        # create observation state array
        self.state = np.array([self.car.x, self.car.y, self.car.dir])
        holearray = np.array(self.holestate)
        self.state = np.append(self.state, holearray)

        self.map_s.add(self.current_map)
        self.player_s.add(self.car)
        self.range_s.add(self.robrange)
        self.path_s.add(self.path)

        pygame.display.set_caption('RoboSimAI')
        pygame.mouse.set_visible(True)
        self.font = pygame.font.Font(None, 24)

        self.background = pygame.Surface(self.screen.get_size())

        self.background.fill((210, 210, 250))
예제 #19
0
def main():
    # initialize objects.
    clock = pygame.time.Clock()
    running = True
    font = pygame.font.Font(None, 24)
    car = player.Player()
    cam = camera.Camera()
    target = gamemode.Finish()
    bound_alert = boundary.Alert()
    time_alert = timeout.Alert()
    info = menu.Alert()
    pointer = direction.Tracker(int(CENTER_W * 2), int(CENTER_H * 2))
    # create sprite groups.
    map_s = pygame.sprite.Group()
    player_s = pygame.sprite.Group()
    traffic_s = pygame.sprite.Group()
    tracks_s = pygame.sprite.Group()
    target_s = pygame.sprite.Group()
    pointer_s = pygame.sprite.Group()
    timer_alert_s = pygame.sprite.Group()
    bound_alert_s = pygame.sprite.Group()
    menu_alert_s = pygame.sprite.Group()

    # generate tiles
    for tile_num in range(0, len(maps.map_tile)):
        maps.map_files.append(load_image(maps.map_tile[tile_num], False))
    for x in range(0, 10):
        for y in range(0, 10):
            map_s.add(maps.Map(maps.map_1[x][y], x * 1000, y * 1000, maps.map_1_rot[x][y]))

    # load tracks
    tracks.initialize()
    # load finish
    target_s.add(target)
    # load direction
    pointer_s.add(pointer)
    # load alerts
    timer_alert_s.add(time_alert)
    bound_alert_s.add(bound_alert)
    menu_alert_s.add(info)
    # load traffic
    traffic.initialize(CENTER_W, CENTER_H)
    for count in range(0, TRAFFIC_COUNT):
        traffic_s.add(traffic.Traffic())

    player_s.add(car)

    cam.set_pos(car.x, car.y)

    while running:
        # Check for key input. (KEYDOWN, trigger often)
        keys = pygame.key.get_pressed()
        # Render loop.

        # Check for menu/reset, (keyup event - trigger ONCE)
        for event in pygame.event.get():
            if event.type == pygame.KEYUP:
                if keys[K_m]:
                    if (info.visibility == True):
                        info.visibility = False

                if (keys[K_p]):
                    car.reset()
                    target.reset()
                if (keys[K_q]):
                    pygame.quit()
                    sys.exit(0)

            if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                running = False
                break


        if (target.timeleft > 0):
            if keys[K_c]:
                car.steerleft()
            if keys[K_b]:
                car.steerright()
            if keys[K_UP]:
                car.accelerate()
            else:
                car.soften()
            if keys[K_DOWN]:
                car.deaccelerate()
            if keys[K_RIGHT]:
                car.breakk()

        cam.set_pos(car.x, car.y)

        # Show text data.
        text_fps = font.render('FPS: ' + str(int(clock.get_fps())), 1, (224, 16, 16))
        textpos_fps = text_fps.get_rect(centery=25, centerx=60)

        text_score = font.render('Score: ' + str(target.score), 1, (224, 16, 16))
        textpos_score = text_fps.get_rect(centery=45, centerx=60)

        text_timer = font.render(
            'Timer: ' + str(int((target.timeleft /1000) / 1000)) + ":" + str(int((target.timeleft / 1500) % 300)), 6,
            (224, 16, 16))
        textpos_timer = text_fps.get_rect(centery=65, centerx=60)

        # Render Scene.
        screen.blit(background, (0, 0))

        # cam.set_pos(car.x, car.y)

        map_s.update(cam.x, cam.y)
        map_s.draw(screen)

        # Conditional renders/effects
        car.grass(screen.get_at(((int(CENTER_W - 5), int(CENTER_H - 5)))).g)
        if (car.tracks):
            tracks_s.add(tracks.Track(cam.x + CENTER_W, cam.y + CENTER_H, car.dir))

        # Just render..
        tracks_s.update(cam.x, cam.y)
        tracks_s.draw(screen)

        player_s.update(cam.x, cam.y)
        player_s.draw(screen)

        traffic_s.update(cam.x, cam.y)
        traffic_s.draw(screen)

        target_s.update(cam.x, cam.y)
        target_s.draw(screen)

        pointer_s.update(car.x + CENTER_W, car.y + CENTER_H, target.x, target.y)
        pointer_s.draw(screen)

        # Conditional renders.
        if (boundary.breaking(car.x + CENTER_W, car.y + CENTER_H) == True):
            bound_alert_s.update()
            bound_alert_s.draw(screen)
        if (target.timeleft == 0):
            timer_alert_s.draw(screen)
            car.speed = 0
            text_score = font.render('Final Score: ' + str(target.score), 1, (224, 16, 16))
            textpos_score = text_fps.get_rect(centery=CENTER_H + 56, centerx=CENTER_W - 20)
        if (info.visibility == True):
            menu_alert_s.draw(screen)

        # Blit Blit..
        screen.blit(text_fps, textpos_fps)
        screen.blit(text_score, textpos_score)
        screen.blit(text_timer, textpos_timer)
        pygame.display.flip()

        # Check collision!!!
        if pygame.sprite.spritecollide(car, traffic_s, False):
            car.impact()
            target.car_crash()

        if pygame.sprite.spritecollide(car, target_s, True):
            target.claim_flag()
            target.generate_finish()
            target_s.add(target)

        clock.tick(64)
예제 #20
0
    "run": run_away,
    "inventory": inventory.inventory
}

Commands_not_print_state = [
    "hilfe", "pickup", "fight", "save", "load", "rest", "inventory"
]

# game loop
if __name__ == "__main__":
    # Player Name
    name = input("Wie heißt du? ")
    # Player start stats
    player = enemies.player(name, 1, 500, 50, 100, 100)
    # generate Map
    maps = maps.Map(10, 10)
    print("Gib \"hilfe\" ein um eine uebersicht der Befehle zu erhalten.\n")
    while True:
        command = input(">>>").lower().split(" ")
        if command[0] in Commands:
            if len(command) > 1:
                Commands[command[0]](player, maps, command[1:])
                clear(command[0])
            else:
                Commands[command[0]](player, maps)
                clear(command[0])
        # Intercept wrong input
        elif command[0] not in Commands:
            print("Du rennst im Keis und tuhst garnichts.")
        if command[0] not in Commands:
            pass
예제 #21
0
import maps
import curses

test = maps.Map("firstfloorhome.map", [1, 2])
rows, columns = test.get_size()

screen = curses.initscr()

curses.curs_set(0)
curses.noecho()

map_window = curses.newwin(rows + 1, columns + 1, 0, 0)

c = None

running = 1
while (running):
    try:
        test.render(map_window)
        map_window.refresh()
        screen.refresh()
        c = chr(screen.getch())
        if c in ['w', 'd', 's', 'a']:
            test.move_player(c)
        if c == 'e':
            test.interact()
        if c == 'q':
            running = 0
    except Exception as e:
        curses.endwin()
        print("Critical failure")
예제 #22
0
car_yellow = car.Car(start_values["1"][0],start_values["1"][1],start_values["1"][2],start_values["1"][3],start_values["1"][4],start_values["1"][5])
car_red = car.Car(start_values["2"][0],start_values["2"][1],start_values["2"][2],start_values["2"][3],start_values["2"][4],start_values["2"][5])
car_blue = car.Car(start_values["3"][0],start_values["3"][1],start_values["3"][2],start_values["3"][3],start_values["3"][4],start_values["3"][5])
car_green = car.Car(start_values["4"][0],start_values["4"][1],start_values["4"][2],start_values["4"][3],start_values["4"][4],start_values["4"][5])

cars_obj = {}

car_draw_obj = {}

user_number = 0
dead_players = []
disconnected_players = []

#objects for graphics
game_map = maps.Map('media/maps/full.png',0,0)
game_map_s = pygame.sprite.Group()
game_map_s.add(game_map)

collision_map = maps.Map('media/maps/blocks.png',0,0)
collision_map_s = pygame.sprite.Group()
collision_map_s.add(collision_map)

victory_sound = pygame.mixer.Sound("media/music/victory.wav")
lose_sound = pygame.mixer.Sound("media/music/lose.wav")
button_sound = pygame.mixer.Sound("media/music/button.wav")
music_stopped = True

rules_read = False

with open('config/config.json','r') as json_file:
예제 #23
0
RiverTiles.append(
    Tiles.Tile("a snake in the water", 1, "Snake", "a dead snake"))
RiverTiles.append(
    Tiles.Tile("water with a shiny surface", 1, "Net", "fishing net"))
RiverTiles.append(Tiles.Tile("river Tile 4", 1, "", "old lure"))
RiverTiles.append(Tiles.Tile("river Tile 5", 1, "", "torn shirt"))
#These are the filler scenario tiles.  Don't put items here.  You can do it separately when the GenerateMap() code is called  You can put events here.
RiverFluffTiles.append(Tiles.Tile("clear, open water", 0, "", ""))
RiverFluffTiles.append(Tiles.Tile("blue water", 0, "", ""))
RiverFluffTiles.append(Tiles.Tile("beautiful, blue water", 0, "", ""))
RiverFluffTiles.append(Tiles.Tile("slightly, murky water", 0, "", ""))
#Generate the scenario map!
RiverMap = GenerateMap(5, 5, RiverTiles, RiverFluffTiles, RiverAvailableItems)
#ToDo:Need this in everyone's code!
#Setup the default map
RiverMap = Maps.Map(RiverMap, 5, 5,
                    "The river bank is too steep to exit here!")
MasterListOfItems += RiverMap.GetItems()
#print "John"
#print MasterListOfItems
#    **************************  River specific code end  **************************

#    ************************** Casino specific code start **************************
CasinoMap = []  #This is the scenario map which holds all the tiles
CasinoTiles = [
]  #Important tiles, will be randomized over the map.  (Only placed once)
CasinoFluffTiles = [
]  #"filler tiles" to populate around the "real scenario tiles".  (Can appear multiple times)
CasinoAvailableItems = [
    "Dice", "Craps Stick", "Marked Deck", "Crab Leg", "Lucky Rabbit Foot"
]  #Available items which can be placed randomly over the map.
#Usage:Tiles.Tile("Tile description",ignore this field, pass a number,"name of an event you can test for and act on","name of item which can be found on tile"
예제 #24
0
    def run(self):

        # generate tiles
        for tile_num in range(0, len(maps.map_tile)):
            maps.map_files.append(load_image(maps.map_tile[tile_num], False))
        for x in range(0, 10):
            for y in range(0, 10):
                self.map_s.add(
                    maps.Map(maps.map_1[x][y], x * 1000, y * 1000,
                             maps.map_1_rot[x][y]))

        # load tracks
        tracks.initialize()
        # load finish
        self.target_s.add(self.target)
        # load direction
        self.pointer_s.add(self.pointer)
        # load alerts
        self.timer_alert_s.add(self.time_alert)
        self.bound_alert_s.add(self.bound_alert)
        self.celular_s.add(self.celular_alert)
        self.stop_s.add(self.stop_alert)

        self.menu_alert_s.add(self.info)
        # load traffic
        traffic.initialize(CENTER_W, CENTER_H)
        for count in range(0, self.quantidadeVeiculos):
            self.traffic_s.add(traffic.Traffic())

        self.player_s.add(self.car)

        self.cam.set_pos(self.car.x, self.car.y)

        while self.running:
            # Render loop.
            # Check for menu/reset, (keyup event - trigger ONCE)
            for event in pygame.event.get():
                if event.type == pygame.KEYUP:
                    if keys[K_m]:
                        if (self.info.visibility == True):
                            self.info.visibility = False
                        else:
                            self.info.visibility = True
                    if (keys[K_p]):
                        self.car.reset()
                        self.target.reset()
                    if (keys[K_q]):
                        pygame.quit()
                        sys.exit(0)
                    if (keys[K_z]):  # atende ligacao
                        self.celular_alert.atender = True

                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                    from source.menu import Menu as menu2
                    aux = menu2()
                    aux.main_menu()
                    running = False
                    break

            # Check for key input. (KEYDOWN, trigger often)
            keys = pygame.key.get_pressed()
            if (self.target.timeleft > 0):
                if keys[K_LEFT]:
                    self.car.steerleft()
                if keys[K_RIGHT]:
                    self.car.steerright()
                if keys[K_UP]:
                    self.car.accelerate()
                else:
                    self.car.soften()
                if keys[K_DOWN]:
                    self.car.deaccelerate()

                self.cam.set_pos(self.car.x, self.car.y)

            # Show text data.

            text_fps = self.font.render('', 1, (224, 16, 16))
            textpos_fps = text_fps.get_rect(centery=25, centerx=60)

            text_score = self.font.render(
                'Pontuacao: ' + str(self.target.score), 1, (224, 16, 16))
            textpos_score = text_fps.get_rect(centery=45, centerx=60)

            text_timer = self.font.render(
                'Tempo: ' + str(int((self.target.timeleft / 60) / 60)) + ":" +
                str(int((self.target.timeleft / 60) % 60)), 1, (224, 16, 16))
            textpos_timer = text_fps.get_rect(centery=65, centerx=60)

            # Render Scene.
            self.screen.blit(self.background, (0, 0))

            # cam.set_pos(car.x, car.y)

            self.map_s.update(self.cam.x, self.cam.y)
            self.map_s.draw(self.screen)

            # Conditional renders/effects
            self.car.grass(
                self.screen.get_at(
                    ((int(self.CENTER_W - 5), int(self.CENTER_H - 5)))).g)
            if self.car.tracks:
                self.tracks_s.add(
                    tracks.Track(self.cam.x + self.CENTER_W,
                                 self.cam.y + self.CENTER_H, self.car.dir))

            # Just render..
            self.tracks_s.update(self.cam.x, self.cam.y)
            self.tracks_s.draw(self.screen)

            self.player_s.update(self.cam.x, self.cam.y)
            self.player_s.draw(self.screen)

            self.traffic_s.update(self.cam.x, self.cam.y)
            self.traffic_s.draw(self.screen)

            self.target_s.update(self.cam.x, self.cam.y)
            self.target_s.draw(self.screen)

            self.pointer_s.update(self.car.x + self.CENTER_W,
                                  self.car.y + self.CENTER_H, self.target.x,
                                  self.target.y)
            self.pointer_s.draw(self.screen)

            # stop_alert.updateTimer(time.time())
            # Conditional renders.
            if (bounds.breaking(self.car.x + self.CENTER_W,
                                self.car.y + self.CENTER_H) == True):
                self.bound_alert_s.update()
                self.bound_alert_s.draw(self.screen)

            if (self.target.timeleft == 0):
                self.timer_alert_s.draw(self.screen)
                self.car.speed = 0
                text_score = self.font.render(
                    'Pontuacao Final: ' + str(self.target.score), 1,
                    (224, 16, 16))
                textpos_score = text_fps.get_rect(centery=self.CENTER_H + 56,
                                                  centerx=self.CENTER_W - 20)

                self.celular_alert.grass(
                    self.screen.get_at(
                        ((int(self.CENTER_W - 5), int(self.CENTER_H - 5)))).g,
                    self.car.speed)
            if (int((self.target.timeleft / 60) % 60) % 20 == 0):
                self.celular_alert.visibility = True
                self.celular_alert.startTimer()
            if (self.celular_alert.tocando):
                self.celular_alert.chron.run()

            if (self.target.timeleft > 0
                    and self.celular_alert.visibility is True):
                self.celular_s.draw(self.screen)
                keys = pygame.key.get_pressed()
                if (keys[K_c] and self.car.speed > 0.4):
                    self.target.score -= 50
                    self.celular_alert.tocando = False
                    self.celular_alert.visibility = False
                if (keys[K_c] and self.car.speed <= 0.4):
                    self.target.score += 200
                    self.celular_alert.tocando = False
                    self.celular_alert.visibility = False
                if (not self.celular_alert.cel_time()):
                    self.target.score -= 100
                    self.celular_alert.tocando = False
                    self.celular_alert.visibility = False

                self.stop_alert.stop_car(self.car.speed)
            if (int((self.target.timeleft / 60) % 60) % 15 == 0
                    and self.car.speed >= 0.1):
                self.stop_alert.visibility = True

            if (self.target.timeleft > 0
                    and self.stop_alert.visibility is True):
                self.stop_s.draw(self.screen)
                if (self.car.speed < 0.1):
                    self.target.score += 200
                    self.stop_alert.visibility = False
                else:
                    self.target.score -= 1

            if (self.info.visibility == True):
                self.menu_alert_s.draw(self.screen)

            # Blit Blit..
            pygame.draw.rect(self.screen, (216, 216, 216), [40, 30, 200, 55])
            self.screen.blit(text_fps, textpos_fps)
            self.screen.blit(text_score, textpos_score)
            self.screen.blit(text_timer, textpos_timer)
            pygame.display.flip()

            # Check collision!!!
            if pygame.sprite.spritecollide(self.car, self.traffic_s, False):
                self.car.impact()
                self.target.car_crash()
                self.target.score -= 5

            if pygame.sprite.spritecollide(self.car, self.target_s, True):
                self.target.claim_flag()
                self.target.score += 50
                self.target.generate_finish()
                self.target_s.add(self.target)

            self.clock.tick(64)

    # cria semaforo

    # initialization
        pygame.init()
        print pygame.display.Info().current_w
        print pygame.display.Info().current_h
        '''
        screen = pygame.display.set_mode((pygame.display.Info().current_w,
                                          pygame.display.Info().current_h),
                                          pygame.FULLSCREEN)
        '''
        self.screen = pygame.display.set_mode((1024, 768), pygame.FULLSCREEN)

        pygame.display.set_caption('Race of Math.')
        pygame.mouse.set_visible(True)
        self.font = pygame.font.Font(None, 24)
        # CENTER_W = int(1024 / 2)
        # CENTER_H = int(768 / 2)
        '''
        CENTER_W =  int(pygame.display.Info().current_w /2)
        CENTER_H =  int(pygame.display.Info().current_h /2)
        '''

        # new background surface
        self.background = pygame.Surface(self.screen.get_size())
        self.background = self.background.convert_alpha()
        self.background.fill((26, 26, 26))
예제 #25
0
def main():
    clock = pygame.time.Clock()
    running = True
    font = pygame.font.Font(None, 24)
    car = player.Player()
    cam = camera.Camera()
    target = gamemode.Final()
    bound_alert = bounds.Alert()
    time_alert = timeout.Alerta()
    info = menu.Alerta()

    # se crea un sprite con los grupos
    game_main_sprite = pygame.sprite.Group()
    map_s = pygame.sprite.Group()
    player_s = pygame.sprite.Group()

    traffic_s = pygame.sprite.Group()
    target_s = pygame.sprite.Group()
    pointer_s = pygame.sprite.Group()
    timer_alerta_s = pygame.sprite.Group()
    bound_alert_s = pygame.sprite.Group()
    menu_alerta_s = pygame.sprite.Group()
    balas = pygame.sprite.Group()

    #Generar tiles
    for tile_num in range(0, len(maps.map_tile)):
        maps.map_files.append(load_image(maps.map_tile[tile_num], False))
    for x in range(0, 10):
        for y in range(0, 10):
            map_s.add(
                maps.Map(maps.map_1[x][y], x * 1000, y * 1000,
                         maps.map_1_rot[x][y]))
#Se carga el final del juego
    game_main_sprite.add(target)
    target_s.add(target)

    #Se cargan las alertas
    timer_alerta_s.add(time_alert)
    bound_alert_s.add(bound_alert)
    menu_alerta_s.add(info)
    #Carga Trafico
    traffic.initialize(Centro_W, Centro_H)
    for count in range(0, Cantidad_trafico):
        game_main_sprite.add(traffic.Traffic())
        traffic_s.add(traffic.Traffic())

    game_main_sprite.add(car)
    player_s.add(car)

    cam.set_pos(car.x, car.y)

    while running:
        for event in pygame.event.get():
            if event.type == pygame.KEYUP:
                if (keys[K_m]):
                    if (info.visibilidad == True):
                        info.visibilidad = False
                    else:
                        info.visibilidad = True
                if (keys[K_p]):
                    car.reset()
                    target.reset()
                if (keys[K_q]):
                    pygame.quit()
                    sys.exit(0)

            if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                running = False
                break


#Check for key input. (KEYDOWN, trigger often)
        keys = pygame.key.get_pressed()
        if (target.timeleft > 0):
            if keys[K_LEFT]:
                car.dirigir_izquierda()
            if keys[K_RIGHT]:
                car.dirigir_derecha()
            if keys[K_UP]:
                car.accelerate()
            else:
                car.soften()
            if keys[K_DOWN]:
                car.deaccelerate()
            if keys[K_SPACE]:
                #Crear objeto bala
                bala = player.DisparoCarro()
                bala.rect.x = car.rect.x
                bala.rect.y = car.rect.y
                bala.dir = car.dir
                bala.image = pygame.transform.rotate(bala.image, bala.dir)
                game_main_sprite.add(bala)
                balas.add(bala)

        cam.set_pos(car.x, car.y)
        text_fps = font.render('FPS: ' + str(int(clock.get_fps())), 1,
                               (224, 16, 16))
        textpos_fps = text_fps.get_rect(centery=25, centerx=60)

        text_score = font.render('Score: ' + str(target.score), 1,
                                 (224, 16, 16))
        textpos_score = text_fps.get_rect(centery=45, centerx=60)

        text_timer = font.render(
            'Timer: ' + str(int((target.timeleft / 30) / 60)) + ":" +
            str(int((target.timeleft / 60) % 60)), 1, (224, 16, 16))
        textpos_timer = text_fps.get_rect(centery=65, centerx=60)

        screen.blit(background, (0, 0))

        cam.set_pos(car.x, car.y)

        map_s.update(cam.x, cam.y)
        map_s.draw(screen)

        player_s.update()
        player_s.draw(screen)

        traffic_s.update(cam.x, cam.y)
        traffic_s.draw(screen)

        target_s.update(cam.x, cam.y)
        target_s.draw(screen)

        pointer_s.update(car.x + Centro_W, car.y + Centro_H, target.x,
                         target.y)
        pointer_s.draw(screen)

        balas.update()
        balas.draw(screen)

        if (bounds.breaking(car.x + Centro_W, car.y + Centro_H) == True):
            bound_alert_s.update()
            bound_alert_s.draw(screen)
        if (target.timeleft == 0):
            timer_alerta_s.draw(screen)
            car.speed = 0
            text_score = font.render('Puntaje Final: ' + str(target.score), 1,
                                     (224, 16, 16))
            textpos_score = text_fps.get_rect(centery=Centro_H + 56,
                                              centerx=Centro_W - 20)
        if (info.visibilidad == True):
            menu_alerta_s.draw(screen)

        screen.blit(text_score, textpos_score)
        screen.blit(text_timer, textpos_timer)
        pygame.display.flip()

        #Colosiones
        if pygame.sprite.spritecollide(car, traffic_s, False):
            car.impact()
            target.colision_carro()

        if pygame.sprite.spritecollide(car, target_s, True):
            target.Bandera()
            target.generar_final()

            target_s.add(target)

        clock.tick(200)
예제 #26
0
def main(id='001'):

    agentePontosGanho = AI_INSTANCES.Agente_Interativo(
        AI_CONFIG._L3_PARAMETRO_pontos, 'gte', gameControl.setVeiculosHardmode)
    agenteTempoGasto = AI_INSTANCES.Agente_Interativo(
        AI_CONFIG._L3_PARAMETRO_tempogasto, 'gte',
        gameControl.setExtraTimeHardmode)
    agenteChamadasAtendidas = AI_INSTANCES.Agente_Interativo(
        AI_CONFIG._L3_PARAMETRO_chamadas_atentidas, 'gte',
        gameControl.setPontosHardmode)
    agenteParadas = AI_INSTANCES.Agente_Interativo(
        AI_CONFIG._L3_PARAMETRO_paradas, 'gte', gameControl.setPontosHardmode)
    agenteEscrita = AI_INSTANCES.Agente_de_Escrita('./logs/' + id + '.txt', id,
                                                   3)

    agenteEscrita.escreveLog(['NOVOJOGO', str(0)])

    totalChamadasAtendidas = 0
    totalParadas = 0

    running = True
    # generate tiles
    for tile_num in range(0, len(maps.map_tile)):
        maps.map_files.append(load_image(maps.map_tile[tile_num], False))
    for x in range(0, 10):
        for y in range(0, 10):
            map_s.add(
                maps.Map(maps.map_1[x][y], x * 1000, y * 1000,
                         maps.map_1_rot[x][y]))

    # load tracks
    tracks.initialize()
    # load finish
    target_s.add(target)
    # load direction
    pointer_s.add(pointer)
    # load alerts
    timer_alert_s.add(time_alert)
    bound_alert_s.add(bound_alert)
    celular_s.add(celular_alert)
    stop_s.add(stop_alert)

    menu_alert_s.add(info)
    # load traffic
    traffic.initialize(CENTER_W, CENTER_H)

    for count in range(0, gameControl.quantidadeVeiculos):
        traffic_s.add(traffic.Traffic())

    player_s.add(car)

    cam.set_pos(car.x, car.y)

    end = False
    while running:
        # Render loop.
        # Check for menu/reset, (keyup event - trigger ONCE)
        keys = pygame.key.get_pressed()
        for event in pygame.event.get():
            if event.type == pygame.KEYUP:
                if keys[K_m]:
                    if (info.visibility == True):
                        info.visibility = False
                    else:
                        info.visibility = True
                if (keys[K_p]):
                    end = False
                    car.reset()
                    target.reset()
                if (keys[K_q]):
                    agenteEscrita.escreveLog(['SAIU', '-'])
                    pygame.quit()
                    sys.exit(0)
                if (keys[K_z]):  # atende ligacao
                    celular_alert.atender = True

            if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                from source.menu import Menu as menu2
                aux = menu2()
                aux.main_menu()
                running = False
                agenteEscrita.escreveLog(['SAIU', '-'])
                break

        # Check for key input. (KEYDOWN, trigger often)
        if (target.timeleft > 0):
            if keys[K_LEFT]:
                car.steerleft()
            if keys[K_RIGHT]:
                car.steerright()
            if keys[K_UP]:
                car.accelerate()
            else:
                car.soften()
            if keys[K_DOWN]:
                car.deaccelerate()

            cam.set_pos(car.x, car.y)

        # Show text data.

        text_fps = font.render('', 1, (224, 16, 16))
        textpos_fps = text_fps.get_rect(centery=25, centerx=60)

        text_score = font.render('Pontuacao: ' + str(target.score), 1,
                                 (224, 16, 16))
        textpos_score = text_fps.get_rect(centery=45, centerx=60)

        text_timer = font.render(
            'Tempo: ' + str(int((target.timeleft / 60) / 60)) + ":" +
            str(int((target.timeleft / 60) % 60)), 1, (224, 16, 16))
        textpos_timer = text_fps.get_rect(centery=65, centerx=60)

        # Render Scene.
        screen.blit(background, (0, 0))

        # cam.set_pos(car.x, car.y)

        map_s.update(cam.x, cam.y)
        map_s.draw(screen)

        # Conditional renders/effects
        car.grass(screen.get_at(((int(CENTER_W - 5), int(CENTER_H - 5)))).g)
        tracks_s = []
        if car.tracks:
            tracks_s.add(
                tracks.Track(cam.x + CENTER_W, cam.y + CENTER_H, car.dir))

        # Just render..
        tracks_s.update(cam.x, cam.y)
        tracks_s.draw(screen)

        player_s.update(cam.x, cam.y)
        player_s.draw(screen)

        traffic_s.update(cam.x, cam.y)
        traffic_s.draw(screen)

        target_s.update(cam.x, cam.y)
        target_s.draw(screen)

        pointer_s.update(car.x + CENTER_W, car.y + CENTER_H, target.x,
                         target.y)
        pointer_s.draw(screen)

        # stop_alert.updateTimer(time.time())
        # Conditional renders.
        if (bounds.breaking(car.x + CENTER_W, car.y + CENTER_H) == True):
            bound_alert_s.update()
            bound_alert_s.draw(screen)

        if (target.timeleft == 0):
            timer_alert_s.draw(screen)
            car.speed = 0
            text_score = font.render('Pontuacao Final: ' + str(target.score),
                                     1, (224, 16, 16))
            textpos_score = text_fps.get_rect(centery=CENTER_H,
                                              centerx=CENTER_W - 100)
            if end is False:
                end = True
                gameControl.extraTimeValue = AI_CONFIG._L3_tempo_extra_facil
                gameControl.quantidadeVeiculos = AI_CONFIG._L3_quantidade_veiculos_facil
                gameControl.pontosChamadaAtendida = AI_CONFIG._L3_ponto_atender_facil
                gameControl.pontosPararCarro = AI_CONFIG._L3_ponto_parar_facil
                agenteEscrita.escreveLog(['TERMINOU', str(target.score)])

        celular_alert.grass(
            screen.get_at(((int(CENTER_W - 5), int(CENTER_H - 5)))).g,
            car.speed)
        if (target.totalTime > 300 and int(
            (target.totalTime / 60) % 60) % 20 == 0):
            celular_alert.visibility = True
            celular_alert.startTimer()
        if (celular_alert.tocando):
            celular_alert.chron.run()

        if (target.timeleft > 0 and celular_alert.visibility is True
                and celular_alert.tocando is True):
            celular_s.draw(screen)
            keys = pygame.key.get_pressed()
            if (keys[K_c] and car.speed > 0.4):
                celular_alert.visibility = False
                celular_alert.tocando = False
                target.score -= 70
                agenteEscrita.escreveLog(['ATENDEUERRADO', -70])
            if (celular_alert.visibility is True
                    and celular_alert.tocando is True and keys[K_c]
                    and car.speed <= 0.4):
                celular_alert.visibility = False
                celular_alert.tocando = False
                target.score += gameControl.pontosChamadaAtendida
                agenteEscrita.escreveLog(['ATENDEU', 200])
                agenteChamadasAtendidas.analizaEntrada(totalChamadasAtendidas)
            if (not celular_alert.cel_time()):
                celular_alert.visibility = False
                celular_alert.tocando = False
                target.score -= 100
                agenteEscrita.escreveLog(['NAOATENDEU', -100])

        stop_alert.stop_car(car.speed)
        if (target.totalTime != 0 and int(
            (target.totalTime / 60) % 60) % 15 == 0 and car.speed >= 0.1):
            stop_alert.visibility = True

        if (target.timeleft > 0 and stop_alert.visibility is True):
            stop_s.draw(screen)
            if (car.speed < 0.1):
                target.score += 200
                stop_alert.visibility = False
                agenteEscrita.escreveLog(['PAROU', 200])
                agenteParadas.analizaEntrada(totalParadas)
            else:
                target.score -= 1

        if (info.visibility == True):
            menu_alert_s.draw(screen)

        # Blit Blit..
        pygame.draw.rect(screen, (216, 216, 216), [40, 30, 200, 55])
        screen.blit(text_fps, textpos_fps)
        screen.blit(text_score, textpos_score)
        screen.blit(text_timer, textpos_timer)
        pygame.display.flip()

        # Check collision!!!
        if pygame.sprite.spritecollide(car, traffic_s, False):
            car.impact()
            target.car_crash()
            target.score -= 5
            agenteEscrita.escreveLog(['BATIDA', '-5'])

        if pygame.sprite.spritecollide(car, target_s, True):
            target.claim_flag(gameControl.extraTimeValue)
            target.score += 50
            target.generate_finish()
            target_s.add(target)
            agenteEscrita.escreveLog(
                ['TEMPOEXTRA', gameControl.extraTimeValue])

        agentePontosGanho.analizaEntrada(target.score)
        agenteTempoGasto.analizaEntrada(target.totalTime)
        clock.tick(64)


# cria semaforo

# Enter the mainloop.
# main()

# pygame.quit()
# sys.exit(0)
예제 #27
0
def create_map():
    import maps

    game_map = maps.Map()
    map_size = config.map_size

    # generate a map on the fly here

    # generate entrance/exit locations
    entrance_loc = [
        random.randrange(1, map_size - 2),
        random.choice([0, map_size - 1]),
    ]
    random.shuffle(entrance_loc)  # to make it nice and even

    # generate empty map
    for row_num in range(map_size):
        if row_num in (0, map_size - 1):
            row = ['wall' for _ in range(map_size)]
        else:
            row = (['wall'] + ['floor'
                               for _ in range(map_size - 2)] + ['wall'])
        game_map.raw.append(row)

    # place entrance/exit
    setattr(game_map, 'entrance', tuple(entrance_loc))
    game_map.raw[entrance_loc[1]][entrance_loc[0]] = 'entrance'

    # find a path
    vertex = entrance_loc
    last_vertex = None

    for iter_count in range(20):
        corridor_len = random.randint(2, 6)
        corridor_dir = random.choice(['dpath', 'upath', 'rpath', 'lpath'])

        if last_vertex is not None:
            game_map.raw[vertex[1]][vertex[0]] = corridor_dir

        if corridor_dir == 'upath':
            for v in range(corridor_len):
                loc = game_map.raw[vertex[1] - 1][vertex[0]]
                if loc in ('upath', 'dpath', 'rpath', 'lpath', 'wall'):
                    break
                game_map.raw[vertex[1] - 1][vertex[0]] = 'upath'
                last_vertex = list(vertex)
                vertex[1] -= 1

        elif corridor_dir == 'dpath':
            for v in range(corridor_len):
                try:
                    loc = game_map.raw[vertex[1] + 1][vertex[0]]
                    if loc in ('upath', 'dpath', 'rpath', 'lpath', 'wall'):
                        break
                    game_map.raw[vertex[1] + 1][vertex[0]] = 'dpath'
                    last_vertex = list(vertex)
                    vertex[1] += 1
                except IndexError:
                    pass

        elif corridor_dir == 'rpath':
            for v in range(corridor_len):
                try:
                    loc = game_map.raw[vertex[1]][vertex[0] + 1]
                    if loc in ('upath', 'dpath', 'rpath', 'lpath', 'wall'):
                        break
                    game_map.raw[vertex[1]][vertex[0] + 1] = 'rpath'
                    last_vertex = list(vertex)
                    vertex[0] += 1
                except IndexError:
                    pass

        elif corridor_dir == 'lpath':
            for v in range(corridor_len):
                loc = game_map.raw[vertex[1]][vertex[0] - 1]
                if loc in ('upath', 'dpath', 'rpath', 'lpath', 'wall'):
                    break
                game_map.raw[vertex[1]][vertex[0] - 1] = 'lpath'
                last_vertex = list(vertex)
                vertex[0] -= 1

    setattr(game_map, 'exit', tuple(vertex))
    game_map.raw[vertex[1]][vertex[0]] = 'exit'

    # place water tiles for looking nice using drunkard walk

    amt = int(0.1 * map_size**2)
    count = 0

    random_loc = [
        random.randint(1, map_size - 2),
        random.randint(1, map_size - 2)
    ]
    current_loc = random_loc

    while count < amt:
        old_loc = list(current_loc)

        # if we are not in a path
        if game_map.raw[current_loc[1]][current_loc[0]] == 'floor':
            game_map.raw[current_loc[1]][current_loc[0]] = 'water'
            count += 1
        else:
            current_loc = old_loc

        new_area = random.randint(1, 100) <= 10

        if not new_area:
            direction = random.choice(['down', 'up', 'left', 'right'])
            if direction == 'down':
                current_loc[1] += 1
            elif direction == 'up':
                current_loc[1] -= 1
            elif direction == 'right':
                current_loc[0] += 1
            elif direction == 'left':
                current_loc[0] -= 1

            # prevent walking off the map
            current_loc[0] = max(current_loc[0], 1)
            current_loc[1] = max(current_loc[1], 1)
            current_loc[0] = min(current_loc[0], map_size - 2)
            current_loc[1] = min(current_loc[1], map_size - 2)

        else:
            current_loc = [
                random.randint(1, map_size - 2),
                random.randint(1, map_size - 2)
            ]

    config.game_map = game_map

    return
예제 #28
0
                                self.wallPos[1] * 2 * spriteR, spriteR,
                                spriteR)
        #rest of functionality pulled from wallTile, as other than init is identical


#on run, ultimately should loop until win/loss
#loop should iterate each agent one step, then redraw screen
#code below is a basic implementation

if __name__ == "__main__":
    agentList = []
    wallList = []
    maplist = "pacman-large.txt", "huge.txt", "complex2.txt", "complex.txt", "default.txt", "empty-large.txt", "pacman.txt", "test.txt"
    i = random.randint(0, 7)
    chosenMap = "maps/" + maplist[i]
    c_map = maps.Map(chosenMap,
                     c_gameType=random.randint(0, 1))  #"maps/complex2.txt")

    for i in range(0, 10):
        r = random.randint(0, 10)
        if r == 0:
            _role = "runner"
            agentList.append(
                agents.agent(c_map=c_map,
                             c_agent_list=agentList,
                             c_alg="Reflex",
                             _role=_role,
                             _index=(len(agentList)),
                             _rand=2))
        elif r >= 1 and r <= 3:
            _role = "runner"
            agentList.append(
예제 #29
0
def parse_map(level):
    import maps

    game_map_file = './assets/maps/map_{}.txt'.format(level)

    # for testing purposes
    # game_map_file = './assets/maps/test.txt'

    with open(game_map_file, 'r') as f:
        raw_data = f.read().splitlines()

    game_map = maps.Map()

    for num, line in enumerate(raw_data):
        row = []
        for charnum, character in enumerate(line):
            if character == '#':
                tile = 'wall'
            elif character == 'w':
                tile = 'water'
            elif character == '.':
                tile = 'floor'
            elif character == 'v':
                tile = 'dpath'
            elif character == '^':
                tile = 'upath'
            elif character == '>':
                tile = 'rpath'
            elif character == '<':
                tile = 'lpath'

            if num == 0:
                if character == 'v':
                    tile = 'entrance'
                elif character == '^':
                    tile = 'exit'
            elif num == len(raw_data) - 1:
                if character == '^':
                    tile = 'entrance'
                elif character == 'v':
                    tile = 'exit'
            elif charnum == 0:
                if character == '>':
                    tile = 'entrance'
                elif character == '<':
                    tile = 'exit'
            elif charnum == len(line) - 1:
                if character == '<':
                    tile = 'entrance'
                if character == '>':
                    tile = 'exit'

            if tile in ('entrance', 'exit'):
                setattr(game_map, tile, (charnum, num))

            row.append(tile)
        game_map.raw.append(row)

    config.game_map = game_map

    return
예제 #30
0
파일: test_maps.py 프로젝트: moroma/DalekRL
 def setUp(self):
     self.player = Mock(spec_set=player.Player)
     self.map = maps.Map(None, interfaces.Position(3, 3), self.player)