Exemple #1
0
def fetch_match(request):
    context = RequestContext(request)
    matchid = request.GET['matchid']
    movecnt = request.GET['movecnt']
    switchflag = request.GET['switchflag']
    match = Match.objects.get(id=matchid)
    if(match == None):
        data = "§§"
    else:
        lastmove = Move.objects.filter(match_id=match.id).order_by("count").last()
        if(lastmove != None):
            movesrc = Match.index_to_koord(lastmove.srcx, lastmove.srcy)
            movedst = Match.index_to_koord(lastmove.dstx, lastmove.dsty)
        if(int(movecnt) == match.count):
            data = "§"
        else:
            data = html_board(match, int(switchflag), movesrc, movedst) + "§" + html_moves(match)

        thread = Match.get_active_thread(match)
        if(thread and not thread.candidate_srcx):
            data += "§<p>thread found with matchid: " + str(thread.match.id) + "</p>"
        elif(thread and thread.candidate_srcx):
            data += "§<p>move candidate: "
            data += Match.index_to_koord(thread.candidate_srcx, thread.candidate_srcy) + "-" + Match.index_to_koord(thread.candidate_dstx, thread.candidate_dsty)
            data += "</p>"
        else:
            data += "§"

    return HttpResponse(data)
Exemple #2
0
def is_move_ok(match, srcx, srcy, dstx, dsty, piece):
    DIRS = rules.DIRS
    direction, stepx, stepy = rk_step(None, srcx, srcy, dstx, dsty)
    if(direction == DIRS['undefined']):
        return False

    color = Match.color_of_piece(piece)

    pin_dir = rules.pin_dir(match, srcx, srcy)

    if(direction == DIRS['north'] or direction == DIRS['south']):
        if(pin_dir != DIRS['north'] and pin_dir != DIRS['south'] and pin_dir != DIRS['undefined']):
            return False
    elif(direction == DIRS['east'] or direction == DIRS['west']):
        if(pin_dir != DIRS['east'] and pin_dir != DIRS['west'] and pin_dir != DIRS['undefined']):
            return False

    x = srcx + stepx
    y = srcy + stepy
    while(x >= 0 and x <= 7 and y >= 0 and y <= 7):
        field = match.readfield(x, y)
        if(x == dstx and y == dsty):
            if(Match.color_of_piece(field) == color):
                return False
            else:
                return True
        elif(field != Match.PIECES['blk']):
            return False

        x += stepx
        y += stepy

    return False
Exemple #3
0
def do_move(request, matchid):
    context = RequestContext(request)
    if request.method == 'POST':
        match = get_object_or_404(Match, pk=matchid)
        movesrc = request.POST['move_src']
        movedst = request.POST['move_dst']
        prompiece = request.POST['prom_piece']
        switch = request.POST['switch']
        if(match.next_color_human()):
            if(len(movesrc) > 0 and len(movedst) > 0 and len(prompiece) > 0):
                srcx,srcy = Match.koord_to_index(movesrc)
                dstx,dsty = Match.koord_to_index(movedst)
                prom_piece = match.PIECES[prompiece]
                flag, msg = rules.is_move_valid(match, srcx, srcy, dstx, dsty, prom_piece)
                status = rules.game_status(match)
                if(flag == True and status == Match.STATUS['open']):
                    move = match.do_move(srcx, srcy, dstx, dsty, prom_piece)
                    move.save()
                    match.save()
                    calc_move_for_immanuel(match)
                    fmtmsg = "<p class='ok'>" + rules.ERROR_MSGS[msg] + "</p>"
                else:
                    fmtmsg = "<p class='error'>" + rules.ERROR_MSGS[msg] + "</p>"
            else:
                fmtmsg = "<p class='error'>Zug-Format ist ungültig.</p>"
        else:
            fmtmsg = "<p class='error'>Farbe ist nicht am Zug.</p>"

        fmtboard = fill_fmtboard(match, int(switch))

        moves = []
        currmove = Move.objects.filter(match_id=match.id).order_by("count").last()
        if(currmove != None):
            if(currmove.count % 2 == 0):
                limit = 22
            else:
                limit = 21
            qmoves = Move.objects.filter(match_id=match.id).order_by("-count")[:limit]
            for qmove in reversed(qmoves):
                moves.append(qmove)

        comments = Comment.objects.filter(match_id=match.id).order_by("created_at").reverse()[:3]

        status = rules.game_status(match)
        if(status != Match.STATUS['open']):
            fmtmsg = "<p class='error'>" + helper.reverse_lookup(Match.STATUS, status) + "</p>"

        if(int(switch) == 0):
            rangeobj = range(8)
        else:
            rangeobj = range(7, -1, -1)

        candidate = ""

        return render(request, 'kate/match.html', { 'match': match, 'board': fmtboard, 'switch': switch, 'movesrc': movesrc, 'movedst': movedst, 'moves': moves, 'comments': comments, 'msg': fmtmsg, 'range': rangeobj, 'candidate': candidate } )
    else:
        return HttpResponseRedirect(reverse('kate:match', args=(matchid, switch)))
Exemple #4
0
def prnt_moves(match):
    count = 1
    print("------------------------------------------------------")
    for move in match.move_list[1:]:
        print(str(count) + ": " + 
              Match.index_to_koord(move.srcx, move.srcy) + " " +
              Match.index_to_koord(move.dstx, move.dsty) + " " +
              helper.reverse_lookup(Match.PIECES, move.prom_piece))
        count += 1
    print("------------------------------------------------------")
Exemple #5
0
 def __init__(self, name, match):
     threading.Thread.__init__(self)
     self.name = name
     self.match = copy.deepcopy(match)
     self.candidate_srcx = None
     self.candidate_srcy = None
     self.candidate_dstx = None
     self.candidate_dsty = None
     self.candidate_prom_piece = None
     Match.remove_outdated_threads(match)
     Match.add_thread(self)
Exemple #6
0
def is_move_ok(match, srcx, srcy, dstx, dsty, piece):
    DIRS = rules.DIRS

    color = Match.color_of_piece(piece)

    opp_color = Match.REVERSED_COLORS[color]

    direction = kg_dir(srcx, srcy, dstx, dsty)
    if(direction == DIRS['sh-castling']):
        return is_sh_castling_ok(match, srcx, srcy, dstx, dsty, piece)
    if(direction == DIRS['lg-castling']):
        return is_lg_castling_ok(match, srcx, srcy, dstx, dsty, piece)
    if(direction == DIRS['undefined']):
        return False

    king = match.readfield(srcx, srcy)
    captured = match.readfield(dstx, dsty)
    match.writefield(srcx, srcy, Match.PIECES['blk'])
    match.writefield(dstx, dsty, king)
    attacked = rules.attacked(match, dstx, dsty, opp_color)
    match.writefield(srcx, srcy, king)
    match.writefield(dstx, dsty, captured)
    if(attacked == True):
        return False

    field = match.readfield(dstx, dsty)
    if(match.color_of_piece(field) == color):
        return False

    return True
Exemple #7
0
def is_lg_castling_ok(match, srcx, srcy, dstx, dsty, piece):
    color = Match.color_of_piece(piece)

    opp_color = Match.REVERSED_COLORS[color]

    for i in range(1, 3, 1):
        fieldx = srcx - i
        field = match.readfield(fieldx, srcy)
        if(field != Match.PIECES['blk']):
            return False

    if(color == Match.COLORS['white']):
        if(match.wKg_first_movecnt != 0 or match.wRk_a1_first_movecnt != 0):
            return False
    else:
        if(match.bKg_first_movecnt != 0 or match.bRk_a8_first_movecnt != 0):
            return False

    king = match.readfield(srcx, srcy)
    match.writefield(srcx, srcy, Match.PIECES['blk'])
    for i in range(0, -3, -1):
        castlingx = srcx + i
        attacked = rules.attacked(match, castlingx, srcy, opp_color)
        if(attacked == True):
            match.writefield(srcx, srcy, king)
            return False

    match.writefield(srcx, srcy, king)
    return True
Exemple #8
0
    def run(self):
        print("Starting " + str(self.name))
        move = Move.objects.filter(match_id=self.match.id).order_by("count").last()
        if(move != None):
            self.match.move_list.append(move)

        if(self.match.level == Match.LEVEL['low']):
            maxdepth = 1
        elif(self.match.level == Match.LEVEL['medium']):
            maxdepth = 2
        elif(self.match.level == Match.LEVEL['high']):
            maxdepth = 3
        else:
            # professional
            maxdepth = 4

        gmove = calc_move(self.match, maxdepth)
        if(gmove != None):
            curr_match = Match.objects.get(id=self.match.id)
            if(curr_match.count == self.match.count and Match.does_thread_exist(self)):
                move = self.match.do_move(gmove.srcx, gmove.srcy, gmove.dstx, gmove.dsty, gmove.prom_piece)
                move.save()
                self.match.save()
                print("move saved")
            else:
                print("thread outdated - move dropped")

        return gmove
Exemple #9
0
def generate_move(match, cnt):
    if(match.next_color() == Match.COLORS['white']):
        move_list = WHITEMOVES
    else:
        move_list = BLACKMOVES

    if(cnt >= CNT):
        return CNT + 1, None

    for i in range(cnt, CNT):
        x1, y1 = Match.koord_to_index(move_list[i][0])
        x2, y2 = Match.koord_to_index(move_list[i][1])
        if(rules.is_move_valid(match, x1, y1, x2, y2, Match.PIECES['blk'])[0]):
            gmove = calc.GenMove(x1, y1, x2, y2, Match.PIECES['blk'])
            return i, gmove

    return CNT + 1, None
Exemple #10
0
def is_move_color_ok_OLD(piece, count):
    color = Match.color_of_piece(piece)
    if count % 2 == 0 and color == Match.COLORS["white"]:
        return True
    elif count % 2 == 1 and color == Match.COLORS["black"]:
        return True
    else:
        return False
Exemple #11
0
def pin_dir(match, scrx, srcy):
    piece = match.readfield(scrx, srcy)
    color = Match.color_of_piece(piece)
    if color == Match.COLORS["white"]:
        kgx = match.wKg_x
        kgy = match.wKg_y
    else:
        kgx = match.bKg_x
        kgy = match.bKg_y

    direction, stepx, stepy = rook.rk_step(None, scrx, srcy, kgx, kgy)
    if direction != DIRS["undefined"]:
        dstx, dsty = search(match, scrx, srcy, stepx, stepy)
        if dstx != UNDEF_X:
            piece = match.readfield(dstx, dsty)
            if (color == Match.COLORS["white"] and piece == Match.PIECES["wKg"]) or (
                color == Match.COLORS["black"] and piece == Match.PIECES["bKg"]
            ):
                reverse_dir = REVERSE_DIRS[direction]
                reverse_dir, stepx, stepy = rook.rk_step(reverse_dir, None, None, None, None)
                dstx, dsty = search(match, scrx, srcy, stepx, stepy)
                if dstx != UNDEF_X:
                    piece = match.readfield(dstx, dsty)
                    if color == Match.COLORS["white"]:
                        if piece == Match.PIECES["bQu"] or piece == Match.PIECES["bRk"]:
                            return direction
                        else:
                            return DIRS["undefined"]
                    else:
                        if piece == Match.PIECES["wQu"] or piece == Match.PIECES["wRk"]:
                            return direction
                        else:
                            return DIRS["undefined"]

    direction, stepx, stepy = bishop.bp_step(None, scrx, srcy, kgx, kgy)
    if direction != DIRS["undefined"]:
        dstx, dsty = search(match, scrx, srcy, stepx, stepy)
        if dstx != UNDEF_X:
            piece = match.readfield(dstx, dsty)
            if (color == Match.COLORS["white"] and piece == Match.PIECES["wKg"]) or (
                color == Match.COLORS["black"] and piece == Match.PIECES["bKg"]
            ):
                reverse_dir = REVERSE_DIRS[direction]
                reverse_dir, stepx, stepy = bishop.bp_step(reverse_dir, None, None, None, None)
                dstx, dsty = search(match, scrx, srcy, stepx, stepy)
                if dstx != UNDEF_X:
                    piece = match.readfield(dstx, dsty)
                    if color == Match.COLORS["white"]:
                        if piece == Match.PIECES["bQu"] or piece == Match.PIECES["bBp"]:
                            return direction
                        else:
                            return DIRS["undefined"]
                    else:
                        if piece == Match.PIECES["wQu"] or piece == Match.PIECES["wBp"]:
                            return direction
                        else:
                            return DIRS["undefined"]
    return DIRS["undefined"]
