how I love refactoring (a roguelike in Python, a diversion)

In working on adding player memory to the map (so cells not immediatly in field-of-view but previously seen are drawn) I realized something. My scrolling/camera code looked like this:

    def scroll(self):
        self.x_offset = min(max(0, player.thing.x - self.width//2), - self.width)
        self.y_offset = min(max(0, player.thing.y - self.height//2), - self.height)

        self.x_left_offset = min(player.thing.x, self.width//2)
        self.x_right_offset = max(0, (self.width//2 - ( - player.thing.x) + (self.width % 2)))
        self.focus_x =  self.x_left_offset + self.x_right_offset

        self.y_top_offset = min(player.thing.y, self.height//2)
        self.y_bottom_offset = max(0, (self.height//2 - ( - player.thing.y) + (self.height % 2)))
        self.focus_y =  self.y_top_offset + self.y_bottom_offset

When it really only needs to look like this:

    def scroll_update(self):
        self.anchor_x = min(max(0, player.thing.x - self.width//2), - self.width)
        self.anchor_y = min(max(0, player.thing.y - self.height//2), - self.height)

The problem was I had been treating where the player was rendered as a special case — in effect putting the player and the camera focus position in the same basket. This wasn’t necessary at all — all you need to know is where the camera or view is positioned on the screen (I chose to keep track of the top left corner of the view with the variables anchor_x and anchor_y). Then you just need to translate world coordinates to view coordinates when you deal with the viewport.

I knew the previous code was too complicated. It feels good to get it into shape!


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: