Beispiel #1
0
    def get_disallowed_actions(self, obs):
        disallowed_actions = []

        refinery_y, refinery_x = get_refineries(self.unit_type)
        geyser_top_left = geysers[0]
        if geyser_top_left[0] in refinery_x and geyser_top_left[1] in refinery_y:
            disallowed_actions.append(get_action_id(ACTION_BUILD_REFINERY_TOP_LEFT))

        geyser_top_right = geysers[1]
        if geyser_top_right[0] in refinery_x and geyser_top_right[1] in refinery_y:
            disallowed_actions.append(get_action_id(ACTION_BUILD_REFINERY_TOP_RIGHT))

        geyser_bottom_left = geysers[2]
        if geyser_bottom_left[0] in refinery_x and geyser_bottom_left[1] in refinery_y:
            disallowed_actions.append(get_action_id(ACTION_BUILD_REFINERY_BOTTOM_LEFT))

        geyser_bottom_right = geysers[3]
        if geyser_bottom_right[0] in refinery_x and geyser_bottom_right[1] in refinery_y:
            disallowed_actions.append(get_action_id(ACTION_BUILD_REFINERY_BOTTOM_RIGHT))

        if self.supply_depots >= len(depots):
            disallowed_actions.append(get_action_id(ACTION_BUILD_SUPPLY_DEPOT))

        if p.get_food_cap(obs) == p.get_food_used(obs):
            disallowed_actions.append(get_action_id(ACTION_BUILD_SCV_START_CC))
            disallowed_actions.append(get_action_id(ACTION_BUILD_SCV_NEW_CC))

        if get_command_center_amount(self.unit_type) == 2:
            disallowed_actions.append(get_action_id(ACTION_BUILD_CC))

        return disallowed_actions
Beispiel #2
0
def main():
    print_header()
    user_name = get_user_name()
    rolls = build_three_rolls()
    player1 = Player(user_name)
    player2 = Player('computer')
    game_loop(rolls, player1, player2)
Beispiel #3
0
class TestPlayerHuman:
    IS_COMP = False
    NAME_PLAYER = "Владимир"
    LEN_90 = 90

    def setup(self):
        random.seed(88)
        self.player = Player()
        self.player.create_game_card(self.NAME_PLAYER, self.IS_COMP)

    def teardown(self):
        pass

    def test_create_game_card(self):
        assert self.player.name == self.NAME_PLAYER
        assert self.player.is_computer == self.IS_COMP
        assert self.player.lost == False
        assert self.player.is_computer == False

    def test_check_number(self):
        assert self.player.check_number(10) == False
        assert self.player.check_number(16) == True
        assert self.player.check_number(0) == True
        assert self.player.check_number(-1) == False

    def test_examination_number(self):
        numb = 0
        for i in range(1, self.LEN_90):
            if not self.player.check_number(i): # Если значения нет, а игрок сказал вычеркнуть значение = проиграл
                numb = i
                break
        self.player.examination_number(numb)
        assert self.player.lost == True, "Игрок должен проиграть при проверке отсутствующего значения"
Beispiel #4
0
    def handle_last_action(self, obs):
        cm = str(p.get_minerals(obs))
        cv = str(p.get_vespene(obs))
        iwc = str(p.get_idle_worker_count(obs))
        depot_count = str(self.supply_depots)
        refinery_count = str(self.refineries)
        command_centers = str(get_command_center_amount(self.unit_type))
        food_used = str(p.get_food_used(obs))
        food_cap = str(p.get_food_cap(obs))
        sp_attempts = str(self.build_supply_depot_attempts)
        sp_attempts_f = str(self.build_supply_depot_attempts_failed)
        refinery_attempts = str(self.build_refinery_attempts)
        refinery_attempts_f = str(self.build_refinery_attempts_failed)
        cc_attempts = str(self.build_cc_attempts)
        cc_attempts_f = str(self.build_cc_attempt_failed)
        score = cs.get_score(obs)
        data = [sp_attempts, sp_attempts_f, depot_count, refinery_attempts, refinery_attempts_f, refinery_count, cc_attempts, cc_attempts_f, cm, cv, iwc, command_centers, food_used + "/" + food_cap, str(score)]
        with open('/home/kenn/Development/sc2-bot/CustomAgents/scores.txt', 'a+') as f:
            f.write('{0[0]:<15}{0[1]:<15}{0[2]:<15}{0[3]:<15}{0[4]:<15}{0[5]:<15}{0[6]:<15}{0[7]:<15}{0[8]:<15}{0[9]:<15}{0[10]:<15}{0[11]:<15}{0[12]:<15}{0[13]:<15}\n'.format(data))

        # If we score less than 4000 we are doing so poorly, we want to learn that it was very bad.
        # Symbolizes the ultimate loss.
        self.qlearn.learn(str(self.previous_state), self.previous_action, int(score) - 4000, 'terminal')

        self.previous_state = None
        self.previous_action = None
        self.move_number = 0

        self.supply_depots = 0
        self.refineries = 0
        self.builder_iterator = 0

        self.build_supply_depot_attempts = 0
        self.build_supply_depot_attempts_failed = 0
        self.build_refinery_attempts = 0
        self.build_refinery_attempts_failed = 0
        self.build_cc_attempts = 0
        self.build_cc_attempt_failed = 0

        self.initializing = 0

        self.qlearn.q_table.to_pickle(DATA_FILE + '.gz', 'gzip')

        return actions.FunctionCall(_NOOP, [])
