Skip to content

Instantly share code, notes, and snippets.

@t-harison
Last active April 9, 2020 19:01
Show Gist options
  • Select an option

  • Save t-harison/e87c6d7c0905dd02ff49d79f47c99795 to your computer and use it in GitHub Desktop.

Select an option

Save t-harison/e87c6d7c0905dd02ff49d79f47c99795 to your computer and use it in GitHub Desktop.
# !/usr/bin/python
# coding=utf-8
def init_board(n):
# Insertion des boules blanches
game = list(map(lambda x: "☺", range(n)))
# Insertion de l'espace
game += " "
# Insertion des boules noires
game += list(map(lambda x: "☻", range(n)))
return game
def draw_board(game):
print("| " + " | ".join(list(map(lambda x: str(x + 1), range(len(game))))) + " |")
print("| " + " | ".join(game) + " |")
def can_move_left(game, step, position):
return position < len(game) \
and position - step >= 0 \
and game[position] == "☻" \
and game[position - step] == " "
def can_move_right(game, step, position):
return position < len(game) \
and position + step < len(game) \
and game[position] == "☺" \
and game[position + step] == " "
def is_valid(game, position):
if can_move_right(game, 1, position):
return swap(game, position, position + 1), True
if can_move_right(game, 2, position):
return swap(game, position, position + 2), True
if can_move_left(game, 1, position):
return swap(game, position, position - 1), True
if can_move_left(game, 2, position):
return swap(game, position, position - 2), True
return game, False
def swap(array, i, j):
print("Moving " + str(array[i]) + " at " + str(i + 1) + " to " + str(j + 1))
temp = array[i]
array[i] = array[j]
array[j] = temp
return array
def is_over(game):
can_move = False
for i in range(len(game)):
can_move = can_move or can_move_left(game, 1, i)
can_move = can_move or can_move_left(game, 2, i)
can_move = can_move or can_move_right(game, 1, i)
can_move = can_move or can_move_right(game, 2, i)
return not can_move
size = int(input("Board size: "))
board = init_board(size)
solved = board[::-1]
while True:
draw_board(board)
pos = int(input("Deck to move: ")) - 1
board, valid = is_valid(board, pos)
if solved == board:
draw_board(board)
print("You win 🎉")
break
if is_over(board):
draw_board(board)
print("You lose 🥺")
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment