コード例 #1
0
ファイル: player.py プロジェクト: reedling/ai-bc
    def __init__(self, name, is_ai):
        self.name = name
        self.is_ai = is_ai
        self.life = 20
        self.position = None
        self.finisher = None
        self.ante_finisher = False
        self.discards = Discards(2)
        self.played_styles = []
        self.played_bases = []
        self.selection = None
        self.active = False
        self.modifiers = []
        self.refresh()

        if name == 'Training Dummy':
            self.character = Dummy()
            self.agent = DummyAgent()
            self.life = float('inf')
        else:
            self.character = character_by_name(name)
            if self.character is None:
                self.character = character_by_name('Simple Bob')

            if self.is_ai:
                self.agent = DummyAgent()
            else:
                self.agent = UserAgentCLI()
コード例 #2
0
    def get(self):
        count = 100
        if self.request.get("count"):
            count = int(self.request.get("count"))

        for i in range(0, count):
            d = Dummy()
            d.put()
コード例 #3
0
    def get(self):
        count = 100
        if self.request.get('count'):
            count = int(self.request.get('count'))

        for i in range(0, count):
            d = Dummy()
            d.put()
コード例 #4
0
 def test_def_decoration(self):
     """Test data provider with a class static method"""
     called_func_mock = Mock()
     dummy = Dummy(called_func_mock)
     dummy.decorated_by_def_method()
     called_func_mock.assert_has_calls([
         call(Dummy.ARG1, Dummy.ARG2),
         call(Dummy.ARG3, Dummy.ARG4),
     ])
コード例 #5
0
 def test_lambda_decoration(self):
     """Test data provider with a lambda function"""
     called_func_mock = Mock()
     dummy = Dummy(called_func_mock)
     dummy.decorated_by_lambda_method()
     called_func_mock.assert_has_calls([
         call(Dummy.ARG1, Dummy.ARG2),
         call(Dummy.ARG3, Dummy.ARG4),
     ])
コード例 #6
0
ファイル: core.py プロジェクト: KarishmaGhiya/IRP2
def searchAll(rawinputs, asyncSearch=True, dummySearch=False):
    """Search all known collections for the given input dictionary."""
    from multiprocessing.pool import ThreadPool
    pool = ThreadPool(processes=8)
    async_handles = []
    results = {}
    for inst in archivesList:
        for coll in inst['collections']:
            classname = coll['class']
            import sys
            module = sys.modules[__name__]
            collClass = getattr(module, classname)
            collObject = collClass()

            if dummySearch: # use dummy collection that does no search..
                collObject = Dummy()
                collObject.setClassName(classname)

            # NOTE: presence of info.fields indicates advanced search support
            if hasattr(collObject, 'info'):
                if 'fields' in collObject.info:
                    inputs = rawinputs
                else:
                    inputs = ''
                    for key in rawinputs:
                        if(len(rawinputs[key].strip()) > 0):
                            if( len(inputs) > 0 ):
                                inputs += ' '+rawinputs[key]
                            else:
                                inputs += rawinputs[key]
            else:
                inputs = ''
                for key in rawinputs:
                    if(len(rawinputs[key].strip()) > 0):
                        if( len(inputs) > 0 ):
                            inputs += ' '+rawinputs[key]
                        else:
                            inputs += rawinputs[key]

            if asyncSearch:
                handle = pool.apply_async(collObject.keywordResultsCount, (inputs,))
                async_handles.append(handle)
            else:
                resultcoll = collObject.keywordResultsCount(inputs)
                result_dict = resultcoll.emit()
                results[result_dict['class']] = result_dict
    if asyncSearch:
        for res in async_handles:
            try:
                resultcoll = res.get(timeout=15)
            except Exception, e:
                logging.exception(e)
                resultcoll = None
                pass
            if resultcoll != None:
                result_dict = resultcoll.emit()
                results[result_dict['class']] = result_dict
コード例 #7
0
ファイル: kumas.py プロジェクト: SamuelBFG/tibia-tools
 def get_mouseposition(self):
     state_left = win32api.GetKeyState(0x01)
     if state_left == -127 or state_left == -128:
         xclick, yclick = win32api.GetCursorPos()
         dummy_pos = xclick, yclick
         d = Dummy(EXERCISE_WEAPON_HOTKEY, CHAR_NAME, dummy_pos)
         self.quit()
         d.main()
     else:
         self.after(10, self.get_mouseposition)
