Beispiel #1
0
    def jogada(self, casa_anterior=(0, 0, 0)):
        def casa_do_indice(ind):
            return Casa.CASAS[Tabuleiro.CASAS[ind]]
        casa_da_jogada = choice(self.casas)  # choice(TABULEIRO)  # TABULEIRO[0]
        alguem_ganha = self.verifica_alguem_ganha(self.jogada_robo,  1 if self.peca_robo == 2 else 2)
        if not alguem_ganha:
            alguem_ganha = self.verifica_alguem_ganha(casa_anterior, self.peca_robo)
        if alguem_ganha:
            casas = alguem_ganha[0]
            casa_vazia = [Casa.CASAS[casa] for casa in casas if Casa.CASAS[casa].tipo_peca() == 0]
            print('humano_ganha:', alguem_ganha, casas, "jogue aqui:", casa_vazia)

            casa_da_jogada = casa_vazia[0]
        # AI: consulta a hitória de vitórias para repetir um lance vitorioso
        if self.vitorias_nesta_jogada and choice(range(10)) >-1:
            # seleciona entre os palpites vitoriosos um que caia numa casa vazia
            palpite = [casa_do_indice(tentativa[1])
                for tentativa in self.vitorias_nesta_jogada
                if casa_do_indice(tentativa[1]) in self.casas]
            # se exite um palpite possível seleciona o primeiro da lista ordenada
            if palpite:
                casa_da_jogada = palpite[0]
        self.remove(casa_da_jogada)
        casa_da_jogada.clicou()
        self.jogada_robo = casa_da_jogada.pos
        return self.jogada_robo
 def random(level):
     if level == 0:
         operator = __random.choice(ProblemGenerator.non_trivial_weighted_operators)
     else:
         operator = __random.choice(ProblemGenerator.weighted_operators)
     #recursive tree call
     left = Expression.random(level + 1)
     right = Expression.random(level + 1)
     return BinaryExpression(left, operator, right)
Beispiel #3
0
 def __init__(self,
              html,
              xy,
              deque,
              face=('ace', 'clubs'),
              version=("0", ),
              sp=True):
     self.html = html
     self.xy = xy
     self.deque = deque
     self.face = face + version
     self.clip = choice(Carta.CLIP)
     name = "".join(self.face)
     Carta.CARDS[name] = self
     ct = self.e_carta = html.IMG(Id=name,
                                  src=FACE % face,
                                  width=CH,
                                  heigth=CV,
                                  Class=self.clip)
     if sp:
         self.position(xy)
     ct.style.position = "absolute"
     ct.style.left, ct.style.top = xy
     deque <= ct
     ct.onclick = self.clicou
     ct.ontransitionend = self.bota
     ct.ondragstart = self.drag_start
 def random_splice(str):
     begin = __random.randint(0,len(str)/2)
     end = __random.randint(len(str)/2, len(str))
     withIter = __random.choice([True, False, False])
     iter = None
     if withIter:
         iter = __random.randint(0, end - begin) + 1
     else:
         iter = 1
     return ListSplice(begin, end, iter, str)
 def random(level):
     if level < ProblemGenerator.difficulty:
         is_num = False
     elif level == ProblemGenerator.max_levels:
         is_num = True
     else:
         is_num = __random.choice([True, True, False])
     if is_num:
         return Number.random(level)
     else:
         return BinaryExpression.random(level)
Beispiel #6
0
    def jogada():
        casa_da_jogada = choice(TABULEIRO) # TABULEIRO[0]
        humano_ganha = verifica_humano_ganha()
        if humano_ganha:
            casas = humano_ganha[0]
            print('humano_ganha:', humano_ganha, casas,"joga aqui:", casas[2])
            # descobre qual casa está vazia
            casa_vazia = [Casa.CASAS[casa] for casa in casas if Casa.CASAS[casa].tipo_peca() == 0]
            print('humano_ganha:', humano_ganha, casas,"jogue aqui:", casa_vazia)

            casa_da_jogada = casa_vazia[0]

        #verifica_robo_ganha()
        TABULEIRO.remove(casa_da_jogada)
        casa_da_jogada.clicou()
Beispiel #7
0
    def jogada(self, casa_anterior=(0, 0, 0)):
        def casa_do_indice(ind):
            return Casa.CASAS[Tabuleiro.CASAS[ind]]

        casa_da_jogada = choice(
            self.casas)  # choice(TABULEIRO)  # TABULEIRO[0]
        alguem_ganha = self.verifica_alguem_ganha(
            self.jogada_robo, 1 if self.peca_robo == 2 else 2)
        if not alguem_ganha:
            alguem_ganha = self.verifica_alguem_ganha(casa_anterior,
                                                      self.peca_robo)
        if alguem_ganha:
            casas = alguem_ganha[0]
            casa_vazia = [
                Casa.CASAS[casa] for casa in casas
                if Casa.CASAS[casa].tipo_peca() == 0
            ]
            print('humano_ganha:', alguem_ganha, casas, "jogue aqui:",
                  casa_vazia)

            casa_da_jogada = casa_vazia[0]
        # AI: consulta a hitória de vitórias para repetir um lance vitorioso
        if self.vitorias_nesta_jogada and choice(range(10)) > -1:
            # seleciona entre os palpites vitoriosos um que caia numa casa vazia
            palpite = [
                casa_do_indice(tentativa[1])
                for tentativa in self.vitorias_nesta_jogada
                if casa_do_indice(tentativa[1]) in self.casas
            ]
            # se exite um palpite possível seleciona o primeiro da lista ordenada
            if palpite:
                casa_da_jogada = palpite[0]
        self.remove(casa_da_jogada)
        casa_da_jogada.clicou()
        self.jogada_robo = casa_da_jogada.pos
        return self.jogada_robo
 def random(level, string, splices):
     splicer = ListSplice.random_splice(string)
     string = splicer.solve()
     splices.append(splicer)
     if level < ProblemGenerator.difficulty - 1:
         is_done= False
     elif level == int((ProblemGenerator.max_levels - 1)/2) or len(string) <= 1:
         is_done = True
     else:
         is_done = __random.choice([True, False, False])
     if is_done:
         splicestr = ""
         for splice in splices:
             splicestr = splicestr + splice.to_string()
         return (splicestr, string)
     else:
         return ListSplice.random(level + 1, string, splices)
Beispiel #9
0
 def __init__(self, html, xy, deque, face=('ace', 'clubs'), version=("0", ), sp=True):
     self.html = html
     self.xy = xy
     self.deque = deque
     self.face = face + version
     self.clip = choice(Carta.CLIP)
     name = "".join(self.face)
     Carta.CARDS[name]=self
     ct = self.e_carta = html.IMG(Id=name, src=FACE % face, width=CH, heigth=CV, Class=self.clip)
     if sp:
         self.position(xy)
     ct.style.position = "absolute"
     ct.style.left, ct.style.top = xy
     deque <= ct
     ct.onclick = self.clicou
     ct.ontransitionend = self.bota
     ct.ondragstart = self.drag_start
Beispiel #10
0
    def jogada():
        casa_da_jogada = choice(TABULEIRO)  #TABULEIRO[0]
        humano_ganha = verifica_humano_ganha()
        if humano_ganha:
            casas = humano_ganha[0]
            print('humano_ganha:', humano_ganha, casas, "Jogue aqui:",
                  casas[2])
            #descobre qual casa está vazia
            casa_vazia = [
                Casa.CASAS[casa] for casa in casas
                if Casa.CASAS[casa].tipo_peca() == 0
            ]
            print('humano_ganha:', humano_ganha, casas, "Jogue aqui:",
                  casa_vazia)

            casa_da_jogada = casa_vazia[0]

        #verifica_robo_ganha()
        TABULEIRO.remove(casa_da_jogada)
        casa_da_jogada.clicou()
Beispiel #11
0
'mousemove', 'mousedown', 'mouseup', 'click', 'dblclick']
TESTS = 3

# Objects to be used in testing are prepared
def listener(value):
    'Closure of dummy listeners to test binding/unbinding'
    return lambda _: responses.append(value)
target = html.BUTTON('Target', id='Target')

# Listeners of each type are bound then randomly unbound while being tested
for event in EVENT_TYPES:
    responses = []
    listeners = []
    tests = list(range(TESTS))
    for test in tests:
        listeners.append(listener(test))
        target.bind(event, listeners[-1])
    while tests:
        # The event is triggered and the results examined
        target.trigger(event)
        assert responses == tests

        # The results are cleared, one random listener is removed
        responses.clear()
        removed = tests.index(random.choice(tests))
        target.unbind(event, listeners[removed])
        del tests[removed]
        del listeners[removed]

