Python Forum
Is there any way to compact this code?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Is there any way to compact this code?
#1
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)
Reply
#2
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]
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
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!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  can itertools compact a list removing all of some value? Skaperen 6 3,158 Sep-02-2019, 03:19 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020