I have a code designed to show the different spaces a knight can move to in a standard chess game. It needs to be a function created that outputs the possible spaces in tuples. I can't figure out how to make the output in tuples and I would appreciate it if anybody knew how to make this code more efficient.

def knightmove(x, y): and have the output turned back into letter, number form rather than the current number, number form that it is in.
    endloop=0
    while endloop==0:
        xcoord=x
        ycoord=y
        xcoord=xcoord.lower()
        if ycoord>8:
            print "The 'Y' co-ordinate you entered is invalid"
            endloop=1
        if xcoord=='a':
            xcoord=1
        elif xcoord=='b':
            xcoord=2
        elif xcoord=='c':
            xcoord=3
        elif xcoord=='d':
            xcoord=4
        elif xcoord=='e':
            xcoord=5
        elif xcoord=='f':
            xcoord=6
        elif xcoord=='g':
            xcoord=7
        elif xcoord=='h':
            xcoord=8
        else:
            print "The 'X' co-ordinate you entered is invalid"
            endloop=1        
        upleft_xcoord=xcoord-1
        upleft_ycoord=ycoord+2
        upright_xcoord=xcoord+1
        upright_ycoord=ycoord+2
        rightup_xcoord=xcoord+2
        rightup_ycoord=ycoord+1
        rightdown_xcoord=xcoord+2
        rightdown_ycoord=ycoord-1
        downright_xcoord=xcoord+1
        downright_ycoord=ycoord-2
        downleft_xcoord=xcoord-1
        downleft_ycoord=ycoord-2
        leftup_xcoord=xcoord-2
        leftup_ycoord=ycoord+1
        leftdown_xcoord=xcoord-2
        leftdown_ycoord=ycoord-1
        print "The possible moves are: "
        if upleft_xcoord>0 and upleft_ycoord<9:
            print "Up to the left:", upleft_xcoord,",",upleft_ycoord
        if upright_xcoord<9 and upright_ycoord<9:
            print "Up to the right:", upright_xcoord,',',upright_ycoord
        if rightup_xcoord<9 and rightup_ycoord<9:
            print "Right then up:", rightup_xcoord,',',rightup_ycoord
        if rightdown_xcoord<9 and rightdown_ycoord>0:
            print "right then down:", rightdown_xcoord,',',rightdown_ycoord
        if downright_xcoord<9 and downright_ycoord>0:
            print "Down to the right:", downright_xcoord,',',downright_ycoord
        if downleft_xcoord>0 and downleft_ycoord>0:
            print "Down to the left:", downleft_xcoord,',',downleft_ycoord
        if leftup_xcoord>0 and leftup_ycoord<9:
            print "Left then up:", leftup_xcoord,',',leftup_ycoord
        if leftdown_xcoord>0 and leftdown_ycoord>0:
            print "Left then down:", leftdown_xcoord,',',leftdown_ycoord
        endloop=1

x=raw_input("what is the X co-ordinate? ")
y=input("what is the Y co-ordinate? ")
knightmove(x, y)

Thanks,


Jaro

Edited 5 Years Ago by jarograv: Additional details

I am not going to give you ready answer, but if you are able to learn this my different style code for information:

from __future__ import print_function
first_move, second_move = 2,1
place = (3, 7)
legal_moves = tuple((place[0] + adiff, place[1] + bdiff)
                    for adiff, bdiff in
                    ((first_move, second_move), (second_move, first_move),
                     (-first_move, second_move), (second_move, -first_move),
                     (first_move, -second_move), (-second_move, first_move),
                     (-first_move,-second_move), (-second_move, -first_move))
                    if (0 < (adiff + place[0]) <= 8 and
                        0 < (bdiff + place[1]) <= 8))