コード例 #8
0
ファイル: tests.py プロジェクト: juanique/django-base-project
    def test_post(self):
        user_res = UserResource()
        dummy_res = DummyResource(user_res)
        request = Dummy()
        request.method="POST"
        request.raw_post_data = json.dumps(user_res._meta.examples['POST'])
        request.path = "/api/resources/user/"

        response = dummy_res.post(request)
        self.assertEqual(201, response.status_code)
        self.assertEqual("",response.content)
コード例 #9
0
ファイル: make_dummy.py プロジェクト: CEIT-UQ/edx-platform
def main(file, locale):
    """
    Takes a source po file, reads it, and writes out a new po file
    in :param locale: containing a dummy translation.
    """
    if not os.path.exists(file):
        raise IOError('File does not exist: %s' % file)
    pofile = polib.pofile(file)
    converter = Dummy()
    converter.init_msgs(pofile.translated_entries())
    for msg in pofile:
        converter.convert_msg(msg)
    new_file = new_filename(file, locale)
    create_dir_if_necessary(new_file)
    pofile.save(new_file)
コード例 #10
0
    def gameStart(self):
        self.dummy = Dummy()
        self.handCardList = self.dummy.getHandCardList()

        self.putCard = PutCard(self.handCardList)
        self.downCardList = self.putCard.getDownCardList()

        for i in range(4):
            downCardNum = str(self.downCardList[i])
            self.downCard[i].setText(downCardNum)

        for i in range(8):
            handCardNum = str(self.handCardList[i])
            self.handCard[i].setText(handCardNum)

        self.dummyDeck.setText('남은 카드 수\n\n'+ str(self.dummy.countDeck()))
コード例 #11
0
ファイル: machine.py プロジェクト: nickthecoder/itchy
 def onSceneCreated(self):
     GridRole.onSceneCreated(self)
     self.makeAlternateOccupant()
     self.costumeFeatures.update(self)
     
     dummy = None
     squareSize = self.square.grid.squareSize
     # Create a dummy actor if we are a wide machine
     pose = self.actor.appearance.pose
     if pose.surface.width > squareSize :
         if pose.offsetX > squareSize :
             dummy = Dummy(self, -1, 0)
         else :
             dummy = Dummy(self, 1, 0)
 
     if dummy :
         dummy.makeAlternateOccupant()        
コード例 #12
0
def main(file, locale):
    """
    Takes a source po file, reads it, and writes out a new po file
    in :param locale: containing a dummy translation.
    """
    if not os.path.exists(file):
        raise IOError('File does not exist: %s' % file)
    pofile = polib.pofile(file)
    converter = Dummy()
    for msg in pofile:
        converter.convert_msg(msg)

    # If any message has a plural, then the file needs plural information.
    # Apply declaration for English pluralization rules so that ngettext will
    # do something reasonable.
    if any(m.msgid_plural for m in pofile):
        pofile.metadata['Plural-Forms'] = 'nplurals=2; plural=(n != 1);'

    new_file = new_filename(file, locale)
    create_dir_if_necessary(new_file)
    pofile.save(new_file)
コード例 #13
0
def main(file, locale):
    """
    Takes a source po file, reads it, and writes out a new po file
    in :param locale: containing a dummy translation.
    """
    if not os.path.exists(file):
        raise IOError('File does not exist: %s' % file)
    pofile = polib.pofile(file)
    converter = Dummy()
    for msg in pofile:
        converter.convert_msg(msg)

    # If any message has a plural, then the file needs plural information.
    # Apply declaration for English pluralization rules so that ngettext will
    # do something reasonable.
    if any(m.msgid_plural for m in pofile):
        pofile.metadata['Plural-Forms'] = 'nplurals=2; plural=(n != 1);'

    new_file = new_filename(file, locale)
    create_dir_if_necessary(new_file)
    pofile.save(new_file)
コード例 #14
0
ファイル: io.py プロジェクト: aryakaul/simdigree
def read_fam(famfile):

    """
    Read the fam file and create Dummy's for each person
    """

    individs = {}
    with open(famfile, 'r') as f:
        for lines in f:
            # extract line information
            line = lines.rstrip().split()
            famid = line[0]
            individ = line[1]
            father = line[2]
            mother = line[3]
            x = [father, mother]
            # sort so deterministic
            x.sort()

            # if no parents known, then it's a founder
            if father == "0" and mother == "0": founder = True
            else: founder = False

            # create dummy
            if individ not in individs:
                dummy = Dummy((x[0], x[1]), founder)
                individs[individ] = dummy

        # loop through dummies
        for dummies in individs:
            dummy = individs[dummies]
            if dummy.is_founder(): continue

            # add child to the mother and father Dummy's
            parents = dummy.get_parents()
            f = individs[parents[0]]
            m = individs[parents[1]]
            f.add_child(dummies)
            m.add_child(dummies)
    return individs
コード例 #15
0
def app():
    cfg = Configuration()
    cfg.parse()

    dummy = Dummy(cfg.fake_count, cfg.snapshots_path)
    dummy.generate()
    dummy.make_snapshot()
コード例 #16
0
ファイル: main.py プロジェクト: polceanum/Sailboat-Project
def main(args):

    # Astar Module
    if args.model == "astar":
        model = Astar()
    # Reinforcement Learning module
    elif args.model == "rl":
        model = Rl()
    # Dummy test
    elif args.model == "dummy":
        model = Dummy()

    # Create an environment
    env = gym.make('voilier-v2').unwrapped
    state = env.reset()
    # TODO Get range from argument
    for step in range(0, 200, 1):
        action = model.step(state)
        state, _, _, _ = env.step(action)
        env.render()
コード例 #17
0
def main(file, locale):
    """
    Takes a source po file, reads it, and writes out a new po file
    in :param locale: containing a dummy translation.
    """
    if not os.path.exists(file):
        raise IOError('File does not exist: %s' % file)
    pofile = polib.pofile(file)
    converter = Dummy()
    converter.init_msgs(pofile.translated_entries())
    for msg in pofile:
        converter.convert_msg(msg)
    new_file = new_filename(file, locale)
    create_dir_if_necessary(new_file)
    pofile.save(new_file)
コード例 #18
0
ファイル: app.py プロジェクト: pashutk/pisdup
    def run(self):
        self.init()

        sm = SceneManager()

        sm.register_scene(DevicesWaiting(self.display, self.ee))

        # sm.go(SceneId.DEVICES_WAITING)
        sm.register_scene(Dummy(self.display))
        # sm.go(SceneId.DUMMY)

        sm.register_scene(Loading(self.display))
        sm.go(SceneId.LOADING)

        while (True):
            if Config.ENABLE_CLI:
                input_str = self.cli.read()
                if input_str == 'exit':
                    sm.destroy()
                    break
                self.handle_cli_command(input_str)

            time.sleep(0.01)
コード例 #19
0
ファイル: main.py プロジェクト: Doug-Campbell/pokemon
from pokemon import Pokemon
from dummy import Dummy

bulb = Pokemon('Bulbasaur', 'Grass', 10, 10, 3, 2)
doug = Dummy('Doug', 69)

bulb.speak()

print(doug.health)
bulb.attack(doug)
print(doug.health)
コード例 #20
0
ファイル: player.py プロジェクト: reedling/ai-bc
class Player:
    def __init__(self, name, is_ai):
        self.name = name
        self.is_ai = is_ai
        self.life = 20
        self.position = None
        self.finisher = None
        self.ante_finisher = False
        self.discards = Discards(2)
        self.played_styles = []
        self.played_bases = []
        self.selection = None
        self.active = False
        self.modifiers = []
        self.refresh()

        if name == 'Training Dummy':
            self.character = Dummy()
            self.agent = DummyAgent()
            self.life = float('inf')
        else:
            self.character = character_by_name(name)
            if self.character is None:
                self.character = character_by_name('Simple Bob')

            if self.is_ai:
                self.agent = DummyAgent()
            else:
                self.agent = UserAgentCLI()

    def __str__(self):
        return self.name + '(' + str(self.life) + ')'

    @property
    def status(self):
        return {'life': self.life, 'position': self.position}

    @property
    def soak(self):
        return self.get_mod_val('soak')

    @property
    def stun_guard(self):
        return self.get_mod_val('stun_guard')

    @property
    def stun_immune(self):
        return self.get_mod_val('stun_immune', False)

    @property
    def can_hit(self):
        return self.get_mod_val('can_hit', True)

    @property
    def dodge(self):
        return self.get_mod_val('dodge', False)

    @property
    def power(self):
        return self.get_mod_val('power')

    @property
    def priority(self):
        return self.get_mod_val('priority')

    @property
    def atk_range(self):
        if self.selection.atk_range is not None:

            def range_val(range_mod):
                return range_mod.val

            range_mods = self.get_relevant_mods('range')
            range_mods = list(map(range_val, range_mods))
            range_mods.append(self.selection.atk_range)
            combos = [[]]
            for m in range_mods:
                t = []
                for y in m:
                    for i in combos:
                        t.append(i + [y])
                combos = t
            return sorted(set([sum(c) for c in combos]))
        else:
            return None

    def get_mod_val(self, mtype, default=0):
        relevant = self.get_relevant_mods(mtype)
        if len(relevant) == 0:
            return default

        if isinstance(default, bool):
            for m in relevant:
                if m.val != default:
                    return m.val
            return default
        elif isinstance(default, (int, float)):
            return reduce((lambda acc, m: acc + m.val), relevant, default)
        else:
            print('Unexpected Mod mtype/def: {} {}'.format(mtype, default))
            return None

    def get_relevant_mods(self, mtype):
        def f(m):
            return m.mtype == mtype

        return list(filter(f, self.modifiers))

    def refresh(self):
        self.stunned = False
        self.actions = []
        self.update_modifiers()

    def update_modifiers(self):
        for i in range(len(self.modifiers)):
            if self.modifiers[i].onset == 0:
                self.modifiers[i].duration -= 1
            else:
                self.modifiers[i].onset -= 1

        def f(m):
            return m.duration > 0

        self.modifiers = list(filter(f, self.modifiers))

    def get_ante(self, state):
        if self.finisher is not None and self.life <= 7:
            if hasattr(self.agent, 'get_ante'):
                if self.agent.get_ante(state) == 'Finisher':
                    self.ante_finisher = True
                    return self.finisher
            else:
                if randint(0, 2) == 2:
                    self.ante_finisher = True
                    return self.finisher
        return None

    def get_ante_effects(self):
        if hasattr(self.character, 'get_ante_effects'):
            return self.character.get_ante_effects()
        else:
            return None

    def discard(self, to_discard):
        self.discard_inner(to_discard)

    def discard_inner(self, to_discard):
        self.discards.discard_inner(to_discard)

    def discard_outer(self, to_discard):
        self.discards.discard_outer(to_discard)

    def select_finisher(self, state):
        if hasattr(self.character, 'finishers'):
            options = self.character.finishers
            if hasattr(self.agent, 'select_finisher'):
                self.finisher = self.agent.select_finisher(options, state)
            else:
                self.finisher = choice(options)

    def init_discards(self, state):
        styles = self.character.styles
        bases = self.character.bases
        if hasattr(self.agent, 'init_discards'):
            to_discard = self.agent.init_discards(styles, bases, state)
            self.discard_outer([styles[to_discard[0]], bases[to_discard[2]]])
            self.discard([styles[to_discard[1]], bases[to_discard[3]]])
        else:
            self.discard_outer([styles[0], bases[0]])
            self.discard([styles[1], bases[1]])

    def recover_discards(self):
        self.discards.cycle_out()

    def recycle(self):
        if self.ante_finisher:
            self.ante_finisher = False
            self.finisher = None
        else:
            self.recover_discards()
            self.discard(self.played_styles.pop())
            self.discard(self.played_bases.pop())
        self.played_styles = []
        self.played_bases = []
        self.selection = None

    def get_selection(self, state):
        av_s = self.available_styles
        av_b = self.available_bases
        if hasattr(self.agent, 'get_selection'):
            style, base = self.agent.get_selection(av_s, av_b, state)
        else:
            style = choice(av_s)
            base = choice(av_b)
        self.played_styles.append(style)
        self.played_bases.append(base)
        return Pair(style, base)

    def get_new_base(self, state):
        av_b = self.available_bases
        if hasattr(self.agent, 'get_new_base'):
            base = self.agent.get_new_base(av_b, state)
        else:
            base = choice(self.available_bases)
        self.played_bases.append(base)
        return base

    @property
    def available_styles(self):
        opts = self.character.styles
        discarded = self.discards.styles
        played = self.played_styles
        return [s for s in opts if s not in discarded and s not in played]

    @property
    def available_bases(self):
        opts = self.character.bases
        discarded = self.discards.bases
        played = self.played_bases
        return [b for b in opts if b not in discarded and b not in played]

    def has_playable_styles(self):
        return len(self.available_styles) > 0

    def has_playable_bases(self):
        return len(self.available_bases) > 0

    def handle_modifier(self, mod):
        if mod.mtype == 'stun' and not self.stun_immune:
            self.stunned = True
        elif callable(mod.mtype):
            mod.mtype(mod.val)
        elif mod.mtype == 'lose_life':
            if self.life - mod.val > 0:
                self.life -= mod.val
            else:
                self.life = 1
        else:
            self.modifiers.append(mod)

    def get_selection_effects(self):
        return self.selection.get_effects()

    def grant_action(self, action):
        self.actions.append(action)

    def remove_action(self, action):
        self.actions.remove(action)

    def get_effects(self, trigger, passed_selection=None):
        if self.selection is not None:
            return self.selection.get_effects(trigger)
        else:
            return passed_selection.get_effects(trigger)

    def get_actions(self, trigger):
        return get_possible(self.selection, trigger)

    def get_behavior(self, actions, state, trigger):
        if hasattr(self.agent, 'get_behavior'):
            chosen, b = self.agent.get_behavior(actions, state, trigger)
        else:
            chosen, b = choose_random_valid_behavior(actions, state)
        return chosen, b

    def handle_damage(self, damage, attacker):
        if damage > 0:
            damage = self.soak_damage(damage)
            if damage > self.stun_guard and not self.stun_immune:
                self.stunned = True
            self.life -= damage
        return damage

    # Returns leftover un-soaked damage
    def soak_damage(self, damage):
        damage = damage - self.soak
        if damage > 0:
            return damage
        else:
            return 0