Beispiel #5
0
 def listen(self):
     """收音并识别为文字"""
     if self.listening == '':
         self.listening = str(int(time.time()))
     # Player.play(constants.getData('./media/beep_hi.wav'))
     audio.play(constants.getData('./media/on.wav'))
     hotword_model = constants.getHotwordModel(
         config.get('hotword', 'default.pmdl'))
     # print(hotword_model)
     listener = snowboydecoder.ActiveListener([hotword_model])
     voice = listener.listen(
         silent_count_threshold=config.get('silent_threshold', 15),
         recording_timeout=config.get('recording_timeout', 5) * 4)
     # Player.play(constants.getData('./media/beep_lo.wav'))
     Player.play(constants.getData('./media/off.wav'))
     query = self.asr.transcribe(voice)
     utils.rmdir(voice)
     logging.debug("listen: " + query)
     self.listening = ''
     return query
Beispiel #6
0
    def handle_first_action(self, obs):
        cc_y, cc_x = get_command_centers(self.unit_type)
        set_command_center_pixels(len(cc_y))
        set_start_command_center_xy(cc_y, cc_x)

        scv_y, scv_x = get_scvs(self.unit_type)
        scv_amount = p.get_food_used(obs)
        set_scv_pixels(int(len(scv_y / float(scv_amount))))

        self.invocations += 1

        return actions.FunctionCall(_SELECT_IDLE_WORKER, [_SELECT_ALL])
Beispiel #7
0
class TestPlayerComp:
    IS_COMP = True
    NAME_PLAYER = "Компьютер 1"

    def setup(self):
        random.seed(88)
        self.player = Player()
        self.player.create_game_card(self.NAME_PLAYER, self.IS_COMP)

    def teardown(self):
        pass

    def test_create_game_card(self):
        assert self.player.name == self.NAME_PLAYER
        assert self.player.is_computer == self.IS_COMP
        assert self.player.lost == False
        assert self.player.is_computer == True

    def test_check_number(self):
        assert self.player.check_number(10) == False
        assert self.player.check_number(16) == True
        assert self.player.check_number(0) == True
        assert self.player.check_number(-1) == False
from mcpi import minecraft
from lib import Building
from lib import Player
from lib import Goods
from lib import Nature
from mcpi import vec3
import time
import math

mc =minecraft.Minecraft.create()
mc.postToChat("hello ")
mc.postToChat("Neu ban tien len 10 buoc nua, thi mot ngoi nha se xuat hien ")


pl = Player.MinePLayer(mc,"gg")
x_root,y_root,z_root = pl.getPos()
mc =minecraft.Minecraft.create('10.15.0.194')
mc.postToChat("hello")
pl = Player.MinePLayer(mc,"mai")

# pl.setPos(100,200,100)
print(pl.id)
def firecurse ():
    while True: 
        x,y,z = pl.getPos()
        dt =mc.getBlockWithData(x,y-1,z)
        if dt.id == 155:
            Building.fireroad(mc,x-10,y,z-10)
        time.sleep(0.5)
        mc.postToChat("{}".format(dt.id))
        chatEvents = mc.events.pollChatPosts()