print('Legal moves from %s are:\n%s' % (place, legal_moves))
print(20 * '_')
print('|   a b c d e f g h |')
for j in range(1,9):
    print('|%2i' % j, end=' ')
    for i in range(1,9):
        if (i,j) == place:
            print('R', end=' ')
        elif (i,j) in legal_moves:
            print('*', end=' ')
        else:
            print(' ', end=' ')
    print('|')
print(20 * '_')

Here simple function that return tuple of sum and difference of parameters:

def sum_diff(a,b):
    return (a+b, a-b)

print(sum_diff(3,4))

You can use a tuple to replace several parts of the code in fact, but first this:

#ycoord=y     ## replace with the following
ycoord = int(y)

#if ycoord>8:     ## replace with the following
if 1 <= ycoord <= 8:
    ## code goes here
    xcoord=xcoord.lower()
    x_choices = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
    if xcoord in x_choices:
        ## code goes here
        xcoord = x_choices.index(xcoord) +1  ## replaces all of the if() statements
    else:
        print x, 'is not a-->h'
else:
    print "The 'Y' co-ordinate you entered is invalid" 
#
#-----------------------------------------------------------
# replace this (only part of the block of code)
"""
upleft_xcoord=xcoord-1
upleft_ycoord=ycoord+2
upright_xcoord=xcoord+1
upright_ycoord=ycoord+2
rightup_xcoord=xcoord+2
rightup_ycoord=ycoord+1
"""
#
#   with a tuple of sub-tuples=(move_x, move_y, 'literal description')
#
moves_tuple = ( (-1, 2, 'Up to the left'),
                (1, 2, 'Up to the right'),
                (2, 1, 'Right then up') )

#
# then loop through the tuple instead of using all of the if() statements
xcoord = 1     ## for testing
ycoord = 5
valid_moves = []
for move in moves_tuple:
    new_x = xcoord + move[0]
    new_y = ycoord + move[1]
    if (1 <= new_x <= 8) and (1 <= new_y <= 8):
        print move[2], new_x, new_y
        valid_moves.append((new_x, new_y, move[2])) ## list of all moves from this position

print valid_moves

Edited 5 Years Ago by woooee: n/a

This sounds like a contest question I did a couple of months ago for practice. (CCC 2010 Problem J5)

Maybe you could take a look at my source code and see if you can salvage anything from there.

class KnightPosition:
    def __init__(self, location, prevLocation=False):
        self.x = location[0]
        self.y = location[1]
        self.j = []
        self.j.append((self.x+1, self.y+2))
        self.j.append((self.x+2, self.y+1))
        self.j.append((self.x+2, self.y-1))
        self.j.append((self.x+1, self.y-2))
        self.j.append((self.x-1, self.y-2))
        self.j.append((self.x-2, self.y-1))
        self.j.append((self.x-2, self.y+1))
        self.j.append((self.x-1, self.y+2))
        i = 0
        while i < len(self.j):
            jump = self.j[i]
            if jump[0] > 8 or jump[0] < 1 or jump[1] > 8 or jump[1] < 1:
                self.j.pop(i)
                continue
            if prevLocation and jump == prevLocation:
                self.j.pop(i)
                continue
            i += 1
            
def findShortestRoute(init, end):
    if init == end:
        return 0
    
    pos = KnightPosition(init)
    steps = 0
    notFound = True
    levels = []
    bufferlocation = [pos]      
    while notFound:
        if len(levels) == 0:
            levels = []
            steps += 1
            for position in bufferlocation:
                for location in position.j:
                    levels.append(KnightPosition(location, (position.x, position.y)))
            
            bufferlocation = []
        
        for location in levels:
            if (location.x, location.y) == end:
                notFound = False
                break
            
        if not notFound:
            break
            
        bufferlocation.append(levels.pop())
    return steps

if __name__ == "__main__":
    start = raw_input().split(" ")
    start = (int(start[0]), int(start[1]))
    end = raw_input().split()
    end = (int(end[0]), int(end[1]))
    print findShortestRoute(start, end)
This article has been dead for over six months. Start a new discussion instead.