Pages

Se afișează postările cu eticheta modules. Afișați toate postările
Se afișează postările cu eticheta modules. 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)

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

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()

luni, 9 februarie 2009

About Pygame python module.

About PYGAME we can find out from web articles and we can get a picture of this python module:
Yet another powerful open source 2D game engine. Pygame is a set of modules allows you to create fully featured games and multimedia programs in the python language. Pygame is portable and runs on every platform and operating system.
Pygame is free. Released under the LGPL license, you can create an open source, free, freeware, shareware, and commercial games with it. See the license for full details.

The Python PyGame module is easy to use in both procedural and object programming.
The installation process is easy:
pip install pygame
The official web page can be found here.
The Wikipedia page with info about this python module can be found here.
The pypi webpage can be found here.
All documentation can be found on this webpage.