Beispiel #9
0
    def step(self, obs):
        super(CollectMineralsAndGas, self).step(obs)

        self.unit_type = obs.observation['screen'][_UNIT_TYPE]

        if obs.last():
            return self.handle_last_action(obs)

        if obs.first():
            return self.handle_first_action(obs)

        if self.initializing < 2:
            return self.handle_initial_action(obs)

        if self.move_number == 0:
            self.update_buildings_built()

            supply_used = p.get_food_used(obs)
            supply_cap = p.get_food_cap(obs)

            scvs_left = get_approx_scvs_in_rectangle_count(self.unit_type, (0, 0), (41, 83))
            scvs_right = get_approx_scvs_in_rectangle_count(self.unit_type, (42, 0), (83, 83))

            current_state = np.zeros(6)
            # Available supply min to reduce state space
            current_state[0] = min(supply_cap - supply_used, 7)
            # Detect how many times we have 100 minerals up to maximum 4 times (Afford a CC) to reduce our state space
            current_state[1] = min(int(p.get_minerals(obs) / 100.0), 4)
            # Any idle workers min to reduce state space
            current_state[2] = min(p.get_idle_worker_count(obs), 3)
            # scvs left side to scvs right side difference
            scv_side_diff = scvs_left - scvs_right
            current_state[3] = max(-7, scv_side_diff) if scv_side_diff < 0 else min(8, scv_side_diff)
            # Number of CCs
            current_state[4] = get_command_center_amount(self.unit_type)
            # Number of supply depots
            current_state[5] = get_supply_depot_amount(self.unit_type)

            if self.previous_action is not None:
                # reward = self.get_reward(obs)
                self.qlearn.learn(str(self.previous_state), self.previous_action, 0, str(current_state))

            disallowed_actions = self.get_disallowed_actions(obs)

            rl_action = self.qlearn.choose_action(str(current_state), disallowed_actions)

            action_name = get_smart_action(int(rl_action))
            action_function, actual_action = self.apply_action(obs, action_name)

            action_id = rl_action
            if actual_action is None:
                action_function = actions.FunctionCall(_NOOP, [])
                action_id = get_action_id(ACTION_DO_NOTHING)

            self.previous_state = current_state
            self.previous_action = action_id

            self.move_number += 1
            return action_function
        elif self.move_number == 1:
            action_name = get_smart_action(self.previous_action)
            action_function, adjusted_action = self.apply_action(obs, action_name)

            if adjusted_action is None:
                action_function = actions.FunctionCall(_NOOP, [])
                self.previous_action = get_action_id(ACTION_DO_NOTHING)

            self.move_number += 1
            return action_function
        elif self.move_number == 2:
            action_name = get_smart_action(self.previous_action)
            action_function, adjusted_action = self.apply_action(obs, action_name)

            if adjusted_action is None:
                action_function = actions.FunctionCall(_NOOP, [])
                self.previous_action = get_action_id(ACTION_DO_NOTHING)

            self.move_number = 0
            return action_function

        return actions.FunctionCall(_NOOP, [])
Beispiel #10
0
from lib import Player, Character, Object

pg.init()
keys = Keys()
winSets = Window()
window = pg.display.set_mode(winSets.DIMENSIONS)
running = True
clock = pg.time.Clock()

gameState = "playing"

sprites = pg.sprite.Group()
objects = pg.sprite.Group()

bgnd = pg.image.load("background.png")
player = Player(300, 300, "Bob")
obj = Player(100, 100, "sprite.png")

objects.add(obj)
sprites.add(player, obj)


def checkQuit(e):
    if e.type == pg.QUIT:
        pg.quit()
        sys.exit()


# main loop
while running:
    window.blit(bgnd, (0, 0))
Beispiel #11
0
from lib import MedalWon, Player
"""
Carlo Molfetta of Italy won the gold medal in the men’s taekwondo 
80kg over Anthony Obame of Gabon. The fight ended tied on points, 9-9, 
but Molfetta was declared the winner by the judges on superiority.
"""

carlo = Player("Carlo Molfetta", "Italy")
anthony = Player("Anthony Obame", "Gabon")

medal_won = MedalWon(event="men's taekwondo 80kg",
                     medal="gold",
                     winners=[carlo],
                     losers=[anthony])

print(medal_won.realize())
# "Carlo Molfetta of Italy won the gold medal in the men's taekwondo 80kg over Anthony Obame of Gabon."

# ----------------------------------------------------------------------------- #

# object of the sentence changed from "gold medal" before to "men's high jump"
"""
Ivan Ukhov of Russia won the men’s high jump with a leap of 2.38 meters, or 7 feet 9 3/4 inches.
"""

ivan = Player("Ivan Ukhov", "Russia")

medal_won = MedalWon(event="men’s high jump", medal="gold", winners=[ivan])
# Ivan Ukhov of Russia won the gold medal in the men’s high jump.

print(medal_won.realize())
from mcpi import minecraft
import time
from lib import Game
from lib import Player
mc = minecraft.Minecraft.create()
a = 0
while True:
    chats = mc.events.pollChatPosts()
    for chat in chats:
        if chat.message == 'game':
            pl = Player.MinePLayer(minecraft_connect=mc, id=chat.entityId)
            x, y, z = pl.getMySight(15)
            Game.arena(mc, x, y, z)
            print(chat)
            a = 1
            break
    if a == 1:
        break

print('aaaaaa')
ids = mc.getPlayerEntityIds()
pls = []
for id in ids:
    pl = Player.MinePLayer(minecraft_connect=mc, id=id)
    pls.append(pl)

while True:
    time.sleep(4)
    for p in pls:
        x, y, z = p.getPos()
        if mc.getBlock(x, y - 1, z) == 57:
Beispiel #13
0
 def setup(self):
     random.seed(88)
     self.player = Player()
     self.player.create_game_card(self.NAME_PLAYER, self.IS_COMP)
Beispiel #14
0
from mcpi import minecraft
from lib import Building
from lib import Player
from lib import Goods
from lib import Nature

mc = minecraft.Minecraft.create()
mc.postToChat("hello")
pl = Player.MinePLayer(mc, "gg")
# pl.setPos(100,200,100)
x, y, z = pl.getPos()

Nature.volcano(mc, x, y, z)
bd = Building.Building(mc, x, y, z)
bd.small_house()

Goods.door(mc, x, y, z)
def main(winstyle=0, framerate=60):
    """
    Street drifter's entry point
    Args:
        winstyle: 0 = windowed, 1 = fullscreen
        framerate: screen refresh rate, also tickrate
    """
    global SCREENRECT
    # Initialize pygame
    if pg.get_sdl_version()[0] == 2:
        # needed for audio later
        pg.mixer.pre_init(44100, 32, 2, 4096)
    pg.init()

    fullscreen = bool(winstyle)
    # Set the display mode
    bestdepth = pg.display.mode_ok(SCREENRECT.size, winstyle, 32)
    screen = pg.display.set_mode(SCREENRECT.size, winstyle, bestdepth)

    # Decorate the game window
    icon = pg.transform.scale(load_image("icon.png"), (32, 32))
    pg.display.set_icon(icon)
    pg.display.set_caption("Street Racer")
    pg.mouse.set_visible(0)

    # Create the background
    # leave it like this, in the future the background can be scrollable
    bgdtile = pg.transform.smoothscale(load_image("background.png"),
                                       SCREENRECT.size)
    background = pg.Surface(SCREENRECT.size)
    for x in range(0, SCREENRECT.width, bgdtile.get_width()):
        background.blit(bgdtile, (x, 0))
    screen.blit(bgdtile, (0, 0))
    pg.display.flip()
    bg_moved = False

    # Load images, assign to sprite classes
    img = pg.transform.smoothscale(load_image("McLarenF1.png"), (32, 71))
    Player.images = [img]

    # Initialize Game Groups
    all_groups = pg.sprite.RenderUpdates()

    # Assign default groups to each sprite class
    Player.containers = all_groups
    Speedmeter.containers = all_groups

    # Initialize the starting sprites
    mclaren_cfg = load_config("McLarenF1.json")
    player = Player(mclaren_cfg, SCREENRECT)
    speed = Speedmeter(position=(1080, 640))
    all_groups.add(speed)
    tachometer = Tachometer(padding=4, position=(800, 640), color="blue")
    all_groups.add(tachometer)

    ## Create Some Starting Values
    clock = pg.time.Clock()
    # set ticksLastFrame to -10ms to make sure math is not broken
    ticksLastFrame = pg.time.get_ticks() - 10
    # cameraOffset = (0,0)

    while True:
        t = pg.time.get_ticks()
        # deltaTime from last tick in seconds.
        deltaTime = (t - ticksLastFrame) / 1000.0  # type: float
        ticksLastFrame = t

        # get input
        for event in pg.event.get():
            if event.type == QUIT or (event.type == KEYDOWN
                                      and event.key == K_ESCAPE):
                pg.quit()
                return

        keystate = pg.key.get_pressed()

        # clear/erase the last drawn sprites
        all_groups.clear(screen, background)

        # update all the sprites
        all_groups.update(deltaTime)
        speed.set(int(player.velocity * 3.6))
        tachometer.set(int(player.engine_RPM))

        # inform the car about current
        direction = keystate[K_UP] - keystate[K_DOWN]
        player.accelerate(direction)
        rotation = keystate[K_LEFT] - keystate[K_RIGHT]
        player.rotate(rotation)

        # draw the scene
        # bg_moved = True
        # if bg_moved:
        #     cameraOffset = cameraOffset[0] + 1, cameraOffset[1] + 1
        #     screen.blit(bgdtile, cameraOffset)
        #     pg.display.flip()
        dirty = all_groups.draw(screen)
        pg.display.update(dirty)

        # wait for next tick
        clock.tick(framerate)