hi , I found this code on the internet , I changed and added some lines to it to make it the way I like . I am very weak in using functions and even worse in using classes , I appreciate it if some one can change this code into functions or classes .

``````'''
this is  a slide puzzle game .
the square marked 'xx' is the empty space
the board is randomly filled so whenever you start the game you
will get a fresh board .

'''

import string
import random
piece=()
move = 0
empty_space=()
list1 = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
#to get shuffled list

random.shuffle(list1)

print('\n'*2)

#to make list of lists
matrix=[]
while list1 !=[]:
matrix.append(list1[:4])
list1 = list1[4:]

# to find the empty space
# we can also delete this section and just add a one line
# empty_space = (x,y) before the print('|xx ..  ) statement

for x in range (len(matrix)):
for y in range(len(matrix[x])):
if matrix[x][y] == 0:
empty_space = (x,y)

print()

#to print the list in two digit matrix
while True:
print('\n+----+----+----+---|')

for x in range (len(matrix)):
for y in range(len(matrix[x])):
if matrix[x][y] == 0:

print('|XX' , end='  ')
else:
print('|' + '{:02d}' .format(matrix[x][y]), end='  ')

print('\n+----+----+----+---|')
num = input('\nplease type the number of the piece to move : ( q ) to quit  ')
if num in ['q','Q']:
break
num = int(num)

for i in range(len(matrix)):
for j in range(len(matrix[i])):
if num == matrix[i][j]:
piece = (i,j)

if num > 15:
print('illegal move  ')
else:

if(empty_space==(piece-1,piece))\
or(empty_space==(piece+1,piece))\
or(empty_space==(piece,piece-1))\
or(empty_space==(piece,piece+1)):
matrix[empty_space][empty_space]=num
matrix[piece][piece]=0
empty_space=(piece,piece)
move = move +1
print()
print('you have made ',move , 'moves so far ')
print(2*'\n')
else:
print('illegal move , try again ')

print('game over  ')
``````

That's a huge improvement in readability.

To make some futher i improvement's.
All code is now in functions,
explanation is moved into function so it work as doc-string(then it's possible to use `help()` on functions).

I have removed all `global` statement which it's not good at all.
Functions should be isolated code,that takes argument's …

## All 5 Replies

I made slight changes to the above code and used functions too . any suggestions for improvement is appriciated .

``````# this is slide puzzle game using functions
# the board is made of list of lists
# a fresh board is made every time the game starts
# the original code was taken from David Schmidt lectures
# but I made considerable chnanges to it

import string
import random
import sys
game_on = True
move = 0

list1 = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

#------------------ to get shuffled list -----------

random.shuffle(list1)

print('\n'*2)

#------------------ to make list of lists -----------
matrix=[]
while list1 !=[]:
matrix.append(list1[:4])
list1 = list1[4:]

#------------------- function to find where the zero is ------

def zero(board):
global empty_space
for x in range (len(board)):
for y in range(len(board[x])):
if board[x][y] == 0:
empty_space = (x,y)

return empty_space

#----------------------- function to draw the board -----------

def draw_board(board):
print('\n\t+-------+-------+-------+-------|')

for x in range (len(board)):
for y in range(len(board[x])):
if board[x][y] == 0:

print('\t|  XX' , end='')
else:
print('\t|  ' + '{:02d}' .format(board[x][y]), end=' ')

print('\n\t+-------+-------+-------+-------|')

# ------------------------ function to ask for the number to move ----------

global num , piece
num = input('\nplease type the number of the piece to move : ( q ) to quit  ')
if num in ['q','Q']:
print('\n\ngame over  ')
sys.exit()
num = int(num)
piece=()
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if num == matrix[i][j]:
piece = (i,j)
return piece , num

#---------------------------------------------- game starts here -------------

zero(matrix)

while game_on:
draw_board(matrix)

if num > 15:
print('illegal move , try again  ')
else:

if(empty_space==(piece-1,piece))\
or(empty_space==(piece+1,piece))\
or(empty_space==(piece,piece-1))\
or(empty_space==(piece,piece+1)):
matrix[empty_space][empty_space]=num
matrix[piece][piece]=0
empty_space=(piece,piece)
move = move +1
print()
print('you have made ',move , 'moves so far ')
print(2*'\n')
else:
print('illegal move , try again ')
``````

That's a huge improvement in readability.

thanks @JamesCherrill

To make some futher i improvement's.
All code is now in functions,
explanation is moved into function so it work as doc-string(then it's possible to use `help()` on functions).

I have removed all `global` statement which it's not good at all.
Functions should be isolated code,that takes argument's and return result out.
This way it's easy to test a singel function,
and you don't have to worry that something magically appear in it from global space.

`range(len(something))` is used to much in Python,better to use `enumerate()`.

``````import random, sys

def board():
'''Make matrix board of random numbers'''
list1 = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
random.shuffle(list1)
matrix = []
while list1 !=[]:
matrix.append(list1[:4])
list1 = list1[4:]
return matrix

def zero(board):
'''function to find where the zero is'''
empty_space = None
for x,item in enumerate(board):
for y,item in enumerate(board):
if board[x][y] == 0:
empty_space = (x,y)
return empty_space

def draw_board(board):
'''function to draw the board'''
print('\n\t+-------+-------+-------+-------|')
for x,item in enumerate(board):
for y,item in enumerate(board):
if board[x][y] == 0:
print('\t|  XX' , end='')
else:
print('\t|  ' + '{:02d}' .format(board[x][y]), end=' ')
print('\n\t+-------+-------+-------+-------|')

''' function to ask for the number to move'''
num = input('\nplease type the number of the piece to move : ( q ) to quit  ')
if num in ['q','Q']:
print('\n\ngame over  ')
sys.exit()
num = int(num)
piece = ()
for i,item in enumerate(board):
for j,item in enumerate(board):
if num == board[i][j]:
piece = (i,j)
return piece , num

def game():
'''Run the game logic'''
matrix = board()
empty_space = zero(matrix)
game_on = True
move = 0
while game_on:
draw_board(matrix)
if num > 15:
print('illegal move , try again  ')
else:
if(empty_space==(piece-1,piece))\
or(empty_space==(piece+1,piece))\
or(empty_space==(piece,piece-1))\
or(empty_space==(piece,piece+1)):
matrix[empty_space][empty_space]=num
matrix[piece][piece]=0
empty_space=(piece,piece)
move = move +1
print()
print('you have made ',move , 'moves so far ')
print(2*'\n')
else:
print('illegal move , try again ')

if __name__ == '__main__':
game()
``````

thanks @snippsat , now I can see where I went wrong , I made those variables global because when I tested each function seperately it worked fine but when I used them in the main program it gave me errors and kept saying the variables are not defined that is when I thought about global , it is more clear to me now , thanks for your time

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.