1 #!/usr/bin/python 2 # jumpsaround - jumper game 3 # (c) 2011 Alexander Kulbartsch 4 5 SIZEX = 6 6 SIZEY = 5 7 8 jump = ((-1,-2), (1,-2), (-2,-1), (2,-1), (-2,1), (2,1), (-1,2), (1,2)) 9 10 # init board 11 board = [] 12 for i in range(SIZEX): 13 col = [] 14 for i in range(SIZEY): 15 col.append(0) 16 board.append(col) 17 18 solutions = 0 19 roundtrips = 0 20 21 def jumpto(x, y, iter): 22 global solutions 23 global roundtrips 24 global board 25 26 board[x][y] = iter 27 28 # finished? 29 if iter >= SIZEX * SIZEY: 30 # check for roundtrips 31 round = 0 32 for np in jump: 33 nx = x + np[0] 34 ny = y + np[1] 35 # check if position is on the board 36 if nx < 0 or nx > (SIZEX-1) or ny < 0 or ny > (SIZEY-1): 37 continue 38 # detect roundtrip 39 if board[nx][ny] == 1: 40 round = True 41 roundtrips += 1 42 break 43 solutions += 1 44 printboard(round) 45 board[x][y] = 0 46 return 47 48 # try next jump 49 for np in jump: 50 nx = x + np[0] 51 ny = y + np[1] 52 # check if position is on the board 53 if nx < 0 or nx > (SIZEX-1) or ny < 0 or ny > (SIZEY-1): 54 continue 55 # check if new field position is still empty 56 if board[nx][ny] != 0: 57 continue 58 jumpto(nx, ny, iter + 1) 59 board[x][y] = 0 60 61 62 def printboard(round): 63 # The syntax in the following line is not accepted by PyPy 64 # print(f"===== Solution #{solutions} - Roundtripps:{roundtrips} ======") 65 print('===== Solution #{} - Roundtripps:{} ======'.format(solutions, roundtrips)) 66 if round: 67 print("*** Roundtrip ***") 68 for i in range(SIZEY): 69 for j in range(SIZEX): 70 print(f"{board[j][i]:2d}", end=":") 71 # print("{}".format(board[j][i]), end=":") 72 print("") 73 print() 74 75 print("Hello, Jumper!") 76 77 jumpto(0, 0, 1) 78 79 print("I am done.") 80 81 # EOF