Snake and Ladder Game in Python

Snake and Ladder Game in Python

Introduction

Are you looking for a fun way to learn Python coding? If so, why not create your own Snake and Ladder Game in Python? This step-by-step tutorial will show you how to craft a fully-functional game of Snake and Ladder in just a few simple steps. You’ll learn basic Python programming concepts, the fundamentals of game design, and the necessary coding skills to bring your project to life. With a little patience and dedication, you can have your own custom game of Snakes and Ladders up and running in no time! So, if you’re ready to take your coding skills to the next level, let’s get started and make your very own Snakes and Ladders game today!

Overview

In this tutorial, we are going to build the snakes and ladders game using two different approaches.

1. Text-based Snake and Ladder Game in Python

This code makes use of the following fundamental concepts:

  •  Dictionary 
  •  List 
  • Choosing a random number from a list
  • Including wait/sleep in the program 
  • Choosing a random number from a list
  • Receiving user input

2. Gui-based Snake and Ladder game in Python using Tkinter

This code uses the following concepts of Python Tkinter:

  • Label widget
  • Button widget
  • Canvas widget
  • Menubutton widget

Both of these techniques take different approaches to developing games, covering various methods, concepts, and principles of Python programming.

Text-based Snake and Ladder Game in Python

#Snake and ladder game using Python

#importing all the required modules
import time
import random
import sys


#function for printing the text for player turn
text_for_plr_turn = [
    "Its your turn. Hit enter to roll the dice.",
    "Are you prepared?",
    "Lets Go.",
    "Please move along.",
    "You are doing great.",
    "Ready to be a champion.",
    "",
]

#function for printing the text for snake bite
text_for_snake_bite = [
    "boom!",
    "bang!",
    "snake bite",
    "oops!",
    "dang",
    "oh shit",
    "alas!"
]

#function for printing the text for ladder jump
text_for_ladder_jump = [
    "yipee!",
    "wahoo!",
    "hurrah!",
    "oh my Goodness...",
    "you are on fire",
    "you are a champion",
    "you are going to win this"
]

# Dictionary containing snake bite positions

#Snake Postions where key is the head of snake and value is the tail of snake
snake_position = {
    12: 4,
    18: 6,
    22: 11,
    36: 7,
    42: 8,
    53: 31,
    67: 36,
    73: 28,
    80: 41,
    84: 53,
    90: 48,
    94: 65,
    96: 80,
    99: 2
}

#Ladder Positions where key is the bottom of ladder and value is the top of ladder
ladders_position = {
    3: 26,
    5: 15,
    13: 44,
    25: 51,
    29: 74,
    36: 57,
    42: 72,
    49: 86,
    57: 76,
    61: 93,
    77: 86,
    81: 98,
    88: 91
}

#function for printing the rules of the game
def first_msg():
    msg = """"""

    print(msg)

# Delay of 1 second between each action
SLEEP_BETWEEN_ACTIONS = 1
MAX_VAL = 100
DICE_FACE = 6


#function define for taking input (Name of player) from user
def get_player_names():
    p1_name = None
    while not p1_name:
        p1_name = input("Name of first player: ").strip()

    p2_name = None
    while not p2_name:
        p2_name = input("Name of second player: ").strip()

    print("\n'" + p1_name + "' and '" + p2_name + " You will play against each other'\n")
    return p1_name, p2_name


#function define for rolling the dice
def get_dice_value():
    time.sleep(SLEEP_BETWEEN_ACTIONS)
    dice_value = random.randint(1, DICE_FACE)
    print("Dice value " + str(dice_value))
    return dice_value


#function define for snake bite
def got_snake_bite(old_value, current_value, player_name):
    print("\n" + random.choice(text_for_snake_bite).upper() + " ~~~~~~~~>")
    print("\n"" " + player_name + " got a bite from snake. Going down from " + str(old_value) + " to " + str(current_value))


#function define for ladder jump
def got_ladder_jump(old_value, current_value, player_name):
    print("\n" + random.choice(text_for_ladder_jump).upper() + " ########")
    print("\n" + player_name + " is clibing the ladder from " + str(old_value) + " to " + str(current_value))

#function define for snake and ladder
def snake_ladder(player_name, current_value, dice_value):
    time.sleep(SLEEP_BETWEEN_ACTIONS)
    old_value = current_value
    current_value = current_value + dice_value

    if current_value > MAX_VAL:
        print("You need " + str(MAX_VAL - old_value) + " to win this game. Keep trying.")
        return old_value

    print("\n" + player_name + " moved from " + str(old_value) + " to " + str(current_value))
    if current_value in snake_position:
        final_value = snake_position.get(current_value)
        got_snake_bite(current_value, final_value, player_name)

    elif current_value in ladders_position:
        final_value = ladders_position.get(current_value)
        got_ladder_jump(current_value, final_value, player_name)

    else:
        final_value = current_value

    return final_value

#function define for checking the winner
def check_win(player_name, position):
    time.sleep(SLEEP_BETWEEN_ACTIONS)
    if MAX_VAL == position:
        print("\n" + player_name + "has  won the game.")
        print("Congratulations " + player_name +"You are the winner")
        sys.exit(1)

#function define for playing the game
def start():
    first_msg()
    time.sleep(SLEEP_BETWEEN_ACTIONS)
    p1_name, p2_name = get_player_names()
    time.sleep(SLEEP_BETWEEN_ACTIONS)

    p1_current_position = 0
    p2_current_position = 0

    while True:
        time.sleep(SLEEP_BETWEEN_ACTIONS)
        input_1 = input("\n" + p1_name + ": " + random.choice(text_for_plr_turn) + " Press enter for rolling the dice: ")
        print("\n d\Dice is being rolled...")
        dice_value = get_dice_value()
        time.sleep(SLEEP_BETWEEN_ACTIONS)
        print(p1_name + " moving....")
        p1_current_position = snake_ladder(p1_name, p1_current_position, dice_value)

        check_win(p1_name, p1_current_position)

        input_2 = input("\n" + p2_name + ": " + random.choice(text_for_plr_turn) + " Press enter for rolling the dice: ")
        print("\n Dice is being rolled...")
        dice_value = get_dice_value()
        time.sleep(SLEEP_BETWEEN_ACTIONS)
        print(p2_name + " moving....")
        p2_current_position = snake_ladder(p2_name, p2_current_position, dice_value)

        check_win(p2_name, p2_current_position)


if __name__ == "__main__":
    start()

Rules to play Text-based Snake and Ladder Game in Python:

  • Both players begin in the same position, i.e. 0.
  • The player who gets to the FINAL position i.e 100 first will be the winner.
  • If you land on the head of a snake, you must slide down to the snake’s tail.
  • If you land at the bottom of a ladder, you can climb your way to the top.
  • For tossing the dice press enter.

The output of the text-based game:

output for Text-based Snake and Ladder Game in Python

Gui-based Snake and Ladder game in Python using Tkinter

We will be using a background image, you can find it here.

# GUI based snake and ladder game

#importing tkinter module
import random
from tkinter import *
import time

#function for generating random number on dice
def dice_roll():
    dice_number = random.randrange(1, 7, 1)
    return dice_number

#function for creating pawn for each player     
def create_pawn(self, x, y, r, **kwargs):
    return self.create_oval(x-r, y-r, x+r, y+r, **kwargs)
Canvas.create_circle = create_pawn

#class for matcing the dice number with the snake and ladder
class matching_position():
    def find_snake_or_ladder(self, block, turn, position):
        x = 35*(turn>=3)
        y = (turn%3)*35
        if(block == 3):
           return 305+x, 150+y, 22
        elif(block == 5):
            return 545+x, 390+y, 8
        elif(block == 11):
            return 185+x, 30+y, 26
        elif(block == 20):
            return 545+x, 30+y, 29
        elif(block == 17):
           return 425+x, 510+y, 4
        elif(block == 19):
           return 665+x, 390+y, 7
        elif(block == 21):
           return 425+x, 390+y, 9
        elif(block == 27):
           return 65+x, 510+y, 1
        else:
            return position[0], position[1], block
        
