Snakes and ladder (Single player) in Python

Python | Snakes and ladder game: Here, we are going to implement a snakes and ladder game for single player using Python program. By Anuj Singh Last updated : April 21, 2023

Snakes and ladder (Single player) Game

  • There are 6 face dice which is being rolled by the player to their chance.
  • The player starts from 0 and has to reach the final position (in our case, its 104).
  • There are some ladder which turns out to be lucky for the player as they shorten the way.
  • There are some snakes present in between the game which turns out to be the enemy of the player as they just lengthen their way to 104.

Now, We are going to implement these rules and build a code for this game. We will be using abstract data type in this article, that is object-oriented programming.

Python code for snakes and ladder (single player) game

class snakesandladder(object):
    def __init__(self, name, position):
        self.name = name
        self.position = position
        self.ladd = [4,24,48,67,86]
        self.lengthladd = [13,23,5,12,13]
        self.snake = [6,26,47,23,55,97]   
        self.lengthsnake = [4,6,7,5,8,9]
        
        
    def dice(self):
        chances = 0
        print("----------------LeTs StArT ThE GaMe----------------\n")
        while self.position <= 104: 
            roll = random.choice([1,2,3,4,5,6])  
            print('roll value: ', roll)
            self.position = roll + self.position
            if self.position > 104:
                self.position = self.position - roll
            if self.position == 104:
                print('completed the game')
                break
            
            if self.position in self.ladd:
                for n in range(len(self.ladd)):
                    if self.position == self.ladd[n]:
                        self.position = self.position + self.lengthladd[n]
            if self.position in self.snake:
                for n in range(len(self.snake)):
                    if self.position == self.snake[n]:
                        self.position = self.position - self.lengthsnake[n]
                        
            print('Current position of the player : ', self.position, '\n')
            chances += 4/4
        print('ToTal number oF chances : ', chances)
    

zack = snakesandladder('zack',0)    
zack.dice()

Output

snakes and ladder single player in Python


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.