Skip to content

Instantly share code, notes, and snippets.

@cyrusn
Last active December 22, 2020 03:51
Show Gist options
  • Save cyrusn/48797591a0e1a01c0fc1a523c5396d97 to your computer and use it in GitHub Desktop.
Save cyrusn/48797591a0e1a01c0fc1a523c5396d97 to your computer and use it in GitHub Desktop.
Game of 15
from os import system
board = [[15, 14, 13, 12], [11, 10, 9, 8], [7, 6, 5, 4], [3, 1, 2, 0]]
answer = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 0]]
r, c = 3, 3
step = 0
def print_row(row):
for cell in row:
if cell != 0:
print(f"{cell:3}", end=" ")
else:
print(" ", end=" ")
print()
def print_board(board):
system('clear')
print(f'step: {step} ')
for row in board:
print_row(row)
print()
def move_down(board):
global r, c, step
if r > 0:
board[r][c] = board[r - 1][c]
board[r - 1][c] = 0
r = r - 1
step = step + 1
def move_up(board):
global r, c, step
if r < 3:
board[r][c] = board[r + 1][c]
board[r + 1][c] = 0
r = r + 1
step = step + 1
def move_right(board):
global r, c, step
if c > 0:
board[r][c] = board[r][c - 1]
board[r][c - 1] = 0
c = c - 1
step = step + 1
def move_left(board):
global r, c, step
if c < 3:
board[r][c] = board[r][c + 1]
board[r][c + 1] = 0
c = c + 1
step = step + 1
print_board(board)
while True:
command = input()
if command == 'd':
move_right(board)
elif command == 'a':
move_left(board)
elif command == 'w':
move_up(board)
elif command == 's':
move_down(board)
else:
continue
print_board(board)
if board == answer:
print('You Win, congratulations')
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment