Created
November 28, 2015 19:46
-
-
Save ssophwang/d7f2cb4ce82449434fdf to your computer and use it in GitHub Desktop.
eight_puzzle.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ui | |
import speech | |
border_color = ('black') | |
moves = 0 | |
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.2) | |
def button_pressed(sender): | |
global moves | |
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) | |
moves += 1 | |
pieces[index] = '' | |
pieces[empty_space_index] = number | |
steps_label.text = 'Steps: ' + str(moves) | |
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=('abcdef')) | |
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 = (0.40, 0.80, 1.00) | |
steps_label.font = ('IowanOldStyle-BoldItalic', 46) | |
steps_label.text = 'Steps: ' + str(moves) | |
v.add_subview(steps_label) | |
board.frame = ((v.width-v.height), 0, v.height, v.height) | |
board.border_width = 2 | |
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 = 1 | |
(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