# TODO: new UI elements like slider etc
Beispiel #12
0
def apply_markdown(src):

    scripts = []
    key = None

    i = 0
    while i<len(src):
        if src[i]=='[':
            start_a = i+1
            while True:
                end_a = src.find(']',i)
                if end_a == -1:
                    break
                if src[end_a-1]=='\\':
                    i = end_a+1
                else:
                    break
            if end_a>-1 and src[start_a:end_a].find('\n')==-1:
                link = src[start_a:end_a]
                rest = src[end_a+1:].lstrip()
                if rest and rest[0]=='(':
                    j = 0
                    while True:
                        end_href = rest.find(')',j)
                        if end_href == -1:
                            break
                        if rest[end_href-1]=='\\':
                            j = end_href+1
                        else:
                            break
                    if end_href>-1 and rest[:end_href].find('\n')==-1:
                        tag = '<a href="'+rest[1:end_href]+'">'+link+'</a>'
                        src = src[:start_a-1]+tag+rest[end_href+1:]
                        i = start_a+len(tag)
                elif rest and rest[0]=='[':
                    j = 0
                    while True:
                        end_key = rest.find(']',j)
                        if end_key == -1:
                            break
                        if rest[end_key-1]=='\\':
                            j = end_key+1
                        else:
                            break
                    if end_key>-1 and rest[:end_key].find('\n')==-1:
                        if not key:
                            key = link
                        if key.lower() not in refs:
                            raise KeyError('unknown reference %s' %key)
                        url = refs[key.lower()]
                        tag = '<a href="'+url+'">'+link+'</a>'
                        src = src[:start_a-1]+tag+rest[end_key+1:]
                        i = start_a+len(tag)
        
        i += 1

    # before applying the markup with _ and *, isolate HTML tags because 
    # they can contain these characters

    # We replace them temporarily by a random string
    rstr = ''.join(random.choice(letters) for i in range(16))
    
    i = 0
    state = None
    start = -1
    data = ''
    tags = []
    while i<len(src):
        if src[i]=='<':
            j = i+1
            while j<len(src):
                if src[j]=='"' or src[j]=="'":
                    if state==src[j] and src[j-1]!='\\':
                        state = None
                        #src = src[:start+1]+data+src[j:]
                        j = start+len(data)+1
                        data = ''
                    elif state==None:
                        state = src[j]
                        start = j
                    else:
                        data += src[j]
                elif src[j]=='>' and state is None:
                    tags.append(src[i:j+1])
                    src = src[:i]+rstr+src[j+1:]
                    i += len(rstr)
                    break
                elif state=='"' or state=="'":
                    data += src[j]
                elif src[j]=='\n':
                    # if a sign < is not followed by > in the same ligne, it
                    # is the sign "lesser than"
                    src = src[:i]+'&lt;'+src[i+1:]
                    j=i+4
                    break
                j += 1
            #i = j
        elif src[i]=='`' and i>0 and src[i-1]!='\\':
            # ignore the content of inline code
            j = i+1
            while j<len(src):
                if src[j]=='`' and src[j-1]!='\\':
                    break
                j += 1
            i = j
        i += 1                    

    # escape "<", ">", "&" and "_" in inline code
    code_pattern = r'\`(.*?)\`'
    src = re.sub(code_pattern,s_escape,src)

    # replace escaped ` _ * by HTML characters
    src = src.replace(r'\\`','&#96;')
    src = src.replace(r'\_','&#95;')
    src = src.replace(r'\*','&#42;')

    # emphasis
    strong_patterns = [('STRONG',r'\*\*(.*?)\*\*'),('B',r'__(.*?)__')]
    for tag,strong_pattern in strong_patterns:
        src = re.sub(strong_pattern,r'<%s>\1</%s>' %(tag,tag),src)

    em_patterns = [('EM',r'\*(.*?)\*'),('I',r'\_(.*?)\_')]
    for tag,em_pattern in em_patterns:
        src = re.sub(em_pattern,r'<%s>\1</%s>' %(tag,tag),src)

    # inline code
    code_pattern = r'\`(.*?)\`'
    src = re.sub(code_pattern,r'<code>\1</code>',src)
    
    # restore tags
    while True:
        pos = src.rfind(rstr)
        if pos==-1:
            break
        repl = tags.pop()
        src = src[:pos]+repl+src[pos+len(rstr):]

    src = '<p>'+src+'</p>'

    return src,scripts
