Rules of the game:
游戏规则:
There are 6 face dice which is being rolled by the player to their chance.
共有6个面子骰子由玩家掷出,这是他们的机会。
The player starts from 0 and has to reach the final position (in our case, its 104).
玩家从0开始,必须到达最终位置(在本例中为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.
在游戏之间存在一些蛇,当它们只是延长其路径到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代码(单人) (Python code for snakes and ladder (single player))
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
输出量
翻译自: https://www.includehelp.com/python/snakes-and-ladder-single-player-in-python.aspx