Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8339221
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T04:49:36+00:00 2026-06-09T04:49:36+00:00

I’m currently writing a very simple game using python and pygame. It has stuff

  • 0

I’m currently writing a very simple game using python and pygame. It has stuff that moves. And to make this stuff move smoothly I arranged the main game loop as said in Fix Your Timestep, with interpolation.

Here is how I handle interpolation now.

class Interpolator(object):
    """Handles interpolation"""
    def __init__(self):
        self.ship_prev = None
        self.ship = None

        self.stars_prev = []
        self.stars = []

        self.bullets_prev = {}
        self.bullets = {}

        self.alpha = 0.5

    def add_ship(self, ship):
        self.ship_prev = self.ship
        self.ship = ship

    def add_stars(self, stars):
        self.stars_prev = self.stars
        self.stars = stars[:]

    def add_bullets(self, bullets):
        self.bullets_prev = self.bullets
        self.bullets = bullets.copy()

    def add_enemies(self, enemies):
        self.enemies_prev = self.enemies
        self.enemies = enemies  # to be continued

    def lerp_ship(self):
        if self.ship_prev is None:
            return self.ship
        return lerp_xy(self.ship_prev, self.ship, self.alpha)

    def lerp_stars(self):
        if len(self.stars_prev) == 0:
            return self.stars
        return (lerp_xy(s1, s2, self.alpha) for s1, s2 in izip(self.stars_prev, self.stars))

    def lerp_bullets(self):
        keys = list(set(self.bullets_prev.keys() + self.bullets.keys()))
        for k in keys:
            # interpolate as usual
            if k in self.bullets_prev and k in self.bullets:
                yield lerp_xy(self.bullets_prev[k], self.bullets[k], self.alpha)
            # bullet is dead
            elif k in self.bullets_prev:
                pass
            # bullet just added
            elif k in self.bullets:
                yield self.bullets[k]

The lerp_xy() function and data types

def lerp_xy(o1, o2, alpha, threshold=100):
    """Expects namedtuples with x and y parameters."""
    if sqrt((o1.x - o2.x) ** 2 + (o1.y - o2.y) ** 2) > 100:
        return o2
    return o1._replace(x=lerp(o1.x, o2.x, alpha), y=lerp(o1.y, o2.y, alpha))

Ship = namedtuple('Ship', 'x, y')
Star = namedtuple('Star', 'x, y, r')
Bullet = namedtuple('Bullet', 'x, y')

The data types are of course temporary, but I still expect they will have the x and y attributes in the future. update: lerper.alpha is updated each frame.

Ship is added as a single object – it’s the player ship. Stars are added as a list. Bullets are added as a dict {id, Bullet}, since bullets are added and removed all the time, I have to track which bullet is which, interpolate if both are present and do something if it just has been added or deleted.

Anyway this code right here is crap. It grew as I added features, and now I want to rewrite it to be more generic, so it can continue growing and not become an unpythonic stinky pile of poo.

Now I’m still pretty new to Python, though I feel pretty comfortable with list comprehensions, generators and coroutines already.

What I have the least experience with is the OO side of Python, and designing an architecture of something bigger than a 10-line hacky disposable script.

The question is not a question as in something I don’t know and can’t do anything about it. I’m sure I’m capable of rewriting this pretty simple code that will work in some way close to what I want.

What I do want to know, is the way experienced Python programmers will solve this simple problem in a pythonic way, so I (and of course others) could learn what is considered an elegant way of handling such a case among Python developers.

So, what I approximately want to achieve, in pseudocode:

lerper = Interpolator()
# game loop
while(1):
    # physics
    # physics done
    lerper.add(ship)
    lerper.add(stars)
    lerper.add(bullets)
    lerper.add(enemies) # you got the idea

    # rendering
    draw_ship(lerper.lerp('Ship'))
    # or
    draw_ship(lerper.lerp_ship())

However don’t let that pseudocode stop you if you have a better solution in mind =)

So. Make all game objects as separate/inherited class? Force them all to have id? Add them all as list/dict lerper.add([ship])? Make a special container class inheriting from dict/whatever? What do you consider an elegant, pythonic way of solving this? How would you do it?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T04:49:38+00:00Added an answer on June 9, 2026 at 4:49 am

    Here is how I ended up handling the interpolation:

    class Thing(object):
        """Generic game object with interpolation"""
        def __init__(self, x=0, y=0):
            self._x = self.x = x
            self._y = self.y = y
    
        def imprint(self):
            """call before changing x and y"""
            self._x = self.x
            self._y = self.y
    
        def __iter__(self):
            """handy to unpack like a tuple"""
            yield self.x
            yield self.y
    
    Ship = Thing
    Bullet = Thing
    
    
    class Star(Thing):
        """docstring for Star"""
        def __init__(self, x, y, r):
            super(Star, self).__init__(x, y)
            self.r = r
    
        def __iter__(self):
            yield self.x
            yield self.y
            yield self.r
    
    
    def lerp_things(things, alpha, threshold=100):
        """Expects iterables of Things"""
        for t in things:
            if sqrt((t._x - t.x) ** 2 + (t._y - t.y) ** 2) > threshold:
                yield (t.x, t.y)
            else:
                yield (lerp(t._x, t.x, alpha), lerp(t._y, t.y, alpha))
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I've got a string that has curly quotes in it. I'd like to replace
I am doing a simple coin flipping experiment for class that involves flipping a
I'm making a simple page using Google Maps API 3. My first. One marker
I know there's a lot of other questions out there that deal with this
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
I want to count how many characters a certain string has in PHP, but

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.