コード例 #21
0
ファイル: plane.py プロジェクト: nickthecoder/itchy
 def onPlacedOnGrid(self) :
     self.dummy = Dummy(self, -self.direction, 0)
     self.dummy.speed = self.speed
     self.dummy.addTag("roundedNW")
     self.dummy.addTag("roundedNE")
コード例 #22
0
ファイル: plane.py プロジェクト: nickthecoder/itchy
class Plane(Movable) :

    def __init__(self) :
        super(Plane,self).__init__()
        self.direction = -1
        self.dummy = None
                
    def onBirth(self):
        super(Plane,self).onBirth()
        self.rolls = False
        self.costumeFeatures.update(self)
        self.squash = "squashE" if self.direction == 1 else "squashW"
        self.speed  = 10

        self.addTag( "explosionTrigger" )
        self.addTag( "deadly" )
        
    def onPlacedOnGrid(self) :
        self.dummy = Dummy(self, -self.direction, 0)
        self.dummy.speed = self.speed
        self.dummy.addTag("roundedNW")
        self.dummy.addTag("roundedNE")


    def tick(self) :

        Movable.tick(self)

        # Check that dummy hasn't been removed from the grid (which will happen if my tick caused it to die)
        if self.dummy.square :
            self.dummy.tick()

        if self.square and not self.isMoving() :

            forward = self.look( self.direction, 0 )

            if forward.hasTag(self.squash) :
                self.move(self.direction, 0)

            
    def canShove( self, pusher, dx, dy, speed, force) :

        if (force < 4) :
            return False

        self.jumpIfNearlyMoved()
        if self.dummy :
            self.dummy.jumpIfNearlyMoved()
        
        if self.isMoving() :
            return False


        if dy == 0 and dx == -self.direction :
            forward = self.look(dx * 2, dy ) # Behind the dummy object
        else :
            forward = self.look(dx, dy) # In the direction of the push...

        if forward.isMoving() :
            return False

        squashD = "squash" + self.getCompassAbbreviation(dx, dy)
        if forward.hasTag( squashD ) :
            if dy != 0 :
                dummyForward = self.dummy.look(dx,dy)
                if dummyForward.isMoving() :
                    return False
                if not dummyForward.hasTag( squashD ) :
                    return False
                
            return True

        return False
    
    def onArrived( self, dx, dy ) :
        # Don't hit things when I've been pushed, only when I've driven forwards.
        if dx == self.direction :
            forward = self.look(dx,dy)
            if (forward.role.hasTag("hittable")) :
                forward.role.onHit( self, dx, dy )

    def onDeath(self) :
        if self.dummy :
            self.dummy.removeFromGrid()
        Movable.onDeath(self)
        
    def move(self, dx, dy,speed=None) :
        Movable.move(self,dx,dy,speed)
        # Check if dummy is still on the grid (it won't be if my movement caused us both to die).
        if self.dummy.square :
            self.dummy.move(dx, dy, speed)
        

    def createCostumeFeatures(self,costume) :
        return PlaneFeatures(costume)


    # Boiler plate code - no need to change this
    def getProperties(self):
        return properties

    # Boiler plate code - no need to change this
    def getClassName(self):
        return ClassName( Role, self.__module__ + ".py" )
コード例 #23
0
ファイル: reloading.py プロジェクト: heitorchang/reading-list
# How to reload a class that was already imported

from importlib import reload
import dummy  # the module containing the desired class

from dummy import Dummy

d = Dummy("Adam")
d.sayHi()

# Now, suppose we change Dummy's sayHi function to "[name] says Hello"
# Then, we run
# >>> reload(dummy)
# Then Ctrl-Enter to rebuild everything
コード例 #24
0
'''
Created on Feb 21, 2018

@author: kosc93
'''
from __future__ import division

from amsldm import __version__
from amsldm import MeasurementSetup, Sweep
from amsldm import FieldFox, PNA, ZVA24
from time import sleep, time
from dummy import Dummy
import os

