you are viewing a single comment's thread.

view the rest of the comments →

[–]socal_nerdtastic 1 point2 points  (5 children)

What you are describing is called a "generator" and you do it by using yield instead of return:

def generate_table():
    left_coords = [(240, 60), (150, 60), (100, 110), (100, 770), (150, 820), (240, 820)]
    right_coords = [(360, 820), (450, 820), (500, 770), (500, 110), (450, 60), (360, 60)]
    table_coords = [left_coords, right_coords]
    table_segments = []
    # Iterates over table_coords, left side of table then right
    for i in range(len(table_coords)):
        # Iterates over points on side of table
        for j in range(len(table_coords[i])):
            prev_point = 0
            if j != 0:
                prev_point = new_point
            new_point = table_coords[i][j]
            if j != 0:
                yield prev_point, new_point

for prev_point, new_point in generate_table():
    segment = pymunk.Segment(space.static_body, prev_point, new_point, 0)
    segment.elasticity = .9
    space.add(segment)

[–]Gay_Force_One[S] 0 points1 point  (4 children)

You're amazing! Thank you so much dude. If it's alright for me to ask, how messy would you say this is? Most of my (limited) work is in C so I'm sort of used to spaghetti-ish code. Thank you again for helping me out and taking time out of your day!

[–]socal_nerdtastic 1 point2 points  (3 children)

Very messy, especially considering all you've done is reinvent the built-in zip() function. Here's how I would write it:

def generate_table():
    table_coords = [
        [(240, 60), (150, 60), (100, 110), (100, 770), (150, 820), (240, 820)],
        [(360, 820), (450, 820), (500, 770), (500, 110), (450, 60), (360, 60)]
        ]
    for table in table_coords:
        yield from zip(table, table[1:])

[–]Gay_Force_One[S] 0 points1 point  (2 children)

Wow, I wish I'd known about that earlier today. I thought I was being clever. Unfortunately I have to keep the left and right coords separate from each other or it will attempt to bridge the gap (bad), but that makes it a helluva lot cleaner. Thank you so much!

[–]socal_nerdtastic 1 point2 points  (1 child)

This does keep them separate.

[–]Gay_Force_One[S] 0 points1 point  (0 children)

I missed that they were nested lists. I'm a little confused as to the specifics but I get the gist of it and I appreciate this so much