Skip to content

Instantly share code, notes, and snippets.

@SpaceVoyager
Created November 26, 2015 23:38
Show Gist options
  • Save SpaceVoyager/8bddfe07201ac6acdc7e to your computer and use it in GitHub Desktop.
Save SpaceVoyager/8bddfe07201ac6acdc7e to your computer and use it in GitHub Desktop.
eight_puzzle_v0.5.py
import ui
import speech
border_color = (1.00, 0.50, 0.00)
def isAdjacent(row1, col1, row2, col2):
if abs(row1-row2) + abs(col1-col2) == 1:
return True
else:
return False
def move_piece(button, x, y):
def animation():
button.x = x
button.y = y
ui.animate(animation, duration=0.5)
def button_pressed(sender):
number = sender.title
index = pieces.index(number)
(row, col) = index2loc(index)
empty_space_index = pieces.index('')
(empty_space_row, empty_space_col) = index2loc(empty_space_index)
if isAdjacent(row, col, empty_space_row, empty_space_col):
move_piece(sender, empty_space_col*sender.width, empty_space_row*sender.width)
pieces[index] = ''
pieces[empty_space_index] = number
if pieces == win_state:
speech.say('you win', 'en-US', 0.3)
pieces = ['5', '1', '6', '3', '4', '8', '7', '', '2']
win_state = ['1', '2', '3', '4', '5', '6', '7', '8', '']
v = ui.View(background_color=(0.50, 0.50, 0.50))
board = ui.View()
v.add_subview(board)
v.present('full_screen')
steps_label = ui.Label()
steps_label.frame = (30, 30, 250, 100)
steps_label.background_color = (1.00, 0.00, 0.50)
steps_label.font = ('Futura-CondensedExtraBold', 50)
steps_label.text = 'Steps: 0'
v.add_subview(steps_label)
board.frame = (v.width-v.height, 0, v.height, v.height)
board.border_width = 3
board.border_color = border_color
board.background_color = (1,1,1)
# convert index of button to row number and column number
def index2loc(index):
row = index / 3
column = index % 3
return (row, column)
for i in range(9):
button_text = pieces[i]
if button_text != '':
button = ui.Button(title=button_text)
button.background_color = (1,1,1)
button.font = ('Futura-CondensedExtraBold', 200)
button.width = v.height/3
button.height = button.width
button.border_color = border_color
button.border_width = 2
(r, c) = index2loc(i)
button.x = button.width*c
button.y = button.height*r
button.action = button_pressed
board.add_subview(button)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment