
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 modulesimport timeimport randomimport sys#function for printing the text for player turntext_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 bitetext_for_snake_bite = ["boom!","bang!","snake bite","oops!","dang","oh shit","alas!"]#function for printing the text for ladder jumptext_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 snakesnake_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 ladderladders_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 gamedef first_msg():msg = """"""print(msg)# Delay of 1 second between each actionSLEEP_BETWEEN_ACTIONS = 1MAX_VAL = 100DICE_FACE = 6#function define for taking input (Name of player) from userdef get_player_names():p1_name = Nonewhile not p1_name:p1_name = input("Name of first player: ").strip()p2_name = Nonewhile 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 dicedef 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 bitedef 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 jumpdef 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 ladderdef snake_ladder(player_name, current_value, dice_value):time.sleep(SLEEP_BETWEEN_ACTIONS)old_value = current_valuecurrent_value = current_value + dice_valueif current_value > MAX_VAL:print("You need " + str(MAX_VAL - old_value) + " to win this game. Keep trying.")return old_valueprint("\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_valuereturn final_value#function define for checking the winnerdef 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 gamedef start():first_msg()time.sleep(SLEEP_BETWEEN_ACTIONS)p1_name, p2_name = get_player_names()time.sleep(SLEEP_BETWEEN_ACTIONS)p1_current_position = 0p2_current_position = 0while 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:
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 moduleimport randomfrom tkinter import *import time#function for generating random number on dicedef dice_roll():dice_number = random.randrange(1, 7, 1)return dice_number#function for creating pawn for each playerdef 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 ladderclass matching_position():def find_snake_or_ladder(self, block, turn, position):x = 35*(turn>=3)y = (turn%3)*35if(block == 3):return 305+x, 150+y, 22elif(block == 5):return 545+x, 390+y, 8elif(block == 11):return 185+x, 30+y, 26elif(block == 20):return 545+x, 30+y, 29elif(block == 17):return 425+x, 510+y, 4elif(block == 19):return 665+x, 390+y, 7elif(block == 21):return 425+x, 390+y, 9elif(block == 27):return 65+x, 510+y, 1else:return position[0], position[1], block#class for displaying the snake and ladder gameclass game_board(object):def __init__(self,master,img):#Create board of snake and ladderboard_width = 850board_height = 600self.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 = 65self.y = 510self.m = []self.num_player = "Players"self.player = []self.position = []self.i = 0self.block=[]self.dice_number = 1self.turn = 0#Menu for choosing number of playersOPTIONS = ["Players", "2", "3", "4", "5", "6"]variable = StringVar(master)variable.set(OPTIONS[0]) # default valuew = 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 gameself.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_piecesdef start_game(self):if(self.num_player == "Players"):passelse:#dice_roll#Screenself.canvas.create_rectangle(810, 150, 760, 100, fill='white', outline='black')self.canvas.pack(fill=BOTH, expand=1)#Buttonself.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 playersdef choose(self, value):self.num_player = value#function for rolling the dicedef rolling_dice(self, position, turn):dice_number = dice_roll()#dice_number = 1#Print dice_roll Value to screendice_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_numberself.block[turn] += dice_numberself.canvas.delete(self.player[turn])self.player_pieces(dice_number, turn)return [self.x, self.y]#function for moving the player_pieces in the boarddef 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 leftfor 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 - 120self.x = 665self.m[turn] = -1elif(self.x>700 and turn >=3):self.y = self.y - 120self.x = 700self.m[turn] = -1if(self.x<65 and turn < 3):self.x = 65self.y -= 120self.m[turn] = 1elif(self.x<100 and turn >=3):self.x = 100self.y -= 120self.m[turn] = 1if(self.y<30):self.y=30# Code For the Animation of pieceself.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] = -1else:self.m[turn] = 1print(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_piecesdef create_peice(self):for i in range(int(self.num_player)):if(i==3):self.x += 35self.y -= 105self.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 gamedef play_game(self):if(self.dice_number == 6):turn = self.turnelse:turn = self.i%self.num_playerself.i += 1self.turn = turnself.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 functiondef 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:
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:
- Create your own ChatGPT with Python
- SQLite | CRUD Operations in Python
- Event Management System Project in Python
- Ticket Booking and Management in Python
- Hostel Management System Project in Python
- Sales Management System Project in Python
- Bank Management System Project in C++
- Python Download File from URL | 4 Methods
- Python Programming Examples | Fundamental Programs in Python
- Spell Checker in Python
- Portfolio Management System in Python
- Stickman Game in Python
- Contact Book project in Python
- Loan Management System Project in Python
- Cab Booking System in Python
- Brick Breaker Game in Python
- Tank game in Python
- GUI Piano in Python
- Ludo Game in Python
- Rock Paper Scissors Game in Python
- Snake and Ladder Game in Python
- Puzzle Game in Python
- Medical Store Management System Project in Python
- Creating Dino Game in Python
- Tic Tac Toe Game in Python
- Test Typing Speed using Python App
- Scientific Calculator in Python
- GUI To-Do List App in Python Tkinter
- Scientific Calculator in Python using Tkinter
- GUI Chat Application in Python Tkinter