Pages

Se afișează postările cu eticheta pygame. Afișați toate postările
Se afișează postările cu eticheta pygame. Afișați toate postările

luni, 10 august 2026

PyGame : Fixing Android Screen Rotation Crashes in Pygame and Pydroid 3.

When developing mobile 2D games using Python, Pygame, and Pydroid 3 on Android, rotating the device frequently causes application crashes or frozen rendering loops. This core instability stems from how the Android operating system handles application lifecycles and SDL video contexts. When an orientation shift occurs, the system destroys the underlying hardware surface. Standard Pygame implementations try to catch this through resize events or re-initialize the surface using display mode settings. On Android architectures, this dynamic re-allocation often triggers memory faults or direct binary crashes. Furthermore, fixed pixel logic locks game entities into rigid coordinate boundaries, causing objects to render off-screen when the display aspect ratio changes
To solve these performance bottlenecks, this script implements a robust mobile rendering pattern that combines three key engineering strategies.
Non-Destructive Context Polling: Instead of intercepting risky window resize events that break SDL bindings, this script queries hardware display properties dynamically per frame using system info calls. This approach preserves the active video memory context, preventing system-level crashes.
Delta Time Frame-Independent Physics: Traditional loop iterations rely on rigid frame counts, which fluctuate wildly during background tasks or screen rotations. This script measures precise time deltas, ensuring that entity velocity calculations remain strictly constant in pixels per second regardless of processor load or refresh rates.
Proportional Relative Mapping: To preserve entity placement during aspect ratio flips, this script tracks horizontal coordinates as normalized fractions. When viewport dimensions swap, entities instantly project to their accurate proportional coordinates without scaling distortion.
Let's see the source code:
import pygame
import random

pygame.init()

info = pygame.display.Info()
WIDTH, HEIGHT = info.current_w, info.current_h

screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.FULLSCREEN)
clock = pygame.time.Clock()

class FallingBox:
    def __init__(self, rel_x):
        self.rel_x = rel_x                      # Horizontal percentage (kept during rotation)
        self.y_pixels = random.uniform(0, 100)  # Current vertical pixel position
        self.size = 50                          # Box size in pixels

        # Maximum falling distance (recalculated dynamically)
        self.max_dist_pixels = random.randint(150, 400)

        # Constant speed in pixels per second
        self.speed_pps = random.uniform(150.0, 300.0)

        self.color = (
            random.randint(100, 255),
            random.randint(100, 255),
            random.randint(100, 255)
        )

    def update(self, dt, current_h):
        # Time‑based movement (dt in seconds)
        self.y_pixels += self.speed_pps * dt

        # Reset if reaching limit or bottom of screen
        if self.y_pixels >= self.max_dist_pixels or self.y_pixels >= current_h - self.size:
            self.y_pixels = 0.0
            self.max_dist_pixels = random.randint(150, int(current_h * 0.6))
            self.speed_pps = random.uniform(150.0, 300.0)

    def draw(self, surface, current_w):
        # X position scales with screen width
        pos_x = int(self.rel_x * current_w) - (self.size // 2)
        pos_y = int(self.y_pixels)

        # Guide line
        limit_y = int(self.max_dist_pixels)
        pygame.draw.line(surface, (70, 70, 90), (pos_x, limit_y), (pos_x + self.size, limit_y), 2)

        # Draw the box
        pygame.draw.rect(surface, self.color, (pos_x, pos_y, self.size, self.size))


# Create 4 falling boxes
boxes = [FallingBox(i / 5.0) for i in range(1, 5)]

running = True
while running:
    dt = clock.tick(60) / 1000.0  # Frame time in seconds

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Update screen size dynamically (rotation, resizing)
    info = pygame.display.Info()
    current_w, current_h = info.current_w, info.current_h

    # Update boxes
    for box in boxes:
        box.update(dt, current_h)

    # Render
    screen.fill((20, 20, 30))

    for box in boxes:
        box.draw(screen, current_w)

    pygame.display.flip()

pygame.quit()

duminică, 5 iulie 2026

PyGame : Real Situation in 2026 for Pygame and Pygame-CE.

Today 05072026, about these two python modules: pygame and pygame-ce, with my blogger chart all time :
pygame pygame-ce chart
Pygame (original)
As of 2026, the original Pygame project remains in a state of minimal maintenance. The last meaningful release was the Pygame 2.5.x series in 2023. After that point, development slowed significantly, and the updates released in 2024, 2025, and 2026 consist only of minor fixes and compatibility patches. These include micro-fixes for stability, adjustments for Python 3.12 and Python 3.13, and small SDL2-related patches. No new features have been introduced, no major optimizations have been added, and the API has not evolved. There is no Pygame 2.6 release, no new rendering improvements, and no integration of major SDL2 upgrades. In practical terms, Pygame is maintained only enough to remain functional on modern Python versions, but it is no longer actively expanded or modernized.
Pygame-CE (Community Edition)
Pygame-CE, the community-driven fork of Pygame, showed strong activity during 2023 and early 2024. The last significant release was Pygame-CE 2.5.1 in 2024. After that, development slowed dramatically. In 2025 and 2026, the project received only small fixes, minor corrections, and maintenance-level updates. There is no Pygame-CE 2.6 release, no new features, no rendering improvements, and no integration of newer SDL2 capabilities. The project effectively entered a low-activity phase, similar to the original Pygame. While Pygame-CE once aimed to modernize the ecosystem, by 2026 it has nearly stopped progressing, with no major roadmap or new technical direction.
Summary
By 2026, both Pygame and Pygame-CE have reached a point where they are stable but stagnant. They continue to function, but they do not evolve. Developers who require modern rendering, GPU acceleration, advanced features, or active development have largely moved to other libraries and engines. The Python game development ecosystem has shifted toward more modern solutions, while Pygame and Pygame-CE remain legacy tools suitable mainly for education, simple prototypes, or nostalgic projects.

duminică, 17 mai 2026

PyGame : simple example python script to toggle fullscreen mode.

Simple example with pygame window to switch on fullscren.
The program starts by initializing Pygame and creating a 640×480 window. It also prepares a font and draws a button on the screen that will be used to toggle fullscreen mode. A variable keeps track of whether the program is currently in fullscreen or windowed mode.
Inside the main loop, the program listens for events. If the user clicks the button or presses the F12 key, the program switches between fullscreen and windowed display modes by recreating the Pygame window with the appropriate settings.
Every frame, the screen is cleared, the button is drawn, and the instruction text "use button or F12 key to switch on fullscreen" is displayed.
The window updates continuously at 60 FPS, so the fullscreen toggle feels instant and smooth.
Let's see the source code.
import pygame
import sys

pygame.init()

# Dimensiuni fereastră
WIDTH, HEIGHT = 640, 480
windowed_size = (WIDTH, HEIGHT)

# Moduri de afișare
screen = pygame.display.set_mode(windowed_size)
pygame.display.set_caption("Fullscreen Toggle Example")

# Font
font = pygame.font.SysFont("Arial", 22)

# Buton fullscreen
button_rect = pygame.Rect(20, 20, 200, 50)

# Stare fullscreen
is_fullscreen = False


def toggle_fullscreen():
    global screen, is_fullscreen

    is_fullscreen = not is_fullscreen

    if is_fullscreen:
        screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
    else:
        screen = pygame.display.set_mode(windowed_size)


# Loop principal
clock = pygame.time.Clock()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

        # Click pe buton
        if event.type == pygame.MOUSEBUTTONDOWN:
            if button_rect.collidepoint(event.pos):
                toggle_fullscreen()

        # Tasta F12
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_F12:
                toggle_fullscreen()

    # Fundal
    screen.fill((30, 30, 30))

    # Desenare buton
    pygame.draw.rect(screen, (70, 130, 180), button_rect)
    btn_text = font.render("Toggle Fullscreen", True, (255, 255, 255))
    screen.blit(btn_text, (button_rect.x + 10, button_rect.y + 12))

    # Text instrucțiuni
    info_text = font.render("use button or F12 key to switch on fullscreen", True, (255, 255, 0))
    screen.blit(info_text, (20, HEIGHT - 40))

    pygame.display.flip()
    clock.tick(60)

luni, 6 aprilie 2026

PyGame-CE : First test example with pygame-ce-2.5.7

The biggest technical difference in version 2.5.7 is the expanded use of SIMD (Single Instruction, Multiple Data)
It utilizes modern CPU instructions like AVX2 (Intel/AMD) and NEON (ARM/Apple Silicon).
Pixel-level operations—such as blending, alpha-compositing, and surface scaling 30% to 100% faster than the original Pygame. If you are doing real-time lighting or heavy particle effects
Let's install with:
python -m pip install pygame-ce
WARNING: Ignoring invalid distribution ~adquery-ocp (C:\Python313_64bit\Lib\site-packages)
Collecting pygame-ce
  Downloading pygame_ce-2.5.7-cp313-cp313-win_amd64.whl.metadata (11 kB)
Downloading pygame_ce-2.5.7-cp313-cp313-win_amd64.whl (10.4 MB)
   ---------------------------------------- 10.4/10.4 MB 2.8 MB/s  0:00:03
WARNING: Ignoring invalid distribution ~adquery-ocp (C:\Python313_64bit\Lib\site-packages)
Installing collected packages: pygame-ce
WARNING: Ignoring invalid distribution ~adquery-ocp (C:\Python313_64bit\Lib\site-packages)
Successfully installed pygame-ce-2.5.7
python
Python 3.13.0 (tags/v3.13.0:60403a5, Oct  7 2024, 09:38:07) [MSC v.1941 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pygame
pygame-ce 2.5.7 (SDL 2.32.10, Python 3.13.0)
>>> print(pygame.version.ver)      # Should be 2.5.7
2.5.7
>>> print(pygame.version.vernum)   # Should show the CE suffix
2.5.7
Comparison Summary: Pygame-CE 2.5.7 vs. Legacy Pygame
Feature Pygame-CE 2.5.7 Legacy Pygame
Rendering Engine Highly optimized C-code with SIMD Basic SDL2 wrappers
OS Integration Full (System notifications, Dark Mode) Minimal
Updates Monthly (Active community) Yearly or less (Stagnant)
Math & Rects Modernized, faster collision logic Older, slower C implementation
Multi-threading Ready for Python 3.13+ "Free-thread" Limited by the GIL
Next python script demonstrates a real-time bridge between a graphical user interface and the operating system's memory by utilizing the Pygame-CE scrap module to exchange text data with the system clipboard via keyboard inputs.
import pygame

# 1. Initialize Pygame
pygame.init()

# 2. Create the window (CRITICAL: Scrap needs a window to talk to the OS)
screen = pygame.display.set_mode((600, 400))
pygame.display.set_caption(f"Pygame-CE 2.5.7 Scrap Fix")

# 3. Initialize scrap safely
try:
    pygame.scrap.init()
except Exception:
    # Some builds initialize this automatically with display.set_mode
    pass

font = pygame.font.SysFont("Arial", 22)
clipboard_text = "Press 'V' to paste"
status_message = "Found: pygame.scrap.get_text"

running = True
while running:
    screen.fill((30, 30, 30))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        
        if event.type == pygame.KEYDOWN:
            # COPY logic using scrap.put_text
            if event.key == pygame.K_c:
                msg = "Hello from Pygame-CE 2.5.7 Scrap!"
                try:
                    # Modern CE method for text
                    pygame.scrap.put_text(msg)
                    status_message = "Copied via scrap.put_text!"
                except AttributeError:
                    # Fallback for some 2.5.7 sub-builds
                    pygame.scrap.put(pygame.SCRAP_TEXT, msg.encode("utf-8"))
                    status_message = "Copied via scrap.put (fallback)!"
            
            # PASTE logic using scrap.get_text
            if event.key == pygame.K_v:
                # Based on your discovery, this IS the method
                txt = pygame.scrap.get_text()
                if txt:
                    # scrap.get_text() usually returns a string directly
                    clipboard_text = txt.replace('\x00', '') # Clean null bytes
                    status_message = "Pasted successfully!"
                else:
                    status_message = "Clipboard is empty."

    # Rendering
    surf_clip = font.render(f"Content: {clipboard_text}", True, (255, 255, 255))
    surf_stat = font.render(status_message, True, (0, 255, 0))
    screen.blit(surf_clip, (50, 150))
    screen.blit(surf_stat, (50, 250))
    
    pygame.display.flip()

pygame.quit()

joi, 22 ianuarie 2026

News : What is the difference between pygame and pygame-ce?

Python game development often begins with the popular pygame library. However, in recent years, a new alternative has emerged: pygame-ce (Community Edition). While both libraries share the same foundation, they differ significantly in development pace, features, and long-term vision.
  • pygame: The original library created in the early 2000s, widely used for 2D games.
  • pygame-ce: A community-driven fork created to modernize pygame and accelerate development.
  • pygame: Updates are infrequent and focus on stability rather than innovation.
  • pygame-ce: Receives frequent updates, bug fixes, and new features contributed by an active community.
  • Better performance: pygame-ce includes optimizations for rendering and event handling.
  • Improved math module: Enhanced Vector2 and Vector3 classes with additional methods.
  • Better timing and framerate control: More accurate clock behavior on modern systems.
  • Extended API: New helper functions and quality-of-life improvements not found in pygame.
  • pygame: May encounter issues on newer platforms such as macOS ARM (M1/M2).
  • pygame-ce: Designed to work smoothly on modern hardware, including ARM-based systems.
  • Better Windows support: pygame-ce fixes several long-standing Windows-specific bugs.
  • High compatibility: Most pygame projects run on pygame-ce without modification.
  • Backward-friendly: pygame-ce maintains the original API while adding optional improvements.
  • Future-proofing: pygame-ce is more likely to support new Python versions quickly.
  • Install pygame: pip install pygame
  • Install pygame-ce: pip install pygame-ce
  • pygame: Stable but slow-moving, with fewer contributors.
  • pygame-ce: Active community, open to new ideas, and focused on modernizing the ecosystem.
  • Future direction: pygame-ce aims to become the standard for new Python game projects.
  • Choose pygame-ce if you want modern features, better performance, and active development.
  • Choose pygame if you maintain older projects or prefer the original library.

sâmbătă, 3 ianuarie 2026

PyGame : conversion tool from shadertoy to shader pygame .

Today I tested a new tool that converts source code for shadertoy language into source code for pygame.
Shadertoy uses a permissive WebGL‑style GLSL ES shader language, while PyGame (through PyOpenGL) requires strict desktop GLSL 330 Core.
This is the result for this shadertoy example.

marți, 23 septembrie 2025

News : ... new pygame version 2.6.0 .

... seams pygame team development works and released a new version, see the GitHub project.

sâmbătă, 19 octombrie 2024

PyGame : 5by5 linux game project - part 001.

The game is about your brain skills to hack the code based on minimal information versus total information.
The code has 5 distinct letters.
  • click on the letters on the keypad
  • the number of guessed letters is displayed in the form: centered - guessed letters on positions and moved guessed letters but on other positions
I used agentpy python module and pygame python module
The game can be found on my fedora pagure account.

sâmbătă, 21 septembrie 2024

PyGame : 8in8 linux game project - part 001.

I started a game project with the python packages pygame and agentpy in the Fedora Linux distribution.
You can find it on my fedora pagure repo

duminică, 16 iunie 2024

PyGame : Game development in PyGame: making a basic map.

Example with PyGame with 3D features ...
The project can be found on the GitHub repo - stage 11 ...

sâmbătă, 30 martie 2024

PyGame : ... antialiased filled circle !

The pygame python module does not implement an antialiased filled circle and this is the scope of this tutorial.
The pygame module for drawing shapes are:
  • pygame.draw.rect - to draw a rectangle
  • pygame.draw.polygon - to draw a polygon
  • pygame.draw.circle - to draw a circle
  • pygame.draw.ellipse - to draw an ellipse
  • pygame.draw.arc - to draw an elliptical arc
  • pygame.draw.line - to draw a straight line
  • pygame.draw.lines - to draw multiple contiguous straight line segments
  • pygame.draw.aaline - to draw a straight antialiased line
  • pygame.draw.aalines - to draw multiple contiguous straight antialiased line segments.
Let's install pygame python module.
pip install pygame
Collecting pygame
  Downloading pygame-2.5.2-cp312-cp312-win_amd64.whl.metadata (13 kB)
...
Installing collected packages: pygame
Successfully installed pygame-2.5.2
Let's see the source code:
import pygame
import pygame.gfxdraw

TARGET_SIZE = 200
BG_ALPHA_COLOR = (0, 0, 0, 100)

class Target(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface((TARGET_SIZE, TARGET_SIZE), pygame.SRCALPHA)
        self.rect = self.image.get_rect()
        self.color = (255, 0, 0)
        self.filled = False
        self.width = 1

    def DrawTarget(self):
        pygame.gfxdraw.aacircle(self.image, int(self.rect.width/2), int(self.rect.height/2),\
                int(self.rect.width/2 - 1), self.color)
        
        pygame.gfxdraw.filled_ellipse(self.image, int(self.rect.width/2), \
            int(self.rect.height/2), int(self.rect.width/2 - 1), int(self.rect.width/2 - 1), self.color)
        
        temp = pygame.Surface((TARGET_SIZE, TARGET_SIZE), pygame.SRCALPHA)
        
        if not self.filled:
            pygame.gfxdraw.filled_ellipse(temp, int(self.rect.width/2), int(self.rect.height/2), \
                int(self.rect.width/2 - self.width), int(self.rect.width/2 - self.width), BG_ALPHA_COLOR)
            pygame.gfxdraw.aacircle(temp, int(self.rect.width/2), int(self.rect.height/2), \
                int(self.rect.width/2 - self.width), BG_ALPHA_COLOR)
        
        self.image.blit(temp, (0, 0), None, pygame.BLEND_ADD)
pygame.init()
screen = pygame.display.set_mode((400, 400))

target = Target()
target.DrawTarget()

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill((255, 255, 255))
    screen.blit(target.image, (100, 100))
    pygame.display.flip()

pygame.quit()

sâmbătă, 8 aprilie 2023

PyGame : ovoid with a random pattern.

Here's how to create an ovoid with a random pattern. Run the script several times to see the differences:
import pygame
import random
pygame.init()

# Set up the display window
screen_size = (400, 400)
screen = pygame.display.set_mode(screen_size)
# Set window title
pygame.display.set_caption("Ovoid with Random Pattern")
# Define the ovoid
ovoid_pos = (150, 100)
ovoid_size = (100, 200)

# Create the ovoid surface
ovoid_surface = pygame.Surface(ovoid_size, pygame.SRCALPHA)

# Define the pattern
pattern_size = (random.randint(1, 9), random.randint(1, 9))
pattern_surface = pygame.Surface(pattern_size)
pattern_surface.fill((255, 255, 255))
pygame.draw.line(pattern_surface, (0, 0, 0), (0, 0), pattern_size)

# Create the mask surface
mask_surface = pygame.Surface(ovoid_size, pygame.SRCALPHA)
pygame.draw.ellipse(mask_surface, (255, 255, 255), mask_surface.get_rect(), 0)

# Apply the pattern to the ovoid surface
for x in range(0, ovoid_size[0], pattern_size[0]):
    for y in range(0, ovoid_size[1], pattern_size[1]):
        ovoid_surface.blit(pattern_surface, (x, y))

# Apply the mask to the ovoid surface
ovoid_surface.blit(mask_surface, (0, 0), special_flags=pygame.BLEND_RGBA_MULT)

# Draw the ovoid to the screen
screen.blit(ovoid_surface, ovoid_pos)

# Update the display
pygame.display.flip()

# Wait for the user to close the window
done = False
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

# Quit pygame properly
pygame.quit()

vineri, 3 martie 2023

PyGame : simple web camera !

In this simple tutorial, I'll show you how to use pygame to use it with a webcam.
Let's install the pygame with the pip tool:
C:\PythonProjects\pygamecamera001>pip install pygame --user
Collecting pygame
  Downloading pygame-2.2.0-cp311-cp311-win_amd64.whl (10.4 MB)
     ---------------------------------------- 10.4/10.4 MB 9.0 MB/s eta 0:00:00
Installing collected packages: pygame
Successfully installed pygame-2.2.0
This is the source code for web camera:
import pygame.camera
import pygame.image
import sys

pygame.camera.init()

cameras = pygame.camera.list_cameras()

webcam = pygame.camera.Camera(cameras[0])

webcam.start()

img = webcam.get_image()

WIDTH = img.get_width()
HEIGHT = img.get_height()

screen = pygame.display.set_mode( ( WIDTH, HEIGHT ) )
pygame.display.set_caption("pyGame webcam")

while True :
    for e in pygame.event.get() :
        if e.type == pygame.QUIT :
            sys.exit()
    screen.blit(img, (0,0))
    pygame.display.flip()
    img = webcam.get_image()

luni, 2 ianuarie 2023

PyGame : simple digital clock.

This is the source code I used and is very simple.
import pygame
import time

# init the Pygame
pygame.init()

# this set the window size
window_size = (640, 100)

# this create the window
screen = pygame.display.set_mode(window_size)

# this set the title of the window
pygame.display.set_caption("Digital Clock")

# this fill the background color to white
screen.fill((255, 255, 255))

# settings for the font and size
font = pygame.font.Font(None, 36)

# the game loop area
running = True
while running:
# use an event to quit
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # get the current time
    current_time = time.strftime("%H:%M:%S")

    # render the time as text
    text = font.render(current_time, True, (0, 0, 0))

    # clear the screen
    screen.fill((255, 255, 255))

    # draw the text on the screen
    screen.blit(text, (10, 10))

    # update the screen
    pygame.display.flip()

# quit Pygame application
pygame.quit()
The result of the running source code is this:

marți, 22 februarie 2022

PyGame : Testing Pygame GUI - part 03.

In this article tutorial I show you how can create a progressbar and set it with value 76.
This example looks like this:
The source code is not very complicated and is very readable for any developer with minimal knowledge in the programming area.
import pygame
import pygame_gui

pygame.init()

pygame.display.set_caption('Quick Start')
window_surface = pygame.display.set_mode((640, 480))

background = pygame.Surface((640, 480))
background.fill(pygame.Color('#0076AB'))

manager = pygame_gui.UIManager((640, 480))

print(dir(pygame_gui.elements.UIProgressBar))
myProgressBar = pygame_gui.elements.UIProgressBar(relative_rect=pygame.Rect((50, 100), (300, 40)),
	visible= 1,
        manager=manager)
myProgressBar.set_current_progress(76)
clock = pygame.time.Clock()
is_running = True

while is_running:
    time_delta = clock.tick(60)/1000.0
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            is_running = False

        if event.type == pygame_gui.UI_BUTTON_PRESSED:
            if event.ui_element == hello_button:
                print('Hello World!')

        manager.process_events(event)

    manager.update(time_delta)

    window_surface.blit(background, (0, 0))
    manager.draw_ui(window_surface)

    pygame.display.update()

duminică, 20 februarie 2022

PyGame : Testing Pygame GUI - part 02.

I repeat, Pygame GUI is a module to help you make graphical user interfaces for games written in pygame.
In this short tutorial I will show you a source code that creates a HealthBar.
This example looks like this:
The source code is not very complicated and is very readable.
import pygame
import pygame_gui

pygame.init()

pygame.display.set_caption('Quick Start')
window_surface = pygame.display.set_mode((640, 480))

background = pygame.Surface((640, 480))
background.fill(pygame.Color('#0076AB'))

manager = pygame_gui.UIManager((640, 480))

HealthBar = pygame_gui.elements.UIScreenSpaceHealthBar(relative_rect=pygame.Rect((50, 100), (300, 40)),
	visible= 1,
        manager=manager)
clock = pygame.time.Clock()
is_running = True

while is_running:
    time_delta = clock.tick(60)/1000.0
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            is_running = False

        if event.type == pygame_gui.UI_BUTTON_PRESSED:
            if event.ui_element == hello_button:
                print('Hello World!')

        manager.process_events(event)

    manager.update(time_delta)

    window_surface.blit(background, (0, 0))
    manager.draw_ui(window_surface)

    pygame.display.update()

vineri, 11 februarie 2022

PyGame : Testing Pygame GUI - part 01.

Pygame GUI is a module to help you make graphical user interfaces for games written in pygame.
The module is firmly forward-looking and is designed to work on Pygame 2 and Python 3.
You can read more about these features for this python package on the official website.
This is a simple interface with python and python pygame and pygame_gui python packages.
You can see a simple example on my GitHub account.

duminică, 16 ianuarie 2022

PyGame : How to use Box2D python package - part 002.

I've written a tutorial in the past about the python package called box2d, see this tutorial.
Today I will be more precise and I will show you a source code related to 2D simulation.
I installed the python package in the Fedora 35 Linux distribution with the DNF tool:
[root@fedora mythcat]# dnf search pybox2d
...
python3-pybox2d.x86_64 : A 2D rigid body simulation library for Python
[root@fedora mythcat]# dnf install python3-pybox2d.x86_64
Last metadata expiration check: 0:18:37 ago on Sun 16 Jan 2022 10:15:43 AM EET.
Dependencies resolved.
...
Installed:
  python3-pybox2d-2.3.2-17.fc35.x86_64                                          

Complete!
I created the working folders and the first python file named example001.py:
[mythcat@fedora ~]$ mkdir PyGameProjects
[mythcat@fedora ~]$ cd PyGameProjects/
[mythcat@fedora PyGameProjects]$ touch example001.py
[mythcat@fedora PyGameProjects]$ vi example001.py
It contains a default source code:
from Box2D import (b2PolygonShape, b2World)
# create word 
world = b2World()  
# set the world 
groundBody = world.CreateStaticBody(position=(0, -10),
                                    shapes=b2PolygonShape(box=(50, 10)),
                                    )
# create a dynamic body at position
body = world.CreateDynamicBody(position=(0, 4))

# add and set a box fixture onto it with a nonzero density, so it will move
box = body.CreatePolygonFixture(box=(1, 1), density=1, friction=0.3)

# use a time step of 1/60 of a second
timeStep = 1.0 / 60

# simulation scenario with 6 velocity/2 position iterations
vel_iters, pos_iters = 6, 2

# the game loop.
for i in range(60):
    # use step of simulation
    world.Step(timeStep, vel_iters, pos_iters)

    # clear body forces even I didn't apply any forces
    world.ClearForces()

    # print the position and angle of the body.
    print(body.position, body.angle)
The result of the run looks like this:
...
b2Vec2(1.8719e-08,1.01496) 6.208252216310939e-06
b2Vec2(1.90152e-08,1.01497) 4.9494738050270826e-06
For a more complex example we created two python files.
One is a class for a box and a file that calls the class.
The first file contains the following source code is named box.py:
import pygame
from Box2D import (b2EdgeShape, b2FixtureDef, b2PolygonShape, b2_dynamicBody,
                   b2_kinematicBody, b2_staticBody, b2World)

class Box:
    def __init__(self, x, y, l, world):
        self.x = x / l
        self.y = y / l
        self.w = .2
        self.h = .2

        self.world = world
        self.attachment = self.world.CreateDynamicBody(
            position=(self.x, self.y),
            fixtures=b2FixtureDef(
                shape=b2PolygonShape(box=(self.w, self.h)), density=0.4, friction = 0.4),)
                
    def display(self, screen):
        for body in self.world.bodies:
            for fixture in body.fixtures:
                shape = fixture.shape
                vertices = [(body.transform * v) * 20 for v in shape.vertices]
                pygame.draw.polygon(screen, 'azure', vertices)
                pygame.draw.polygon(screen, 'blue', vertices,width=3)
The file calling the class has the following source code:
import pygame
from box import Box
from Box2D import b2World

l = 20
fps = 60
frame_rate = 1.0 / fps

pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Physics")
clock = pygame.time.Clock()

# A list for all of our rectangles
list_boxes = []
world = b2World(gravity=(0, 9.8), doSleep=False)

close = False

while not close:
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            close = True
    
    screen.fill('white')

    click, _, _ = pygame.mouse.get_pressed()    
    if click == 1:
        x,y = pygame.mouse.get_pos()
        box = Box(x, y, l, world)
        list_boxes.append(box)

    for box in list_boxes:
        box.display(screen)

    world.Step(frame_rate, 10, 10)
    pygame.display.flip()
    clock.tick(fps)

pygame.quit()
The result of running this file looks like this screenshot with some squares moving to the bottom:

duminică, 9 ianuarie 2022

PyGame : Pygame New Years Jams 2022.

I haven't written about this python package in a long time because I was busy with other solutions of everyday life, but here it should continue with new elements this year ...
If you want to create a simple game, make some graphics or learn very quickly the basics of programming, then I recommend python with pygame.
First of all, the syntax of the programming language is simple and allows you to focus on the programming side, and the implementation of the graphics is just as simple.
It seems that there are users and tendencies to bring to our attention the possibilities of this python package.
Since December 26, the well-known website itch.io come with Pygame New Years Jam.
All submissions was open from December 26th 2021 at 11:00 AM to January 2nd 2022 at 11:00 AM
I did not know this fact but you can find examples to download and test.
For this jam the submission is closed and voting is now in progress.
NOW same website comes with another Winter 2022.
You can find the rules on this webpage.
You may use any game engine to make your game and build for any platform you like, including mobile. For mobile, only APKs can be distributed on itch.io.
You can see more at this web page.