more detours into scrolling (roguelike in Python #3.5.a.i)

Maybe it seems like I’m obsessed with scrolling, but bear with me. After Ludum Dare and PyWeek I’m getting back into the roguelike demo. I knew that the scrolling code was kind of a mess. I won’t bother reposting it here (you can see it here), but basically it was a few if statements for each axis inside a for loop, all to determine where to place the scrolling view on the map and where to draw the focus of the view (typically the player).

Looking at it tonight I realized a few things. First, I definitely don’t need to check where to draw the view focus inside the for loop. And second, I don’t need to determine where to place the scrolling view on the map inside the for loop either!

All I need to know is where the view should be placed. Then the for loop can just start from there. In addition, the placement of the view focus is made much simpler by using basic addition rather than a few if statements.

So here’s the new update method for the scrolling code:

    def update(self):
        self.cells = []
        self.left_view_frame = min(max(0, self.thing.x - self.width//2), world.level_width - self.width)
        self.top_view_frame = min(max(0, self.thing.y - self.height//2), world.level_height - self.height)
        x_left_offset = min(self.thing.x, self.width//2)
        x_right_offset = max(0, (self.width//2 - (world.level_width - self.thing.x) + (self.width % 2)))
        self.view_x =  x_left_offset + x_right_offset
        y_top_offset = min(self.thing.y, self.height//2)
        y_bottom_offset = max(0, (self.height//2 - (world.level_height - self.thing.y) + (self.height % 2)))
        self.view_y =  y_top_offset + y_bottom_offset 
        for i in range(self.height):
            self.y = self.top_view_frame + i
            for j in range(self.width):
                self.x = self.left_view_frame + j
                self.cells.append((self.x, self.y, j, i))

One note about the (self.width % 2) (which applies to y as well) — thanks to Grishnak at the Doryen Library forums I’ve added this fix for the case where the viewport is an even number of cells wide or tall. I was adding one before, as I normally use an odd-sized viewport.


No comments yet

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: