Python Forum
Is there any way to compact this code? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Is there any way to compact this code? (/thread-23066.html)



Is there any way to compact this code? - Vantage - Dec-09-2019

I have created a super basic text based snakes and ladders game. I felt presetting the positions of the snakes and ladders was the best way to go about it, but it just makes it long and tedious to write. Is there any way to compact or condense it down? Or is there no way around this? Thanks in advance, this will help me a lot on my GCSE course. Smile

def snakes_ladders_positions():
    global snake_pos1
    global snake_pos2
    global snake_pos3
    global snake_pos4
    global snake_pos5
    snake_pos1 = random.randint(10,20)
    snake_pos2 = random.randint(22,40)
    snake_pos3 = random.randint(42,60)
    snake_pos4 = random.randint(62,80)
    snake_pos5 = random.randint(82,90)
    global ladder_pos1
    global ladder_pos2
    global ladder_pos3
    global ladder_pos4
    global ladder_pos5
    ladder_pos1 = random.randint(10,20)
    ladder_pos2 = random.randint(22,40)
    ladder_pos3 = random.randint(42,60)
    ladder_pos4 = random.randint(62,80)
    ladder_pos5 = random.randint(82,90)



RE: Is there any way to compact this code? - ichabod801 - Dec-09-2019

First of all, you shouldn't be using globals. They cause a number of problems. Learn how to pass parameters and return values. See the function tutorial on how to do that.

Second, whenever you have variable1, variable2, and so on, you really want a list. Something like:

snake_pos = [random.randint(10,20), random.randint(22,40), random.randint(42,60), random.randint(62,80),
    random.randint(82,90)]
Then you can refer to snake_pos[0], snake_pos[1], and easily loop over them if you need to do something to all of them, like update them. A list comprehension can make this even simpler:

snake_starts = ((10,20), (22,40), (42,60), (62,80), (82,90))
snake_pos = [random.randint(low, high) for low, high in snake_starts]



RE: Is there any way to compact this code? - Vantage - Dec-09-2019

Ahh. Thank you, thank you, thank you, globals have cause numerous problems for me and I will go to that link. I didn't even know about lists, thanks so much for teaching me them. I'll go and improve the code right now. Thanks again!