Exemple #12
0
def retrieve_move(match):
    if(match.count == 0):
        omoves = OpeningMove.objects.filter(movecnt=1)
        if(omoves):
            idx = random.randint(0, len(omoves) - 1)
            x1, y1 = Match.koord_to_index(omoves[idx].src)
            x2, y2 = Match.koord_to_index(omoves[idx].dst)
            gmove = calc.GenMove(x1, y1, x2, y2, Match.PIECES['blk'])
            print("------------ opening move found! --------------")
            return gmove
        else:
            print("############ No opening move found ############")
            return None

    lastmove = Move.objects.get(match_id=match.id, count=match.count)
    movesrc = Match.index_to_koord(lastmove.srcx, lastmove.srcy)
    movedst = Match.index_to_koord(lastmove.dstx, lastmove.dsty)
    prev_omoves = OpeningMove.objects.filter(movecnt=match.count, src=movesrc, dst=movedst)
    prev_list = list(prev_omoves)

    for prev_omove in prev_omoves:
        previous = prev_omove.previous

        while(previous):
            try:
                move = Move.objects.get(match_id=match.id, count=previous.movecnt)
            except Move.DoesNotExist:
                print("---------None---------")
                return None
            prevsrc = Match.index_to_koord(move.srcx, move.srcy)
            prevdst = Match.index_to_koord(move.dstx, move.dsty)
            if(previous.src != prevsrc or previous.dst != prevdst):
                prev_list.remove(prev_omove)
                break
            previous = previous.previous

    if(prev_list):
        previous = prev_list[0]
        omoves = OpeningMove.objects.filter(movecnt=match.count + 1, previous_id=previous.id)
        if(omoves):
            idx = random.randint(0, len(omoves) - 1)
            x1, y1 = Match.koord_to_index(omoves[idx].src)
            x2, y2 = Match.koord_to_index(omoves[idx].dst)
            gmove = calc.GenMove(x1, y1, x2, y2, Match.PIECES['blk'])
            print("------------ opening move found! --------------")
            return gmove
        else:
            print("############ 1: No opening move found! ###############")
            return None
    else:
        print("############ 2: No opening move found! ###############")
        return None
def evaluate_contacts(match):
    supported_whites = 0
    attacked_whites = 0
    supported_blacks = 0
    attacked_blacks = 0
    color = match.next_color()

    for y in range(0, 8, 1):
        for x in range(0, 8, 1):
            piece = match.readfield(x, y)
            if(Match.color_of_piece(piece) == Match.COLORS['undefined']):
                continue
            elif(Match.color_of_piece(piece) == Match.COLORS['white']):
                supported_whites += rules.count_attacks(match, x, y, Match.COLORS['white'])
                attacked_whites += rules.count_attacks(match, x, y, Match.COLORS['black'])
            else:
                supported_blacks += rules.count_attacks(match, x, y, Match.COLORS['black'])
                attacked_blacks += rules.count_attacks(match, x, y, Match.COLORS['white'])

    return (supported_whites - attacked_whites) - (supported_blacks - attacked_blacks)
def evaluate_developments(match):
    developed_whites = 0
    developed_blacks = 0

    for y in range(0, 8, 1):
        for x in range(0, 8, 1):
            piece = match.readfield(x, y)
            if(Match.color_of_piece(piece) == Match.COLORS['undefined']):
                continue
            elif(Match.color_of_piece(piece) == Match.COLORS['white']):
                if(piece == Match.PIECES['wKn']):
                    if(y > 0):
                        developed_whites += 3
                elif(piece == Match.PIECES['wBp']):
                    if(y > 0):
                        developed_whites += 2
                elif(piece == Match.PIECES['wQu']):
                    if(y > 0):
                        developed_whites += 1
                elif(piece == Match.PIECES['wKg']):
                    if(y == 0 and (x == 6 or x == 2)):
                        developed_whites += 2
            else:
                if(piece == Match.PIECES['bKn']):
                    if(y < 7):
                        developed_blacks -= 3
                elif(piece == Match.PIECES['bBp']):
                    if(y < 7):
                        developed_blacks -= 2
                elif(piece == Match.PIECES['bQu']):
                    if(y < 7):
                        developed_blacks -= 1
                elif(piece == Match.PIECES['bKg']):
                    if(y == 7 and (x == 6 or x == 2)):
                        developed_blacks -= 2

    return developed_whites + developed_blacks