Beispiel #13
0
def apply_markdown(src):

    scripts = []
    key = None

    i = 0
    while i < len(src):
        if src[i] == '[':
            start_a = i + 1
            while True:
                end_a = src.find(']', i)
                if end_a == -1:
                    break
                if src[end_a - 1] == '\\':
                    i = end_a + 1
                else:
                    break
            if end_a > -1 and src[start_a:end_a].find('\n') == -1:
                link = src[start_a:end_a]
                rest = src[end_a + 1:].lstrip()
                if rest and rest[0] == '(':
                    j = 0
                    while True:
                        end_href = rest.find(')', j)
                        if end_href == -1:
                            break
                        if rest[end_href - 1] == '\\':
                            j = end_href + 1
                        else:
                            break
                    if end_href > -1 and rest[:end_href].find('\n') == -1:
                        tag = '<a href="' + rest[
                            1:end_href] + '">' + link + '</a>'
                        src = src[:start_a - 1] + tag + rest[end_href + 1:]
                        i = start_a + len(tag)
                elif rest and rest[0] == '[':
                    j = 0
                    while True:
                        end_key = rest.find(']', j)
                        if end_key == -1:
                            break
                        if rest[end_key - 1] == '\\':
                            j = end_key + 1
                        else:
                            break
                    if end_key > -1 and rest[:end_key].find('\n') == -1:
                        if not key:
                            key = link
                        if key.lower() not in refs:
                            raise KeyError('unknown reference %s' % key)
                        url = refs[key.lower()]
                        tag = '<a href="' + url + '">' + link + '</a>'
                        src = src[:start_a - 1] + tag + rest[end_key + 1:]
                        i = start_a + len(tag)

        i += 1

    # before applying the markup with _ and *, isolate HTML tags because
    # they can contain these characters

    # We replace them temporarily by a random string
    rstr = ''.join(random.choice(letters) for i in range(16))

    i = 0
    state = None
    start = -1
    data = ''
    tags = []
    while i < len(src):
        if src[i] == '<':
            j = i + 1
            while j < len(src):
                if src[j] == '"' or src[j] == "'":
                    if state == src[j] and src[j - 1] != '\\':
                        state = None
                        #src = src[:start+1]+data+src[j:]
                        j = start + len(data) + 1
                        data = ''
                    elif state == None:
                        state = src[j]
                        start = j
                    else:
                        data += src[j]
                elif src[j] == '>' and state is None:
                    tags.append(src[i:j + 1])
                    src = src[:i] + rstr + src[j + 1:]
                    i += len(rstr)
                    break
                elif state == '"' or state == "'":
                    data += src[j]
                elif src[j] == '\n':
                    # if a sign < is not followed by > in the same ligne, it
                    # is the sign "lesser than"
                    src = src[:i] + '&lt;' + src[i + 1:]
                    j = i + 4
                    break
                j += 1
            #i = j
        elif src[i] == '`' and i > 0 and src[i - 1] != '\\':
            # ignore the content of inline code
            j = i + 1
            while j < len(src):
                if src[j] == '`' and src[j - 1] != '\\':
                    break
                j += 1
            i = j
        i += 1

    # escape "<", ">", "&" and "_" in inline code
    code_pattern = r'\`(.*?)\`'
    src = re.sub(code_pattern, s_escape, src)

    # replace escaped ` _ * by HTML characters
    src = src.replace(r'\\`', '&#96;')
    src = src.replace(r'\_', '&#95;')
    src = src.replace(r'\*', '&#42;')

    # emphasis
    strong_patterns = [('STRONG', r'\*\*(.*?)\*\*'), ('B', r'__(.*?)__')]
    for tag, strong_pattern in strong_patterns:
        src = re.sub(strong_pattern, r'<%s>\1</%s>' % (tag, tag), src)

    em_patterns = [('EM', r'\*(.*?)\*'), ('I', r'\_(.*?)\_')]
    for tag, em_pattern in em_patterns:
        src = re.sub(em_pattern, r'<%s>\1</%s>' % (tag, tag), src)

    # inline code
    code_pattern = r'\`(.*?)\`'
    src = re.sub(code_pattern, r'<code>\1</code>', src)

    # restore tags
    while True:
        pos = src.rfind(rstr)
        if pos == -1:
            break
        repl = tags.pop()
        src = src[:pos] + repl + src[pos + len(rstr):]

    src = '<p>' + src + '</p>'

    return src, scripts
 def generate_list_splice():
     word = __random.choice(ProblemGenerator.__words)
     problem = ListSplice.random(0, word, [])
     problem[0] = '\'' + word + '\'' + problem[0]
     problem[1] = '\'' + problem[1] + '\''
     return problem