#class for displaying the snake and ladder game
class game_board(object):
    def __init__(self,master,img):

        #Create board of snake and ladder
        board_width = 850
        board_height = 600
        self.color = ["#FFF", "#F00", "#0F0", "#00F", "#FF0", "#0FF"]
        self.canvas = Canvas(master, width = board_width, height = board_height, bg = "brown")
        self.canvas.grid(padx=0, pady=0)
        self.canvas.create_image(360,300,anchor=CENTER, image = img)

        self.x = 65
        self.y = 510
        self.m = []
        self.num_player = "Players"
        self.player = []
        self.position = []
        self.i = 0
        self.block=[]
        self.dice_number = 1
        self.turn = 0
        
        
        #Menu for choosing number of players
        OPTIONS = ["Players", "2", "3", "4", "5", "6"]
        variable = StringVar(master)
        variable.set(OPTIONS[0]) # default value
        w = OptionMenu(self.canvas, variable, *OPTIONS, command=self.choose)
        w.pack()
        w.place(x=740, y=225)
        w.config(font=('calibri',(10)),bg='white',width=5)
        
        #Button for starting the game
        self.start_game = Button(self.canvas, text="Start", background='white', command = self.start_game, font=("Helvetica"))
        self.start_game.place(x=770, y=400)

     #function for moving the player_pieces
    def start_game(self):
        if(self.num_player == "Players"):
            pass
        else:
            #dice_roll
            #Screen
            self.canvas.create_rectangle(810, 150, 760, 100, fill='white', outline='black')
            self.canvas.pack(fill=BOTH, expand=1)
            #Button
            self.diceRoll = Button(self.canvas, text="Roll",background='white',
                                   command = self.play_game, font=("Helvetica"))
            self.num_player = int(self.num_player)
            self.diceRoll.place(x=770, y=165)
            self.create_peice()
            self.start_game.place(x=-30, y=-30)

    #function for choosing number of players
    def choose(self, value):
        self.num_player = value

    #function for rolling the dice
    def rolling_dice(self, position, turn):
        dice_number = dice_roll()
        #dice_number = 1
        #Print dice_roll Value to screen
        dice_value = Label(self.canvas, text=str(dice_number),
                           background='white', font=("Helvetica", 25))
        dice_value.pack()
        dice_value.place(x=775, y=105)
        
        
        self.x, self.y = position[0], position[1]
        if(dice_number+self.block[turn] > 30):
            return [self.x, self.y]
        
        self.dice_number = dice_number
        self.block[turn] += dice_number
        
        self.canvas.delete(self.player[turn])
        self.player_pieces(dice_number, turn)

        return [self.x, self.y]

     #function for moving the player_pieces in the board   
    def player_pieces(self, dice_number, turn):
        #Starting value of and x and y should be 120 and 120
        #In create_circle initial value of x and y should be 100 and 550
        #To reach to the last block x should be 5*x and y should be 4*y
        #X should be added to value and Y should be subtracted
        # 5x120=600 and 4*120=480
        #m is the constant that tells which side to dice_number i.e. left to right or right to left
        for i in range(dice_number,0,-1):
            self.x = self.x+120*self.m[turn]

            if(self.x>665 and turn < 3):
                self.y = self.y - 120
                self.x = 665
                self.m[turn] = -1
            elif(self.x>700 and turn >=3):
                self.y = self.y - 120
                self.x = 700
                self.m[turn] = -1
            if(self.x<65 and turn < 3):
                self.x = 65
                self.y -= 120
                self.m[turn] = 1
            elif(self.x<100 and turn >=3):
                self.x = 100
                self.y -= 120
                self.m[turn] = 1 
            if(self.y<30):
                self.y=30

            # Code For the Animation of piece
            self.canvas.delete(self.player[turn])
            self.player[turn] = self.canvas.create_circle(self.x, self.y, 15, fill=self.color[turn], outline=self.color[turn])
            self.canvas.update()
            time.sleep(0.25)

            
        print(self.x, self.y, self.block[turn])
        self.x, self.y, self.block[turn] = matching_position().find_snake_or_ladder(self.block[turn], turn, [self.x, self.y])
        
        if(any(self.y == ai for ai in [390, 425, 460, 150, 185, 220])):
            self.m[turn] = -1
        else:
            self.m[turn] = 1
        print(self.x,self.y, self.block[turn])
        self.canvas.delete(self.player[turn])
        self.player[turn] = self.canvas.create_circle(self.x, self.y, 15, fill=self.color[turn], outline="")


    #function for creating the player_pieces
    def create_peice(self):
        for i in range(int(self.num_player)):
            if(i==3):
                self.x += 35
                self.y -= 105
            self.player.append(self.canvas.create_circle(self.x, self.y, 15, fill=self.color[i], outline=""))
            self.position.append([self.x, self.y])
            self.m.append(1)
            self.block.append(1)
            self.y += 35

    #function for playing the game
    def play_game(self):
        if(self.dice_number == 6):
            turn = self.turn
        else:
            turn = self.i%self.num_player
            self.i += 1
            self.turn = turn
        self.position[turn] = self.rolling_dice(self.position[turn], turn)
        if(self.block[self.turn] >= 30):
            self.diceRoll.place(x=-30, y=-30)
            print("Won", self.turn+1)
            top = Toplevel()
            top.title("Snake and Ladder")
            message = "Player " + str(self.turn+1) + " Won" 
            msg = Message(top, text=message)
            top.geometry("%dx%d%+d%+d" % (100, 100, 250, 125))
            msg.pack()
            button = Button(top, text="Dismiss", command=top.destroy)
            button.pack()
            
 
#defining the main function    
def main():
    master = Tk()
    master.title("Snake and Ladder")
    master.geometry("850x600")
    img = PhotoImage( file = "snake-ladder-board.gif")
    x = game_board(master,img)
    master.mainloop()

main()

The output of GUI-based game:

output for Gui-based Snake and Ladder game in Python using Tkinter

Conclusion

In this step-by-step tutorial! We created Snake and Ladder Game in Python quickly and easily. We have learned how to design the game board, create the game logic, and create a user interface. We developed two amazing games using different approaches.

Thank you for visiting our website.


Also Read:

Share:

Author: Ayush Purawr