Simulate elliptical orbit using Pygame

In this tutorial, we will look at another way to implement Python in more fun way. We will see how to draw an elliptical orbit using Pygame in Python.

We will use packages similar to bouncing ball tutorial. You can read the tutorial to know more about how graphical visuals are usually implemented in Python with Pygame.

Stimulate bouncing game using Pygame

The pre-requisites required to draw elliptical orbit would be to decide on the radius of major and minor axis. We will also be drawing circles at a different position with different angles to give an effect of simulation.

To do that, we will import the math module from Python packages.

import pygame
import math
import sys
pygame.init()
screen=pygame.display.set_mode((640,480))
pygame.display.set_caption("elliptical orbit")
clock=pygame.time.Clock
while(True):
     for event in pygame.event.get():
         if event.type == pygame.QUIT:
             sys.exit()
     xRadius = 250
     yRadius = 100
     for degree in range(0,360,10):
         x1 = int(math.cos(degree * 2 * math.pi / 360) * xRadius)+ 300
         y1 = int(math.cos(degree * 2 * math.pi / 360) * yRadius)+ 150
         screen.fill((black))
#syntax : pygame.draw.circle(screen, color, (x,y), radius, thickness)
         pygame.draw.circle(screen,(255,0,0),[300,150],35)
#syntax : pygame.draw.ellipse(screen, color, (x,y), [x, y, width, height], thickness)
         pygame.draw.ellipse(screen, (250, 255, 255), [50, 50, 50, 200], 1)
         pygame.draw.circle(screen, (0, 0, 255), [x1,y1], 15)
         pygame.display.flip()
         clock.tick(5)

If you look closer into the code we will see that the color of the shapes are not described as “black” or “white” as such. Instead, their codes are mentioned. For example Black color code is (0,0,0), White is (255,255,255), Red is (255,0,0) and so on. These are the standard code that is available for different colors.

The general syntax for drawing a circle and ellipse is given inside the code for reference.

Leave a Reply

Your email address will not be published.