Pages

marți, 28 mai 2019

PyGame : First interface - part 9.

Today I start with another tutorial with pygame python module and python version 3.7.3.
For this series of tutorials, I will introduce you a radar interface.
The advantages of using such an interface are evident from technical considerations and not only. This type of interface is very used in games because most users have become accustomed to it.
Let's start installing the pygame python module.
C:\Python373\Scripts>pip install pygame
Requirement already satisfied: pygame in c:\python373\lib\site-packages (1.9.6)
I try to follow some goals, like:
  • install pygame with pip tool for python 3.7.3;
  • create an interface for drawing;
  • use a configuration with values, see: screen_size;
  • use events to stop the script;
  • use line and circle with math and radians;
  • use the pygame.gfxdraw module to draw lines and circles;
This python script is simple to understand:
import pygame
import math
from pygame.locals import *
import pygame.gfxdraw

configuration = {
        'screen_size': (500,500),
}
pygame.init()
screen = pygame.display.set_mode(configuration['screen_size'])
FPSCLOCK = pygame.time.Clock()
done = False
screen.fill((0, 0, 0))
azimuth_degrees=0
while not done:
    screen.fill(0)
    # get events
    for e in pygame.event.get():
        if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE):
            done = True
            break
    screen.fill((0, 0, 0))
    # radar position on window     
    radar = (250,250)
    # radar lenght 
    radar_len = 276
    for x in range(1, 250, 30):
        # radar circle position on window
        pygame.gfxdraw.circle(screen,radar[0],radar[1],x,(0,0,255))   

    # calculate the x and y radar beam
    x = radar[0] + math.cos(math.radians( azimuth_degrees)) * radar_len
    y = radar[1] + math.sin(math.radians( azimuth_degrees)) * radar_len
    
    # then render the line radar with value (x,y)
    pygame.gfxdraw.line(screen, radar[0],radar[1], int(x),int(y), Color("blue"))
    pygame.display.flip() 

      
    azimuth_degrees+=1
    FPSCLOCK.tick(40)