Exemple #15
0
def match(request, matchid=None, switch=0):
    context = RequestContext(request)
    if(matchid == None):
        match = Match(white_player=None, black_player=None)
        match.setboardbase()
    else:
        match = Match.objects.get(id=matchid)

    lastmove = Move.objects.filter(match_id=match.id).order_by("count").last()
    if(lastmove):
        movesrc = Match.index_to_koord(lastmove.srcx, lastmove.srcy)
        movedst = Match.index_to_koord(lastmove.dstx, lastmove.dsty)
    else:
        movesrc = ''
        movedst = ''

    fmtboard = fill_fmtboard(match, int(switch))

    moves = []
    currmove = Move.objects.filter(match_id=match.id).order_by("count").last()
    if(currmove != None):
        if(currmove.count % 2 == 0):
            limit = 22
        else:
            limit = 21
        qmoves = Move.objects.filter(match_id=match.id).order_by("-count")[:limit]
        for qmove in reversed(qmoves):
            moves.append(qmove)

    comments = Comment.objects.filter(match_id=match.id).order_by("created_at").reverse()[:3]
    fmtmsg = "<p class='ok'></p>"
    if(int(switch) == 0):
        rangeobj = range(8)
    else:
        rangeobj = range(7, -1, -1)

    return render(request, 'kate/match.html', { 'match': match, 'board': fmtboard, 'switch': switch, 'movesrc': movesrc, 'movedst': movedst, 'moves': moves, 'comments': comments, 'msg': fmtmsg, 'range': rangeobj } )
Exemple #16
0
def is_move_valid(match, srcx, srcy, dstx, dsty, prom_piece):
    # print(" counts " + str(match.wKg_first_movecnt) + " " + str(match.wRk_h1_first_movecnt)  + " " + str(match.wRk_a1_first_movecnt))
    # print(" counts " + str(match.bKg_first_movecnt) + " " + str(match.bRk_h8_first_movecnt)  + " " + str(match.bRk_a8_first_movecnt))
    # print("-------------------------------------------")
    if not is_move_inbounds(srcx, srcy, dstx, dsty):
        return False, ERROR_CODES["out-of-bounds"]

    piece = match.readfield(srcx, srcy)

    if match.next_color() != Match.color_of_piece(piece):
        return False, ERROR_CODES["wrong-color"]

    if piece != Match.PIECES["wKg"] and piece != Match.PIECES["bKg"]:
        if is_king_after_move_attacked(match, srcx, srcy, dstx, dsty):
            return False, ERROR_CODES["king-error"]

    if piece == Match.PIECES["wPw"] or piece == Match.PIECES["bPw"]:
        if not pawn.is_move_ok(match, srcx, srcy, dstx, dsty, piece, prom_piece):
            return False, ERROR_CODES["pawn-error"]
        else:
            return True, ERROR_CODES["none"]
    elif piece == Match.PIECES["wRk"] or piece == Match.PIECES["bRk"]:
        if not rook.is_move_ok(match, srcx, srcy, dstx, dsty, piece):
            return False, ERROR_CODES["rook-error"]
        else:
            return True, ERROR_CODES["none"]
    elif piece == Match.PIECES["wKn"] or piece == Match.PIECES["bKn"]:
        if not knight.is_move_ok(match, srcx, srcy, dstx, dsty, piece):
            return False, ERROR_CODES["knight-error"]
        else:
            return True, ERROR_CODES["none"]
    elif piece == Match.PIECES["wBp"] or piece == Match.PIECES["bBp"]:
        if not bishop.is_move_ok(match, srcx, srcy, dstx, dsty, piece):
            return False, ERROR_CODES["bishop-error"]
        else:
            return True, ERROR_CODES["none"]
    elif piece == Match.PIECES["wQu"] or piece == Match.PIECES["bQu"]:
        if not queen.is_move_ok(match, srcx, srcy, dstx, dsty, piece):
            return False, ERROR_CODES["queen-error"]
        else:
            return True, ERROR_CODES["none"]
    elif piece == Match.PIECES["wKg"] or piece == Match.PIECES["bKg"]:
        if not king.is_move_ok(match, srcx, srcy, dstx, dsty, piece):
            return False, ERROR_CODES["king-error"]
        else:
            return True, ERROR_CODES["none"]
    else:
        return False, ERROR_CODES["general-error"]
