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+----+----+----+---|')       
    #ask for the next move
    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[0]-1,piece[1]))\
           or(empty_space==(piece[0]+1,piece[1]))\
           or(empty_space==(piece[0],piece[1]-1))\
           or(empty_space==(piece[0],piece[1]+1)):
            matrix[empty_space[0]][empty_space[1]]=num
            matrix[piece[0]][piece[1]]=0
            empty_space=(piece[0],piece[1])
            move = move +1
            print()
            print('you have made ',move , 'moves so far ')
            print(2*'\n')
        else:
            print('illegal move , try again ')

print('game over  ')

Recommended Answers

All 8 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 ---------- 

def ask_number():
    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)      

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

        if(empty_space==(piece[0]-1,piece[1]))\
           or(empty_space==(piece[0]+1,piece[1]))\
           or(empty_space==(piece[0],piece[1]-1))\
           or(empty_space==(piece[0],piece[1]+1)):
            matrix[empty_space[0]][empty_space[1]]=num
            matrix[piece[0]][piece[1]]=0
            empty_space=(piece[0],piece[1])
            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+-------+-------+-------+-------|')

def ask_number(board):
    ''' 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)
        piece,num = ask_number(matrix)
        if num > 15:
            print('illegal move , try again  ')
        else:
            if(empty_space==(piece[0]-1,piece[1]))\
               or(empty_space==(piece[0]+1,piece[1]))\
               or(empty_space==(piece[0],piece[1]-1))\
               or(empty_space==(piece[0],piece[1]+1)):
                matrix[empty_space[0]][empty_space[1]]=num
                matrix[piece[0]][piece[1]]=0
                empty_space=(piece[0],piece[1])
                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

If I could just chime in here, you might also consider type hints. As an example, here are two function declarations:

def MyFunc(parm1, parm2, parm3):

def MyFunc(parm1: int, parmn2: str, parm3: float) -> float:

Ignore for the moment that I chose non-descriptive parameter names, the second form indicates the types of the parameters, and the type of the returned value. While Python ignores type hints (you can pass any types for the parameters), other tools, such as mypy can run checks against your code using type hints for verification.

Even if Python ignores the hints, it is still a quick reminder when you are reading your code.

Can anyone explain the last else part in which,if-else statement is added..

Be a part of the DaniWeb community

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