os.system('guvcview -j test.avi  -o mp3 -u h264 -y 30 -e &')
m = MeasurementSetup("test_setup")
m.add_instrument(ZVA24('192.168.2.159'))
m.add_sweep(Sweep(Dummy('A'), 0., 2., 5))

m.run()
コード例 #25
0
ファイル: test_module.py プロジェクト: dfee/dummy_tox
def test_repr():
    assert repr(Dummy()) == 'Dummy()'
コード例 #26
0
import os
import pulumi

from dummy import Dummy

config = pulumi.Config();

resource_count = config.require_int('resource_count')
resource_payload_bytes = config.require_int('resource_payload_bytes')

for i in range(0, resource_count):
    deadweight = '{:08}'.format(i) * int(resource_payload_bytes / 8)
    dummy = Dummy(f'dummy-{i}', deadweight=deadweight)
    if i == 0:
        pulumi.export('ResourcePayloadBytes', dummy.deadweight.apply(lambda s: len(s)))

pulumi.export('ResourceCount', resource_count)
コード例 #27
0
ファイル: start.py プロジェクト: Silveryu/ekains
def main(argv):
    inputfile = None
    visual = True
    agentproxy = False
    url = 'ws://localhost:8765'
    url = None
    StudentAgent = Agent1
    studentAgent_name = "Agent1"
    student_url = None
    OponentAgent = Agent1
    oponentAgent_name = "Agent2"
    oponent_url = None
    timeout = sys.maxsize
    try:
        opts, args = getopt.getopt(argv, "hm:s:o:pt:", [
            "help", "map=", "disable-video", "student-agent", "oponent-agent",
            "proxy", "timeout"
        ])
    except getopt.GetoptError as e:
        print(e)
        print(
            'start.py [-h/--help -m/--map <mapfile> --disable-video -p/--proxy -s/--student-agent AgentName,Name[,websocket] -o/--oponent-name AgentName,Name[,websocket] --timeout]'
        )
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print(
                'start.py [-h/--help -m/--map <mapfile> --disable-video -p/--proxy -s/--student-agent AgentName,Name[,websocket] -o/--oponent-name AgentName,Name[,websocket] --timeout]'
            )
            sys.exit()
        elif opt in ("-m", "--map"):
            inputfile = arg
        elif opt in ("-t", "--timeout"):
            timeout = int(arg)
        elif opt in ("--disable-video"):
            visual = False
        elif opt in ("-p", "--proxy"):
            agentproxy = True
        elif opt in ("-s", "--student-agent"):
            a = arg.split(',')
            classmodule = importlib.import_module(a[0].lower())
            classInst = getattr(classmodule, a[0])
            StudentAgent = classInst
            studentAgent_name = a[1]
            if len(a) > 2:
                student_url = a[2]
        elif opt in ("-o", "--oponent-agent"):
            a = arg.split(',')
            classmodule = importlib.import_module(a[0].lower())
            classInst = getattr(classmodule, a[0])
            OponentAgent = classInst
            oponentAgent_name = a[1]
            if len(a) > 2:
                oponent_url = a[2]

    if agentproxy:
        if student_url == None:
            print("Must specify --student-agent Agent,name,websocket")
            sys.exit(1)
        print("Connecting to {}".format(student_url))
        asyncio.get_event_loop().run_until_complete(
            proxy(student_url, StudentAgent, studentAgent_name))
    else:
        try:
            game = SnakeGame(hor=60,
                             ver=40,
                             tilesize=15,
                             fps=50,
                             visual=visual,
                             obstacles=15,
                             mapa=inputfile)
            print("Launching game <{}>".format(game.gameid))
            game.setPlayers([
                StudentAgent([game.playerPos()], name=studentAgent_name) if
                student_url == None else StudentAgent([game.playerPos()],
                                                      name=studentAgent_name,
                                                      url=student_url,
                                                      gameid=game.gameid),
                Dummy([game.playerPos()], name=oponentAgent_name) if
                oponent_url == None else OponentAgent([game.playerPos()],
                                                      name=oponentAgent_name,
                                                      url=oponent_url,
                                                      gameid=game.gameid),
            ])
        except Exception as e:
            print(e)
            sys.exit(1)

        game.start()
コード例 #28
0
class GUI(QWidget):
    def __init__(self):
        super().__init__()
        self.warning = QMessageBox()

        # Button
        self.startButton = basicButton('게임시작', self.startClicked)
        self.howToPlayButton = basicButton('게임방법', self.howClicked)
        self.exitButton = basicButton('게임종료', self.exitClicked)

        self.oneToHun1 = QPushButton('99\n\n↑\n\n1')
        self.oneToHun2 = QPushButton('99\n\n↑\n\n1')
        self.hunToOne1 = QPushButton('100\n\n↓\n\n2')
        self.hunToOne2 = QPushButton('100\n\n↓\n\n2')

        self.downCard = []
        for i in range(4):
            self.downCard.append(downCard('', i, self.downCardClicked))

        self.dummyDeck = QPushButton('남은 카드 수\n\n')
        self.dummyDeck.setFixedHeight(100)
        self.dummyDeck.setFixedWidth(80)

        self.turnEndButton = basicButton('턴 종료', self.turnEndClicked)
        self.turnEndButton.setFixedWidth(120)

        self.handCard = []
        for i in range(8):
            self.handCard.append(handCard('', self.handCardClicked))


        # Layout
        menuLayout = QHBoxLayout()
        menuLayout.addWidget(self.startButton)
        menuLayout.addWidget(self.howToPlayButton)
        menuLayout.addWidget(self.exitButton)

        basicCardLayout = QHBoxLayout()
        basicCardLayout.addWidget(self.oneToHun1)
        basicCardLayout.addWidget(self.oneToHun2)
        basicCardLayout.addWidget(self.hunToOne1)
        basicCardLayout.addWidget(self.hunToOne2)

        downCardLayout = QHBoxLayout()
        for i in range(4):
            downCardLayout.addWidget(self.downCard[i])

        downLayout = QVBoxLayout()
        downLayout.addLayout(basicCardLayout)
        downLayout.addLayout(downCardLayout)

        dummyLayout = QHBoxLayout()
        dummyLayout.addWidget(self.dummyDeck)

        turnEndLayout = QVBoxLayout()
        turnEndLayout.addLayout(dummyLayout)
        turnEndLayout.addWidget(self.turnEndButton)

        settingLayout = QHBoxLayout()
        settingLayout.addLayout(downLayout)
        settingLayout.addStretch()
        settingLayout.addLayout(turnEndLayout)
        settingLayout.addStretch()

        handCardLayout = QHBoxLayout()
        for i in range(8):
            handCardLayout.addWidget(self.handCard[i])

        mainLayout = QVBoxLayout()
        mainLayout.addLayout(menuLayout)
        mainLayout.addLayout(settingLayout)
        mainLayout.addLayout(handCardLayout)

        self.setLayout(mainLayout)

        self.setWindowTitle('The Game')
        self.setGeometry(300, 100, 600, 400)

        self.show()
        self.gameStart()



    def gameStart(self):
        self.dummy = Dummy()
        self.handCardList = self.dummy.getHandCardList()

        self.putCard = PutCard(self.handCardList)
        self.downCardList = self.putCard.getDownCardList()

        for i in range(4):
            downCardNum = str(self.downCardList[i])
            self.downCard[i].setText(downCardNum)

        for i in range(8):
            handCardNum = str(self.handCardList[i])
            self.handCard[i].setText(handCardNum)

        self.dummyDeck.setText('남은 카드 수\n\n'+ str(self.dummy.countDeck()))


    # esc눌러서 게임종료
    def keyPressEvent(self, e):
        if e.key() == Qt.Key_Escape:

            Endkey = self.warning.question(self, '', "정말로 종료하시겠습니까?", self.warning.Yes | self.warning.No)
            if Endkey == self.warning.Yes:
                self.close()
            elif Endkey== self.warning.No:
                pass
            #정말 종료하시겠습니까?
            self.close()

    #게임시작
    def startClicked(self):
        self.gameStart()


    #게임방법
    def howClicked(self):
        self.warning.question(self, '게임방법',
                              '# 게임의 진행\n' +
                              '2~98까지의 숫자카드 98장을 잘 섞어 더미를 만들고 플레이어에게 8장을 나누어 줍니다.' +
                              '한 차례에 최소 2장의 카드를 내려놓아야합니다.' +
                              '원한다면 더 많은 카드를 내려놓을 수 있습니다.' +
                              '카드를 내려놓을 때는 한 번에 한 장씩 내려놓아야 하며, 내려놓을 때마다 원하는 위치를 선택한 뒤, 내려고하는 카드를 선택합니다.' +
                              '오름차순 위치에 카드를 놓을 때는 반드시 이전에 놓인 카드보다 높은 숫자를 놓아야 합니다.' +
                              '내림차순 위치는 오름차순 위치와 반대로 이전에 놓인 카드보다 낮은 숫자를 놓아야 합니다.'+
                              '카드를 조건에 맞게 내려놓았다면 차례를 마칠 수 있습니다.'
                              '차례를 종료하면 이번에 내려놓은 만큼의 카드를 더미에서 가져옵니다.\n\n' +

                              '#되돌리기 규칙\n' +
                              '일반적으로는 열마다 정해진 규칙대로 카드를 놓아야 하지만, 되돌리기 규칙에 해당하는 카드는 일반 규칙을 무시하고 놓을 수 있습니다.' +
                              '-오름차순 위치: 현재 위치에 표시된 카드보다 정확히 10이 낮은 카드를 낼 수 있습니다.' +
                              '-내림차순 위치: 현재 위치에 표시된 카드보다 정확히 10이 높은 카드를 낼 수 있습니다.\n\n' +

                              '#게임의 종료\n' +
                              '숫자 카드 더미가 떨어지면, 더 이상 카드를 뽑지 않고 게임을 진행합니다.'+
                              '만약 한 차례에 놓아야 하는 최소한의 카드를 내려놓을 수 없다면(카드 더미가 남아있다면 2장, 카드 더미가 없다면 1장)'+
                              '게임은 즉시 종료되고 플레이어는 게임에서 패배합니다.'+
                              '만약 플레이어가 자신의 카드를 전부 내려놓았다면, 플레이어들의 승리입니다.'

                              , QMessageBox.Yes)



    #게임종료
    def exitClicked(self):
        #정말 종료하시겠습니까?
        Endkey = self.warning.question(self, '', "정말로 종료하시겠습니까?", self.warning.Yes | self.warning.No)
        if Endkey== self.warning.Yes:
            self.close()
        elif Endkey== self.warning.No:
            pass
        self.close()



    #턴 종료
    def turnEndClicked(self):
        self.putCount = self.putCard.getPutCount()
        self.handCardList = self.dummy.getHandCardList()

        if self.putCount >= 2:
            self.dummy.takeCard(self.handCardList)

            self.deckNum = self.dummy.countDeck()

            self.dummyDeck.setText('남은 카드 수\n\n' + str(self.deckNum))
            for i in range(8):
                self.handCard[i].setText(self.handCardList[i])
                self.handCard[i].setEnabled(False)
            self.putCard.resetPutCount()

            if self.putCard.guess(self.handCardList, self.deckNum) == False: #여긴 덱 장수 신경안씀
                self.warning.question(self, 'Game Over', 'You lose', QMessageBox.Yes)
                #self.startClicked() #게임 자동초기화
            else:
                pass
        else:
            self.warning.question(self, 'Error', '두 장 이상의 카드를 옮긴 후 종료 할 수 있습니다.', QMessageBox.Yes)
            self.dummyDeck.setText('남은 카드 수\n\n' + str(self.dummy.countDeck()))




    # 내려놓아진 패
    def downCardClicked(self):
        self.downLocation = self.sender()
        for i in range(8):
            self.handCard[i].setEnabled(True)


    # 사용자의 덱에 있는 카드
    def handCardClicked(self):
        self.holdNum = self.sender()

        try:
            downNum = int(self.downLocation.text())
            holdNum = int(self.holdNum.text())

            if self.putCard.checkPut(downNum, holdNum, self.downLocation.label):
                num = self.dummy.takenCard(self.holdNum.text())
                self.downLocation.setText(num)
                self.holdNum.setText('')

            for i in range(8):
                self.handCard[i].setEnabled(False)

            self.handCardList = self.dummy.getHandCardList()
            self.deckNum = self.dummy.countDeck()

            if self.deckNum == 0 and self.handCardList.count('')== 8:
                self.warning.question(self, 'Game Over', 'You Win (ノ゚▽゚)ノ', QMessageBox.Yes)
                #self.startClicked() #게임 자동초기화
            elif self.putCard.guess(self.handCardList, self.deckNum)== False and self.deckNum == 0:
                self.warning.question(self, 'Game Over', 'You lose', QMessageBox.Yes)#여기선 덱이 0장일때만 승패관리함
                #self.startClicked() #게임 자동초기화
            else:
                pass

        except:
            self.warning.question(self, 'Error', '이미 낸 카드입니다.', QMessageBox.Yes)
コード例 #29
0
ファイル: publish.py プロジェクト: gumpu/Snippet
#!/usr/bin/env python

import zmq
import time
from dummy import Dummy

context = zmq.Context(1)

command_socket  = context.socket( zmq.PUB )
command_socket.bind( "tcp://*:9001" )

dummy = Dummy()
dummy.a_hash['foo']='bar'
dummy.a_hash[12]='12bar'

while True :
    time.sleep(1)
    command_socket.send_pyobj( dummy )
    print "Awake"