Exemple #17
0
def is_move_ok(match, srcx, srcy, dstx, dsty, piece, prom_piece):
    DIRS = rules.DIRS
    direction = pw_dir(srcx, srcy, dstx, dsty, piece)
    if(direction == DIRS['undefined']):
        return False

    pin_dir = rules.pin_dir(match, srcx, srcy)

    if(direction == DIRS['north'] or direction == DIRS['south'] or direction == DIRS['2north'] 
        or direction == DIRS['2south']):
        if(pin_dir != DIRS['north'] and pin_dir != DIRS['south'] and pin_dir != DIRS['undefined']):
            return False
    elif(direction == DIRS['north-west'] or direction == DIRS['south-east']):
        if(pin_dir != DIRS['north-west'] and pin_dir != DIRS['south-east'] and pin_dir != DIRS['undefined']):
            return False
    elif(direction == DIRS['north-east'] or direction == DIRS['south-west']):
        if(pin_dir != DIRS['north-east'] and pin_dir != DIRS['south-west'] and pin_dir != DIRS['undefined']):
            return False

    dstpiece = match.readfield(dstx, dsty)
    dstcolor = Match.color_of_piece(dstpiece)
    if(direction == DIRS['north'] or direction == DIRS['south']):
        if(dstpiece != Match.PIECES['blk']):
            return False
    elif(direction == DIRS['2north']):
        midpiece = match.readfield(dstx, srcy + 1)
        if(midpiece != Match.PIECES['blk'] or dstpiece != Match.PIECES['blk']):
            return False
    elif(direction == DIRS['2south']):
        midpiece = match.readfield(dstx, srcy - 1)
        if(midpiece != Match.PIECES['blk'] or dstpiece != Match.PIECES['blk']):
            return False
    if(direction == DIRS['north-west'] or direction == DIRS['north-east']):
        if(dstcolor != Match.COLORS['black']):
            return is_white_ep_move_ok(match, srcx, srcy, dstx, dsty)
    elif(direction == DIRS['south-east'] or direction == DIRS['south-west']):
        if(dstcolor != Match.COLORS['white']):
            return is_black_ep_move_ok(match, srcx, srcy, dstx, dsty)

    if(piece == Match.PIECES['wPw'] and dsty == 7 and not (prom_piece == Match.PIECES['wQu'] or
       prom_piece == Match.PIECES['wRk'] or prom_piece == Match.PIECES['wBp'] or prom_piece == Match.PIECES['wKn'])):
        return False
    elif(piece == Match.PIECES['bPw'] and dsty == 0 and not (prom_piece == Match.PIECES['bQu'] or 
         prom_piece == Match.PIECES['bRk'] or prom_piece == Match.PIECES['bBp'] or prom_piece == Match.PIECES['bKn'])):
        return False

    return True
Exemple #18
0
def is_move_available(match):
    color = match.next_color()
    for y1 in range(8):
        for x1 in range(8):
            piece = match.readfield(x1, y1)
            if color == Match.color_of_piece(piece):
                if color == Match.COLORS["white"]:
                    prom_piece = Match.PIECES["wQu"]
                else:
                    prom_piece = Match.PIECES["bQu"]

                for y2 in range(8):
                    for x2 in range(8):
                        flag = is_move_valid(match, x1, y1, x2, y2, prom_piece)[0]
                        if flag:
                            return True
    return False
def evaluate_piece_moves(match, srcx, srcy):
    color = match.next_color()
    piece = match.readfield(srcx, srcy)
    movecnt = 0

    if(Match.color_of_piece(piece) != color):
        return movecnt
        
    if(piece == Match.PIECES['wQu'] or piece == Match.PIECES['bQu']):
        dirs = [ [0, 1], [0, -1], [1, 0], [-1, 0], [1, 1], [-1, -1], [-1, 1], [1, -1] ]
        dircnt = 8
        stepcnt = 7
        value = 2
    elif(piece == Match.PIECES['wRk'] or piece == Match.PIECES['bRk']):
        dirs = [ [0, 1], [0, -1], [1, 0], [-1, 0] ]
        dircnt = 4
        stepcnt = 7
        value = 4
    elif(piece == Match.PIECES['wBp'] or piece == Match.PIECES['bBp']):
        dirs = [ [1, 1], [-1, -1], [-1, 1], [1, -1] ]
        dircnt = 4
        stepcnt = 7
        value = 6
    elif(piece == Match.PIECES['wKn'] or piece == Match.PIECES['bKn']):
        dirs =  [ [1, 2], [2, 1], [2, -1], [1, -2], [-1, -2], [-2, -1], [-2, 1], [-1, 2] ]
        dircnt = 8
        stepcnt = 1
        value = 6
    else:
        return movecnt

    for j in range(dircnt):
        stepx = dirs[j][0]
        stepy = dirs[j][1]
        dstx = srcx
        dsty = srcy
        for i in range(stepcnt):
            dstx += stepx
            dsty += stepy
            flag,errcode = rules.is_move_valid(match, srcx, srcy, dstx, dsty, Match.PIECES['blk'])
            if(flag):
                movecnt += value
            elif(errcode == rules.ERROR_CODES['out-of-bounds']):
                break

    return (movecnt // 10)
Exemple #20
0
def is_king_after_move_attacked(match, srcx, srcy, dstx, dsty):
    piece = match.readfield(srcx, srcy)
    match.writefield(srcx, srcy, Match.PIECES["blk"])
    dstpiece = match.readfield(dstx, dsty)
    match.writefield(dstx, dsty, piece)

    color = Match.color_of_piece(piece)

    if color == Match.COLORS["white"]:
        flag = attacked(match, match.wKg_x, match.wKg_y, Match.COLORS["black"])
    else:
        flag = attacked(match, match.bKg_x, match.bKg_y, Match.COLORS["white"])

    match.writefield(dstx, dsty, dstpiece)
    match.writefield(srcx, srcy, piece)

    return flag
Exemple #21
0
def is_move_ok(match, srcx, srcy, dstx, dsty, piece):
    DIRS = rules.DIRS
    direction = kn_dir(srcx, srcy, dstx, dsty)
    if(direction == DIRS['undefined']):
        return False

    color = Match.color_of_piece(piece)

    pin_dir = rules.pin_dir(match, srcx, srcy)

    if(pin_dir != DIRS['undefined']):
        return False

    field = match.readfield(dstx, dsty)
    if(match.color_of_piece(field) == color):
        return False

    return True
Exemple #22
0
def prnt_move(msg, move):
    print(msg + 
        Match.index_to_koord(move.srcx, move.srcy) + " " +
        Match.index_to_koord(move.dstx, move.dsty) + " " +
        helper.reverse_lookup(Match.PIECES, move.prom_piece), end="")
Exemple #23
0
def calc_min(match, maxdepth, depth, alpha, beta):
    generator = Generator()
    generator.match = match
    gmove = None
    color = match.next_color()
    newscore = None
    minscore = 200000
    oldscore = 0
    count = 0

    while(generator.active):
        flag, newgmove = generator.generate_move()

        if(flag):
            count += 1
            oldscore = match.score
            move = match.do_move(newgmove.srcx, newgmove.srcy, newgmove.dstx, newgmove.dsty, newgmove.prom_piece)
            match.move_list.append(move)
            if(depth == 1):
                msg = "\nmatch.id:" + str(match.id) + " calculate "
                prnt_move(msg, newgmove)
                if(gmove):
                    prnt_move(" CANDIDATE ", gmove)
                    print(" score: " + str(newscore))
                    thread = Match.get_active_thread(match)
                    if(thread and newscore):
                        thread.populate_candiate(gmove)

            if(depth <= maxdepth):
                newscore = calc_max(match, maxdepth, depth + 1, alpha, minscore)[0]
            elif(depth <= maxdepth + 2):
                if(match.next_color() == Match.COLORS['white']):
                    wkg_attacked = rules.attacked(match, match.wKg_x, match.wKg_y, Match.COLORS['black'])
                    white_promotion = match.readfield(newgmove.dstx, newgmove.dsty) == Match.PIECES['wPw'] and newgmove.dsty >= 6
                    if(oldscore != match.score or wkg_attacked or white_promotion ):
                        newscore = calc_max(match, maxdepth, depth + 1, alpha, minscore)[0]
                    else:
                        newscore = match.score + calc_helper.evaluate_position(match)
                else:
                    bkg_attacked = rules.attacked(match, match.bKg_x, match.bKg_y, Match.COLORS['white'])
                    black_promotion = match.readfield(newgmove.dstx, newgmove.dsty) == Match.PIECES['bPw'] and newgmove.dsty <= 1
                    if(oldscore != match.score or bkg_attacked or black_promotion):
                        newscore = calc_max(match, maxdepth, depth + 1, alpha, minscore)[0]
                    else:
                        newscore = match.score + calc_helper.evaluate_position(match)
            elif(depth <= maxdepth + 4 and oldscore != match.score):
                newscore = calc_max(match, maxdepth, depth + 1, alpha, minscore)[0]
            else:
                newscore = match.score + calc_helper.evaluate_position(match)

            newscore, gmove = rate(color, gmove, newgmove, minscore, newscore)
            match.undo_move(True)
            if(newscore < minscore):
                minscore = newscore
                if(minscore <= alpha):
                    break
        else:
            if(count == 0):
                status = rules.game_status(match)
                if(status == Match.STATUS['winner_black']):
                    newscore = Match.SCORES[Match.PIECES['wKg']]
                elif(status == Match.STATUS['winner_white']):
                    newscore = Match.SCORES[Match.PIECES['bKg']]
                elif(status == Match.STATUS['draw']):
                    newscore = Match.SCORES[Match.PIECES['blk']]
                else:
                    newscore = match.score

                if(depth == 1):
                    msg = "\nmatch.id:" + str(match.id) + " CANDIDATE "
                    prnt_move(msg, gmove)
                    print(" score: " + str(newscore))
                    thread = Match.get_active_thread(match)
                    if(thread):
                        thread.populate_candiate(gmove)
                return newscore, gmove

    return minscore, gmove
Exemple #24
0
    def generate_move(self):
        gmove = GenMove()
        color = self.match.next_color()

        while(self.active):
            if(self.steps == None):
                piece = self.match.readfield(self.board_x, self.board_y)
                if(piece == Match.PIECES['blk'] or color != Match.color_of_piece(piece)):
                    if(self.rotate_field()):
                        continue
                    else:
                        return False, gmove
                else:
                    if(piece == Match.PIECES['wPw']):
                        if(self.board_y < 6):
                            self.steps = WPW_STEPS
                            self.dir_idx = 0
                            self.max_dir = 4
                            self.step_idx = 0
                            self.max_step = 1
                        else:
                            self.steps = WPROM_STEPS
                            self.dir_idx = 0
                            self.max_dir = 3
                            self.step_idx = 0
                            self.max_step = 4
                    elif(piece == Match.PIECES['bPw']):
                        if(self.board_y > 1):
                            self.steps = BPW_STEPS
                            self.dir_idx = 0
                            self.max_dir = 4
                            self.step_idx = 0
                            self.max_step = 1
                        else:
                            self.steps = BPROM_STEPS
                            self.dir_idx = 0
                            self.max_dir = 3
                            self.step_idx = 0
                            self.max_step = 4
                    elif(piece == Match.PIECES['wRk'] or piece == Match.PIECES['bRk']):
                        self.steps = RK_STEPS
                        self.dir_idx = 0
                        self.max_dir = 4
                        self.step_idx = 0
                        self.max_step = 7
                    elif(piece == Match.PIECES['wBp'] or piece == Match.PIECES['bBp']):
                        self.steps = BP_STEPS
                        self.dir_idx = 0
                        self.max_dir = 4
                        self.step_idx = 0
                        self.max_step = 7
                    elif(piece == Match.PIECES['wKn'] or piece == Match.PIECES['bKn']):
                        self.steps = KN_STEPS
                        self.dir_idx = 0
                        self.max_dir = 8
                        self.step_idx = 0
                        self.max_step = 1
                    elif(piece == Match.PIECES['wQu'] or piece == Match.PIECES['bQu']):
                        self.steps = QU_STEPS
                        self.dir_idx = 0
                        self.max_dir = 8
                        self.step_idx = 0
                        self.max_step = 7
                    else:
                        self.steps = KG_STEPS
                        self.dir_idx = 0
                        self.max_dir = 10
                        self.step_idx = 0
                        self.max_step = 1
            stepx, stepy, prom_piece = self.read_steps()
            dstx = self.board_x + stepx
            dsty = self.board_y + stepy
            flag, errmsg = rules.is_move_valid(self.match, self.board_x, self.board_y, dstx, dsty, prom_piece)
            if(flag):
                gmove = GenMove(self.board_x, self.board_y, dstx, dsty, prom_piece)
                self.rotate()
                return True, gmove
            else:
                if(errmsg == rules.ERROR_CODES['king-error']):
                    self.rotate()
                else:
                    if(self.rotate_dir() == False):
                        return False, gmove
        return False, gmove
Exemple #25
0
def create(request):
    context = RequestContext(request)
    if(request.method == 'POST'):
        match = Match()

        match.white_player = request.POST['white_player']
        if(request.POST.get('white_player_human')):
            match.white_player_human = True
        else:
            match.white_player_human = False

        match.black_player = request.POST['black_player']
        if(request.POST.get('black_player_human')):
            match.black_player_human = True
        else:
            match.black_player_human = False

        levellist = request.POST.getlist('level')
        match.level = Match.LEVEL[levellist[0]]

        if(len(match.white_player) > 0 and len(match.black_player) > 0):
            match.setboardbase()
            match.save()
            calc_move_for_immanuel(match)
            return HttpResponseRedirect(reverse('kate:match', args=(match.id,)))
    return render(request, 'kate/new.html', { 'white_player': match.white_player, 'white_player_human': match.white_player_human, 'black_player': match.black_player, 'black_player_human': match.black_player_human } )