bro
No files matched your search
@@ -1,145 +1,154 @@
|
||||
These examples should help get you started with pygame. Here is a
|
||||
brief rundown of what you get. The source code for all examples
|
||||
is in the public domain. Feel free to use for your own projects.
|
||||
These examples are a good introduction to various Pygame modules and
|
||||
techniques. They are beginner-friendly with source code in the public
|
||||
domain that can be adapted for your projects.
|
||||
|
||||
|
||||
aacircles.py
|
||||
An example of using the gfxdraw module to drawing anti-aliased circles.
|
||||
|
||||
aliens.py
|
||||
This started off as a port of the SDL demonstration, Aliens.
|
||||
Now it has evolved into something sort of resembling fun.
|
||||
This demonstrates a lot of different uses of sprites and
|
||||
optimized blitting. Also transparency, colorkeys, fonts, sound,
|
||||
music, joystick, and more. (PS, my high score is 117! goodluck)
|
||||
An arcade-style space shooter game that showcases various common and
|
||||
important Pygame modules and techniques.
|
||||
|
||||
arraydemo.py
|
||||
Another example filled with various surfarray effects.
|
||||
It requires the surfarray and image modules to be installed.
|
||||
This little demo can also make a good starting point for any of
|
||||
your own tests with surfarray
|
||||
Showcases the use of Numpy with Pygame to perform efficient
|
||||
pixel manipulation.
|
||||
|
||||
audiocapture.py
|
||||
Record sound from a microphone, and play back the recorded sound.
|
||||
Use the mixer module to record sound from a microphone, and
|
||||
play back the recorded sound.
|
||||
|
||||
blend_fill.py
|
||||
BLEND_ing colors in different ways with Surface.fill().
|
||||
Demonstrates how to perform surface blending and filling
|
||||
with Pygame.
|
||||
|
||||
blit_blends.py
|
||||
BLEND_ing colors Surface.blit().
|
||||
Uses blit functions to showcase some of Pygame's different
|
||||
blending modes.
|
||||
|
||||
camera.py
|
||||
Basic image capturing and display using pygame.camera
|
||||
|
||||
chimp.py
|
||||
A simple game featuring a chimp that showcases the use of
|
||||
common and important Pygame modules and techniques.
|
||||
|
||||
cursors.py
|
||||
Make custom cursors :)
|
||||
Demonstrates the creation of custom cursors with Pygame.
|
||||
|
||||
dropevent.py
|
||||
Drag and drop files. Using the following events.
|
||||
Drag and drop files using the following events:
|
||||
DROPBEGIN, DROPCOMPLETE, DROPTEXT, DROPFILE
|
||||
|
||||
eventlist.py
|
||||
Learn about pygame events and input.
|
||||
Watch the events fly by. Click the mouse, and see the mouse
|
||||
event come up. Press a keyboard key, and see the key up event.
|
||||
A utility for displaying and logging real-time Pygame events,
|
||||
useful for debugging.
|
||||
|
||||
font_viewer.py
|
||||
Display all available fonts in a scrolling window.
|
||||
Demonstrates how to display all available fonts in a
|
||||
scrolling window.
|
||||
|
||||
fonty.py
|
||||
Super quick, super simple application demonstrating
|
||||
the different ways to render fonts with the font module
|
||||
A simple application demonstrating the different ways
|
||||
to render fonts with the font module
|
||||
|
||||
freetype_misc.py
|
||||
FreeType is a world famous font project.
|
||||
Shows how to use the freetype module to perform font
|
||||
rendering and manipulation.
|
||||
|
||||
glcube.py
|
||||
Using PyOpenGL and Pygame, this creates a spinning 3D multicolored cube.
|
||||
|
||||
go_over_there.py
|
||||
Demonstrates Vector.move_towards.
|
||||
Demonstrates the important Vector.move_towards() function.
|
||||
|
||||
grid.py
|
||||
A simple example of grid-based movement.
|
||||
|
||||
headless_no_windows_needed.py
|
||||
For using pygame in scripts.
|
||||
Shows how to run Pygame in scripts.
|
||||
|
||||
joystick.py
|
||||
Shows how to integrate joysticks or game controllers into Pygame.
|
||||
|
||||
liquid.py
|
||||
This example was created in a quick comparison with the
|
||||
BlitzBasic gaming language. Nonetheless, it demonstrates a quick
|
||||
8-bit setup (with colormap).
|
||||
Demonstrates how to create a simple liquid effect in an image.
|
||||
|
||||
mask.py
|
||||
Single bit pixel manipulation. Fast for collision detection,
|
||||
and also good for computer vision.
|
||||
Showcases how to use masks for collision detection and sprite
|
||||
interaction.
|
||||
|
||||
midi.py
|
||||
For connecting pygame to musical equipment.
|
||||
Demonstrates how to use MIDI I/O using the midi module.
|
||||
|
||||
moveit.py
|
||||
A very simple example of moving stuff.
|
||||
Illustrates how to accomplish sprite movement and animation.
|
||||
|
||||
music_drop_fade.py
|
||||
Fade in and play music from a list while observing
|
||||
several events. Uses fade_ms added in pygame2, as well as set_endevent,
|
||||
set_volume, drag and drop events, and the scrap module.
|
||||
|
||||
ninepatch.py
|
||||
Demonstrate the purpose of the 9-patch scale method and a way to implement it.
|
||||
Showcases dropping music files into Pygame, and how to
|
||||
apply a fade effect to music playback.
|
||||
|
||||
pixelarray.py
|
||||
Process whole arrays of pixels at a time.
|
||||
Like numpy, but for pixels, and also built into pygame.
|
||||
Manipulation of individual pixels using the PixelArray module.
|
||||
|
||||
playmus.py
|
||||
Simple music playing example.
|
||||
Uses the mixer module to play music files with CLI.
|
||||
|
||||
prevent_display_stretching.py
|
||||
A windows specific example.
|
||||
Illustrates how to maintain aspect ratio when resizing a window
|
||||
in Pygame.
|
||||
|
||||
resizing_new.py
|
||||
Showcases various window resizing events and how to fit graphics
|
||||
to new dimensions.
|
||||
|
||||
scaletest.py
|
||||
Showing how to scale Surfaces.
|
||||
Showcases the scaling of Surfaces.
|
||||
|
||||
scrap_clipboard.py
|
||||
A simple demonstration example for the clipboard support.
|
||||
Shows how to implement clipboard interaction with Pygame's scrap module.
|
||||
|
||||
scroll.py
|
||||
An example that implements smooth scrolling backgrounds for side-scrolling
|
||||
games or parallax effects.
|
||||
|
||||
setmodescale.py
|
||||
SCALED allows you to work in 320x200 and have it show up big.
|
||||
It handles mouse scaling and selection of a good sized window depending
|
||||
Handles mouse scaling and selection of a good sized window depending
|
||||
on the display.
|
||||
|
||||
sound.py
|
||||
Extremely basic testing of the mixer module. Load a
|
||||
sound and play it. All from the command shell, no graphics.
|
||||
Illustrates how to implement sound effects and music using Pygame.
|
||||
|
||||
sound_array_demos.py
|
||||
Echo, delay and other array based processing of sounds.
|
||||
Showcases echo, delay and other array based processing of sounds.
|
||||
|
||||
sprite_texture.py
|
||||
Shows how to use hardware Image Textures with pygame.sprite.
|
||||
Demonstrates how to use textured sprites in Pygame.
|
||||
|
||||
stars.py
|
||||
A simple starfield example. You can change the center of
|
||||
perspective by leftclicking the mouse on the screen.
|
||||
A simple starfield implementation in which the perspective can be
|
||||
changed by a mouse click.
|
||||
|
||||
testsprite.py
|
||||
More of a test example. If you're interested in how to use sprites,
|
||||
then check out the aliens.py example instead.
|
||||
Showcases the basics of sprite handling, namely collision
|
||||
detection and animation.
|
||||
|
||||
textinput.py
|
||||
A little "console" where you can write in text.
|
||||
Shows how to use the TEXTEDITING and TEXTINPUT events.
|
||||
|
||||
vgrade.py
|
||||
Demonstrates creating a vertical gradient with
|
||||
Numpy. The app will create a new gradient every half
|
||||
second and report the time needed to create and display the
|
||||
image. If you're not prepared to start working with the
|
||||
Numpy arrays, don't worry about the source for this one :]
|
||||
Shows how to apply vertical gradients to surfaces using Pygame.
|
||||
|
||||
video.py
|
||||
It explores some new video APIs in pygame 2.
|
||||
Including multiple windows, Textures, and such.
|
||||
Showcases the movie module, including the display of playback
|
||||
controls.
|
||||
|
||||
data/
|
||||
Directory with the resources for the examples.
|
||||
|
||||
There's LOTS of examples on the pygame website, and on places like github.
|
||||
|
||||
We're always on the lookout for more examples and/or example
|
||||
requests. Code like this is probably the best way to start
|
||||
getting involved with Python gaming.
|
||||
More examples can be found on the Pygame website and GitHub.
|
||||
We're always looking for new examples and/or example requests. Examining
|
||||
code such as this is a great way to get started with Python-based
|
||||
game development.
|
||||
@@ -10,7 +10,7 @@ def main():
|
||||
pygame.init()
|
||||
screen = pygame.display.set_mode((500, 500))
|
||||
screen.fill((255, 0, 0))
|
||||
s = pygame.Surface(screen.get_size(), pygame.SRCALPHA)
|
||||
s = pygame.Surface(screen.get_size(), pygame.SRCALPHA, 32)
|
||||
pygame.draw.line(s, (0, 0, 0), (250, 250), (250 + 200, 250))
|
||||
|
||||
width = 1
|
||||
@@ -23,23 +23,18 @@ def main():
|
||||
pygame.draw.circle(screen, "green", (50, 100), 10)
|
||||
pygame.draw.circle(screen, "black", (50, 100), 10, 1)
|
||||
|
||||
running = True
|
||||
|
||||
clock = pygame.Clock()
|
||||
|
||||
while running:
|
||||
clock.tick(10)
|
||||
|
||||
for event in pygame.event.get():
|
||||
pygame.display.flip()
|
||||
try:
|
||||
while True:
|
||||
event = pygame.event.wait()
|
||||
if event.type == pygame.QUIT:
|
||||
running = False
|
||||
elif event.type == pygame.KEYDOWN:
|
||||
if event.key == pygame.K_q:
|
||||
running = False
|
||||
|
||||
pygame.display.flip()
|
||||
|
||||
pygame.quit()
|
||||
break
|
||||
if event.type == pygame.KEYDOWN:
|
||||
if event.key == pygame.K_ESCAPE or event.unicode == "q":
|
||||
break
|
||||
pygame.display.flip()
|
||||
finally:
|
||||
pygame.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.aliens
|
||||
""" pygame.examples.aliens
|
||||
|
||||
Shows a mini game where you have to defend against aliens.
|
||||
|
||||
What does it show you about pygame?
|
||||
|
||||
* pygame.sprite, the difference between Sprite and Group.
|
||||
* pg.sprite, the difference between Sprite and Group.
|
||||
* dirty rectangle optimization for processing for speed.
|
||||
* music with pygame.mixer.music, including fadeout
|
||||
* sound effects with pygame.Sound
|
||||
* music with pg.mixer.music, including fadeout
|
||||
* sound effects with pg.Sound
|
||||
* event processing, keyboard handling, QUIT handling.
|
||||
* a main loop frame limited with a game clock from the pygame.time module
|
||||
* a main loop frame limited with a game clock from pg.time.Clock
|
||||
* fullscreen switching.
|
||||
|
||||
|
||||
@@ -18,19 +18,20 @@ Controls
|
||||
--------
|
||||
|
||||
* Left and right arrows to move.
|
||||
* Space bar to shoot.
|
||||
* Space bar to shoot
|
||||
* f key to toggle between fullscreen.
|
||||
|
||||
"""
|
||||
|
||||
import os
|
||||
import random
|
||||
from typing import List
|
||||
|
||||
# import basic pygame modules
|
||||
import pygame
|
||||
import pygame as pg
|
||||
|
||||
# see if we can load more than standard BMP
|
||||
if not pygame.image.get_extended():
|
||||
if not pg.image.get_extended():
|
||||
raise SystemExit("Sorry, extended image module required")
|
||||
|
||||
|
||||
@@ -39,7 +40,7 @@ MAX_SHOTS = 2 # most player bullets onscreen
|
||||
ALIEN_ODDS = 22 # chances a new alien appears
|
||||
BOMB_ODDS = 60 # chances a new bomb will drop
|
||||
ALIEN_RELOAD = 12 # frames between new aliens
|
||||
SCREENRECT = pygame.Rect(0, 0, 640, 480)
|
||||
SCREENRECT = pg.Rect(0, 0, 640, 480)
|
||||
SCORE = 0
|
||||
|
||||
main_dir = os.path.split(os.path.abspath(__file__))[0]
|
||||
@@ -49,21 +50,21 @@ def load_image(file):
|
||||
"""loads an image, prepares it for play"""
|
||||
file = os.path.join(main_dir, "data", file)
|
||||
try:
|
||||
surface = pygame.image.load(file)
|
||||
except pygame.error:
|
||||
raise SystemExit(f'Could not load image "{file}" {pygame.get_error()}')
|
||||
surface = pg.image.load(file)
|
||||
except pg.error:
|
||||
raise SystemExit(f'Could not load image "{file}" {pg.get_error()}')
|
||||
return surface.convert()
|
||||
|
||||
|
||||
def load_sound(file):
|
||||
"""because pygame can be compiled without mixer."""
|
||||
if not pygame.mixer:
|
||||
if not pg.mixer:
|
||||
return None
|
||||
file = os.path.join(main_dir, "data", file)
|
||||
try:
|
||||
sound = pygame.mixer.Sound(file)
|
||||
sound = pg.mixer.Sound(file)
|
||||
return sound
|
||||
except pygame.error:
|
||||
except pg.error:
|
||||
print(f"Warning, unable to load, {file}")
|
||||
return None
|
||||
|
||||
@@ -76,20 +77,19 @@ def load_sound(file):
|
||||
# since it is passed extra information about the keyboard.
|
||||
|
||||
|
||||
class Player(pygame.sprite.Sprite):
|
||||
class Player(pg.sprite.Sprite):
|
||||
"""Representing the player as a moon buggy type car."""
|
||||
|
||||
speed = 10
|
||||
bounce = 24
|
||||
gun_offset = -11
|
||||
images = []
|
||||
containers = None
|
||||
images: List[pg.Surface] = []
|
||||
|
||||
def __init__(self):
|
||||
super().__init__(self.containers)
|
||||
def __init__(self, *groups):
|
||||
pg.sprite.Sprite.__init__(self, *groups)
|
||||
self.image = self.images[0]
|
||||
self.rect = self.image.get_rect(midbottom=SCREENRECT.midbottom)
|
||||
self.reloading = False
|
||||
self.reloading = 0
|
||||
self.origtop = self.rect.top
|
||||
self.facing = -1
|
||||
|
||||
@@ -109,16 +109,15 @@ class Player(pygame.sprite.Sprite):
|
||||
return pos, self.rect.top
|
||||
|
||||
|
||||
class Alien(pygame.sprite.Sprite):
|
||||
class Alien(pg.sprite.Sprite):
|
||||
"""An alien space ship. That slowly moves down the screen."""
|
||||
|
||||
speed = 13
|
||||
animcycle = 12
|
||||
images = []
|
||||
containers = None
|
||||
images: List[pg.Surface] = []
|
||||
|
||||
def __init__(self):
|
||||
pygame.sprite.Sprite.__init__(self, self.containers)
|
||||
def __init__(self, *groups):
|
||||
pg.sprite.Sprite.__init__(self, *groups)
|
||||
self.image = self.images[0]
|
||||
self.rect = self.image.get_rect()
|
||||
self.facing = random.choice((-1, 1)) * Alien.speed
|
||||
@@ -126,7 +125,7 @@ class Alien(pygame.sprite.Sprite):
|
||||
if self.facing < 0:
|
||||
self.rect.right = SCREENRECT.right
|
||||
|
||||
def update(self):
|
||||
def update(self, *args, **kwargs):
|
||||
self.rect.move_ip(self.facing, 0)
|
||||
if not SCREENRECT.contains(self.rect):
|
||||
self.facing = -self.facing
|
||||
@@ -136,21 +135,20 @@ class Alien(pygame.sprite.Sprite):
|
||||
self.image = self.images[self.frame // self.animcycle % 3]
|
||||
|
||||
|
||||
class Explosion(pygame.sprite.Sprite):
|
||||
class Explosion(pg.sprite.Sprite):
|
||||
"""An explosion. Hopefully the Alien and not the player!"""
|
||||
|
||||
defaultlife = 12
|
||||
animcycle = 3
|
||||
images = []
|
||||
containers = None
|
||||
images: List[pg.Surface] = []
|
||||
|
||||
def __init__(self, actor):
|
||||
pygame.sprite.Sprite.__init__(self, self.containers)
|
||||
def __init__(self, actor, *groups):
|
||||
pg.sprite.Sprite.__init__(self, *groups)
|
||||
self.image = self.images[0]
|
||||
self.rect = self.image.get_rect(center=actor.rect.center)
|
||||
self.life = self.defaultlife
|
||||
|
||||
def update(self):
|
||||
def update(self, *args, **kwargs):
|
||||
"""called every time around the game loop.
|
||||
|
||||
Show the explosion surface for 'defaultlife'.
|
||||
@@ -164,19 +162,18 @@ class Explosion(pygame.sprite.Sprite):
|
||||
self.kill()
|
||||
|
||||
|
||||
class Shot(pygame.sprite.Sprite):
|
||||
class Shot(pg.sprite.Sprite):
|
||||
"""a bullet the Player sprite fires."""
|
||||
|
||||
speed = -11
|
||||
images = []
|
||||
containers = None
|
||||
images: List[pg.Surface] = []
|
||||
|
||||
def __init__(self, pos):
|
||||
pygame.sprite.Sprite.__init__(self, self.containers)
|
||||
def __init__(self, pos, *groups):
|
||||
pg.sprite.Sprite.__init__(self, *groups)
|
||||
self.image = self.images[0]
|
||||
self.rect = self.image.get_rect(midbottom=pos)
|
||||
|
||||
def update(self):
|
||||
def update(self, *args, **kwargs):
|
||||
"""called every time around the game loop.
|
||||
|
||||
Every tick we move the shot upwards.
|
||||
@@ -186,19 +183,19 @@ class Shot(pygame.sprite.Sprite):
|
||||
self.kill()
|
||||
|
||||
|
||||
class Bomb(pygame.sprite.Sprite):
|
||||
class Bomb(pg.sprite.Sprite):
|
||||
"""A bomb the aliens drop."""
|
||||
|
||||
speed = 9
|
||||
images = []
|
||||
containers = None
|
||||
images: List[pg.Surface] = []
|
||||
|
||||
def __init__(self, alien):
|
||||
pygame.sprite.Sprite.__init__(self, self.containers)
|
||||
def __init__(self, alien, explosion_group, *groups):
|
||||
pg.sprite.Sprite.__init__(self, *groups)
|
||||
self.image = self.images[0]
|
||||
self.rect = self.image.get_rect(midbottom=alien.rect.move(0, 5).midbottom)
|
||||
self.explosion_group = explosion_group
|
||||
|
||||
def update(self):
|
||||
def update(self, *args, **kwargs):
|
||||
"""called every time around the game loop.
|
||||
|
||||
Every frame we move the sprite 'rect' down.
|
||||
@@ -209,141 +206,139 @@ class Bomb(pygame.sprite.Sprite):
|
||||
"""
|
||||
self.rect.move_ip(0, self.speed)
|
||||
if self.rect.bottom >= 470:
|
||||
Explosion(self)
|
||||
Explosion(self, self.explosion_group)
|
||||
self.kill()
|
||||
|
||||
|
||||
class Score(pygame.sprite.Sprite):
|
||||
class Score(pg.sprite.Sprite):
|
||||
"""to keep track of the score."""
|
||||
|
||||
def __init__(self):
|
||||
pygame.sprite.Sprite.__init__(self)
|
||||
self.font = pygame.Font(None, 20)
|
||||
self.font.set_italic(True)
|
||||
def __init__(self, *groups):
|
||||
pg.sprite.Sprite.__init__(self, *groups)
|
||||
self.font = pg.font.Font(None, 20)
|
||||
self.font.set_italic(1)
|
||||
self.color = "white"
|
||||
self.lastscore = -1
|
||||
self.update()
|
||||
self.rect = self.image.get_rect().move(10, 450)
|
||||
|
||||
def update(self):
|
||||
def update(self, *args, **kwargs):
|
||||
"""We only update the score in update() when it has changed."""
|
||||
if SCORE != self.lastscore:
|
||||
self.lastscore = SCORE
|
||||
msg = "Score: %d" % SCORE
|
||||
self.image = self.font.render(msg, False, self.color)
|
||||
msg = f"Score: {SCORE}"
|
||||
self.image = self.font.render(msg, 0, self.color)
|
||||
|
||||
|
||||
def main():
|
||||
def main(winstyle=0):
|
||||
# Initialize pygame
|
||||
pygame.mixer.pre_init(44100, 32, 2, 1024)
|
||||
pygame.init()
|
||||
if pygame.mixer and not pygame.mixer.get_init():
|
||||
if pg.get_sdl_version()[0] == 2:
|
||||
pg.mixer.pre_init(44100, 32, 2, 1024)
|
||||
pg.init()
|
||||
if pg.mixer and not pg.mixer.get_init():
|
||||
print("Warning, no sound")
|
||||
pygame.mixer = None
|
||||
pg.mixer = None
|
||||
|
||||
fullscreen = False
|
||||
# Set the display mode
|
||||
winstyle = 0 # |FULLSCREEN
|
||||
screen = pygame.display.set_mode(SCREENRECT.size, winstyle)
|
||||
bestdepth = pg.display.mode_ok(SCREENRECT.size, winstyle, 32)
|
||||
screen = pg.display.set_mode(SCREENRECT.size, winstyle, bestdepth)
|
||||
|
||||
# Load images, assign to sprite classes
|
||||
# (do this before the classes are used, after screen setup)
|
||||
img = load_image("player1.gif")
|
||||
Player.images = [img, pygame.transform.flip(img, True, False)]
|
||||
Player.images = [img, pg.transform.flip(img, 1, 0)]
|
||||
img = load_image("explosion1.gif")
|
||||
Explosion.images = [img, pygame.transform.flip(img, True, True)]
|
||||
Explosion.images = [img, pg.transform.flip(img, 1, 1)]
|
||||
Alien.images = [load_image(im) for im in ("alien1.gif", "alien2.gif", "alien3.gif")]
|
||||
Bomb.images = [load_image("bomb.gif")]
|
||||
Shot.images = [load_image("shot.gif")]
|
||||
|
||||
# decorate the game window
|
||||
icon = pygame.transform.scale(Alien.images[0], (32, 32))
|
||||
pygame.display.set_icon(icon)
|
||||
pygame.display.set_caption("Pygame Aliens")
|
||||
pygame.mouse.set_visible(False)
|
||||
icon = pg.transform.scale(Alien.images[0], (32, 32))
|
||||
pg.display.set_icon(icon)
|
||||
pg.display.set_caption("Pygame Aliens")
|
||||
pg.mouse.set_visible(0)
|
||||
|
||||
# create the background, tile the bgd image
|
||||
bgdtile = load_image("background.gif")
|
||||
background = pygame.Surface(SCREENRECT.size)
|
||||
background = pg.Surface(SCREENRECT.size)
|
||||
for x in range(0, SCREENRECT.width, bgdtile.get_width()):
|
||||
background.blit(bgdtile, (x, 0))
|
||||
pygame.display.flip()
|
||||
screen.blit(background, (0, 0))
|
||||
pg.display.flip()
|
||||
|
||||
# load the sound effects
|
||||
boom_sound = load_sound("boom.wav")
|
||||
shoot_sound = load_sound("car_door.wav")
|
||||
if pygame.mixer:
|
||||
if pg.mixer:
|
||||
music = os.path.join(main_dir, "data", "house_lo.wav")
|
||||
pygame.mixer.music.load(music)
|
||||
pygame.mixer.music.play(-1)
|
||||
pg.mixer.music.load(music)
|
||||
pg.mixer.music.play(-1)
|
||||
|
||||
# Initialize Game Groups
|
||||
aliens = pygame.sprite.Group()
|
||||
shots = pygame.sprite.Group()
|
||||
bombs = pygame.sprite.Group()
|
||||
all_sprites = pygame.sprite.Group()
|
||||
lastalien = pygame.sprite.GroupSingle()
|
||||
|
||||
# assign default groups to each sprite class
|
||||
Player.containers = all_sprites
|
||||
Alien.containers = aliens, all_sprites, lastalien
|
||||
Shot.containers = shots, all_sprites
|
||||
Bomb.containers = bombs, all_sprites
|
||||
Explosion.containers = all_sprites
|
||||
Score.containers = all_sprites
|
||||
aliens = pg.sprite.Group()
|
||||
shots = pg.sprite.Group()
|
||||
bombs = pg.sprite.Group()
|
||||
all = pg.sprite.RenderUpdates()
|
||||
lastalien = pg.sprite.GroupSingle()
|
||||
|
||||
# Create Some Starting Values
|
||||
alienreload = ALIEN_RELOAD
|
||||
clock = pygame.Clock()
|
||||
clock = pg.time.Clock()
|
||||
|
||||
# initialize our starting sprites
|
||||
global SCORE
|
||||
player = Player()
|
||||
Alien() # note, this 'lives' because it goes into a sprite group
|
||||
if pygame.font:
|
||||
all_sprites.add(Score())
|
||||
player = Player(all)
|
||||
Alien(
|
||||
aliens, all, lastalien
|
||||
) # note, this 'lives' because it goes into a sprite group
|
||||
if pg.font:
|
||||
all.add(Score(all))
|
||||
|
||||
# Run our main loop whilst the player is alive.
|
||||
while player.alive():
|
||||
# Erase last frame by blitting the background to the screen
|
||||
screen.blit(background, (0, 0))
|
||||
|
||||
# get input
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
for event in pg.event.get():
|
||||
if event.type == pg.QUIT:
|
||||
return
|
||||
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
|
||||
if event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE:
|
||||
return
|
||||
elif event.type == pygame.KEYDOWN:
|
||||
if event.key == pygame.K_f:
|
||||
if event.type == pg.KEYDOWN:
|
||||
if event.key == pg.K_f:
|
||||
if not fullscreen:
|
||||
print("Changing to FULLSCREEN")
|
||||
screen_backup = screen.copy()
|
||||
screen = pygame.display.set_mode(
|
||||
SCREENRECT.size,
|
||||
winstyle | pygame.FULLSCREEN | pygame.SCALED,
|
||||
screen = pg.display.set_mode(
|
||||
SCREENRECT.size, winstyle | pg.FULLSCREEN, bestdepth
|
||||
)
|
||||
screen.blit(screen_backup, (0, 0))
|
||||
else:
|
||||
print("Changing to windowed mode")
|
||||
screen_backup = screen.copy()
|
||||
screen = pygame.display.set_mode(SCREENRECT.size, winstyle)
|
||||
screen = pg.display.set_mode(
|
||||
SCREENRECT.size, winstyle, bestdepth
|
||||
)
|
||||
screen.blit(screen_backup, (0, 0))
|
||||
pygame.display.flip()
|
||||
pg.display.flip()
|
||||
fullscreen = not fullscreen
|
||||
|
||||
keystate = pygame.key.get_pressed()
|
||||
keystate = pg.key.get_pressed()
|
||||
|
||||
# clear/erase the last drawn sprites
|
||||
all.clear(screen, background)
|
||||
|
||||
# update all the sprites
|
||||
all_sprites.update()
|
||||
all.update()
|
||||
|
||||
# handle player input
|
||||
direction = keystate[pygame.K_RIGHT] - keystate[pygame.K_LEFT]
|
||||
direction = keystate[pg.K_RIGHT] - keystate[pg.K_LEFT]
|
||||
player.move(direction)
|
||||
firing = keystate[pygame.K_SPACE]
|
||||
firing = keystate[pg.K_SPACE]
|
||||
if not player.reloading and firing and len(shots) < MAX_SHOTS:
|
||||
Shot(player.gunpos())
|
||||
if pygame.mixer:
|
||||
Shot(player.gunpos(), shots, all)
|
||||
if pg.mixer and shoot_sound is not None:
|
||||
shoot_sound.play()
|
||||
player.reloading = firing
|
||||
|
||||
@@ -351,50 +346,50 @@ def main():
|
||||
if alienreload:
|
||||
alienreload = alienreload - 1
|
||||
elif not int(random.random() * ALIEN_ODDS):
|
||||
Alien()
|
||||
Alien(aliens, all, lastalien)
|
||||
alienreload = ALIEN_RELOAD
|
||||
|
||||
# Drop bombs
|
||||
if lastalien and not int(random.random() * BOMB_ODDS):
|
||||
Bomb(lastalien.sprite)
|
||||
Bomb(lastalien.sprite, all, bombs, all)
|
||||
|
||||
# Detect collisions between aliens and players.
|
||||
for alien in pygame.sprite.spritecollide(player, aliens, True):
|
||||
if pygame.mixer:
|
||||
for alien in pg.sprite.spritecollide(player, aliens, 1):
|
||||
if pg.mixer and boom_sound is not None:
|
||||
boom_sound.play()
|
||||
Explosion(alien)
|
||||
Explosion(player)
|
||||
Explosion(alien, all)
|
||||
Explosion(player, all)
|
||||
SCORE = SCORE + 1
|
||||
player.kill()
|
||||
|
||||
# See if shots hit the aliens.
|
||||
for alien in pygame.sprite.groupcollide(aliens, shots, True, True).keys():
|
||||
if pygame.mixer:
|
||||
for alien in pg.sprite.groupcollide(aliens, shots, 1, 1).keys():
|
||||
if pg.mixer and boom_sound is not None:
|
||||
boom_sound.play()
|
||||
Explosion(alien)
|
||||
Explosion(alien, all)
|
||||
SCORE = SCORE + 1
|
||||
|
||||
# See if alien bombs hit the player.
|
||||
for bomb in pygame.sprite.spritecollide(player, bombs, True):
|
||||
if pygame.mixer:
|
||||
for bomb in pg.sprite.spritecollide(player, bombs, 1):
|
||||
if pg.mixer and boom_sound is not None:
|
||||
boom_sound.play()
|
||||
Explosion(player)
|
||||
Explosion(bomb)
|
||||
Explosion(player, all)
|
||||
Explosion(bomb, all)
|
||||
player.kill()
|
||||
|
||||
# draw the scene
|
||||
all_sprites.draw(screen)
|
||||
pygame.display.flip()
|
||||
dirty = all.draw(screen)
|
||||
pg.display.update(dirty)
|
||||
|
||||
# cap the framerate at 40fps. Also called 40HZ or 40 times per second.
|
||||
clock.tick(40)
|
||||
|
||||
if pygame.mixer:
|
||||
pygame.mixer.music.fadeout(1000)
|
||||
pygame.time.wait(1000)
|
||||
if pg.mixer:
|
||||
pg.mixer.music.fadeout(1000)
|
||||
pg.time.wait(1000)
|
||||
|
||||
|
||||
# call the "main" function if running this script
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
pygame.quit()
|
||||
pg.quit()
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.arraydemo
|
||||
""" pygame.examples.arraydemo
|
||||
|
||||
Welcome to the arraydemo!
|
||||
|
||||
@@ -16,7 +16,7 @@ This demo will show you a few things:
|
||||
|
||||
import os
|
||||
|
||||
import pygame
|
||||
import pygame as pg
|
||||
from pygame import surfarray
|
||||
|
||||
main_dir = os.path.split(os.path.abspath(__file__))[0]
|
||||
@@ -24,19 +24,19 @@ main_dir = os.path.split(os.path.abspath(__file__))[0]
|
||||
|
||||
def surfdemo_show(array_img, name):
|
||||
"displays a surface, waits for user to continue"
|
||||
screen = pygame.display.set_mode(array_img.shape[:2])
|
||||
screen = pg.display.set_mode(array_img.shape[:2], 0, 32)
|
||||
surfarray.blit_array(screen, array_img)
|
||||
pygame.display.flip()
|
||||
pygame.display.set_caption(name)
|
||||
pg.display.flip()
|
||||
pg.display.set_caption(name)
|
||||
while True:
|
||||
e = pygame.event.wait()
|
||||
e = pg.event.wait()
|
||||
# Force application to only advance when main button is released
|
||||
if e.type == pygame.MOUSEBUTTONUP and e.button == pygame.BUTTON_LEFT:
|
||||
if e.type == pg.MOUSEBUTTONUP and e.button == pg.BUTTON_LEFT:
|
||||
break
|
||||
elif e.type == pygame.KEYDOWN and e.key == pygame.K_s:
|
||||
pygame.image.save(screen, name + ".png")
|
||||
elif e.type == pygame.QUIT:
|
||||
pygame.quit()
|
||||
elif e.type == pg.KEYDOWN and e.key == pg.K_s:
|
||||
pg.image.save(screen, name + ".png")
|
||||
elif e.type == pg.QUIT:
|
||||
pg.quit()
|
||||
raise SystemExit()
|
||||
|
||||
|
||||
@@ -45,7 +45,7 @@ def main():
|
||||
import numpy as np
|
||||
from numpy import int32, uint
|
||||
|
||||
pygame.init()
|
||||
pg.init()
|
||||
|
||||
print("Using Numpy")
|
||||
print("Press the left mouse button to advance image.")
|
||||
@@ -64,8 +64,8 @@ def main():
|
||||
surfdemo_show(striped, "striped")
|
||||
|
||||
# rgbarray
|
||||
imagename = os.path.join(main_dir, "data", "arraydemo.webp")
|
||||
imgsurface = pygame.image.load(imagename)
|
||||
imagename = os.path.join(main_dir, "data", "arraydemo.bmp")
|
||||
imgsurface = pg.image.load(imagename)
|
||||
rgbarray = surfarray.array3d(imgsurface)
|
||||
surfdemo_show(rgbarray, "rgbarray")
|
||||
|
||||
@@ -113,7 +113,7 @@ def main():
|
||||
surfdemo_show(xfade, "xfade")
|
||||
|
||||
# all done
|
||||
pygame.quit()
|
||||
pg.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,23 +1,30 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.audiocapture
|
||||
""" pygame.examples.audiocapture
|
||||
|
||||
A pygame 2 experiment.
|
||||
|
||||
* record sound from a microphone
|
||||
* play back the recorded sound
|
||||
"""
|
||||
|
||||
import pygame as pg
|
||||
import time
|
||||
|
||||
import pygame
|
||||
from pygame._sdl2 import (
|
||||
AUDIO_ALLOW_FORMAT_CHANGE,
|
||||
AUDIO_F32,
|
||||
AudioDevice,
|
||||
get_audio_device_names,
|
||||
AudioDevice,
|
||||
AUDIO_F32,
|
||||
AUDIO_ALLOW_FORMAT_CHANGE,
|
||||
)
|
||||
from pygame._sdl2.mixer import set_post_mix
|
||||
|
||||
|
||||
pg.mixer.pre_init(44100, 32, 2, 512)
|
||||
pg.init()
|
||||
|
||||
# init_subsystem(INIT_AUDIO)
|
||||
names = get_audio_device_names(True)
|
||||
print(names)
|
||||
|
||||
sounds = []
|
||||
sound_chunks = []
|
||||
|
||||
@@ -41,42 +48,31 @@ def postmix_callback(postmix, audiomemoryview):
|
||||
print(postmix)
|
||||
|
||||
|
||||
def main():
|
||||
pygame.mixer.pre_init(44100, 32, 2, 512)
|
||||
pygame.init()
|
||||
set_post_mix(postmix_callback)
|
||||
|
||||
# init_subsystem(INIT_AUDIO)
|
||||
names = get_audio_device_names(True)
|
||||
print(names)
|
||||
audio = AudioDevice(
|
||||
devicename=names[0],
|
||||
iscapture=True,
|
||||
frequency=44100,
|
||||
audioformat=AUDIO_F32,
|
||||
numchannels=2,
|
||||
chunksize=512,
|
||||
allowed_changes=AUDIO_ALLOW_FORMAT_CHANGE,
|
||||
callback=callback,
|
||||
)
|
||||
# start recording.
|
||||
audio.pause(0)
|
||||
|
||||
set_post_mix(postmix_callback)
|
||||
print(audio)
|
||||
|
||||
audio = AudioDevice(
|
||||
devicename=names[0],
|
||||
iscapture=True,
|
||||
frequency=44100,
|
||||
audioformat=AUDIO_F32,
|
||||
numchannels=2,
|
||||
chunksize=512,
|
||||
allowed_changes=AUDIO_ALLOW_FORMAT_CHANGE,
|
||||
callback=callback,
|
||||
)
|
||||
# start recording.
|
||||
audio.pause(0)
|
||||
|
||||
print(audio)
|
||||
|
||||
print(f"recording with '{names[0]}'")
|
||||
time.sleep(5)
|
||||
|
||||
print("Turning data into a pygame.mixer.Sound")
|
||||
sound = pygame.mixer.Sound(buffer=b"".join(sound_chunks))
|
||||
|
||||
print("playing back recorded sound")
|
||||
sound.play()
|
||||
time.sleep(5)
|
||||
pygame.quit()
|
||||
print(f"recording with '{names[0]}'")
|
||||
time.sleep(5)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
print("Turning data into a pg.mixer.Sound")
|
||||
sound = pg.mixer.Sound(buffer=b"".join(sound_chunks))
|
||||
|
||||
print("playing back recorded sound")
|
||||
sound.play()
|
||||
time.sleep(5)
|
||||
pg.quit()
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.blend_fill
|
||||
""" pygame.examples.blend_fill
|
||||
|
||||
BLEND_ing colors in different ways with Surface.fill().
|
||||
|
||||
@@ -10,10 +10,8 @@ Keyboard Controls:
|
||||
* A - ADD, S- SUB, M- MULT, - MIN, + MAX to change the blend modes
|
||||
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
import pygame
|
||||
import pygame as pg
|
||||
from pygame import K_1, K_2, K_3, K_4, K_5, K_6, K_7, K_8, K_9
|
||||
|
||||
|
||||
@@ -34,63 +32,63 @@ def main():
|
||||
blendtype = 0
|
||||
step = 5
|
||||
|
||||
pygame.init()
|
||||
screen = pygame.display.set_mode((640, 480))
|
||||
pg.init()
|
||||
screen = pg.display.set_mode((640, 480), 0, 32)
|
||||
screen.fill((100, 100, 100))
|
||||
|
||||
image = pygame.image.load(os.path.join(data_dir, "liquid.webp")).convert()
|
||||
blendimage = pygame.image.load(os.path.join(data_dir, "liquid.webp")).convert()
|
||||
image = pg.image.load(os.path.join(data_dir, "liquid.bmp")).convert()
|
||||
blendimage = pg.image.load(os.path.join(data_dir, "liquid.bmp")).convert()
|
||||
screen.blit(image, (10, 10))
|
||||
screen.blit(blendimage, (200, 10))
|
||||
|
||||
pygame.display.flip()
|
||||
pygame.key.set_repeat(500, 30)
|
||||
pg.display.flip()
|
||||
pg.key.set_repeat(500, 30)
|
||||
usage()
|
||||
|
||||
going = True
|
||||
while going:
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
for event in pg.event.get():
|
||||
if event.type == pg.QUIT:
|
||||
going = False
|
||||
|
||||
if event.type == pygame.KEYDOWN:
|
||||
if event.type == pg.KEYDOWN:
|
||||
usage()
|
||||
|
||||
if event.key == pygame.K_ESCAPE:
|
||||
if event.key == pg.K_ESCAPE:
|
||||
going = False
|
||||
|
||||
if event.key == pygame.K_r:
|
||||
if event.key == pg.K_r:
|
||||
color[0] += step
|
||||
if color[0] > 255:
|
||||
color[0] = 0
|
||||
changed = True
|
||||
|
||||
elif event.key == pygame.K_g:
|
||||
elif event.key == pg.K_g:
|
||||
color[1] += step
|
||||
if color[1] > 255:
|
||||
color[1] = 0
|
||||
changed = True
|
||||
|
||||
elif event.key == pygame.K_b:
|
||||
elif event.key == pg.K_b:
|
||||
color[2] += step
|
||||
if color[2] > 255:
|
||||
color[2] = 0
|
||||
changed = True
|
||||
|
||||
elif event.key == pygame.K_a:
|
||||
blendtype = pygame.BLEND_ADD
|
||||
elif event.key == pg.K_a:
|
||||
blendtype = pg.BLEND_ADD
|
||||
changed = True
|
||||
elif event.key == pygame.K_s:
|
||||
blendtype = pygame.BLEND_SUB
|
||||
elif event.key == pg.K_s:
|
||||
blendtype = pg.BLEND_SUB
|
||||
changed = True
|
||||
elif event.key == pygame.K_m:
|
||||
blendtype = pygame.BLEND_MULT
|
||||
elif event.key == pg.K_m:
|
||||
blendtype = pg.BLEND_MULT
|
||||
changed = True
|
||||
elif event.key == pygame.K_PLUS:
|
||||
blendtype = pygame.BLEND_MAX
|
||||
elif event.key == pg.K_PLUS:
|
||||
blendtype = pg.BLEND_MAX
|
||||
changed = True
|
||||
elif event.key == pygame.K_MINUS:
|
||||
blendtype = pygame.BLEND_MIN
|
||||
elif event.key == pg.K_MINUS:
|
||||
blendtype = pg.BLEND_MIN
|
||||
changed = True
|
||||
|
||||
elif event.key in (K_1, K_2, K_3, K_4, K_5, K_6, K_7, K_8, K_9):
|
||||
@@ -100,15 +98,16 @@ def main():
|
||||
screen.fill((100, 100, 100))
|
||||
screen.blit(image, (10, 10))
|
||||
blendimage.blit(image, (0, 0))
|
||||
# blendimage.fill (color, (0, 0, 20, 20), blendtype)
|
||||
blendimage.fill(color, None, blendtype)
|
||||
screen.blit(blendimage, (200, 10))
|
||||
print(
|
||||
f"Color: {tuple(color)}, Pixel (0,0): {[blendimage.get_at((0, 0))]}"
|
||||
)
|
||||
changed = False
|
||||
pygame.display.flip()
|
||||
pg.display.flip()
|
||||
|
||||
pygame.quit()
|
||||
pg.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.blit_blends
|
||||
""" pygame.examples.blit_blends
|
||||
|
||||
Blending colors in different ways with different blend modes.
|
||||
|
||||
@@ -19,32 +19,30 @@ Keyboard Controls
|
||||
* 1, 2, 3, 4 - use different images.
|
||||
|
||||
"""
|
||||
|
||||
import os
|
||||
import pygame as pg
|
||||
import time
|
||||
|
||||
import pygame
|
||||
|
||||
main_dir = os.path.split(os.path.abspath(__file__))[0]
|
||||
data_dir = os.path.join(main_dir, "data")
|
||||
|
||||
try:
|
||||
import numpy
|
||||
import pygame.surfarray
|
||||
import numpy
|
||||
except ImportError:
|
||||
print("no surfarray for you! install numpy")
|
||||
|
||||
|
||||
def main():
|
||||
pygame.init()
|
||||
pygame.mixer.quit() # remove ALSA underflow messages for Debian squeeze
|
||||
screen = pygame.display.set_mode((640, 480))
|
||||
pg.init()
|
||||
pg.mixer.quit() # remove ALSA underflow messages for Debian squeeze
|
||||
screen = pg.display.set_mode((640, 480))
|
||||
|
||||
im1 = pygame.Surface(screen.get_size())
|
||||
im1 = pg.Surface(screen.get_size())
|
||||
# im1= im1.convert()
|
||||
im1.fill((100, 0, 0))
|
||||
|
||||
im2 = pygame.Surface(screen.get_size())
|
||||
im2 = pg.Surface(screen.get_size())
|
||||
im2.fill((0, 50, 0))
|
||||
# we make a srcalpha copy of it.
|
||||
# im3= im2.convert(SRCALPHA)
|
||||
@@ -52,50 +50,50 @@ def main():
|
||||
im3.set_alpha(127)
|
||||
|
||||
images = {}
|
||||
images[pygame.K_1] = im2
|
||||
images[pygame.K_2] = pygame.image.load(os.path.join(data_dir, "chimp.webp"))
|
||||
images[pygame.K_3] = pygame.image.load(os.path.join(data_dir, "alien3.gif"))
|
||||
images[pygame.K_4] = pygame.image.load(os.path.join(data_dir, "liquid.webp"))
|
||||
images[pg.K_1] = im2
|
||||
images[pg.K_2] = pg.image.load(os.path.join(data_dir, "chimp.png"))
|
||||
images[pg.K_3] = pg.image.load(os.path.join(data_dir, "alien3.gif"))
|
||||
images[pg.K_4] = pg.image.load(os.path.join(data_dir, "liquid.bmp"))
|
||||
img_to_blit = im2.convert()
|
||||
iaa = img_to_blit.convert_alpha()
|
||||
|
||||
blits = {}
|
||||
blits[pygame.K_a] = pygame.BLEND_ADD
|
||||
blits[pygame.K_s] = pygame.BLEND_SUB
|
||||
blits[pygame.K_m] = pygame.BLEND_MULT
|
||||
blits[pygame.K_EQUALS] = pygame.BLEND_MAX
|
||||
blits[pygame.K_MINUS] = pygame.BLEND_MIN
|
||||
blits[pg.K_a] = pg.BLEND_ADD
|
||||
blits[pg.K_s] = pg.BLEND_SUB
|
||||
blits[pg.K_m] = pg.BLEND_MULT
|
||||
blits[pg.K_EQUALS] = pg.BLEND_MAX
|
||||
blits[pg.K_MINUS] = pg.BLEND_MIN
|
||||
|
||||
blitsn = {}
|
||||
blitsn[pygame.K_a] = "BLEND_ADD"
|
||||
blitsn[pygame.K_s] = "BLEND_SUB"
|
||||
blitsn[pygame.K_m] = "BLEND_MULT"
|
||||
blitsn[pygame.K_EQUALS] = "BLEND_MAX"
|
||||
blitsn[pygame.K_MINUS] = "BLEND_MIN"
|
||||
blitsn[pg.K_a] = "BLEND_ADD"
|
||||
blitsn[pg.K_s] = "BLEND_SUB"
|
||||
blitsn[pg.K_m] = "BLEND_MULT"
|
||||
blitsn[pg.K_EQUALS] = "BLEND_MAX"
|
||||
blitsn[pg.K_MINUS] = "BLEND_MIN"
|
||||
|
||||
screen.blit(im1, (0, 0))
|
||||
pygame.display.flip()
|
||||
clock = pygame.Clock()
|
||||
pg.display.flip()
|
||||
clock = pg.time.Clock()
|
||||
print("one pixel is:%s:" % [im1.get_at((0, 0))])
|
||||
|
||||
going = True
|
||||
while going:
|
||||
clock.tick(60)
|
||||
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
for event in pg.event.get():
|
||||
if event.type == pg.QUIT:
|
||||
going = False
|
||||
if event.type == pygame.KEYDOWN:
|
||||
if event.type == pg.KEYDOWN:
|
||||
usage()
|
||||
|
||||
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
|
||||
if event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE:
|
||||
going = False
|
||||
|
||||
elif event.type == pygame.KEYDOWN and event.key in images.keys():
|
||||
elif event.type == pg.KEYDOWN and event.key in images.keys():
|
||||
img_to_blit = images[event.key]
|
||||
iaa = img_to_blit.convert_alpha()
|
||||
|
||||
elif event.type == pygame.KEYDOWN and event.key in blits.keys():
|
||||
elif event.type == pg.KEYDOWN and event.key in blits.keys():
|
||||
t1 = time.time()
|
||||
# blits is a dict keyed with key -> blit flag. eg BLEND_ADD.
|
||||
im1.blit(img_to_blit, (0, 0), None, blits[event.key])
|
||||
@@ -103,7 +101,7 @@ def main():
|
||||
print("one pixel is:%s:" % [im1.get_at((0, 0))])
|
||||
print(f"time to do:{t2 - t1}:")
|
||||
|
||||
elif event.type == pygame.KEYDOWN and event.key in [pygame.K_t]:
|
||||
elif event.type == pg.KEYDOWN and event.key in [pg.K_t]:
|
||||
for bkey in blits.keys():
|
||||
t1 = time.time()
|
||||
|
||||
@@ -116,7 +114,7 @@ def main():
|
||||
onedoing = blitsn[bkey]
|
||||
print(f"time to do :{onedoing}: is :{t2 - t1}:")
|
||||
|
||||
elif event.type == pygame.KEYDOWN and event.key in [pygame.K_o]:
|
||||
elif event.type == pg.KEYDOWN and event.key in [pg.K_o]:
|
||||
t1 = time.time()
|
||||
# blits is a dict keyed with key -> blit flag. eg BLEND_ADD.
|
||||
im1.blit(iaa, (0, 0))
|
||||
@@ -124,7 +122,7 @@ def main():
|
||||
print("one pixel is:%s:" % [im1.get_at((0, 0))])
|
||||
print(f"time to do:{t2 - t1}:")
|
||||
|
||||
elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
|
||||
elif event.type == pg.KEYDOWN and event.key == pg.K_SPACE:
|
||||
# this additive blend without clamp two surfaces.
|
||||
# im1.set_alpha(127)
|
||||
# im1.blit(im1, (0,0))
|
||||
@@ -140,7 +138,7 @@ def main():
|
||||
print("one pixel is:%s:" % [im1.get_at((0, 0))])
|
||||
print(f"time to do:{t2 - t1}:")
|
||||
|
||||
elif event.type == pygame.KEYDOWN and event.key in [pygame.K_z]:
|
||||
elif event.type == pg.KEYDOWN and event.key in [pg.K_z]:
|
||||
t1 = time.time()
|
||||
im1p = pygame.surfarray.pixels3d(im1)
|
||||
im2p = pygame.surfarray.pixels3d(im2)
|
||||
@@ -156,25 +154,21 @@ def main():
|
||||
print("one pixel is:%s:" % [im1.get_at((0, 0))])
|
||||
print(f"time to do:{t2 - t1}:")
|
||||
|
||||
elif event.type == pygame.KEYDOWN and event.key in [
|
||||
pygame.K_r,
|
||||
pygame.K_g,
|
||||
pygame.K_b,
|
||||
]:
|
||||
elif event.type == pg.KEYDOWN and event.key in [pg.K_r, pg.K_g, pg.K_b]:
|
||||
# this adds one to each pixel.
|
||||
colmap = {}
|
||||
colmap[pygame.K_r] = 0x10000
|
||||
colmap[pygame.K_g] = 0x00100
|
||||
colmap[pygame.K_b] = 0x00001
|
||||
colmap[pg.K_r] = 0x10000
|
||||
colmap[pg.K_g] = 0x00100
|
||||
colmap[pg.K_b] = 0x00001
|
||||
im1p = pygame.surfarray.pixels2d(im1)
|
||||
im1p += colmap[event.key]
|
||||
del im1p
|
||||
print("one pixel is:%s:" % [im1.get_at((0, 0))])
|
||||
|
||||
elif event.type == pygame.KEYDOWN and event.key == pygame.K_p:
|
||||
elif event.type == pg.KEYDOWN and event.key == pg.K_p:
|
||||
print("one pixel is:%s:" % [im1.get_at((0, 0))])
|
||||
|
||||
elif event.type == pygame.KEYDOWN and event.key == pygame.K_f:
|
||||
elif event.type == pg.KEYDOWN and event.key == pg.K_f:
|
||||
# this additive blend without clamp two surfaces.
|
||||
|
||||
t1 = time.time()
|
||||
@@ -187,9 +181,9 @@ def main():
|
||||
print(f"time to do:{t2 - t1}:")
|
||||
|
||||
screen.blit(im1, (0, 0))
|
||||
pygame.display.flip()
|
||||
pg.display.flip()
|
||||
|
||||
pygame.quit()
|
||||
pg.quit()
|
||||
|
||||
|
||||
def usage():
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.camera
|
||||
""" pygame.examples.camera
|
||||
|
||||
Basic image capturing and display using pygame.camera
|
||||
|
||||
@@ -11,8 +11,7 @@ Keyboard controls
|
||||
- 9, start camera 9.
|
||||
- 10, start camera... wait a minute! There's not 10 key!
|
||||
"""
|
||||
|
||||
import pygame
|
||||
import pygame as pg
|
||||
import pygame.camera
|
||||
|
||||
|
||||
@@ -24,7 +23,7 @@ class VideoCapturePlayer:
|
||||
super().__init__(**argd)
|
||||
|
||||
# create a display surface. standard pygame stuff
|
||||
self.display = pygame.display.set_mode(self.size)
|
||||
self.display = pg.display.set_mode(self.size)
|
||||
self.init_cams(0)
|
||||
|
||||
def init_cams(self, which_cam_idx):
|
||||
@@ -47,11 +46,11 @@ class VideoCapturePlayer:
|
||||
# starts the camera
|
||||
self.camera.start()
|
||||
|
||||
self.clock = pygame.Clock()
|
||||
self.clock = pg.time.Clock()
|
||||
|
||||
# create a surface to capture to. for performance purposes, you want the
|
||||
# bit depth to be the same as that of the display surface.
|
||||
self.snapshot = pygame.surface.Surface(self.size, 0, self.display)
|
||||
self.snapshot = pg.surface.Surface(self.size, 0, self.display)
|
||||
# return the name of the camera being used, to be included in the window name
|
||||
return cam_id
|
||||
|
||||
@@ -78,7 +77,7 @@ class VideoCapturePlayer:
|
||||
# self.snapshot = self.camera.get_image(self.display)
|
||||
# # self.display.blit(self.snapshot, (0,0))
|
||||
|
||||
pygame.display.flip()
|
||||
pg.display.flip()
|
||||
|
||||
def main(self):
|
||||
# get the camera list. If there are no cameras, raise a value error.
|
||||
@@ -98,15 +97,13 @@ class VideoCapturePlayer:
|
||||
|
||||
going = True
|
||||
while going:
|
||||
events = pygame.event.get()
|
||||
events = pg.event.get()
|
||||
for e in events:
|
||||
if e.type == pygame.QUIT or (
|
||||
e.type == pygame.KEYDOWN and e.key == pygame.K_ESCAPE
|
||||
):
|
||||
if e.type == pg.QUIT or (e.type == pg.KEYDOWN and e.key == pg.K_ESCAPE):
|
||||
going = False
|
||||
if e.type == pygame.KEYDOWN:
|
||||
if e.key in range(pygame.K_0, pygame.K_0 + 10):
|
||||
camera = self.init_cams(e.key - pygame.K_0)
|
||||
if e.type == pg.KEYDOWN:
|
||||
if e.key in range(pg.K_0, pg.K_0 + 10):
|
||||
camera = self.init_cams(e.key - pg.K_0)
|
||||
|
||||
self.get_and_flip()
|
||||
self.clock.tick()
|
||||
@@ -114,10 +111,10 @@ class VideoCapturePlayer:
|
||||
|
||||
|
||||
def main():
|
||||
pygame.init()
|
||||
pg.init()
|
||||
pygame.camera.init()
|
||||
VideoCapturePlayer().main()
|
||||
pygame.quit()
|
||||
pg.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.chimp
|
||||
""" pygame.examples.chimp
|
||||
|
||||
This simple example is used for the line-by-line tutorial
|
||||
that comes with pygame. It is based on a 'popular' web banner.
|
||||
@@ -7,14 +7,14 @@ Note there are comments here, but for the full explanation,
|
||||
follow along in the tutorial.
|
||||
"""
|
||||
|
||||
|
||||
# Import Modules
|
||||
import os
|
||||
import pygame as pg
|
||||
|
||||
import pygame
|
||||
|
||||
if not pygame.font:
|
||||
if not pg.font:
|
||||
print("Warning, fonts disabled")
|
||||
if not pygame.mixer:
|
||||
if not pg.mixer:
|
||||
print("Warning, sound disabled")
|
||||
|
||||
main_dir = os.path.split(os.path.abspath(__file__))[0]
|
||||
@@ -24,15 +24,17 @@ data_dir = os.path.join(main_dir, "data")
|
||||
# functions to create our resources
|
||||
def load_image(name, colorkey=None, scale=1):
|
||||
fullname = os.path.join(data_dir, name)
|
||||
image = pygame.image.load(fullname)
|
||||
image = pg.image.load(fullname)
|
||||
image = image.convert()
|
||||
|
||||
image = pygame.transform.scale_by(image, scale)
|
||||
size = image.get_size()
|
||||
size = (size[0] * scale, size[1] * scale)
|
||||
image = pg.transform.scale(image, size)
|
||||
|
||||
if colorkey is not None:
|
||||
if colorkey == -1:
|
||||
colorkey = image.get_at((0, 0))
|
||||
image.set_colorkey(colorkey, pygame.RLEACCEL)
|
||||
image.set_colorkey(colorkey, pg.RLEACCEL)
|
||||
return image, image.get_rect()
|
||||
|
||||
|
||||
@@ -41,28 +43,28 @@ def load_sound(name):
|
||||
def play(self):
|
||||
pass
|
||||
|
||||
if not pygame.mixer.get_init():
|
||||
if not pg.mixer or not pg.mixer.get_init():
|
||||
return NoneSound()
|
||||
|
||||
fullname = os.path.join(data_dir, name)
|
||||
sound = pygame.mixer.Sound(fullname)
|
||||
sound = pg.mixer.Sound(fullname)
|
||||
|
||||
return sound
|
||||
|
||||
|
||||
# classes for our game objects
|
||||
class Fist(pygame.sprite.Sprite):
|
||||
class Fist(pg.sprite.Sprite):
|
||||
"""moves a clenched fist on the screen, following the mouse"""
|
||||
|
||||
def __init__(self):
|
||||
pygame.sprite.Sprite.__init__(self) # call Sprite initializer
|
||||
self.image, self.rect = load_image("fist.webp", -1)
|
||||
pg.sprite.Sprite.__init__(self) # call Sprite initializer
|
||||
self.image, self.rect = load_image("fist.png", -1)
|
||||
self.fist_offset = (-235, -80)
|
||||
self.punching = False
|
||||
|
||||
def update(self):
|
||||
"""move the fist based on the mouse position"""
|
||||
pos = pygame.mouse.get_pos()
|
||||
pos = pg.mouse.get_pos()
|
||||
self.rect.topleft = pos
|
||||
self.rect.move_ip(self.fist_offset)
|
||||
if self.punching:
|
||||
@@ -80,14 +82,14 @@ class Fist(pygame.sprite.Sprite):
|
||||
self.punching = False
|
||||
|
||||
|
||||
class Chimp(pygame.sprite.Sprite):
|
||||
class Chimp(pg.sprite.Sprite):
|
||||
"""moves a monkey critter across the screen. it can spin the
|
||||
monkey when it is punched."""
|
||||
|
||||
def __init__(self):
|
||||
pygame.sprite.Sprite.__init__(self) # call Sprite initializer
|
||||
self.image, self.rect = load_image("chimp.webp", -1, 4)
|
||||
screen = pygame.display.get_surface()
|
||||
pg.sprite.Sprite.__init__(self) # call Sprite initializer
|
||||
self.image, self.rect = load_image("chimp.png", -1, 4)
|
||||
screen = pg.display.get_surface()
|
||||
self.area = screen.get_rect()
|
||||
self.rect.topleft = 10, 90
|
||||
self.move = 18
|
||||
@@ -107,7 +109,7 @@ class Chimp(pygame.sprite.Sprite):
|
||||
if self.rect.left < self.area.left or self.rect.right > self.area.right:
|
||||
self.move = -self.move
|
||||
newpos = self.rect.move((self.move, 0))
|
||||
self.image = pygame.transform.flip(self.image, True, False)
|
||||
self.image = pg.transform.flip(self.image, True, False)
|
||||
self.rect = newpos
|
||||
|
||||
def _spin(self):
|
||||
@@ -118,7 +120,7 @@ class Chimp(pygame.sprite.Sprite):
|
||||
self.dizzy = False
|
||||
self.image = self.original
|
||||
else:
|
||||
rotate = pygame.transform.rotate
|
||||
rotate = pg.transform.rotate
|
||||
self.image = rotate(self.original, self.dizzy)
|
||||
self.rect = self.image.get_rect(center=center)
|
||||
|
||||
@@ -134,33 +136,34 @@ def main():
|
||||
it initializes everything it needs, then runs in
|
||||
a loop until the function returns."""
|
||||
# Initialize Everything
|
||||
pygame.init()
|
||||
screen = pygame.display.set_mode((1280, 480), pygame.SCALED)
|
||||
pygame.display.set_caption("Monkey Fever")
|
||||
pygame.mouse.set_visible(False)
|
||||
pg.init()
|
||||
screen = pg.display.set_mode((1280, 480), pg.SCALED)
|
||||
pg.display.set_caption("Monkey Fever")
|
||||
pg.mouse.set_visible(False)
|
||||
|
||||
# Create The Background
|
||||
background = pygame.Surface(screen.get_size())
|
||||
background = pg.Surface(screen.get_size())
|
||||
background = background.convert()
|
||||
background.fill((170, 238, 187))
|
||||
|
||||
# Put Text On The Background, Centered
|
||||
font = pygame.Font(None, 64)
|
||||
text = font.render("Pummel The Chimp, And Win $$$", True, (10, 10, 10))
|
||||
textpos = text.get_rect(centerx=background.get_width() / 2, y=10)
|
||||
background.blit(text, textpos)
|
||||
if pg.font:
|
||||
font = pg.font.Font(None, 64)
|
||||
text = font.render("Pummel The Chimp, And Win $$$", True, (10, 10, 10))
|
||||
textpos = text.get_rect(centerx=background.get_width() / 2, y=10)
|
||||
background.blit(text, textpos)
|
||||
|
||||
# Display The Background
|
||||
screen.blit(background, (0, 0))
|
||||
pygame.display.flip()
|
||||
pg.display.flip()
|
||||
|
||||
# Prepare Game Objects
|
||||
whiff_sound = load_sound("whiff.wav")
|
||||
punch_sound = load_sound("punch.wav")
|
||||
chimp = Chimp()
|
||||
fist = Fist()
|
||||
all_sprites = pygame.sprite.Group(chimp, fist)
|
||||
clock = pygame.Clock()
|
||||
allsprites = pg.sprite.RenderPlain((chimp, fist))
|
||||
clock = pg.time.Clock()
|
||||
|
||||
# Main Loop
|
||||
going = True
|
||||
@@ -168,28 +171,28 @@ def main():
|
||||
clock.tick(60)
|
||||
|
||||
# Handle Input Events
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
for event in pg.event.get():
|
||||
if event.type == pg.QUIT:
|
||||
going = False
|
||||
elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
|
||||
elif event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE:
|
||||
going = False
|
||||
elif event.type == pygame.MOUSEBUTTONDOWN:
|
||||
elif event.type == pg.MOUSEBUTTONDOWN:
|
||||
if fist.punch(chimp):
|
||||
punch_sound.play() # punch
|
||||
chimp.punched()
|
||||
else:
|
||||
whiff_sound.play() # miss
|
||||
elif event.type == pygame.MOUSEBUTTONUP:
|
||||
elif event.type == pg.MOUSEBUTTONUP:
|
||||
fist.unpunch()
|
||||
|
||||
all_sprites.update()
|
||||
allsprites.update()
|
||||
|
||||
# Draw Everything
|
||||
screen.blit(background, (0, 0))
|
||||
all_sprites.draw(screen)
|
||||
pygame.display.flip()
|
||||
allsprites.draw(screen)
|
||||
pg.display.flip()
|
||||
|
||||
pygame.quit()
|
||||
pg.quit()
|
||||
|
||||
|
||||
# Game Over
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.cursors
|
||||
""" pygame.examples.cursors
|
||||
Click a button and the cursor will change.
|
||||
This example will show you:
|
||||
*The different types of cursors that exist
|
||||
@@ -8,30 +8,30 @@ This example will show you:
|
||||
*How to make a simple button
|
||||
"""
|
||||
|
||||
import pygame as pg
|
||||
import os
|
||||
|
||||
import pygame
|
||||
|
||||
# Create a system cursor
|
||||
|
||||
system_cursor1 = pygame.SYSTEM_CURSOR_CROSSHAIR
|
||||
system_cursor2 = pygame.SYSTEM_CURSOR_HAND
|
||||
system_cursor3 = pygame.SYSTEM_CURSOR_IBEAM
|
||||
system_cursor1 = pg.SYSTEM_CURSOR_CROSSHAIR
|
||||
system_cursor2 = pg.SYSTEM_CURSOR_HAND
|
||||
system_cursor3 = pg.SYSTEM_CURSOR_IBEAM
|
||||
|
||||
|
||||
# Create a color cursor
|
||||
|
||||
surf = pygame.Surface((40, 40))
|
||||
surf = pg.Surface((40, 40))
|
||||
surf.fill((120, 50, 50))
|
||||
color_cursor = pygame.cursors.Cursor((20, 20), surf)
|
||||
color_cursor = pg.cursors.Cursor((20, 20), surf)
|
||||
|
||||
|
||||
# Create a color cursor with an image surface
|
||||
|
||||
main_dir = os.path.split(os.path.abspath(__file__))[0]
|
||||
image_name = os.path.join(main_dir, "data", "cursor.webp")
|
||||
image = pygame.image.load(image_name)
|
||||
image_cursor = pygame.cursors.Cursor(
|
||||
image_name = os.path.join(main_dir, "data", "cursor.png")
|
||||
image = pg.image.load(image_name)
|
||||
image_cursor = pg.cursors.Cursor(
|
||||
(image.get_width() // 2, image.get_height() // 2), image
|
||||
)
|
||||
|
||||
@@ -66,16 +66,16 @@ thickarrow_strings = (
|
||||
" ",
|
||||
)
|
||||
|
||||
bitmap_cursor1 = pygame.cursors.Cursor(
|
||||
bitmap_cursor1 = pg.cursors.Cursor(
|
||||
(24, 24),
|
||||
(0, 0),
|
||||
*pygame.cursors.compile(thickarrow_strings, black="X", white=".", xor="o"),
|
||||
*pg.cursors.compile(thickarrow_strings, black="X", white=".", xor="o"),
|
||||
)
|
||||
|
||||
|
||||
# Create a bitmap cursor from premade simple strings
|
||||
|
||||
bitmap_cursor2 = pygame.cursors.diamond
|
||||
bitmap_cursor2 = pg.cursors.diamond
|
||||
|
||||
|
||||
# Calculate if mouse position is inside circle
|
||||
@@ -84,14 +84,14 @@ def check_circle(mouse_pos_x, mouse_pos_y, center_x, center_y, radius):
|
||||
|
||||
|
||||
def main():
|
||||
pygame.init()
|
||||
pygame.display.set_caption("Cursors Example")
|
||||
pg.init()
|
||||
pg.display.set_caption("Cursors Example")
|
||||
|
||||
pygame.font.init()
|
||||
font = pygame.Font(None, 30)
|
||||
font1 = pygame.Font(None, 24)
|
||||
pg.font.init()
|
||||
font = pg.font.Font(None, 30)
|
||||
font1 = pg.font.Font(None, 24)
|
||||
|
||||
bg = pygame.display.set_mode((500, 400))
|
||||
bg = pg.display.set_mode((500, 400))
|
||||
bg.fill((183, 201, 226))
|
||||
|
||||
# Initialize circles
|
||||
@@ -119,17 +119,17 @@ def main():
|
||||
pos_y6 = 220
|
||||
pos_y7 = 140
|
||||
|
||||
circle1 = pygame.draw.circle(bg, (255, 255, 255), (pos_x1, pos_y1), radius1)
|
||||
circle2 = pygame.draw.circle(bg, (255, 255, 255), (pos_x2, pos_y2), radius2)
|
||||
circle3 = pygame.draw.circle(bg, (255, 255, 255), (pos_x3, pos_y3), radius3)
|
||||
circle4 = pygame.draw.circle(bg, (255, 255, 255), (pos_x4, pos_y4), radius4)
|
||||
circle5 = pygame.draw.circle(bg, (255, 255, 255), (pos_x5, pos_y5), radius5)
|
||||
circle6 = pygame.draw.circle(bg, (255, 255, 255), (pos_x6, pos_y6), radius6)
|
||||
circle7 = pygame.draw.circle(bg, (255, 255, 255), (pos_x7, pos_y7), radius7)
|
||||
circle1 = pg.draw.circle(bg, (255, 255, 255), (pos_x1, pos_y1), radius1)
|
||||
circle2 = pg.draw.circle(bg, (255, 255, 255), (pos_x2, pos_y2), radius2)
|
||||
circle3 = pg.draw.circle(bg, (255, 255, 255), (pos_x3, pos_y3), radius3)
|
||||
circle4 = pg.draw.circle(bg, (255, 255, 255), (pos_x4, pos_y4), radius4)
|
||||
circle5 = pg.draw.circle(bg, (255, 255, 255), (pos_x5, pos_y5), radius5)
|
||||
circle6 = pg.draw.circle(bg, (255, 255, 255), (pos_x6, pos_y6), radius6)
|
||||
circle7 = pg.draw.circle(bg, (255, 255, 255), (pos_x7, pos_y7), radius7)
|
||||
|
||||
# Initialize button
|
||||
button_text = font1.render("Click here to change cursor", True, (0, 0, 0))
|
||||
button = pygame.draw.rect(
|
||||
button = pg.draw.rect(
|
||||
bg,
|
||||
(180, 180, 180),
|
||||
(139, 300, button_text.get_width() + 5, button_text.get_height() + 50),
|
||||
@@ -137,7 +137,7 @@ def main():
|
||||
button_text_rect = button_text.get_rect(center=button.center)
|
||||
bg.blit(button_text, button_text_rect)
|
||||
|
||||
pygame.display.update()
|
||||
pg.display.update()
|
||||
|
||||
cursors = [
|
||||
system_cursor1,
|
||||
@@ -150,60 +150,60 @@ def main():
|
||||
]
|
||||
|
||||
index = 0
|
||||
pygame.mouse.set_cursor(cursors[index])
|
||||
pg.mouse.set_cursor(cursors[index])
|
||||
|
||||
was_pressed = False
|
||||
clock = pygame.Clock()
|
||||
pressed = False
|
||||
clock = pg.time.Clock()
|
||||
|
||||
while True:
|
||||
clock.tick(50)
|
||||
|
||||
mouse_x, mouse_y = pygame.mouse.get_pos()
|
||||
mouse_x, mouse_y = pg.mouse.get_pos()
|
||||
|
||||
# Check if mouse is inside a circle to change its color
|
||||
if check_circle(mouse_x, mouse_y, circle1.centerx, circle1.centery, radius1):
|
||||
circle1 = pygame.draw.circle(bg, (255, 0, 0), (pos_x1, pos_y1), radius1)
|
||||
circle1 = pg.draw.circle(bg, (255, 0, 0), (pos_x1, pos_y1), radius1)
|
||||
else:
|
||||
circle1 = pygame.draw.circle(bg, (255, 255, 255), (pos_x1, pos_y1), radius1)
|
||||
circle1 = pg.draw.circle(bg, (255, 255, 255), (pos_x1, pos_y1), radius1)
|
||||
|
||||
if check_circle(mouse_x, mouse_y, circle2.centerx, circle2.centery, radius2):
|
||||
circle2 = pygame.draw.circle(bg, (255, 127, 0), (pos_x2, pos_y2), radius2)
|
||||
circle2 = pg.draw.circle(bg, (255, 127, 0), (pos_x2, pos_y2), radius2)
|
||||
else:
|
||||
circle2 = pygame.draw.circle(bg, (255, 255, 255), (pos_x2, pos_y2), radius2)
|
||||
circle2 = pg.draw.circle(bg, (255, 255, 255), (pos_x2, pos_y2), radius2)
|
||||
|
||||
if check_circle(mouse_x, mouse_y, circle3.centerx, circle3.centery, radius3):
|
||||
circle3 = pygame.draw.circle(bg, (255, 255, 0), (pos_x3, pos_y3), radius3)
|
||||
circle3 = pg.draw.circle(bg, (255, 255, 0), (pos_x3, pos_y3), radius3)
|
||||
else:
|
||||
circle3 = pygame.draw.circle(bg, (255, 255, 255), (pos_x3, pos_y3), radius3)
|
||||
circle3 = pg.draw.circle(bg, (255, 255, 255), (pos_x3, pos_y3), radius3)
|
||||
|
||||
if check_circle(mouse_x, mouse_y, circle4.centerx, circle4.centery, radius3):
|
||||
circle4 = pygame.draw.circle(bg, (0, 255, 0), (pos_x4, pos_y4), radius4)
|
||||
circle4 = pg.draw.circle(bg, (0, 255, 0), (pos_x4, pos_y4), radius4)
|
||||
else:
|
||||
circle4 = pygame.draw.circle(bg, (255, 255, 255), (pos_x4, pos_y4), radius4)
|
||||
circle4 = pg.draw.circle(bg, (255, 255, 255), (pos_x4, pos_y4), radius4)
|
||||
|
||||
if check_circle(mouse_x, mouse_y, circle5.centerx, circle5.centery, radius4):
|
||||
circle5 = pygame.draw.circle(bg, (0, 0, 255), (pos_x5, pos_y5), radius5)
|
||||
circle5 = pg.draw.circle(bg, (0, 0, 255), (pos_x5, pos_y5), radius5)
|
||||
else:
|
||||
circle5 = pygame.draw.circle(bg, (255, 255, 255), (pos_x5, pos_y5), radius5)
|
||||
circle5 = pg.draw.circle(bg, (255, 255, 255), (pos_x5, pos_y5), radius5)
|
||||
|
||||
if check_circle(mouse_x, mouse_y, circle6.centerx, circle6.centery, radius6):
|
||||
circle6 = pygame.draw.circle(bg, (75, 0, 130), (pos_x6, pos_y6), radius6)
|
||||
circle6 = pg.draw.circle(bg, (75, 0, 130), (pos_x6, pos_y6), radius6)
|
||||
else:
|
||||
circle6 = pygame.draw.circle(bg, (255, 255, 255), (pos_x6, pos_y6), radius6)
|
||||
circle6 = pg.draw.circle(bg, (255, 255, 255), (pos_x6, pos_y6), radius6)
|
||||
|
||||
if check_circle(mouse_x, mouse_y, circle7.centerx, circle7.centery, radius7):
|
||||
circle7 = pygame.draw.circle(bg, (148, 0, 211), (pos_x7, pos_y7), radius7)
|
||||
circle7 = pg.draw.circle(bg, (148, 0, 211), (pos_x7, pos_y7), radius7)
|
||||
else:
|
||||
circle7 = pygame.draw.circle(bg, (255, 255, 255), (pos_x7, pos_y7), radius7)
|
||||
circle7 = pg.draw.circle(bg, (255, 255, 255), (pos_x7, pos_y7), radius7)
|
||||
|
||||
bg.fill((183, 201, 226), (0, 15, bg.get_width(), 50))
|
||||
text1 = font.render(
|
||||
(f"This is a {pygame.mouse.get_cursor().type} cursor"), True, (0, 0, 0)
|
||||
(f"This is a {pg.mouse.get_cursor().type} cursor"), True, (0, 0, 0)
|
||||
)
|
||||
text_rect1 = text1.get_rect(center=(bg.get_width() / 2, 40))
|
||||
bg.blit(text1, text_rect1)
|
||||
|
||||
button = pygame.draw.rect(
|
||||
button = pg.draw.rect(
|
||||
bg,
|
||||
(100, 149, 240),
|
||||
(139, 300, button_text.get_width() + 5, button_text.get_height() + 50),
|
||||
@@ -212,7 +212,7 @@ def main():
|
||||
|
||||
# Check if button was clicked and change cursor
|
||||
if button.collidepoint(mouse_x, mouse_y):
|
||||
button = pygame.draw.rect(
|
||||
button = pg.draw.rect(
|
||||
bg,
|
||||
(60, 100, 255),
|
||||
(
|
||||
@@ -224,8 +224,8 @@ def main():
|
||||
)
|
||||
bg.blit(button_text, button_text_rect)
|
||||
|
||||
if pygame.mouse.get_pressed()[0] and not was_pressed:
|
||||
button = pygame.draw.rect(
|
||||
if pg.mouse.get_pressed()[0] == 1 and pressed is False:
|
||||
button = pg.draw.rect(
|
||||
bg,
|
||||
(0, 0, 139),
|
||||
(
|
||||
@@ -238,18 +238,21 @@ def main():
|
||||
bg.blit(button_text, button_text_rect)
|
||||
index += 1
|
||||
index %= len(cursors)
|
||||
pygame.mouse.set_cursor(cursors[index])
|
||||
pygame.display.update()
|
||||
pygame.time.delay(40)
|
||||
pg.mouse.set_cursor(cursors[index])
|
||||
pg.display.update()
|
||||
pg.time.delay(40)
|
||||
|
||||
was_pressed = pygame.mouse.get_pressed()[0]
|
||||
if pg.mouse.get_pressed()[0] == 1:
|
||||
pressed = True
|
||||
elif pg.mouse.get_pressed()[0] == 0:
|
||||
pressed = False
|
||||
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
pygame.quit()
|
||||
for event in pg.event.get():
|
||||
if event.type == pg.QUIT:
|
||||
pg.quit()
|
||||
raise SystemExit
|
||||
|
||||
pygame.display.update()
|
||||
pg.display.update()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
|
Before Width: | Height: | Size: 39 KiB |
|
Before Width: | Height: | Size: 38 KiB |
@@ -1,7 +0,0 @@
|
||||
surfonasinewave.xm:
|
||||
By FearofDark
|
||||
https://modarchive.org/index.php?request=view_by_moduleid&query=169104
|
||||
|
||||
MIDI_sample.mid
|
||||
Dogman15 at English Wikipedia
|
||||
https://en.wikipedia.org/wiki/File:MIDI_sample.mid
|
||||
|
Before Width: | Height: | Size: 622 B |
|
Before Width: | Height: | Size: 960 B |
|
Before Width: | Height: | Size: 47 KiB |
|
Before Width: | Height: | Size: 124 B |
|
Before Width: | Height: | Size: 1.8 KiB |
|
Before Width: | Height: | Size: 9.3 KiB |
|
Before Width: | Height: | Size: 580 B |
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.dropfile
|
||||
""" pygame.examples.dropfile
|
||||
|
||||
Drag and drop an image on here.
|
||||
|
||||
@@ -10,69 +10,62 @@ Uses these events:
|
||||
* DROPTEXT
|
||||
* DROPFILE
|
||||
"""
|
||||
|
||||
import pygame
|
||||
|
||||
pygame.init()
|
||||
import pygame as pg
|
||||
|
||||
|
||||
def main():
|
||||
running = True
|
||||
screen_size = (640, 480)
|
||||
surf = pygame.display.set_mode(screen_size)
|
||||
font = pygame.font.SysFont("Arial", 24)
|
||||
font.align = pygame.FONT_CENTER
|
||||
clock = pygame.Clock()
|
||||
pg.init()
|
||||
|
||||
spr_file_text = font.render("Feed me some file or image!", True, (255, 255, 255))
|
||||
going = True
|
||||
surf = pg.display.set_mode((640, 480))
|
||||
font = pg.font.SysFont("Arial", 24)
|
||||
clock = pg.time.Clock()
|
||||
|
||||
spr_file_text = font.render("Drag and drop a file or image!", 1, (255, 255, 255))
|
||||
spr_file_text_rect = spr_file_text.get_rect()
|
||||
spr_file_text_rect.center = surf.get_rect().center
|
||||
|
||||
spr_file_image = None
|
||||
spr_file_image_rect = None
|
||||
|
||||
while running:
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
running = False
|
||||
elif event.type == pygame.DROPBEGIN:
|
||||
print(event)
|
||||
while going:
|
||||
for ev in pg.event.get():
|
||||
if ev.type == pg.QUIT:
|
||||
going = False
|
||||
elif ev.type == pg.DROPBEGIN:
|
||||
print(ev)
|
||||
print("File drop begin!")
|
||||
elif event.type == pygame.DROPCOMPLETE:
|
||||
print(event)
|
||||
elif ev.type == pg.DROPCOMPLETE:
|
||||
print(ev)
|
||||
print("File drop complete!")
|
||||
elif event.type == pygame.DROPTEXT:
|
||||
print(event)
|
||||
spr_file_text = font.render(
|
||||
event.text, True, (255, 255, 255), wraplength=screen_size[0] - 10
|
||||
)
|
||||
elif ev.type == pg.DROPTEXT:
|
||||
print(ev)
|
||||
spr_file_text = font.render(ev.text, 1, (255, 255, 255))
|
||||
spr_file_text_rect = spr_file_text.get_rect()
|
||||
spr_file_text_rect.center = surf.get_rect().center
|
||||
elif event.type == pygame.DROPFILE:
|
||||
print(event)
|
||||
spr_file_text = font.render(
|
||||
event.file, True, (255, 255, 255), None, screen_size[0] - 10
|
||||
)
|
||||
elif ev.type == pg.DROPFILE:
|
||||
print(ev)
|
||||
spr_file_text = font.render(ev.file, 1, (255, 255, 255))
|
||||
spr_file_text_rect = spr_file_text.get_rect()
|
||||
spr_file_text_rect.center = surf.get_rect().center
|
||||
|
||||
# Try to open the file if it's an image
|
||||
filetype = event.file[-3:]
|
||||
filetype = ev.file[-3:]
|
||||
if filetype in ["png", "bmp", "jpg"]:
|
||||
spr_file_image = pygame.image.load(event.file).convert()
|
||||
spr_file_image = pg.image.load(ev.file).convert()
|
||||
spr_file_image.set_alpha(127)
|
||||
spr_file_image_rect = spr_file_image.get_rect()
|
||||
spr_file_image_rect.center = surf.get_rect().center
|
||||
|
||||
surf.fill((0, 0, 0))
|
||||
surf.blit(spr_file_text, spr_file_text_rect)
|
||||
if spr_file_image:
|
||||
if spr_file_image and spr_file_image_rect is not None:
|
||||
surf.blit(spr_file_image, spr_file_image_rect)
|
||||
|
||||
pygame.display.flip()
|
||||
pg.display.flip()
|
||||
clock.tick(30)
|
||||
|
||||
pygame.quit()
|
||||
pg.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.eventlist
|
||||
""" pygame.examples.eventlist
|
||||
|
||||
Learn about pygame events and input.
|
||||
|
||||
@@ -12,7 +12,7 @@ usage = """
|
||||
Mouse Controls
|
||||
==============
|
||||
|
||||
- 1st button on mouse (left click) to toggle events 'grabbed'.
|
||||
- 1st button on mouse (left click) to toggle events 'grabed'.
|
||||
- 3rd button on mouse (right click) to toggle mouse visible.
|
||||
- The window can be resized.
|
||||
- Mouse the mouse around to see mouse events.
|
||||
@@ -24,20 +24,17 @@ Keyboard Joystick Controls
|
||||
|
||||
- press keys up an down to see events.
|
||||
- you can see joystick events if any are plugged in.
|
||||
- press "c" to toggle events generated by controllers.
|
||||
"""
|
||||
|
||||
import pygame
|
||||
from typing import List
|
||||
import pygame as pg
|
||||
|
||||
try:
|
||||
import pygame._sdl2.controller
|
||||
import pygame._sdl2.controller
|
||||
|
||||
pygame._sdl2.controller.init()
|
||||
SDL2 = True
|
||||
except ImportError:
|
||||
SDL2 = False
|
||||
|
||||
img_on_off = []
|
||||
font = None
|
||||
img_on_off: List[pg.Surface] = []
|
||||
font: pg.font.Font
|
||||
last_key = None
|
||||
|
||||
# these are a running counter of mouse.get_rel() calls.
|
||||
@@ -58,36 +55,36 @@ def drawstatus(win):
|
||||
win.blit(font.render("Status Area", 1, (155, 155, 155), bgcolor), (2, 2))
|
||||
|
||||
pos = showtext(win, (10, 30), "Mouse Focus", (255, 255, 255), bgcolor)
|
||||
win.blit(img_on_off[pygame.mouse.get_focused()], pos)
|
||||
win.blit(img_on_off[pg.mouse.get_focused()], pos)
|
||||
|
||||
pos = showtext(
|
||||
win, (pos[0] + 50, pos[1]), "Mouse visible", (255, 255, 255), bgcolor
|
||||
)
|
||||
win.blit(img_on_off[pygame.mouse.get_visible()], pos)
|
||||
win.blit(img_on_off[pg.mouse.get_visible()], pos)
|
||||
|
||||
pos = showtext(win, (330, 30), "Keyboard Focus", (255, 255, 255), bgcolor)
|
||||
win.blit(img_on_off[pygame.key.get_focused()], pos)
|
||||
win.blit(img_on_off[pg.key.get_focused()], pos)
|
||||
|
||||
pos = showtext(win, (10, 60), "Mouse Position(rel)", (255, 255, 255), bgcolor)
|
||||
rel = pygame.mouse.get_rel()
|
||||
rel = pg.mouse.get_rel()
|
||||
virtual_x += rel[0]
|
||||
virtual_y += rel[1]
|
||||
|
||||
mouse_data = tuple(list(pygame.mouse.get_pos()) + list(rel))
|
||||
mouse_data = tuple(list(pg.mouse.get_pos()) + list(rel))
|
||||
p = "%s, %s (%s, %s)" % mouse_data
|
||||
showtext(win, pos, p, bgcolor, (255, 255, 55))
|
||||
|
||||
pos = showtext(win, (330, 60), "Last Keypress", (255, 255, 255), bgcolor)
|
||||
if last_key:
|
||||
p = "%d, %s" % (last_key, pygame.key.name(last_key))
|
||||
p = "%d, %s" % (last_key, pg.key.name(last_key))
|
||||
else:
|
||||
p = "None"
|
||||
showtext(win, pos, p, bgcolor, (255, 255, 55))
|
||||
|
||||
pos = showtext(win, (10, 90), "Input Grabbed", (255, 255, 255), bgcolor)
|
||||
win.blit(img_on_off[pygame.event.get_grab()], pos)
|
||||
win.blit(img_on_off[pg.event.get_grab()], pos)
|
||||
|
||||
is_virtual_mouse = pygame.event.get_grab() and not pygame.mouse.get_visible()
|
||||
is_virtual_mouse = pg.event.get_grab() and not pg.mouse.get_visible()
|
||||
pos = showtext(win, (330, 90), "Virtual Mouse", (255, 255, 255), bgcolor)
|
||||
win.blit(img_on_off[is_virtual_mouse], pos)
|
||||
if is_virtual_mouse:
|
||||
@@ -98,84 +95,98 @@ def drawstatus(win):
|
||||
def drawhistory(win, history):
|
||||
img = font.render("Event History Area", 1, (155, 155, 155), (0, 0, 0))
|
||||
win.blit(img, (2, 132))
|
||||
|
||||
img = font.render("\n".join(history), 1, (50, 200, 50), (0, 0, 0), wraplength=640)
|
||||
win.blit(img, (10, 250))
|
||||
ypos = 450
|
||||
h = list(history)
|
||||
h.reverse()
|
||||
for line in h:
|
||||
r = win.blit(line, (10, ypos))
|
||||
win.fill(0, (r.right, r.top, 620, r.height))
|
||||
ypos -= font.get_height()
|
||||
|
||||
|
||||
def draw_usage_in_history(history, text):
|
||||
for line in text.split("\n"):
|
||||
if "===" not in line and line != "":
|
||||
history.append(line)
|
||||
lines = text.split("\n")
|
||||
for line in lines:
|
||||
if line == "" or "===" in line:
|
||||
continue
|
||||
img = font.render(line, 1, (50, 200, 50), (0, 0, 0))
|
||||
history.append(img)
|
||||
|
||||
|
||||
def main():
|
||||
pygame.init()
|
||||
pg.init()
|
||||
pygame._sdl2.controller.init()
|
||||
|
||||
print(usage)
|
||||
|
||||
win = pygame.display.set_mode((640, 480), pygame.RESIZABLE)
|
||||
pygame.display.set_caption("Mouse Focus Workout. h key for help")
|
||||
win = pg.display.set_mode((640, 480), pg.RESIZABLE)
|
||||
pg.display.set_caption("Mouse Focus Workout. h key for help")
|
||||
|
||||
global font
|
||||
font = pygame.Font(None, 26)
|
||||
font = pg.font.Font(None, 26)
|
||||
|
||||
global img_on_off
|
||||
img_on_off.append(font.render("Off", 1, (0, 0, 0), (255, 50, 50)))
|
||||
img_on_off.append(font.render("On", 1, (0, 0, 0), (50, 255, 50)))
|
||||
|
||||
# stores lines of text representing what has gone through the event queue
|
||||
# stores surfaces of text representing what has gone through the event queue
|
||||
history = []
|
||||
|
||||
# let's turn on the joysticks just so we can play with em
|
||||
for x in range(pygame.joystick.get_count()):
|
||||
if SDL2 and pygame._sdl2.controller.is_controller(x):
|
||||
for x in range(pg.joystick.get_count()):
|
||||
if pygame._sdl2.controller.is_controller(x):
|
||||
c = pygame._sdl2.controller.Controller(x)
|
||||
txt = f"Enabled controller: {c.name}"
|
||||
txt = "Enabled controller: " + c.name
|
||||
else:
|
||||
j = pygame.joystick.Joystick(x)
|
||||
txt = f"Enabled joystick: {j.get_name()}"
|
||||
j = pg.joystick.Joystick(x)
|
||||
txt = "Enabled joystick: " + j.get_name()
|
||||
|
||||
history.append(txt)
|
||||
|
||||
if not pygame.joystick.get_count():
|
||||
history.append("No Joysticks to Initialize")
|
||||
img = font.render(txt, 1, (50, 200, 50), (0, 0, 0))
|
||||
history.append(img)
|
||||
if not pg.joystick.get_count():
|
||||
img = font.render("No Joysticks to Initialize", 1, (50, 200, 50), (0, 0, 0))
|
||||
history.append(img)
|
||||
|
||||
going = True
|
||||
while going:
|
||||
for e in pygame.event.get():
|
||||
if e.type == pygame.KEYDOWN:
|
||||
if e.key == pygame.K_ESCAPE:
|
||||
for e in pg.event.get():
|
||||
if e.type == pg.KEYDOWN:
|
||||
if e.key == pg.K_ESCAPE:
|
||||
going = False
|
||||
else:
|
||||
global last_key
|
||||
last_key = e.key
|
||||
if e.key == pygame.K_h:
|
||||
if e.key == pg.K_h:
|
||||
draw_usage_in_history(history, usage)
|
||||
if e.key == pg.K_c:
|
||||
current_state = pygame._sdl2.controller.get_eventstate()
|
||||
pygame._sdl2.controller.set_eventstate(not current_state)
|
||||
|
||||
if e.type == pygame.MOUSEBUTTONDOWN and e.button == 1:
|
||||
pygame.event.set_grab(not pygame.event.get_grab())
|
||||
if e.type == pg.MOUSEBUTTONDOWN and e.button == 1:
|
||||
pg.event.set_grab(not pg.event.get_grab())
|
||||
|
||||
if e.type == pygame.MOUSEBUTTONDOWN and e.button == 3:
|
||||
pygame.mouse.set_visible(not pygame.mouse.get_visible())
|
||||
if e.type == pg.MOUSEBUTTONDOWN and e.button == 3:
|
||||
pg.mouse.set_visible(not pg.mouse.get_visible())
|
||||
|
||||
if e.type != pygame.MOUSEMOTION:
|
||||
txt = f"{pygame.event.event_name(e.type)}: {e.dict}"
|
||||
history.append(txt)
|
||||
if e.type != pg.MOUSEMOTION:
|
||||
txt = f"{pg.event.event_name(e.type)}: {e.dict}"
|
||||
img = font.render(txt, 1, (50, 200, 50), (0, 0, 0))
|
||||
history.append(img)
|
||||
history = history[-13:]
|
||||
|
||||
if e.type == pygame.VIDEORESIZE:
|
||||
win = pygame.display.set_mode(e.size, pygame.RESIZABLE)
|
||||
if e.type == pg.VIDEORESIZE:
|
||||
win = pg.display.set_mode(e.size, pg.RESIZABLE)
|
||||
|
||||
if e.type == pygame.QUIT:
|
||||
if e.type == pg.QUIT:
|
||||
going = False
|
||||
|
||||
drawstatus(win)
|
||||
drawhistory(win, history)
|
||||
|
||||
pygame.display.flip()
|
||||
pygame.time.wait(10)
|
||||
pg.display.flip()
|
||||
pg.time.wait(10)
|
||||
|
||||
pygame.quit()
|
||||
pg.quit()
|
||||
raise SystemExit
|
||||
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.font_viewer
|
||||
""" pygame.examples.font_viewer
|
||||
Scroll through your system fonts from a list of surfaces or one huge buffer.
|
||||
|
||||
This example exhibits:
|
||||
@@ -22,11 +22,10 @@ Keyboard Controls:
|
||||
* Press up or down to scroll
|
||||
* Press escape to exit
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import os
|
||||
|
||||
import pygame
|
||||
import pygame as pg
|
||||
|
||||
use_big_surface = False # draw into large buffer and save png file
|
||||
|
||||
@@ -42,15 +41,16 @@ class FontViewer:
|
||||
MOUSE_SCROLL_SPEED = 50
|
||||
|
||||
def __init__(self):
|
||||
pygame.init()
|
||||
pg.init()
|
||||
|
||||
# create a window that uses 80 percent of the screen
|
||||
info = pygame.display.Info()
|
||||
self.screen_size = (int(info.current_w * 0.8), int(info.current_h * 0.8))
|
||||
pygame.display.set_mode(self.screen_size)
|
||||
self.font_size = self.screen_size[1] // 16
|
||||
info = pg.display.Info()
|
||||
w = info.current_w
|
||||
h = info.current_h
|
||||
pg.display.set_mode((int(w * 0.8), int(h * 0.8)))
|
||||
self.font_size = h // 20
|
||||
|
||||
self.clock = pygame.Clock()
|
||||
self.clock = pg.time.Clock()
|
||||
self.y_offset = 0
|
||||
self.grabbed = False
|
||||
self.render_fonts("&N abcDEF789")
|
||||
@@ -70,10 +70,11 @@ class FontViewer:
|
||||
path = ""
|
||||
if len(sys.argv) > 1 and os.path.exists(sys.argv[1]):
|
||||
path = os.path.join(sys.argv[1], "")
|
||||
fonts = []
|
||||
if os.path.exists(path):
|
||||
fonts = [font for font in os.listdir(path) if font.endswith(".ttf")]
|
||||
return fonts or pygame.font.get_fonts(), path
|
||||
else:
|
||||
fonts = pg.font.get_fonts()
|
||||
return fonts, path
|
||||
|
||||
def render_fonts(self, text="A display of font &N"):
|
||||
"""
|
||||
@@ -91,27 +92,23 @@ class FontViewer:
|
||||
total_height = 0
|
||||
max_width = 0
|
||||
|
||||
load_font = pygame.Font if path else pygame.font.SysFont
|
||||
load_font = pg.font.Font if path else pg.font.SysFont
|
||||
|
||||
# display instructions at the top of the display
|
||||
font = pygame.font.SysFont(pygame.font.get_default_font(), font_size)
|
||||
font.align = pygame.FONT_CENTER
|
||||
instructions = (
|
||||
"Use the scroll wheel or click and drag to scroll up "
|
||||
"and down. Fonts that don't use the Latin Alphabet "
|
||||
"might render incorrectly. Here are your "
|
||||
f"{len(fonts)} fonts"
|
||||
font = pg.font.SysFont(pg.font.get_default_font(), font_size)
|
||||
lines = (
|
||||
"Use the scroll wheel or click and drag",
|
||||
"to scroll up and down.",
|
||||
"Fonts that don't use the Latin Alphabet",
|
||||
"might render incorrectly.",
|
||||
f"Here are your {len(fonts)} fonts",
|
||||
"",
|
||||
)
|
||||
surf = font.render(
|
||||
instructions,
|
||||
True,
|
||||
instruction_color,
|
||||
self.back_color,
|
||||
self.screen_size[0] - 20,
|
||||
)
|
||||
font_surfaces.append((surf, total_height))
|
||||
total_height += surf.get_height()
|
||||
max_width = max(max_width, surf.get_width())
|
||||
for line in lines:
|
||||
surf = font.render(line, 1, instruction_color, self.back_color)
|
||||
font_surfaces.append((surf, total_height))
|
||||
total_height += surf.get_height()
|
||||
max_width = max(max_width, surf.get_width())
|
||||
|
||||
# render all the fonts and store them with the total height
|
||||
for name in sorted(fonts):
|
||||
@@ -121,10 +118,8 @@ class FontViewer:
|
||||
continue
|
||||
line = text.replace("&N", name)
|
||||
try:
|
||||
surf = font.render(
|
||||
line, True, color, self.back_color, self.screen_size[0] - 20
|
||||
)
|
||||
except pygame.error as e:
|
||||
surf = font.render(line, 1, color, self.back_color)
|
||||
except pg.error as e:
|
||||
print(e)
|
||||
break
|
||||
|
||||
@@ -136,16 +131,16 @@ class FontViewer:
|
||||
self.total_height = total_height
|
||||
self.max_width = max_width
|
||||
self.font_surfaces = font_surfaces
|
||||
self.max_y = total_height - pygame.display.get_surface().get_height()
|
||||
self.max_y = total_height - pg.display.get_surface().get_height()
|
||||
|
||||
def display_fonts(self):
|
||||
"""
|
||||
Display the visible fonts based on the y_offset value(updated in
|
||||
handle_events) and the height of the pygame window.
|
||||
"""
|
||||
pygame.display.set_caption("Font Viewer")
|
||||
display = pygame.display.get_surface()
|
||||
clock = pygame.Clock()
|
||||
pg.display.set_caption("Font Viewer")
|
||||
display = pg.display.get_surface()
|
||||
clock = pg.time.Clock()
|
||||
center = display.get_width() // 2
|
||||
|
||||
while True:
|
||||
@@ -157,12 +152,12 @@ class FontViewer:
|
||||
bottom >= self.y_offset
|
||||
and top <= self.y_offset + display.get_height()
|
||||
):
|
||||
x = center - surface.get_width() / 2
|
||||
x = center - surface.get_width() // 2
|
||||
display.blit(surface, (x, top - self.y_offset))
|
||||
# get input and update the screen
|
||||
if not self.handle_events():
|
||||
break
|
||||
pygame.display.flip()
|
||||
pg.display.flip()
|
||||
clock.tick(30)
|
||||
|
||||
def render_surface(self):
|
||||
@@ -175,7 +170,7 @@ class FontViewer:
|
||||
be useful for testing large surfaces.
|
||||
"""
|
||||
|
||||
large_surface = pygame.surface.Surface(
|
||||
large_surface = pg.surface.Surface(
|
||||
(self.max_width, self.total_height)
|
||||
).convert()
|
||||
large_surface.fill(self.back_color)
|
||||
@@ -197,9 +192,7 @@ class FontViewer:
|
||||
x = center - int(w / 2)
|
||||
large_surface.blit(surface, (x, y))
|
||||
y += surface.get_height()
|
||||
self.max_y = (
|
||||
large_surface.get_height() - pygame.display.get_surface().get_height()
|
||||
)
|
||||
self.max_y = large_surface.get_height() - pg.display.get_surface().get_height()
|
||||
self.surface = large_surface
|
||||
|
||||
def display_surface(self, time=10):
|
||||
@@ -208,12 +201,12 @@ class FontViewer:
|
||||
based on the y_offset value(set in handle_events) and the height of the
|
||||
pygame window.
|
||||
"""
|
||||
screen = pygame.display.get_surface()
|
||||
screen = pg.display.get_surface()
|
||||
|
||||
# Create a Rect equal to size of screen. Then we can just change its
|
||||
# top attribute to draw the desired part of the rendered font surface
|
||||
# to the display surface
|
||||
rect = pygame.rect.Rect(
|
||||
rect = pg.rect.Rect(
|
||||
0,
|
||||
0,
|
||||
self.surface.get_width(),
|
||||
@@ -228,11 +221,11 @@ class FontViewer:
|
||||
screen.fill(self.back_color)
|
||||
rect.top = self.y_offset
|
||||
screen.blit(self.surface, (x, 0), rect)
|
||||
pygame.display.flip()
|
||||
pg.display.flip()
|
||||
self.clock.tick(20)
|
||||
|
||||
def save_png(self, name="font_viewer.png"):
|
||||
pygame.image.save(self.surface, name)
|
||||
pg.image.save(self.surface, name)
|
||||
file_size = os.path.getsize(name) // 1024
|
||||
print(f"font surface saved to {name}\nsize: {file_size:,}Kb")
|
||||
|
||||
@@ -243,37 +236,37 @@ class FontViewer:
|
||||
changed based on mouse and keyboard input. display_fonts() and
|
||||
display_surface() use the y_offset to scroll display.
|
||||
"""
|
||||
events = pygame.event.get()
|
||||
events = pg.event.get()
|
||||
for e in events:
|
||||
if e.type == pygame.QUIT:
|
||||
if e.type == pg.QUIT:
|
||||
return False
|
||||
elif e.type == pygame.KEYDOWN:
|
||||
if e.key == pygame.K_ESCAPE:
|
||||
elif e.type == pg.KEYDOWN:
|
||||
if e.key == pg.K_ESCAPE:
|
||||
return False
|
||||
elif e.type == pygame.MOUSEWHEEL:
|
||||
elif e.type == pg.MOUSEWHEEL:
|
||||
self.y_offset += e.y * self.MOUSE_SCROLL_SPEED * -1
|
||||
elif e.type == pygame.MOUSEBUTTONDOWN:
|
||||
elif e.type == pg.MOUSEBUTTONDOWN:
|
||||
# enter dragging mode on mouse down
|
||||
self.grabbed = True
|
||||
pygame.event.set_grab(True)
|
||||
elif e.type == pygame.MOUSEBUTTONUP:
|
||||
pg.event.set_grab(True)
|
||||
elif e.type == pg.MOUSEBUTTONUP:
|
||||
# exit drag mode on mouse up
|
||||
self.grabbed = False
|
||||
pygame.event.set_grab(False)
|
||||
pg.event.set_grab(False)
|
||||
|
||||
# allow simple accelerated scrolling with the keyboard
|
||||
keys = pygame.key.get_pressed()
|
||||
if keys[pygame.K_UP]:
|
||||
keys = pg.key.get_pressed()
|
||||
if keys[pg.K_UP]:
|
||||
self.key_held += 1
|
||||
self.y_offset -= int(self.KEY_SCROLL_SPEED * (self.key_held // 10))
|
||||
elif keys[pygame.K_DOWN]:
|
||||
elif keys[pg.K_DOWN]:
|
||||
self.key_held += 1
|
||||
self.y_offset += int(self.KEY_SCROLL_SPEED * (self.key_held // 10))
|
||||
else:
|
||||
self.key_held = 20
|
||||
|
||||
# set the y_offset for scrolling and keep it between 0 and max_y
|
||||
y = pygame.mouse.get_rel()[1]
|
||||
y = pg.mouse.get_rel()[1]
|
||||
if y and self.grabbed:
|
||||
self.y_offset -= y
|
||||
|
||||
@@ -281,6 +274,5 @@ class FontViewer:
|
||||
return True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
viewer = FontViewer()
|
||||
pygame.quit()
|
||||
viewer = FontViewer()
|
||||
pg.quit()
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.fonty
|
||||
""" pygame.examples.fonty
|
||||
|
||||
Here we load a .TTF True Type font file, and display it in
|
||||
a basic pygame window.
|
||||
@@ -8,17 +8,16 @@ Demonstrating several Font object attributes.
|
||||
|
||||
- basic window, event, and font management.
|
||||
"""
|
||||
|
||||
import pygame
|
||||
import pygame as pg
|
||||
|
||||
|
||||
def main():
|
||||
# initialize
|
||||
pygame.init()
|
||||
pg.init()
|
||||
resolution = 400, 200
|
||||
screen = pygame.display.set_mode(resolution)
|
||||
screen = pg.display.set_mode(resolution)
|
||||
|
||||
## pygame.mouse.set_cursor(*pygame.cursors.diamond)
|
||||
## pg.mouse.set_cursor(*pg.cursors.diamond)
|
||||
|
||||
fg = 250, 240, 230
|
||||
bg = 5, 5, 5
|
||||
@@ -28,7 +27,7 @@ def main():
|
||||
screen.fill(wincolor)
|
||||
|
||||
# load font, prepare values
|
||||
font = pygame.Font(None, 80)
|
||||
font = pg.font.Font(None, 80)
|
||||
text = "Fonty"
|
||||
size = font.size(text)
|
||||
|
||||
@@ -42,7 +41,7 @@ def main():
|
||||
screen.blit(ren, (10, 40 + size[1]))
|
||||
font.set_underline(0)
|
||||
|
||||
a_sys_font = pygame.font.SysFont("Arial", 60)
|
||||
a_sys_font = pg.font.SysFont("Arial", 60)
|
||||
|
||||
# AA, no transparency, bold
|
||||
a_sys_font.set_bold(1)
|
||||
@@ -70,16 +69,12 @@ def main():
|
||||
##screen.blit(ren, (30 + size[0], 40 + size[1]))
|
||||
|
||||
# show the surface and await user quit
|
||||
pygame.display.flip()
|
||||
pg.display.flip()
|
||||
while True:
|
||||
# use event.wait to keep from polling 100% cpu
|
||||
if pygame.event.wait().type in (
|
||||
pygame.QUIT,
|
||||
pygame.KEYDOWN,
|
||||
pygame.MOUSEBUTTONDOWN,
|
||||
):
|
||||
if pg.event.wait().type in (pg.QUIT, pg.KEYDOWN, pg.MOUSEBUTTONDOWN):
|
||||
break
|
||||
pygame.quit()
|
||||
pg.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.freetype_misc
|
||||
""" pygame.examples.freetype_misc
|
||||
|
||||
|
||||
Miscellaneous (or misc) means:
|
||||
@@ -29,20 +29,18 @@ Herein lies a *BOLD* demo consisting of a mixture of various things.
|
||||
|
||||
Enjoy!
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
import pygame
|
||||
import pygame as pg
|
||||
import pygame.freetype as freetype
|
||||
|
||||
|
||||
def run():
|
||||
pygame.init()
|
||||
pg.init()
|
||||
|
||||
fontdir = os.path.dirname(os.path.abspath(__file__))
|
||||
font = freetype.Font(os.path.join(fontdir, "data", "sans.ttf"))
|
||||
|
||||
screen = pygame.display.set_mode((800, 600))
|
||||
screen = pg.display.set_mode((800, 600))
|
||||
screen.fill("gray")
|
||||
|
||||
font.underline_adjustment = 0.5
|
||||
@@ -146,17 +144,13 @@ def run():
|
||||
style=freetype.STYLE_NORMAL,
|
||||
)
|
||||
|
||||
pygame.display.flip()
|
||||
pg.display.flip()
|
||||
|
||||
while True:
|
||||
if pygame.event.wait().type in (
|
||||
pygame.QUIT,
|
||||
pygame.KEYDOWN,
|
||||
pygame.MOUSEBUTTONDOWN,
|
||||
):
|
||||
if pg.event.wait().type in (pg.QUIT, pg.KEYDOWN, pg.MOUSEBUTTONDOWN):
|
||||
break
|
||||
|
||||
pygame.quit()
|
||||
pg.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.glcube
|
||||
""" pygame.examples.glcube
|
||||
|
||||
Draw a cube on the screen.
|
||||
|
||||
@@ -23,11 +23,10 @@ Keyboard Controls
|
||||
* f key to toggle fullscreen.
|
||||
|
||||
"""
|
||||
|
||||
import ctypes
|
||||
import math
|
||||
import ctypes
|
||||
|
||||
import pygame
|
||||
import pygame as pg
|
||||
|
||||
try:
|
||||
import OpenGL.GL as GL
|
||||
@@ -37,11 +36,12 @@ except ImportError:
|
||||
raise SystemExit
|
||||
|
||||
try:
|
||||
from numpy import array, dot, eye, float32, uint32, zeros
|
||||
from numpy import array, dot, eye, zeros, float32, uint32
|
||||
except ImportError:
|
||||
print("numpy missing. The GLCUBE example requires: pyopengl numpy")
|
||||
raise SystemExit
|
||||
|
||||
|
||||
# do we want to use the 'modern' OpenGL API or the old one?
|
||||
# This example shows you how to do both.
|
||||
USE_MODERN_GL = True
|
||||
@@ -259,16 +259,16 @@ def init_gl_modern(display_size):
|
||||
uniform mat4 view;
|
||||
uniform mat4 projection;
|
||||
|
||||
uniform vec4 color_mul;
|
||||
uniform vec4 color_add;
|
||||
uniform vec4 colour_mul;
|
||||
uniform vec4 colour_add;
|
||||
|
||||
in vec4 vertex_color; // vertex color in
|
||||
in vec4 vertex_colour; // vertex colour in
|
||||
in vec3 vertex_position;
|
||||
|
||||
out vec4 vertex_color_out; // vertex color out
|
||||
out vec4 vertex_color_out; // vertex colour out
|
||||
void main()
|
||||
{
|
||||
vertex_color_out = (color_mul * vertex_color) + color_add;
|
||||
vertex_color_out = (colour_mul * vertex_colour) + colour_add;
|
||||
gl_Position = projection * view * model * vec4(vertex_position, 1.0);
|
||||
}
|
||||
|
||||
@@ -276,7 +276,7 @@ def init_gl_modern(display_size):
|
||||
|
||||
fragment_code = """
|
||||
#version 150
|
||||
in vec4 vertex_color_out; // vertex color from vertex shader
|
||||
in vec4 vertex_color_out; // vertex colour from vertex shader
|
||||
out vec4 fragColor;
|
||||
void main()
|
||||
{
|
||||
@@ -320,7 +320,9 @@ def init_gl_modern(display_size):
|
||||
# ------------------------------------------
|
||||
|
||||
# Cube Data
|
||||
vertices = zeros(8, [("vertex_position", float32, 3), ("vertex_color", float32, 4)])
|
||||
vertices = zeros(
|
||||
8, [("vertex_position", float32, 3), ("vertex_colour", float32, 4)]
|
||||
)
|
||||
|
||||
vertices["vertex_position"] = [
|
||||
[1, 1, 1],
|
||||
@@ -333,7 +335,7 @@ def init_gl_modern(display_size):
|
||||
[-1, -1, -1],
|
||||
]
|
||||
|
||||
vertices["vertex_color"] = [
|
||||
vertices["vertex_colour"] = [
|
||||
[0, 1, 1, 1],
|
||||
[0, 0, 1, 1],
|
||||
[0, 0, 0, 1],
|
||||
@@ -408,7 +410,7 @@ def init_gl_modern(display_size):
|
||||
|
||||
offset = ctypes.c_void_p(vertices.dtype["vertex_position"].itemsize)
|
||||
|
||||
loc = GL.glGetAttribLocation(program, "vertex_color")
|
||||
loc = GL.glGetAttribLocation(program, "vertex_colour")
|
||||
GL.glEnableVertexAttribArray(loc)
|
||||
GL.glVertexAttribPointer(loc, 4, GL.GL_FLOAT, False, stride, offset)
|
||||
|
||||
@@ -442,19 +444,19 @@ def init_gl_modern(display_size):
|
||||
)
|
||||
GL.glUniformMatrix4fv(shader_data["constants"]["projection"], 1, False, eye(4))
|
||||
|
||||
# This color is multiplied with the base vertex color in producing
|
||||
# This colour is multiplied with the base vertex colour in producing
|
||||
# the final output
|
||||
shader_data["constants"]["color_mul"] = GL.glGetUniformLocation(
|
||||
program, "color_mul"
|
||||
shader_data["constants"]["colour_mul"] = GL.glGetUniformLocation(
|
||||
program, "colour_mul"
|
||||
)
|
||||
GL.glUniform4f(shader_data["constants"]["color_mul"], 1, 1, 1, 1)
|
||||
GL.glUniform4f(shader_data["constants"]["colour_mul"], 1, 1, 1, 1)
|
||||
|
||||
# This color is added on to the base vertex color in producing
|
||||
# This colour is added on to the base vertex colour in producing
|
||||
# the final output
|
||||
shader_data["constants"]["color_add"] = GL.glGetUniformLocation(
|
||||
program, "color_add"
|
||||
shader_data["constants"]["colour_add"] = GL.glGetUniformLocation(
|
||||
program, "colour_add"
|
||||
)
|
||||
GL.glUniform4f(shader_data["constants"]["color_add"], 0, 0, 0, 0)
|
||||
GL.glUniform4f(shader_data["constants"]["colour_add"], 0, 0, 0, 0)
|
||||
|
||||
# Set GL drawing data
|
||||
# -------------------
|
||||
@@ -489,8 +491,8 @@ def draw_cube_modern(shader_data, filled_cube_indices, outline_cube_indices, rot
|
||||
GL.glDisable(GL.GL_BLEND)
|
||||
GL.glEnable(GL.GL_DEPTH_TEST)
|
||||
GL.glEnable(GL.GL_POLYGON_OFFSET_FILL)
|
||||
GL.glUniform4f(shader_data["constants"]["color_mul"], 1, 1, 1, 1)
|
||||
GL.glUniform4f(shader_data["constants"]["color_add"], 0, 0, 0, 0.0)
|
||||
GL.glUniform4f(shader_data["constants"]["colour_mul"], 1, 1, 1, 1)
|
||||
GL.glUniform4f(shader_data["constants"]["colour_add"], 0, 0, 0, 0.0)
|
||||
GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, shader_data["buffer"]["filled"])
|
||||
GL.glDrawElements(
|
||||
GL.GL_TRIANGLES, len(filled_cube_indices), GL.GL_UNSIGNED_INT, None
|
||||
@@ -499,14 +501,14 @@ def draw_cube_modern(shader_data, filled_cube_indices, outline_cube_indices, rot
|
||||
# Outlined cube
|
||||
GL.glDisable(GL.GL_POLYGON_OFFSET_FILL)
|
||||
GL.glEnable(GL.GL_BLEND)
|
||||
GL.glUniform4f(shader_data["constants"]["color_mul"], 0, 0, 0, 0.0)
|
||||
GL.glUniform4f(shader_data["constants"]["color_add"], 1, 1, 1, 1.0)
|
||||
GL.glUniform4f(shader_data["constants"]["colour_mul"], 0, 0, 0, 0.0)
|
||||
GL.glUniform4f(shader_data["constants"]["colour_add"], 1, 1, 1, 1.0)
|
||||
GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, shader_data["buffer"]["outline"])
|
||||
GL.glDrawElements(GL.GL_LINES, len(outline_cube_indices), GL.GL_UNSIGNED_INT, None)
|
||||
|
||||
# Rotate cube
|
||||
# rotation.theta += 1.0 # degrees
|
||||
# rotation.phi += 1.0 # degrees
|
||||
rotation.phi += 1.0 # degrees
|
||||
# rotation.psi += 1.0 # degrees
|
||||
model = eye(4, dtype=float32)
|
||||
# rotate(model, rotation.theta, 0, 0, 1)
|
||||
@@ -518,10 +520,8 @@ def draw_cube_modern(shader_data, filled_cube_indices, outline_cube_indices, rot
|
||||
def main():
|
||||
"""run the demo"""
|
||||
|
||||
# initialize pygame-ce and setup an opengl display
|
||||
|
||||
pygame.init()
|
||||
clock = pygame.time.Clock()
|
||||
# initialize pygame and setup an opengl display
|
||||
pg.init()
|
||||
|
||||
gl_version = (3, 0) # GL Version number (Major, Minor)
|
||||
if USE_MODERN_GL:
|
||||
@@ -529,22 +529,16 @@ def main():
|
||||
|
||||
# By setting these attributes we can choose which Open GL Profile
|
||||
# to use, profiles greater than 3.2 use a different rendering path
|
||||
pygame.display.gl_set_attribute(pygame.GL_CONTEXT_MAJOR_VERSION, gl_version[0])
|
||||
pygame.display.gl_set_attribute(pygame.GL_CONTEXT_MINOR_VERSION, gl_version[1])
|
||||
pygame.display.gl_set_attribute(
|
||||
pygame.GL_CONTEXT_PROFILE_MASK, pygame.GL_CONTEXT_PROFILE_CORE
|
||||
pg.display.gl_set_attribute(pg.GL_CONTEXT_MAJOR_VERSION, gl_version[0])
|
||||
pg.display.gl_set_attribute(pg.GL_CONTEXT_MINOR_VERSION, gl_version[1])
|
||||
pg.display.gl_set_attribute(
|
||||
pg.GL_CONTEXT_PROFILE_MASK, pg.GL_CONTEXT_PROFILE_CORE
|
||||
)
|
||||
|
||||
# start in windowed mode
|
||||
fullscreen = False # start in windowed mode
|
||||
|
||||
display_size = (640, 480)
|
||||
try:
|
||||
pygame.display.set_mode(
|
||||
display_size, pygame.OPENGL | pygame.DOUBLEBUF | pygame.RESIZABLE, vsync=1
|
||||
)
|
||||
except:
|
||||
pygame.display.set_mode(
|
||||
display_size, pygame.OPENGL | pygame.DOUBLEBUF | pygame.RESIZABLE
|
||||
)
|
||||
pg.display.set_mode(display_size, pg.OPENGL | pg.DOUBLEBUF | pg.RESIZABLE)
|
||||
|
||||
if USE_MODERN_GL:
|
||||
gpu, f_indices, o_indices = init_gl_modern(display_size)
|
||||
@@ -552,55 +546,45 @@ def main():
|
||||
else:
|
||||
init_gl_stuff_old()
|
||||
|
||||
delta_time = 0
|
||||
going = True
|
||||
while going:
|
||||
# check for quit'n events
|
||||
events = pygame.event.get()
|
||||
events = pg.event.get()
|
||||
for event in events:
|
||||
if event.type == pygame.QUIT or (
|
||||
event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE
|
||||
if event.type == pg.QUIT or (
|
||||
event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE
|
||||
):
|
||||
going = False
|
||||
|
||||
elif event.type == pygame.KEYDOWN and event.key == pygame.K_f:
|
||||
if not pygame.display.is_fullscreen():
|
||||
elif event.type == pg.KEYDOWN and event.key == pg.K_f:
|
||||
if not fullscreen:
|
||||
print("Changing to FULLSCREEN")
|
||||
pygame.display.set_mode(
|
||||
display_size,
|
||||
pygame.OPENGL | pygame.DOUBLEBUF | pygame.FULLSCREEN,
|
||||
pg.display.set_mode(
|
||||
(640, 480), pg.OPENGL | pg.DOUBLEBUF | pg.FULLSCREEN
|
||||
)
|
||||
else:
|
||||
print("Changing to windowed mode")
|
||||
pygame.display.set_mode(
|
||||
display_size, pygame.OPENGL | pygame.DOUBLEBUF
|
||||
)
|
||||
|
||||
pg.display.set_mode((640, 480), pg.OPENGL | pg.DOUBLEBUF)
|
||||
fullscreen = not fullscreen
|
||||
if gl_version[0] >= 4 or (gl_version[0] == 3 and gl_version[1] >= 2):
|
||||
gpu, f_indices, o_indices = init_gl_modern(display_size)
|
||||
rotation = Rotation()
|
||||
else:
|
||||
init_gl_stuff_old()
|
||||
|
||||
# orbit camera around by 60 degrees per second
|
||||
angle = (delta_time / 1000) * 60
|
||||
if USE_MODERN_GL:
|
||||
rotation.phi += angle
|
||||
draw_cube_modern(gpu, f_indices, o_indices, rotation)
|
||||
else:
|
||||
# clear screen and move camera
|
||||
GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
|
||||
# rotate camera to angle
|
||||
GL.glRotatef(angle, 0, 1, 0)
|
||||
# orbit camera around by 1 degree
|
||||
GL.glRotatef(1, 0, 1, 0)
|
||||
drawcube_old()
|
||||
|
||||
pygame.display.flip()
|
||||
if pygame.display.is_vsync():
|
||||
delta_time = clock.tick()
|
||||
else:
|
||||
delta_time = clock.tick(60)
|
||||
pg.display.flip()
|
||||
pg.time.wait(10)
|
||||
|
||||
pygame.quit()
|
||||
pg.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""pygame.examples.go_over_there
|
||||
""" pg.examples.go_over_there
|
||||
This simple tech demo is showcasing the use of Vector2.move_towards()
|
||||
using multiple circles to represent Vectors. Each circle will have a
|
||||
random position and speed once the demo starts.
|
||||
@@ -10,16 +10,19 @@ Keyboard Controls:
|
||||
* Press R to restart the demo
|
||||
"""
|
||||
|
||||
import pygame as pg
|
||||
import random
|
||||
|
||||
import pygame
|
||||
|
||||
MIN_SPEED = 0.25
|
||||
MAX_SPEED = 5
|
||||
MAX_BALLS = 1600
|
||||
SCREEN_SIZE = pygame.Vector2(1000, 600)
|
||||
SCREEN_SIZE = pg.Vector2(1000, 600)
|
||||
CIRCLE_RADIUS = 5
|
||||
|
||||
pg.init()
|
||||
screen = pg.display.set_mode(SCREEN_SIZE)
|
||||
clock = pg.time.Clock()
|
||||
|
||||
target_position = None
|
||||
balls = []
|
||||
|
||||
@@ -37,7 +40,7 @@ def reset():
|
||||
target_position = None
|
||||
balls = []
|
||||
for x in range(MAX_BALLS):
|
||||
pos = pygame.Vector2(
|
||||
pos = pg.Vector2(
|
||||
random.randint(0, int(SCREEN_SIZE.x)), random.randint(0, int(SCREEN_SIZE.y))
|
||||
)
|
||||
speed = random.uniform(MIN_SPEED, MAX_SPEED)
|
||||
@@ -46,47 +49,41 @@ def reset():
|
||||
balls.append(b)
|
||||
|
||||
|
||||
def main():
|
||||
global target_position
|
||||
global balls
|
||||
reset()
|
||||
delta_time = 0
|
||||
running = True
|
||||
while running:
|
||||
for event in pg.event.get():
|
||||
if event.type == pg.QUIT:
|
||||
running = False
|
||||
|
||||
pygame.init()
|
||||
screen = pygame.display.set_mode(SCREEN_SIZE)
|
||||
clock = pygame.Clock()
|
||||
if event.type == pg.MOUSEBUTTONUP:
|
||||
target_position = pg.mouse.get_pos()
|
||||
|
||||
reset()
|
||||
delta_time = 0
|
||||
running = True
|
||||
while running:
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
if event.type == pg.KEYUP:
|
||||
if event.key == pg.K_ESCAPE:
|
||||
running = False
|
||||
|
||||
if event.type == pygame.MOUSEBUTTONUP:
|
||||
target_position = pygame.mouse.get_pos()
|
||||
if event.key == pg.K_r:
|
||||
reset()
|
||||
|
||||
if event.type == pygame.KEYUP:
|
||||
if event.key == pygame.K_ESCAPE:
|
||||
running = False
|
||||
screen.fill((31, 143, 65))
|
||||
|
||||
if event.key == pygame.K_r:
|
||||
reset()
|
||||
|
||||
screen.fill((31, 143, 65))
|
||||
|
||||
for o in balls:
|
||||
if target_position is not None:
|
||||
for o in balls:
|
||||
if target_position is not None:
|
||||
try:
|
||||
o.position.move_towards_ip(target_position, o.speed * delta_time)
|
||||
pygame.draw.circle(screen, (118, 207, 145), o.position, CIRCLE_RADIUS)
|
||||
except AttributeError:
|
||||
raise RuntimeError(
|
||||
f"""Version {pg.__version__} doesn't have Vector.move_towards_ip function.
|
||||
Please update to >=2.1.3"""
|
||||
)
|
||||
pg.draw.circle(screen, (118, 207, 145), o.position, CIRCLE_RADIUS)
|
||||
|
||||
pygame.display.flip()
|
||||
delta_time = clock.tick(60)
|
||||
pygame.display.set_caption(
|
||||
f"fps: {round(clock.get_fps(), 2)}, ball count: {len(balls)}"
|
||||
)
|
||||
pg.display.flip()
|
||||
delta_time = clock.tick(60)
|
||||
pg.display.set_caption(
|
||||
f"fps: {round(clock.get_fps(), 2)}, ball count: {len(balls)}"
|
||||
)
|
||||
|
||||
pygame.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
pg.quit()
|
||||
@@ -1,13 +1,12 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.headless_no_windows_needed
|
||||
""" pygame.examples.headless_no_windows_needed
|
||||
|
||||
How to use pygame-ce with no windowing system, like on headless servers.
|
||||
How to use pygame with no windowing system, like on headless servers.
|
||||
|
||||
Thumbnail generation with scaling is an example of what you can do with pygame.
|
||||
NOTE: the pygame scale function uses mmx/sse if available, and can be run
|
||||
in multiple threads.
|
||||
"""
|
||||
|
||||
usage = """-scale inputimage outputimage new_width new_height
|
||||
eg. -scale in.png out.png 50 50
|
||||
|
||||
@@ -16,22 +15,25 @@ eg. -scale in.png out.png 50 50
|
||||
import os
|
||||
import sys
|
||||
|
||||
import pygame
|
||||
|
||||
# set SDL to use the NULL video driver,
|
||||
# set SDL to use the dummy NULL video driver,
|
||||
# so it doesn't need a windowing system.
|
||||
os.environ["SDL_VIDEODRIVER"] = pygame.NULL_VIDEODRIVER
|
||||
os.environ["SDL_VIDEODRIVER"] = "dummy"
|
||||
|
||||
import pygame as pg
|
||||
|
||||
# Some platforms need to init the display for some parts of pygame.
|
||||
pygame.display.init()
|
||||
screen = pygame.display.set_mode((1, 1))
|
||||
# Some platforms need to init the display for some parts of pg.
|
||||
pg.display.init()
|
||||
screen = pg.display.set_mode((1, 1))
|
||||
|
||||
|
||||
def scaleit(fin, fout, w, h):
|
||||
i = pygame.image.load(fin)
|
||||
scaled_image = pygame.transform.smoothscale(i, (w, h))
|
||||
pygame.image.save(scaled_image, fout)
|
||||
i = pg.image.load(fin)
|
||||
|
||||
if hasattr(pg.transform, "smoothscale"):
|
||||
scaled_image = pg.transform.smoothscale(i, (w, h))
|
||||
else:
|
||||
scaled_image = pg.transform.scale(i, (w, h))
|
||||
pg.image.save(scaled_image, fout)
|
||||
|
||||
|
||||
def main(fin, fout, w, h):
|
||||
|
||||
@@ -3,24 +3,43 @@ import pygame
|
||||
pygame.init()
|
||||
|
||||
|
||||
def indent(text, indentation_level=0):
|
||||
return (" " * indentation_level) + text
|
||||
# This is a simple class that will help us print to the screen.
|
||||
# It has nothing to do with the joysticks, just outputting the
|
||||
# information.
|
||||
class TextPrint:
|
||||
def __init__(self):
|
||||
self.reset()
|
||||
self.font = pygame.font.Font(None, 25)
|
||||
|
||||
def tprint(self, screen, text):
|
||||
text_bitmap = self.font.render(text, True, (0, 0, 0))
|
||||
screen.blit(text_bitmap, (self.x, self.y))
|
||||
self.y += self.line_height
|
||||
|
||||
def reset(self):
|
||||
self.x = 10
|
||||
self.y = 10
|
||||
self.line_height = 15
|
||||
|
||||
def indent(self):
|
||||
self.x += 10
|
||||
|
||||
def unindent(self):
|
||||
self.x -= 10
|
||||
|
||||
|
||||
def main():
|
||||
# Set the size of the screen (width, height), and name the window.
|
||||
size = (500, 700)
|
||||
screen = pygame.display.set_mode(size)
|
||||
# Set the width and height of the screen (width, height), and name the window.
|
||||
screen = pygame.display.set_mode((500, 700))
|
||||
pygame.display.set_caption("Joystick example")
|
||||
|
||||
# Used to manage how fast the screen updates.
|
||||
clock = pygame.Clock()
|
||||
clock = pygame.time.Clock()
|
||||
|
||||
# Get ready to print.
|
||||
font = pygame.font.SysFont(None, 25)
|
||||
wraplength = size[0] - 20
|
||||
text_print = TextPrint()
|
||||
|
||||
# This dict can be left as-is, since pygame-ce will generate a
|
||||
# This dict can be left as-is, since pygame will generate a
|
||||
# pygame.JOYDEVICEADDED event for every joystick connected
|
||||
# at the start of the program.
|
||||
joysticks = {}
|
||||
@@ -50,82 +69,73 @@ def main():
|
||||
# joystick, filling up the list without needing to create them manually.
|
||||
joy = pygame.joystick.Joystick(event.device_index)
|
||||
joysticks[joy.get_instance_id()] = joy
|
||||
print(f"Joystick {joy.get_instance_id()} connected")
|
||||
print(f"Joystick {joy.get_instance_id()} connencted")
|
||||
|
||||
if event.type == pygame.JOYDEVICEREMOVED:
|
||||
if event.instance_id in joysticks:
|
||||
del joysticks[event.instance_id]
|
||||
print(f"Joystick {event.instance_id} disconnected")
|
||||
else:
|
||||
print(
|
||||
f"Tried to disconnect Joystick {event.instance_id}, "
|
||||
"but couldn't find it in the joystick list"
|
||||
)
|
||||
del joysticks[event.instance_id]
|
||||
print(f"Joystick {event.instance_id} disconnected")
|
||||
|
||||
# Drawing step
|
||||
# First, clear the screen to white. Don't put other drawing commands
|
||||
# above this, or they will be erased with this command.
|
||||
screen.fill((255, 255, 255))
|
||||
indentation = 0
|
||||
lines = []
|
||||
text_print.reset()
|
||||
|
||||
# Get count of joysticks.
|
||||
joystick_count = pygame.joystick.get_count()
|
||||
lines.append(indent(f"Number of joysticks: {joystick_count}", indentation))
|
||||
indentation += 1
|
||||
|
||||
text_print.tprint(screen, f"Number of joysticks: {joystick_count}")
|
||||
text_print.indent()
|
||||
|
||||
# For each joystick:
|
||||
for joystick in joysticks.values():
|
||||
jid = joystick.get_instance_id()
|
||||
|
||||
lines.append(indent(f"Joystick {jid}", indentation))
|
||||
indentation += 1
|
||||
text_print.tprint(screen, f"Joystick {jid}")
|
||||
text_print.indent()
|
||||
|
||||
# Get the name from the OS for the controller/joystick.
|
||||
name = joystick.get_name()
|
||||
lines.append(indent(f"Joystick name: {name}", indentation))
|
||||
text_print.tprint(screen, f"Joystick name: {name}")
|
||||
|
||||
guid = joystick.get_guid()
|
||||
lines.append(indent(f"GUID: {guid}", indentation))
|
||||
text_print.tprint(screen, f"GUID: {guid}")
|
||||
|
||||
power_level = joystick.get_power_level()
|
||||
lines.append(indent(f"Joystick's power level: {power_level}", indentation))
|
||||
text_print.tprint(screen, f"Joystick's power level: {power_level}")
|
||||
|
||||
# Usually axis run in pairs, up/down for one, and left/right for
|
||||
# the other. Triggers count as axes.
|
||||
axes = joystick.get_numaxes()
|
||||
lines.append(indent(f"Number of axes: {axes}", indentation))
|
||||
indentation += 1
|
||||
text_print.tprint(screen, f"Number of axes: {axes}")
|
||||
text_print.indent()
|
||||
|
||||
for i in range(axes):
|
||||
axis = joystick.get_axis(i)
|
||||
lines.append(indent(f"Axis {i} value: {axis:>6.3f}", indentation))
|
||||
indentation -= 1
|
||||
text_print.tprint(screen, f"Axis {i} value: {axis:>6.3f}")
|
||||
text_print.unindent()
|
||||
|
||||
buttons = joystick.get_numbuttons()
|
||||
lines.append(indent(f"Number of buttons: {buttons}", indentation))
|
||||
indentation += 1
|
||||
text_print.tprint(screen, f"Number of buttons: {buttons}")
|
||||
text_print.indent()
|
||||
|
||||
for i in range(buttons):
|
||||
button = joystick.get_button(i)
|
||||
lines.append(indent(f"Button {i:>2} value: {button}", indentation))
|
||||
indentation -= 1
|
||||
text_print.tprint(screen, f"Button {i:>2} value: {button}")
|
||||
text_print.unindent()
|
||||
|
||||
hats = joystick.get_numhats()
|
||||
lines.append(indent(f"Number of hats: {hats}", indentation))
|
||||
indentation += 1
|
||||
text_print.tprint(screen, f"Number of hats: {hats}")
|
||||
text_print.indent()
|
||||
|
||||
# Hat position. All or nothing for direction, not a float like
|
||||
# get_axis(). Position is a tuple of int values (x, y).
|
||||
for i in range(hats):
|
||||
hat = joystick.get_hat(i)
|
||||
lines.append(indent(f"Hat {i} value: {str(hat)}", indentation))
|
||||
indentation -= 2
|
||||
text_print.tprint(screen, f"Hat {i} value: {str(hat)}")
|
||||
text_print.unindent()
|
||||
|
||||
# draw the accumulated text
|
||||
screen.blit(
|
||||
font.render("\n".join(lines), True, "black", "white", wraplength), (10, 10)
|
||||
)
|
||||
text_print.unindent()
|
||||
|
||||
# Go ahead and update the screen with what we've drawn.
|
||||
pygame.display.flip()
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.liquid
|
||||
""" pygame.examples.liquid
|
||||
|
||||
This example demonstrates a simplish water effect of an
|
||||
image. It attempts to create a hardware display surface that
|
||||
@@ -13,24 +13,24 @@ pygame to compare the results. I didn't bother porting the text and
|
||||
sound stuff, that's an easy enough challenge for the reader :]
|
||||
"""
|
||||
|
||||
import pygame as pg
|
||||
import os
|
||||
from math import sin
|
||||
|
||||
import pygame
|
||||
import time
|
||||
|
||||
main_dir = os.path.split(os.path.abspath(__file__))[0]
|
||||
|
||||
|
||||
def main():
|
||||
# initialize and setup screen
|
||||
pygame.init()
|
||||
screen = pygame.display.set_mode((640, 480), pygame.DOUBLEBUF)
|
||||
pg.init()
|
||||
screen = pg.display.set_mode((640, 480), pg.HWSURFACE | pg.DOUBLEBUF)
|
||||
|
||||
# load image and quadruple
|
||||
imagename = os.path.join(main_dir, "data", "liquid.webp")
|
||||
bitmap = pygame.image.load(imagename)
|
||||
bitmap = pygame.transform.scale2x(bitmap)
|
||||
bitmap = pygame.transform.scale2x(bitmap)
|
||||
imagename = os.path.join(main_dir, "data", "liquid.bmp")
|
||||
bitmap = pg.image.load(imagename)
|
||||
bitmap = pg.transform.scale2x(bitmap)
|
||||
bitmap = pg.transform.scale2x(bitmap)
|
||||
|
||||
# get the image and screen in the same format
|
||||
if screen.get_bitsize() == 8:
|
||||
@@ -44,15 +44,10 @@ def main():
|
||||
# mainloop
|
||||
xblocks = range(0, 640, 20)
|
||||
yblocks = range(0, 480, 20)
|
||||
stop_events = pygame.QUIT, pygame.KEYDOWN, pygame.MOUSEBUTTONDOWN
|
||||
|
||||
clock = pygame.Clock()
|
||||
|
||||
stopevents = pg.QUIT, pg.KEYDOWN, pg.MOUSEBUTTONDOWN
|
||||
while True:
|
||||
clock.tick(60)
|
||||
|
||||
for event in pygame.event.get():
|
||||
if event.type in stop_events:
|
||||
for e in pg.event.get():
|
||||
if e.type in stopevents:
|
||||
return
|
||||
|
||||
anim = anim + 0.02
|
||||
@@ -62,12 +57,13 @@ def main():
|
||||
ypos = (y + (sin(anim + y * 0.01) * 15)) + 20
|
||||
screen.blit(bitmap, (x, y), (xpos, ypos, 20, 20))
|
||||
|
||||
pygame.display.flip()
|
||||
pg.display.flip()
|
||||
time.sleep(0.01)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
pygame.quit()
|
||||
pg.quit()
|
||||
|
||||
|
||||
"""BTW, here is the code from the BlitzBasic example this was derived
|
||||
|
||||
@@ -41,12 +41,12 @@ import os
|
||||
import random
|
||||
import sys
|
||||
|
||||
import pygame
|
||||
import pygame as pg
|
||||
|
||||
|
||||
class Sprite:
|
||||
"""
|
||||
Moving Sprite demonstrating pixel-perfect collisions between pygame.mask.Mask objects
|
||||
Moving Sprite demonstrating pixel-perfect collisions between pg.mask.Mask objects
|
||||
"""
|
||||
|
||||
def __init__(self, pos, vel, surface, mask=None):
|
||||
@@ -54,18 +54,18 @@ class Sprite:
|
||||
Positional arguments:
|
||||
pos: Position of the sprite (sequence of 2 integers)
|
||||
vel: Movement velocity of the sprite (sequence of 2 integers)
|
||||
surface: Image (as a pygame.Surface) of the sprite
|
||||
mask: pygame.mask.Mask object (optional)
|
||||
surface: Image (as a pg.Surface) of the sprite
|
||||
mask: pg.mask.Mask object (optional)
|
||||
"""
|
||||
self.surface = surface
|
||||
self.width, self.height = self.surface.get_size()
|
||||
if mask is not None:
|
||||
self.mask = mask
|
||||
else:
|
||||
self.mask = pygame.mask.from_surface(self.surface)
|
||||
self.mask = pg.mask.from_surface(self.surface)
|
||||
|
||||
self.pos = pygame.Vector2(pos)
|
||||
self.vel = pygame.Vector2(vel)
|
||||
self.pos = pg.Vector2(pos)
|
||||
self.vel = pg.Vector2(vel)
|
||||
|
||||
def collide(self, sprite):
|
||||
"""
|
||||
@@ -82,7 +82,7 @@ class Sprite:
|
||||
# Calculate collision normal
|
||||
|
||||
# Number of collisions
|
||||
n_collisions = pygame.Vector2(
|
||||
n_collisions = pg.Vector2(
|
||||
# x axis
|
||||
self.mask.overlap_area(sprite.mask, (offset[0] + 1, offset[1]))
|
||||
- self.mask.overlap_area(sprite.mask, (offset[0] - 1, offset[1])),
|
||||
@@ -122,23 +122,23 @@ def main(*args):
|
||||
Positional arguments:
|
||||
one or more image file names.
|
||||
|
||||
This pygame.masks demo will display multiple moving sprites bouncing
|
||||
This pg.masks demo will display multiple moving sprites bouncing
|
||||
off each other. More than one sprite image can be provided.
|
||||
"""
|
||||
|
||||
if len(args) == 0:
|
||||
raise ValueError("Require at least one image file name: non given")
|
||||
pygame.init()
|
||||
pg.init()
|
||||
|
||||
screen_size = (640, 480)
|
||||
screen = pygame.display.set_mode(screen_size)
|
||||
clock = pygame.Clock()
|
||||
screen = pg.display.set_mode(screen_size)
|
||||
clock = pg.time.Clock()
|
||||
|
||||
images = []
|
||||
masks = []
|
||||
for image_path in args:
|
||||
images.append(pygame.image.load(image_path).convert_alpha())
|
||||
masks.append(pygame.mask.from_surface(images[-1]))
|
||||
images.append(pg.image.load(image_path).convert_alpha())
|
||||
masks.append(pg.mask.from_surface(images[-1]))
|
||||
|
||||
sprites = []
|
||||
for i in range(20):
|
||||
@@ -158,8 +158,8 @@ def main(*args):
|
||||
sprites.append(sprite)
|
||||
|
||||
while True:
|
||||
for event in pygame.event.get():
|
||||
if event.type in (pygame.QUIT, pygame.KEYDOWN):
|
||||
for event in pg.event.get():
|
||||
if event.type in (pg.QUIT, pg.KEYDOWN):
|
||||
return
|
||||
|
||||
screen.fill((240, 220, 100))
|
||||
@@ -186,7 +186,7 @@ def main(*args):
|
||||
screen.blit(sprite.surface, sprite.pos)
|
||||
|
||||
clock.tick(30)
|
||||
pygame.display.flip()
|
||||
pg.display.flip()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
@@ -199,4 +199,4 @@ if __name__ == "__main__":
|
||||
|
||||
else:
|
||||
main(*sys.argv[1:])
|
||||
pygame.quit()
|
||||
pg.quit()
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.midi
|
||||
""" pygame.examples.midi
|
||||
|
||||
midi input, and a separate example of midi output.
|
||||
|
||||
@@ -10,10 +10,12 @@ python -m pygame.examples.midi --input
|
||||
python -m pygame.examples.midi --input
|
||||
"""
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
import sys
|
||||
import os
|
||||
from typing import Any, Dict, List, Literal, Optional, Set, Tuple, Union
|
||||
|
||||
import pygame
|
||||
import pygame as pg
|
||||
import pygame.midi
|
||||
|
||||
# black and white piano keys use b/w color values directly
|
||||
@@ -44,7 +46,7 @@ def _print_device_info():
|
||||
|
||||
|
||||
def input_main(device_id=None):
|
||||
pygame.init()
|
||||
pg.init()
|
||||
|
||||
pygame.midi.init()
|
||||
|
||||
@@ -58,15 +60,15 @@ def input_main(device_id=None):
|
||||
print(f"using input_id :{input_id}:")
|
||||
i = pygame.midi.Input(input_id)
|
||||
|
||||
pygame.display.set_mode((1, 1))
|
||||
pg.display.set_mode((1, 1))
|
||||
|
||||
going = True
|
||||
while going:
|
||||
events = pygame.event.get()
|
||||
for e in events:
|
||||
if e.type in [pygame.QUIT]:
|
||||
if e.type in [pg.QUIT]:
|
||||
going = False
|
||||
if e.type in [pygame.KEYDOWN]:
|
||||
if e.type in [pg.KEYDOWN]:
|
||||
going = False
|
||||
if e.type in [pygame.midi.MIDIIN]:
|
||||
print(e)
|
||||
@@ -135,35 +137,35 @@ def output_main(device_id=None):
|
||||
|
||||
key_mapping = make_key_mapping(
|
||||
[
|
||||
pygame.K_TAB,
|
||||
pygame.K_1,
|
||||
pygame.K_q,
|
||||
pygame.K_2,
|
||||
pygame.K_w,
|
||||
pygame.K_3,
|
||||
pygame.K_e,
|
||||
pygame.K_r,
|
||||
pygame.K_5,
|
||||
pygame.K_t,
|
||||
pygame.K_6,
|
||||
pygame.K_y,
|
||||
pygame.K_u,
|
||||
pygame.K_8,
|
||||
pygame.K_i,
|
||||
pygame.K_9,
|
||||
pygame.K_o,
|
||||
pygame.K_0,
|
||||
pygame.K_p,
|
||||
pygame.K_LEFTBRACKET,
|
||||
pygame.K_EQUALS,
|
||||
pygame.K_RIGHTBRACKET,
|
||||
pygame.K_BACKSPACE,
|
||||
pygame.K_BACKSLASH,
|
||||
pg.K_TAB,
|
||||
pg.K_1,
|
||||
pg.K_q,
|
||||
pg.K_2,
|
||||
pg.K_w,
|
||||
pg.K_3,
|
||||
pg.K_e,
|
||||
pg.K_r,
|
||||
pg.K_5,
|
||||
pg.K_t,
|
||||
pg.K_6,
|
||||
pg.K_y,
|
||||
pg.K_u,
|
||||
pg.K_8,
|
||||
pg.K_i,
|
||||
pg.K_9,
|
||||
pg.K_o,
|
||||
pg.K_0,
|
||||
pg.K_p,
|
||||
pg.K_LEFTBRACKET,
|
||||
pg.K_EQUALS,
|
||||
pg.K_RIGHTBRACKET,
|
||||
pg.K_BACKSPACE,
|
||||
pg.K_BACKSLASH,
|
||||
],
|
||||
start_note,
|
||||
)
|
||||
|
||||
pygame.init()
|
||||
pg.init()
|
||||
pygame.midi.init()
|
||||
|
||||
_print_device_info()
|
||||
@@ -180,25 +182,25 @@ def output_main(device_id=None):
|
||||
midi_out.set_instrument(instrument)
|
||||
keyboard = Keyboard(start_note, n_notes)
|
||||
|
||||
screen = pygame.display.set_mode(keyboard.rect.size)
|
||||
screen = pg.display.set_mode(keyboard.rect.size)
|
||||
screen.fill(BACKGROUNDCOLOR)
|
||||
pygame.display.flip()
|
||||
pg.display.flip()
|
||||
|
||||
background = pygame.Surface(screen.get_size())
|
||||
background = pg.Surface(screen.get_size())
|
||||
background.fill(BACKGROUNDCOLOR)
|
||||
dirty_rects = []
|
||||
keyboard.draw(screen, background, dirty_rects)
|
||||
pygame.display.update(dirty_rects)
|
||||
pg.display.update(dirty_rects)
|
||||
|
||||
regions = pygame.Surface(screen.get_size()) # initial color (0,0,0)
|
||||
regions = pg.Surface(screen.get_size()) # initial color (0,0,0)
|
||||
keyboard.map_regions(regions)
|
||||
|
||||
pygame.event.set_blocked(pygame.MOUSEMOTION)
|
||||
pg.event.set_blocked(pg.MOUSEMOTION)
|
||||
mouse_note = 0
|
||||
on_notes = set()
|
||||
while True:
|
||||
e = pygame.event.wait()
|
||||
if e.type == pygame.MOUSEBUTTONDOWN:
|
||||
e = pg.event.wait()
|
||||
if e.type == pg.MOUSEBUTTONDOWN:
|
||||
mouse_note, velocity, __, __ = regions.get_at(e.pos)
|
||||
if mouse_note and mouse_note not in on_notes:
|
||||
keyboard.key_down(mouse_note)
|
||||
@@ -206,16 +208,16 @@ def output_main(device_id=None):
|
||||
on_notes.add(mouse_note)
|
||||
else:
|
||||
mouse_note = 0
|
||||
elif e.type == pygame.MOUSEBUTTONUP:
|
||||
elif e.type == pg.MOUSEBUTTONUP:
|
||||
if mouse_note:
|
||||
midi_out.note_off(mouse_note)
|
||||
keyboard.key_up(mouse_note)
|
||||
on_notes.remove(mouse_note)
|
||||
mouse_note = 0
|
||||
elif e.type == pygame.QUIT:
|
||||
elif e.type == pg.QUIT:
|
||||
break
|
||||
elif e.type == pygame.KEYDOWN:
|
||||
if e.key == pygame.K_ESCAPE:
|
||||
elif e.type == pg.KEYDOWN:
|
||||
if e.key == pg.K_ESCAPE:
|
||||
break
|
||||
try:
|
||||
note, velocity = key_mapping[e.key]
|
||||
@@ -226,7 +228,7 @@ def output_main(device_id=None):
|
||||
keyboard.key_down(note)
|
||||
midi_out.note_on(note, velocity)
|
||||
on_notes.add(note)
|
||||
elif e.type == pygame.KEYUP:
|
||||
elif e.type == pg.KEYUP:
|
||||
try:
|
||||
note, __ = key_mapping[e.key]
|
||||
except KeyError:
|
||||
@@ -239,7 +241,7 @@ def output_main(device_id=None):
|
||||
|
||||
dirty_rects = []
|
||||
keyboard.draw(screen, background, dirty_rects)
|
||||
pygame.display.update(dirty_rects)
|
||||
pg.display.update(dirty_rects)
|
||||
finally:
|
||||
del midi_out
|
||||
pygame.midi.quit()
|
||||
@@ -254,7 +256,7 @@ def make_key_mapping(keys, start_note):
|
||||
|
||||
|
||||
class NullKey:
|
||||
"""A null key that ignores events passed to it by other keys
|
||||
"""A dummy key that ignores events passed to it by other keys
|
||||
|
||||
A NullKey instance is the left key instance used by default
|
||||
for the left most keyboard key.
|
||||
@@ -277,7 +279,169 @@ class NullKey:
|
||||
null_key = NullKey()
|
||||
|
||||
|
||||
def key_class(updates, image_strip, image_rects, is_white_key=True):
|
||||
@dataclass
|
||||
class KeyData:
|
||||
"""Used for passing in data to subclasses of the Key class."""
|
||||
|
||||
is_white_key: bool
|
||||
c_width: int
|
||||
c_height: int
|
||||
c_down_state_initial: int
|
||||
c_down_state_rect_initial: pg.Rect
|
||||
c_notify_down_method: str
|
||||
c_notify_up_method: str
|
||||
c_updates: Set[Any]
|
||||
c_event_down: Dict[int, Tuple[int, pg.Rect]]
|
||||
c_event_up: Dict[int, Tuple[int, pg.Rect]]
|
||||
c_image_strip: pg.Surface
|
||||
c_event_right_white_down: Dict[int, Tuple[int, Union[pg.Rect, None]]]
|
||||
c_event_right_white_up: Dict[int, Tuple[int, Union[pg.Rect, None]]]
|
||||
c_event_right_black_down: Dict[int, Tuple[int, Union[pg.Rect, None]]]
|
||||
c_event_right_black_up: Dict[int, Tuple[int, Union[pg.Rect, None]]]
|
||||
|
||||
|
||||
class Key:
|
||||
"""A key widget, maintains key state and draws the key's image
|
||||
|
||||
Constructor arguments:
|
||||
ident - A unique key identifier. Any immutable type suitable as a key.
|
||||
posn - The location of the key on the display surface.
|
||||
key_left - Optional, the adjacent white key to the left. Changes in
|
||||
up and down state are propagated to that key.
|
||||
|
||||
A key has an associated position and state. Related to state is the
|
||||
image drawn. State changes are managed with method calls, one method
|
||||
per event type. The up and down event methods are public. Other
|
||||
internal methods are for passing on state changes to the key_left
|
||||
key instance.
|
||||
|
||||
"""
|
||||
|
||||
key_data: KeyData
|
||||
|
||||
def __init__(self, ident, posn, key_left=None):
|
||||
"""Return a new Key instance
|
||||
|
||||
The initial state is up, with all adjacent keys to the right also
|
||||
up.
|
||||
|
||||
"""
|
||||
if key_left is None:
|
||||
key_left = null_key
|
||||
rect = pg.Rect(posn[0], posn[1], self.key_data.c_width, self.key_data.c_height)
|
||||
self.rect = rect
|
||||
self._state = self.key_data.c_down_state_initial
|
||||
self._source_rect = self.key_data.c_down_state_rect_initial
|
||||
self._ident = ident
|
||||
self._hash = hash(ident)
|
||||
self._notify_down = getattr(key_left, self.key_data.c_notify_down_method)
|
||||
self._notify_up = getattr(key_left, self.key_data.c_notify_up_method)
|
||||
self._key_left = key_left
|
||||
self._background_rect = pg.Rect(
|
||||
rect.left, rect.bottom - 10, self.key_data.c_width, 10
|
||||
)
|
||||
self.key_data.c_updates.add(self)
|
||||
self.is_white = self.key_data.is_white_key
|
||||
|
||||
def down(self):
|
||||
"""Signal that this key has been depressed (is down)"""
|
||||
|
||||
self._state, source_rect = self.key_data.c_event_down[self._state]
|
||||
if source_rect is not None:
|
||||
self._source_rect = source_rect
|
||||
self.key_data.c_updates.add(self)
|
||||
self._notify_down()
|
||||
|
||||
def up(self):
|
||||
"""Signal that this key has been released (is up)"""
|
||||
|
||||
self._state, source_rect = self.key_data.c_event_up[self._state]
|
||||
if source_rect is not None:
|
||||
self._source_rect = source_rect
|
||||
self.key_data.c_updates.add(self)
|
||||
self._notify_up()
|
||||
|
||||
def _right_white_down(self):
|
||||
"""Signal that the adjacent white key has been depressed
|
||||
|
||||
This method is for internal propagation of events between
|
||||
key instances.
|
||||
|
||||
"""
|
||||
|
||||
self._state, source_rect = self.key_data.c_event_right_white_down[self._state]
|
||||
if source_rect is not None:
|
||||
self._source_rect = source_rect
|
||||
self.key_data.c_updates.add(self)
|
||||
|
||||
def _right_white_up(self):
|
||||
"""Signal that the adjacent white key has been released
|
||||
|
||||
This method is for internal propagation of events between
|
||||
key instances.
|
||||
|
||||
"""
|
||||
|
||||
self._state, source_rect = self.key_data.c_event_right_white_up[self._state]
|
||||
if source_rect is not None:
|
||||
self._source_rect = source_rect
|
||||
self.key_data.c_updates.add(self)
|
||||
|
||||
def _right_black_down(self):
|
||||
"""Signal that the adjacent black key has been depressed
|
||||
|
||||
This method is for internal propagation of events between
|
||||
key instances.
|
||||
|
||||
"""
|
||||
|
||||
self._state, source_rect = self.key_data.c_event_right_black_down[self._state]
|
||||
if source_rect is not None:
|
||||
self._source_rect = source_rect
|
||||
self.key_data.c_updates.add(self)
|
||||
|
||||
def _right_black_up(self):
|
||||
"""Signal that the adjacent black key has been released
|
||||
|
||||
This method is for internal propagation of events between
|
||||
key instances.
|
||||
|
||||
"""
|
||||
|
||||
self._state, source_rect = self.key_data.c_event_right_black_up[self._state]
|
||||
if source_rect is not None:
|
||||
self._source_rect = source_rect
|
||||
self.key_data.c_updates.add(self)
|
||||
|
||||
def __eq__(self, other):
|
||||
"""True if same identifiers"""
|
||||
|
||||
return self._ident == other._ident
|
||||
|
||||
def __hash__(self):
|
||||
"""Return the immutable hash value"""
|
||||
|
||||
return self._hash
|
||||
|
||||
def __str__(self):
|
||||
"""Return the key's identifier and position as a string"""
|
||||
|
||||
return "<Key %s at (%d, %d)>" % (self._ident, self.rect.top, self.rect.left)
|
||||
|
||||
def draw(self, surf, background, dirty_rects):
|
||||
"""Redraw the key on the surface surf
|
||||
|
||||
The background is redrawn. The altered region is added to the
|
||||
dirty_rects list.
|
||||
|
||||
"""
|
||||
|
||||
surf.blit(background, self._background_rect, self._background_rect)
|
||||
surf.blit(self.key_data.c_image_strip, self.rect, self._source_rect)
|
||||
dirty_rects.append(self.rect)
|
||||
|
||||
|
||||
def key_class(updates, image_strip, image_rects: List[pg.Rect], is_white_key=True):
|
||||
"""Return a keyboard key widget class
|
||||
|
||||
Arguments:
|
||||
@@ -362,9 +526,13 @@ def key_class(updates, image_strip, image_rects, is_white_key=True):
|
||||
# along with corresponding image, for the related event. If no redrawing
|
||||
# is required for the state change then the image rect is simply None.
|
||||
#
|
||||
c_event_down = {down_state_none: (down_state_self, image_rects[1])}
|
||||
c_event_up = {down_state_self: (down_state_none, image_rects[0])}
|
||||
c_event_right_white_down = {
|
||||
c_event_down: Dict[int, Tuple[int, pygame.Rect]] = {
|
||||
down_state_none: (down_state_self, image_rects[1])
|
||||
}
|
||||
c_event_up: Dict[int, Tuple[int, pygame.Rect]] = {
|
||||
down_state_self: (down_state_none, image_rects[0])
|
||||
}
|
||||
c_event_right_white_down: Dict[int, Tuple[int, Union[pygame.Rect, None]]] = {
|
||||
down_state_none: (down_state_none, None),
|
||||
down_state_self: (down_state_self, None),
|
||||
}
|
||||
@@ -424,153 +592,32 @@ def key_class(updates, image_strip, image_rects, is_white_key=True):
|
||||
)
|
||||
c_event_right_black_up[down_state_all] = (down_state_self_white, image_rects[2])
|
||||
|
||||
class Key:
|
||||
"""A key widget, maintains key state and draws the key's image
|
||||
class OurKey(Key):
|
||||
key_data = KeyData(
|
||||
is_white_key,
|
||||
c_width,
|
||||
c_height,
|
||||
c_down_state_initial,
|
||||
c_down_state_rect_initial,
|
||||
c_notify_down_method,
|
||||
c_notify_up_method,
|
||||
c_updates,
|
||||
c_event_down,
|
||||
c_event_up,
|
||||
c_image_strip,
|
||||
c_event_right_white_down,
|
||||
c_event_right_white_up,
|
||||
c_event_right_black_down,
|
||||
c_event_right_black_up,
|
||||
)
|
||||
|
||||
Constructor arguments:
|
||||
ident - A unique key identifier. Any immutable type suitable as a key.
|
||||
posn - The location of the key on the display surface.
|
||||
key_left - Optional, the adjacent white key to the left. Changes in
|
||||
up and down state are propagated to that key.
|
||||
|
||||
A key has an associated position and state. Related to state is the
|
||||
image drawn. State changes are managed with method calls, one method
|
||||
per event type. The up and down event methods are public. Other
|
||||
internal methods are for passing on state changes to the key_left
|
||||
key instance.
|
||||
|
||||
"""
|
||||
|
||||
is_white = is_white_key
|
||||
|
||||
def __init__(self, ident, posn, key_left=None):
|
||||
"""Return a new Key instance
|
||||
|
||||
The initial state is up, with all adjacent keys to the right also
|
||||
up.
|
||||
|
||||
"""
|
||||
if key_left is None:
|
||||
key_left = null_key
|
||||
rect = pygame.Rect(posn[0], posn[1], c_width, c_height)
|
||||
self.rect = rect
|
||||
self._state = c_down_state_initial
|
||||
self._source_rect = c_down_state_rect_initial
|
||||
self._ident = ident
|
||||
self._hash = hash(ident)
|
||||
self._notify_down = getattr(key_left, c_notify_down_method)
|
||||
self._notify_up = getattr(key_left, c_notify_up_method)
|
||||
self._key_left = key_left
|
||||
self._background_rect = pygame.Rect(
|
||||
rect.left, rect.bottom - 10, c_width, 10
|
||||
)
|
||||
c_updates.add(self)
|
||||
|
||||
def down(self):
|
||||
"""Signal that this key has been depressed (is down)"""
|
||||
|
||||
self._state, source_rect = c_event_down[self._state]
|
||||
if source_rect is not None:
|
||||
self._source_rect = source_rect
|
||||
c_updates.add(self)
|
||||
self._notify_down()
|
||||
|
||||
def up(self):
|
||||
"""Signal that this key has been released (is up)"""
|
||||
|
||||
self._state, source_rect = c_event_up[self._state]
|
||||
if source_rect is not None:
|
||||
self._source_rect = source_rect
|
||||
c_updates.add(self)
|
||||
self._notify_up()
|
||||
|
||||
def _right_white_down(self):
|
||||
"""Signal that the adjacent white key has been depressed
|
||||
|
||||
This method is for internal propagation of events between
|
||||
key instances.
|
||||
|
||||
"""
|
||||
|
||||
self._state, source_rect = c_event_right_white_down[self._state]
|
||||
if source_rect is not None:
|
||||
self._source_rect = source_rect
|
||||
c_updates.add(self)
|
||||
|
||||
def _right_white_up(self):
|
||||
"""Signal that the adjacent white key has been released
|
||||
|
||||
This method is for internal propagation of events between
|
||||
key instances.
|
||||
|
||||
"""
|
||||
|
||||
self._state, source_rect = c_event_right_white_up[self._state]
|
||||
if source_rect is not None:
|
||||
self._source_rect = source_rect
|
||||
c_updates.add(self)
|
||||
|
||||
def _right_black_down(self):
|
||||
"""Signal that the adjacent black key has been depressed
|
||||
|
||||
This method is for internal propagation of events between
|
||||
key instances.
|
||||
|
||||
"""
|
||||
|
||||
self._state, source_rect = c_event_right_black_down[self._state]
|
||||
if source_rect is not None:
|
||||
self._source_rect = source_rect
|
||||
c_updates.add(self)
|
||||
|
||||
def _right_black_up(self):
|
||||
"""Signal that the adjacent black key has been released
|
||||
|
||||
This method is for internal propagation of events between
|
||||
key instances.
|
||||
|
||||
"""
|
||||
|
||||
self._state, source_rect = c_event_right_black_up[self._state]
|
||||
if source_rect is not None:
|
||||
self._source_rect = source_rect
|
||||
c_updates.add(self)
|
||||
|
||||
def __eq__(self, other):
|
||||
"""True if same identifiers"""
|
||||
|
||||
return self._ident == other._ident
|
||||
|
||||
def __hash__(self):
|
||||
"""Return the immutable hash value"""
|
||||
|
||||
return self._hash
|
||||
|
||||
def __str__(self):
|
||||
"""Return the key's identifier and position as a string"""
|
||||
|
||||
return "<Key %s at (%d, %d)>" % (self._ident, self.rect.top, self.rect.left)
|
||||
|
||||
def draw(self, surf, background, dirty_rects):
|
||||
"""Redraw the key on the surface surf
|
||||
|
||||
The background is redrawn. The altered region is added to the
|
||||
dirty_rects list.
|
||||
|
||||
"""
|
||||
|
||||
surf.blit(background, self._background_rect, self._background_rect)
|
||||
surf.blit(c_image_strip, self.rect, self._source_rect)
|
||||
dirty_rects.append(self.rect)
|
||||
|
||||
return Key
|
||||
return OurKey
|
||||
|
||||
|
||||
def key_images():
|
||||
def key_images() -> Tuple[pg.Surface, Dict[str, pg.Rect]]:
|
||||
"""Return a keyboard keys image strip and a mapping of image locations
|
||||
|
||||
The return tuple is a surface and a dictionary of rects mapped to key
|
||||
type.
|
||||
The return tuple is a pygame.Surface and a dictionary keyed by key name and valued by a pygame.Rect.
|
||||
|
||||
This function encapsulates the constants relevant to the keyboard image
|
||||
file. There are five key types. One is the black key. The other four
|
||||
@@ -583,12 +630,12 @@ def key_images():
|
||||
"""
|
||||
|
||||
my_dir = os.path.split(os.path.abspath(__file__))[0]
|
||||
strip_file = os.path.join(my_dir, "data", "midikeys.webp")
|
||||
strip_file = os.path.join(my_dir, "data", "midikeys.png")
|
||||
white_key_width = 42
|
||||
white_key_height = 160
|
||||
black_key_width = 22
|
||||
black_key_height = 94
|
||||
strip = pygame.image.load(strip_file)
|
||||
strip = pg.image.load(strip_file)
|
||||
names = [
|
||||
"black none",
|
||||
"black self",
|
||||
@@ -613,11 +660,11 @@ def key_images():
|
||||
]
|
||||
rects = {}
|
||||
for i in range(2):
|
||||
rects[names[i]] = pygame.Rect(
|
||||
rects[names[i]] = pg.Rect(
|
||||
i * white_key_width, 0, black_key_width, black_key_height
|
||||
)
|
||||
for i in range(2, len(names)):
|
||||
rects[names[i]] = pygame.Rect(
|
||||
rects[names[i]] = pg.Rect(
|
||||
i * white_key_width, 0, white_key_width, white_key_height
|
||||
)
|
||||
return strip, rects
|
||||
@@ -641,7 +688,7 @@ class Keyboard:
|
||||
white_key_width, white_key_height = _rects["white none"].size
|
||||
black_key_width, black_key_height = _rects["black none"].size
|
||||
|
||||
_updates = set()
|
||||
_updates: Set[Any] = set()
|
||||
|
||||
# There are five key classes, representing key shape:
|
||||
# black key (BlackKey), plain white key (WhiteKey), white key to the left
|
||||
@@ -690,14 +737,14 @@ class Keyboard:
|
||||
],
|
||||
)
|
||||
|
||||
def __init__(self, start_note, n_notes):
|
||||
def __init__(self, start_note: int, n_notes: int):
|
||||
"""Return a new Keyboard instance with n_note keys"""
|
||||
|
||||
self._start_note = start_note
|
||||
self._end_note = start_note + n_notes - 1
|
||||
self._add_keys()
|
||||
|
||||
def _add_keys(self):
|
||||
def _add_keys(self) -> None:
|
||||
"""Populate the keyboard with key instances
|
||||
|
||||
Set the _keys and rect attributes.
|
||||
@@ -709,7 +756,7 @@ class Keyboard:
|
||||
# note positions should never be accessed, so are set None to ensure
|
||||
# the bug is quickly detected.
|
||||
#
|
||||
key_map = [None] * 128
|
||||
key_map: list[Key | Literal[None]] = [None] * 128
|
||||
|
||||
start_note = self._start_note
|
||||
end_note = self._end_note
|
||||
@@ -743,9 +790,13 @@ class Keyboard:
|
||||
key_map[note] = key
|
||||
self._keys = key_map
|
||||
|
||||
kb_width = key_map[self._end_note].rect.right
|
||||
the_key = key_map[self._end_note]
|
||||
if the_key is None:
|
||||
kb_width = 0
|
||||
else:
|
||||
kb_width = the_key.rect.right
|
||||
kb_height = self.white_key_height
|
||||
self.rect = pygame.Rect(0, 0, kb_width, kb_height)
|
||||
self.rect = pg.Rect(0, 0, kb_width, kb_height)
|
||||
|
||||
def map_regions(self, regions):
|
||||
"""Draw the key regions onto surface regions.
|
||||
@@ -763,12 +814,13 @@ class Keyboard:
|
||||
black_keys = []
|
||||
for note in range(self._start_note, self._end_note + 1):
|
||||
key = self._keys[note]
|
||||
if key.is_white:
|
||||
if key is not None and key.is_white:
|
||||
fill_region(regions, note, key.rect, cutoff)
|
||||
else:
|
||||
black_keys.append((note, key))
|
||||
for note, key in black_keys:
|
||||
fill_region(regions, note, key.rect, cutoff)
|
||||
if key is not None:
|
||||
fill_region(regions, note, key.rect, cutoff)
|
||||
|
||||
def draw(self, surf, background, dirty_rects):
|
||||
"""Redraw all altered keyboard keys"""
|
||||
@@ -779,13 +831,15 @@ class Keyboard:
|
||||
|
||||
def key_down(self, note):
|
||||
"""Signal a key down event for note"""
|
||||
|
||||
self._keys[note].down()
|
||||
key = self._keys[note]
|
||||
if key is not None:
|
||||
key.down()
|
||||
|
||||
def key_up(self, note):
|
||||
"""Signal a key up event for note"""
|
||||
|
||||
self._keys[note].up()
|
||||
key = self._keys[note]
|
||||
if key is not None:
|
||||
key.up()
|
||||
|
||||
|
||||
def fill_region(regions, note, rect, cutoff):
|
||||
@@ -859,6 +913,7 @@ def main(mode="output", device_id=None):
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
device_id: Optional[int] = None
|
||||
try:
|
||||
device_id = int(sys.argv[-1])
|
||||
except ValueError:
|
||||
@@ -874,4 +929,4 @@ if __name__ == "__main__":
|
||||
else:
|
||||
usage()
|
||||
|
||||
pygame.quit()
|
||||
pg.quit()
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.moveit
|
||||
""" pygame.examples.moveit
|
||||
|
||||
This is the full and final example from the Pygame Tutorial,
|
||||
"How Do I Make It Move". It creates 10 objects and animates
|
||||
@@ -11,10 +11,8 @@ Note it's a bit scant on error checking, but it's easy to read. :]
|
||||
Fortunately, this is python, and we needn't wrestle with a pile of
|
||||
error codes.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
import pygame
|
||||
import pygame as pg
|
||||
|
||||
main_dir = os.path.split(os.path.abspath(__file__))[0]
|
||||
|
||||
@@ -58,23 +56,23 @@ class GameObject:
|
||||
# quick function to load an image
|
||||
def load_image(name):
|
||||
path = os.path.join(main_dir, "data", name)
|
||||
return pygame.image.load(path).convert()
|
||||
return pg.image.load(path).convert()
|
||||
|
||||
|
||||
# here's the full code
|
||||
def main():
|
||||
pygame.init()
|
||||
clock = pygame.Clock()
|
||||
screen = pygame.display.set_mode((WIDTH, HEIGHT))
|
||||
pg.init()
|
||||
clock = pg.time.Clock()
|
||||
screen = pg.display.set_mode((WIDTH, HEIGHT))
|
||||
|
||||
player = load_image("player1.gif")
|
||||
entity = load_image("alien1.gif")
|
||||
background = load_image("liquid.webp")
|
||||
background = load_image("liquid.bmp")
|
||||
|
||||
# scale the background image so that it fills the window and
|
||||
# successfully overwrites the old sprite position.
|
||||
background = pygame.transform.scale2x(background)
|
||||
background = pygame.transform.scale2x(background)
|
||||
background = pg.transform.scale2x(background)
|
||||
background = pg.transform.scale2x(background)
|
||||
|
||||
screen.blit(background, (0, 0))
|
||||
|
||||
@@ -84,26 +82,26 @@ def main():
|
||||
o = GameObject(entity, x * 40, x)
|
||||
objects.append(o)
|
||||
|
||||
pygame.display.set_caption("Move It!")
|
||||
pg.display.set_caption("Move It!")
|
||||
|
||||
# This is a simple event handler that enables player input.
|
||||
while True:
|
||||
# Get all keys currently pressed, and move when an arrow key is held.
|
||||
keys = pygame.key.get_pressed()
|
||||
if keys[pygame.K_UP]:
|
||||
keys = pg.key.get_pressed()
|
||||
if keys[pg.K_UP]:
|
||||
p.move(up=True)
|
||||
if keys[pygame.K_DOWN]:
|
||||
if keys[pg.K_DOWN]:
|
||||
p.move(down=True)
|
||||
if keys[pygame.K_LEFT]:
|
||||
if keys[pg.K_LEFT]:
|
||||
p.move(left=True)
|
||||
if keys[pygame.K_RIGHT]:
|
||||
if keys[pg.K_RIGHT]:
|
||||
p.move(right=True)
|
||||
|
||||
# Draw the background
|
||||
screen.blit(background, (0, 0))
|
||||
for e in pygame.event.get():
|
||||
for e in pg.event.get():
|
||||
# quit upon screen exit
|
||||
if e.type == pygame.QUIT:
|
||||
if e.type == pg.QUIT:
|
||||
return
|
||||
for o in objects:
|
||||
screen.blit(background, o.pos, o.pos)
|
||||
@@ -111,10 +109,11 @@ def main():
|
||||
o.move(right=True)
|
||||
screen.blit(o.image, o.pos)
|
||||
screen.blit(p.image, p.pos)
|
||||
pygame.display.update()
|
||||
clock.tick(60)
|
||||
pg.display.update()
|
||||
pg.time.delay(100)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
pygame.quit()
|
||||
pg.quit()
|
||||
@@ -1,157 +0,0 @@
|
||||
import sys
|
||||
|
||||
import pygame
|
||||
|
||||
WIDTH, HEIGHT = 500, 500
|
||||
|
||||
|
||||
def connect_joystick(index, active_players, players, colors):
|
||||
if len(active_players) < len(players):
|
||||
joy = pygame.Joystick(index)
|
||||
index = players.index(None)
|
||||
# player data
|
||||
players[index] = {
|
||||
"joy": joy,
|
||||
"pos": [WIDTH * 0.25 + index * 64, 128],
|
||||
"surf_idx": index,
|
||||
"surf": colors[index],
|
||||
"joined": False,
|
||||
}
|
||||
active_players[joy.get_instance_id()] = index
|
||||
print(f"P{index + 1} Connected")
|
||||
|
||||
|
||||
def disconnect_joystick(instance_id: int, active_players, players):
|
||||
index = active_players[instance_id]
|
||||
players[index] = None
|
||||
del active_players[instance_id]
|
||||
print(f"P{index + 1} Disconnected")
|
||||
|
||||
|
||||
def control_player(player): # move player
|
||||
joy = player["joy"]
|
||||
if not player["joined"]:
|
||||
return
|
||||
player["pos"][0] += joy.get_axis(0) * 5
|
||||
player["pos"][1] += joy.get_axis(1) * 5
|
||||
|
||||
|
||||
def create_surf(size, color):
|
||||
surf = pygame.Surface(size)
|
||||
surf.fill(color)
|
||||
return surf
|
||||
|
||||
|
||||
def main():
|
||||
pygame.init()
|
||||
|
||||
screen = pygame.display.set_mode((WIDTH, HEIGHT))
|
||||
pygame.display.set_caption("Multiplayer Joystick example")
|
||||
clock = pygame.Clock()
|
||||
font_b = pygame.font.SysFont(None, 25)
|
||||
font_a = pygame.font.SysFont(None, 16)
|
||||
|
||||
players = [None, None] # two players limit
|
||||
active_players = {}
|
||||
|
||||
colors = [
|
||||
create_surf((32, 32), (220, 180, 10)),
|
||||
create_surf((32, 32), (60, 230, 170)),
|
||||
create_surf((32, 32), (230, 20, 70)),
|
||||
create_surf((32, 32), (20, 170, 230)),
|
||||
]
|
||||
are_no_controllers_connected = True
|
||||
|
||||
while True:
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
pygame.quit()
|
||||
sys.exit()
|
||||
elif event.type == pygame.JOYDEVICEADDED:
|
||||
if len(active_players) < len(players):
|
||||
# connect controller
|
||||
connect_joystick(
|
||||
event.device_index, active_players, players, colors
|
||||
)
|
||||
are_no_controllers_connected = False
|
||||
elif event.type == pygame.JOYDEVICEREMOVED:
|
||||
# disconnect controller
|
||||
if event.instance_id in active_players:
|
||||
disconnect_joystick(event.instance_id, active_players, players)
|
||||
# check if there is at least one controller connected
|
||||
are_no_controllers_connected = True
|
||||
for player in players:
|
||||
if player:
|
||||
are_no_controllers_connected = False
|
||||
break
|
||||
elif event.type == pygame.JOYBUTTONDOWN:
|
||||
if event.instance_id in active_players:
|
||||
# join player
|
||||
if event.button == 0:
|
||||
index = active_players[event.instance_id]
|
||||
players[index]["joined"] = True
|
||||
print(f"P{index + 1} joined")
|
||||
# leave player
|
||||
if event.button == 1:
|
||||
index = active_players[event.instance_id]
|
||||
if players[index]["joined"]:
|
||||
players[index]["joined"] = False
|
||||
players[index]["pos"] = [WIDTH * 0.25 + index * 64, 128]
|
||||
print(f"P{index + 1} leave")
|
||||
elif event.type == pygame.JOYAXISMOTION:
|
||||
if event.instance_id in active_players:
|
||||
# change the color if player still hasn't joined
|
||||
if event.axis == 0:
|
||||
index = active_players[event.instance_id]
|
||||
player = players[index]
|
||||
if not player["joined"]:
|
||||
if event.value >= 1.0:
|
||||
player["surf_idx"] += 1
|
||||
elif event.value <= -1.0:
|
||||
player["surf_idx"] -= 1
|
||||
player["surf_idx"] = player["surf_idx"] % len(colors)
|
||||
player["surf"] = colors[player["surf_idx"]]
|
||||
|
||||
screen.fill((30, 30, 30))
|
||||
pygame.draw.line(screen, (230, 230, 230), (0, 96), (WIDTH, 96), 2)
|
||||
|
||||
# update and draw players
|
||||
for player in players:
|
||||
if player:
|
||||
control_player(player)
|
||||
screen.blit(player["surf"], player["pos"])
|
||||
|
||||
# draw available colors
|
||||
for i, surf in enumerate(colors):
|
||||
screen.blit(surf, (WIDTH * 0.25 + i * 64, 32))
|
||||
|
||||
# show message for connecting a controller
|
||||
if are_no_controllers_connected:
|
||||
screen.blit(
|
||||
font_b.render(
|
||||
"Please connect a controller.",
|
||||
True,
|
||||
(230, 230, 230),
|
||||
None,
|
||||
500 - 20,
|
||||
),
|
||||
(WIDTH * 0.3, HEIGHT * 0.5),
|
||||
)
|
||||
|
||||
screen.blit(
|
||||
font_a.render(
|
||||
"A: join B: leave Joystick: move / change color",
|
||||
True,
|
||||
(230, 230, 230),
|
||||
None,
|
||||
WIDTH - 20,
|
||||
),
|
||||
(10, HEIGHT - 20),
|
||||
)
|
||||
|
||||
clock.tick(60)
|
||||
pygame.display.update()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.music_drop_fade
|
||||
""" pygame.examples.music_drop_fade
|
||||
Fade in and play music from a list while observing several events
|
||||
|
||||
Adds music files to a playlist whenever played by one of the following methods
|
||||
@@ -15,24 +15,11 @@ Keyboard Controls:
|
||||
* Press any other button to skip to the next music file in the list
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
import pygame
|
||||
from typing import List
|
||||
import pygame as pg
|
||||
import os, sys
|
||||
|
||||
VOLUME_CHANGE_AMOUNT = 0.02 # how fast should up and down arrows change the volume?
|
||||
SCREEN_SIZE = (640, 480)
|
||||
|
||||
MUSIC_DONE = pygame.event.custom_type() # event to be set as mixer.music.set_endevent()
|
||||
main_dir = os.path.split(os.path.abspath(__file__))[0]
|
||||
data_dir = os.path.join(main_dir, "data")
|
||||
|
||||
starting_pos = 0 # needed to fast forward and rewind
|
||||
volume = 0.75
|
||||
music_file_list = []
|
||||
music_file_types = ("mp3", "ogg", "mid", "mod", "it", "xm", "wav")
|
||||
music_can_seek = ("mp3", "ogg", "mod", "it", "xm")
|
||||
screen = None
|
||||
|
||||
|
||||
def add_file(filename):
|
||||
@@ -72,15 +59,15 @@ def play_file(filename):
|
||||
|
||||
if add_file(filename):
|
||||
try: # we must do this in case the file is not a valid audio file
|
||||
pygame.mixer.music.load(music_file_list[-1])
|
||||
except pygame.error as e:
|
||||
pg.mixer.music.load(music_file_list[-1])
|
||||
except pg.error as e:
|
||||
print(e) # print description such as 'Not an Ogg Vorbis audio stream'
|
||||
if filename in music_file_list:
|
||||
music_file_list.remove(filename)
|
||||
print(f"{filename} removed from file list")
|
||||
return
|
||||
pygame.mixer.music.play(fade_ms=4000)
|
||||
pygame.mixer.music.set_volume(volume)
|
||||
pg.mixer.music.play(fade_ms=4000)
|
||||
pg.mixer.music.set_volume(volume)
|
||||
|
||||
if filename.rpartition(".")[2].lower() in music_can_seek:
|
||||
print("file supports seeking")
|
||||
@@ -88,7 +75,7 @@ def play_file(filename):
|
||||
else:
|
||||
print("file does not support seeking")
|
||||
starting_pos = -1
|
||||
pygame.mixer.music.set_endevent(MUSIC_DONE)
|
||||
pg.mixer.music.set_endevent(MUSIC_DONE)
|
||||
|
||||
|
||||
def play_next():
|
||||
@@ -103,8 +90,8 @@ def play_next():
|
||||
nxt = music_file_list.pop(0)
|
||||
|
||||
try:
|
||||
pygame.mixer.music.load(nxt)
|
||||
except pygame.error as e:
|
||||
pg.mixer.music.load(nxt)
|
||||
except pg.error as e:
|
||||
print(e)
|
||||
print(f"{nxt} removed from file list")
|
||||
|
||||
@@ -112,9 +99,9 @@ def play_next():
|
||||
print("starting next song: ", nxt)
|
||||
else:
|
||||
nxt = music_file_list[0]
|
||||
pygame.mixer.music.play(fade_ms=4000)
|
||||
pygame.mixer.music.set_volume(volume)
|
||||
pygame.mixer.music.set_endevent(MUSIC_DONE)
|
||||
pg.mixer.music.play(fade_ms=4000)
|
||||
pg.mixer.music.set_volume(volume)
|
||||
pg.mixer.music.set_endevent(MUSIC_DONE)
|
||||
|
||||
if nxt.rpartition(".")[2].lower() in music_can_seek:
|
||||
starting_pos = 0
|
||||
@@ -122,6 +109,20 @@ def play_next():
|
||||
starting_pos = -1
|
||||
|
||||
|
||||
def draw_text_line(text, y=0):
|
||||
"""
|
||||
Draws a line of text onto the display surface
|
||||
The text will be centered horizontally at the given y position
|
||||
The text's height is added to y and returned to the caller
|
||||
"""
|
||||
screen = pg.display.get_surface()
|
||||
surf = font.render(text, 1, (255, 255, 255))
|
||||
y += surf.get_height()
|
||||
x = (screen.get_width() - surf.get_width()) / 2
|
||||
screen.blit(surf, (x, y))
|
||||
return y
|
||||
|
||||
|
||||
def change_music_position(amount):
|
||||
"""
|
||||
Changes current playback position by amount seconds.
|
||||
@@ -133,17 +134,27 @@ def change_music_position(amount):
|
||||
global starting_pos
|
||||
|
||||
if starting_pos >= 0: # will be -1 unless play_file() was OGG or MP3
|
||||
played_for = pygame.mixer.music.get_pos() / 1000.0
|
||||
played_for = pg.mixer.music.get_pos() / 1000.0
|
||||
old_pos = starting_pos + played_for
|
||||
starting_pos = old_pos + amount
|
||||
pygame.mixer.music.play(start=starting_pos)
|
||||
pg.mixer.music.play(start=starting_pos)
|
||||
print(f"jumped from {old_pos} to {starting_pos}")
|
||||
|
||||
|
||||
MUSIC_DONE = pg.event.custom_type() # event to be set as mixer.music.set_endevent()
|
||||
main_dir = os.path.split(os.path.abspath(__file__))[0]
|
||||
data_dir = os.path.join(main_dir, "data")
|
||||
|
||||
starting_pos = 0 # needed to fast forward and rewind
|
||||
volume = 0.75
|
||||
music_file_list: List[str] = []
|
||||
music_file_types = ("mp3", "ogg", "mid", "mod", "it", "xm", "wav")
|
||||
music_can_seek = ("mp3", "ogg", "mod", "it", "xm")
|
||||
|
||||
|
||||
def main():
|
||||
global font # this will be used by the draw_text_line function
|
||||
global volume, starting_pos
|
||||
global screen
|
||||
running = True
|
||||
paused = False
|
||||
|
||||
@@ -152,15 +163,16 @@ def main():
|
||||
# the change_volume variable will be set by key down events and cleared by key up events
|
||||
change_volume = 0
|
||||
|
||||
pygame.init()
|
||||
screen = pygame.display.set_mode(SCREEN_SIZE)
|
||||
font = pygame.font.SysFont("Arial", 24)
|
||||
font.align = pygame.FONT_CENTER
|
||||
clock = pygame.Clock()
|
||||
pg.init()
|
||||
pg.display.set_mode((640, 480))
|
||||
font = pg.font.SysFont("Arial", 24)
|
||||
clock = pg.time.Clock()
|
||||
|
||||
clipped = ""
|
||||
if pygame.scrap.has_text():
|
||||
clipped = pygame.scrap.get_text()
|
||||
pg.scrap.init()
|
||||
pg.SCRAP_TEXT = pg.scrap.get_types()[0] # TODO remove when scrap module is fixed
|
||||
scrap_get = pg.scrap.get(pg.SCRAP_TEXT)
|
||||
clipped = "" if scrap_get is None else scrap_get.decode("UTF-8")
|
||||
# store the current text from the clipboard TODO remove decode
|
||||
|
||||
# add the command line arguments to the music_file_list
|
||||
for arg in sys.argv[1:]:
|
||||
@@ -168,74 +180,73 @@ def main():
|
||||
play_file("house_lo.ogg") # play default music included with pygame
|
||||
|
||||
# draw instructions on screen
|
||||
text = """
|
||||
Drop music files or path names onto this window
|
||||
Copy file names into the clipboard
|
||||
Or feed them from the command line
|
||||
If it's music it will play!
|
||||
y = draw_text_line("Drop music files or path names onto this window", 20)
|
||||
y = draw_text_line("Copy file names into the clipboard", y)
|
||||
y = draw_text_line("Or feed them from the command line", y)
|
||||
y = draw_text_line("If it's music it will play!", y)
|
||||
y = draw_text_line("SPACE to pause or UP/DOWN to change volume", y)
|
||||
y = draw_text_line("LEFT and RIGHT will skip around the track", y)
|
||||
draw_text_line("Other keys will start the next track", y)
|
||||
|
||||
LEFT and RIGHT will skip around the track
|
||||
UP and DOWN will change volume
|
||||
ENTER or SPACE will pause/unpause the track
|
||||
Other keys will start the next track"""
|
||||
screen.blit(font.render(text, True, "white", "black", SCREEN_SIZE[0] - 20), (10, 5))
|
||||
"""
|
||||
This is the main loop
|
||||
It will respond to drag and drop, clipboard changes, and key presses
|
||||
"""
|
||||
while running:
|
||||
for ev in pygame.event.get():
|
||||
if ev.type == pygame.QUIT:
|
||||
for ev in pg.event.get():
|
||||
if ev.type == pg.QUIT:
|
||||
running = False
|
||||
elif ev.type == pygame.DROPTEXT:
|
||||
elif ev.type == pg.DROPTEXT:
|
||||
play_file(ev.text)
|
||||
elif ev.type == pygame.DROPFILE:
|
||||
elif ev.type == pg.DROPFILE:
|
||||
play_file(ev.file)
|
||||
elif ev.type == MUSIC_DONE:
|
||||
play_next()
|
||||
elif ev.type == pygame.KEYDOWN:
|
||||
if ev.key == pygame.K_ESCAPE:
|
||||
elif ev.type == pg.KEYDOWN:
|
||||
if ev.key == pg.K_ESCAPE:
|
||||
running = False # exit loop
|
||||
elif ev.key in (pygame.K_SPACE, pygame.K_RETURN):
|
||||
elif ev.key in (pg.K_SPACE, pg.K_RETURN):
|
||||
if paused:
|
||||
pygame.mixer.music.unpause()
|
||||
pg.mixer.music.unpause()
|
||||
paused = False
|
||||
else:
|
||||
pygame.mixer.music.pause()
|
||||
pg.mixer.music.pause()
|
||||
paused = True
|
||||
elif ev.key == pygame.K_UP:
|
||||
elif ev.key == pg.K_UP:
|
||||
change_volume = VOLUME_CHANGE_AMOUNT
|
||||
elif ev.key == pygame.K_DOWN:
|
||||
elif ev.key == pg.K_DOWN:
|
||||
change_volume = -VOLUME_CHANGE_AMOUNT
|
||||
elif ev.key == pygame.K_RIGHT:
|
||||
elif ev.key == pg.K_RIGHT:
|
||||
change_music_position(+5)
|
||||
elif ev.key == pygame.K_LEFT:
|
||||
elif ev.key == pg.K_LEFT:
|
||||
change_music_position(-5)
|
||||
|
||||
else:
|
||||
play_next()
|
||||
|
||||
elif ev.type == pygame.KEYUP:
|
||||
if ev.key in (pygame.K_UP, pygame.K_DOWN):
|
||||
elif ev.type == pg.KEYUP:
|
||||
if ev.key in (pg.K_UP, pg.K_DOWN):
|
||||
change_volume = 0
|
||||
|
||||
# is the user holding up or down?
|
||||
if change_volume:
|
||||
volume += change_volume
|
||||
volume = min(max(0, volume), 1) # volume should be between 0 and 1
|
||||
pygame.mixer.music.set_volume(volume)
|
||||
pg.mixer.music.set_volume(volume)
|
||||
print("volume:", volume)
|
||||
|
||||
if pygame.scrap.has_text():
|
||||
new_text = pygame.scrap.get_text()
|
||||
if new_text != clipped:
|
||||
clipped = new_text
|
||||
play_file(clipped)
|
||||
# TODO remove decode when SDL2 scrap is fixed
|
||||
scrap_get = pg.scrap.get(pg.SCRAP_TEXT)
|
||||
new_text = "" if scrap_get is None else scrap_get.decode("UTF-8")
|
||||
|
||||
pygame.display.flip()
|
||||
if new_text != clipped: # has the clipboard changed?
|
||||
clipped = new_text
|
||||
play_file(clipped) # try to play the file if it has
|
||||
|
||||
pg.display.flip()
|
||||
clock.tick(9) # keep CPU use down by updating screen less often
|
||||
|
||||
pygame.quit()
|
||||
pg.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,164 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.ninepatch
|
||||
Demonstrate the purpose of the 9-patch scale method and a way to implement it.
|
||||
|
||||
9-patch scaling allows us to scale a surface while keeping 4 corners intact.
|
||||
This is very useful for GUI applications.
|
||||
|
||||
How it works:
|
||||
The 4 corners are extracted from the original surface and pasted on the new surface.
|
||||
The 4 sides in between the corners are scaled horizontally or vertically to fit
|
||||
between the new surface corners.
|
||||
The central part of the image is scaled and pasted.
|
||||
|
||||
In this example a green fill is used which can be done faster and easier with pygame.draw.rect
|
||||
but usually you'd have a custom surface that needs intact corners.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
import pygame
|
||||
|
||||
SCREEN_SIZE = pygame.Vector2(600, 500)
|
||||
SCALE_SIZE = pygame.Vector2(500, 150)
|
||||
INNER_SCALE_SIZE = pygame.Vector2(400, 115)
|
||||
CORNER_SIZE = 20
|
||||
INNER_CORNER_SIZE = 7
|
||||
|
||||
|
||||
def ninepatch_scale(
|
||||
surface: pygame.Surface,
|
||||
size: pygame.typing.Point,
|
||||
corner_size: int,
|
||||
alpha: bool = True,
|
||||
smooth: bool = False,
|
||||
dest_surface: pygame.Surface | None = None,
|
||||
) -> pygame.Surface:
|
||||
# the code of this function also emulates how a transform-like ninepatch function would likely behave
|
||||
if dest_surface is not None:
|
||||
ret_surface = dest_surface
|
||||
if ret_surface.size != size:
|
||||
raise ValueError("Destination surface doesn't match the provided size")
|
||||
else:
|
||||
ret_surface = pygame.Surface(
|
||||
size, pygame.SRCALPHA * alpha
|
||||
) # when alpha is False the flags become 0
|
||||
|
||||
# aliases
|
||||
ret_w, ret_h = size # non-sequence argument caught by python
|
||||
src_w, src_h = surface.size
|
||||
c = corner_size
|
||||
scale_func = pygame.transform.smoothscale if smooth else pygame.transform.scale
|
||||
subsurface = surface.subsurface # alias for performance/clarity
|
||||
|
||||
if corner_size < 0 or corner_size > min(ret_w, ret_h):
|
||||
raise ValueError(
|
||||
"Corner size must be nonnegative and not greater than the smaller between width and height"
|
||||
)
|
||||
if corner_size == 0: # default to normal scaling
|
||||
return scale_func(surface, size)
|
||||
|
||||
src_x_side, src_y_side = surface.size - pygame.Vector2(c) * 2
|
||||
ret_x_side, ret_y_side = size - pygame.Vector2(c) * 2
|
||||
|
||||
ret_surface.blit( # topleft corner
|
||||
subsurface(0, 0, c, c), (0, 0)
|
||||
)
|
||||
ret_surface.blit( # topright corner
|
||||
subsurface(src_w - c, 0, c, c), (ret_w - c, 0)
|
||||
)
|
||||
ret_surface.blit( # bottomleft corner
|
||||
subsurface(0, src_h - c, c, c), (0, ret_h - c)
|
||||
)
|
||||
ret_surface.blit( # bottomright corner
|
||||
subsurface(src_w - c, src_h - c, c, c), (ret_w - c, ret_h - c)
|
||||
)
|
||||
|
||||
if src_x_side > 0:
|
||||
ret_surface.blit( # top side
|
||||
scale_func(subsurface(c, 0, src_x_side, c), (ret_x_side, c)), (c, 0)
|
||||
)
|
||||
ret_surface.blit( # bottom side
|
||||
scale_func(subsurface(c, src_h - c, src_x_side, c), (ret_x_side, c)),
|
||||
(c, ret_h - c),
|
||||
)
|
||||
|
||||
if src_y_side > 0:
|
||||
ret_surface.blit( # left side
|
||||
scale_func(subsurface(0, c, c, src_y_side), (c, ret_y_side)), (0, c)
|
||||
)
|
||||
ret_surface.blit( # right side
|
||||
scale_func(subsurface(src_w - c, c, c, src_y_side), (c, ret_y_side)),
|
||||
(ret_w - c, c),
|
||||
)
|
||||
|
||||
if src_x_side > 0 and src_y_side > 0:
|
||||
ret_surface.blit( # central area
|
||||
scale_func(
|
||||
subsurface(c, c, src_x_side, src_y_side), (ret_x_side, ret_y_side)
|
||||
),
|
||||
(c, c),
|
||||
)
|
||||
|
||||
return ret_surface
|
||||
|
||||
|
||||
def main():
|
||||
pygame.init()
|
||||
screen = pygame.display.set_mode(SCREEN_SIZE)
|
||||
pygame.display.set_caption("9-Patch Scale and Normal Scale Example")
|
||||
clock = pygame.Clock()
|
||||
font = pygame.Font(None, 30)
|
||||
|
||||
main_dir = os.path.split(os.path.abspath(__file__))[0]
|
||||
example_image = pygame.image.load(os.path.join(main_dir, "data", "frame.webp"))
|
||||
|
||||
original_surface = pygame.Surface((100, 100), pygame.SRCALPHA)
|
||||
pygame.draw.rect(
|
||||
original_surface, "green", original_surface.get_rect(), 0, CORNER_SIZE
|
||||
)
|
||||
|
||||
normal_scale = pygame.transform.scale(original_surface, SCALE_SIZE)
|
||||
normal_center = SCREEN_SIZE.elementwise() / pygame.Vector2(2, 4)
|
||||
normal_rect = normal_scale.get_rect(center=normal_center)
|
||||
example_normal_scale = pygame.transform.scale(example_image, INNER_SCALE_SIZE)
|
||||
example_normal_rect = example_normal_scale.get_rect(center=normal_center)
|
||||
|
||||
ninepatch = ninepatch_scale(
|
||||
original_surface, SCALE_SIZE, CORNER_SIZE, True, False, None
|
||||
)
|
||||
ninepatch_center = SCREEN_SIZE.elementwise() / pygame.Vector2(2, 4 / 3)
|
||||
ninepatch_rect = ninepatch.get_rect(center=ninepatch_center)
|
||||
example_ninepatch = ninepatch_scale(
|
||||
example_image, INNER_SCALE_SIZE, INNER_CORNER_SIZE, True, False, None
|
||||
)
|
||||
example_ninepatch_rect = example_ninepatch.get_rect(center=ninepatch_center)
|
||||
|
||||
text_normal = font.render("Normal Scale", True, "black")
|
||||
text_normal_rect = text_normal.get_rect(center=normal_center)
|
||||
text_9patch = font.render("9-Patch Scale", True, "black")
|
||||
text_9patch_rect = text_9patch.get_rect(center=ninepatch_center)
|
||||
|
||||
running = True
|
||||
while running:
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
running = False
|
||||
|
||||
screen.fill(0)
|
||||
|
||||
screen.blit(normal_scale, normal_rect)
|
||||
screen.blit(example_normal_scale, example_normal_rect)
|
||||
screen.blit(ninepatch, ninepatch_rect)
|
||||
screen.blit(example_ninepatch, example_ninepatch_rect)
|
||||
screen.blit(text_normal, text_normal_rect)
|
||||
screen.blit(text_9patch, text_9patch_rect)
|
||||
|
||||
pygame.display.flip()
|
||||
clock.tick(60)
|
||||
|
||||
pygame.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.pixelarray
|
||||
""" pygame.examples.pixelarray
|
||||
|
||||
PixelArray does array processing of pixels.
|
||||
Sort of like another array processor called 'numpy' - But for pixels.
|
||||
@@ -13,39 +13,38 @@ Controls
|
||||
|
||||
To see different effects - press a key or click a mouse.
|
||||
"""
|
||||
|
||||
import os
|
||||
import pygame as pg
|
||||
|
||||
import pygame
|
||||
|
||||
main_dir = os.path.split(os.path.abspath(__file__))[0]
|
||||
data_dir = os.path.join(main_dir, "data")
|
||||
|
||||
|
||||
def show(image):
|
||||
screen = pygame.display.get_surface()
|
||||
screen = pg.display.get_surface()
|
||||
screen.fill((255, 255, 255))
|
||||
screen.blit(image, (0, 0))
|
||||
pygame.display.flip()
|
||||
pg.display.flip()
|
||||
while True:
|
||||
event = pygame.event.wait()
|
||||
if event.type == pygame.QUIT:
|
||||
pygame.quit()
|
||||
event = pg.event.wait()
|
||||
if event.type == pg.QUIT:
|
||||
pg.quit()
|
||||
raise SystemExit
|
||||
if event.type in [pygame.MOUSEBUTTONDOWN, pygame.KEYDOWN]:
|
||||
if event.type in [pg.MOUSEBUTTONDOWN, pg.KEYDOWN]:
|
||||
break
|
||||
|
||||
|
||||
def main():
|
||||
pygame.init()
|
||||
pg.init()
|
||||
|
||||
pygame.display.set_mode((255, 255))
|
||||
surface = pygame.Surface((255, 255))
|
||||
pg.display.set_mode((255, 255))
|
||||
surface = pg.Surface((255, 255))
|
||||
|
||||
pygame.display.flip()
|
||||
pg.display.flip()
|
||||
|
||||
# Create the PixelArray.
|
||||
ar = pygame.PixelArray(surface)
|
||||
ar = pg.PixelArray(surface)
|
||||
|
||||
# Do some easy gradient effect.
|
||||
for y in range(255):
|
||||
@@ -55,83 +54,83 @@ def main():
|
||||
show(surface)
|
||||
|
||||
# We have made some gradient effect, now flip it.
|
||||
ar = pygame.PixelArray(surface)
|
||||
ar = pg.PixelArray(surface)
|
||||
ar[:] = ar[:, ::-1]
|
||||
del ar
|
||||
show(surface)
|
||||
|
||||
# Every second column will be made blue
|
||||
ar = pygame.PixelArray(surface)
|
||||
ar = pg.PixelArray(surface)
|
||||
ar[::2] = (0, 0, 255)
|
||||
del ar
|
||||
show(surface)
|
||||
|
||||
# Every second row will be made green
|
||||
ar = pygame.PixelArray(surface)
|
||||
ar = pg.PixelArray(surface)
|
||||
ar[:, ::2] = (0, 255, 0)
|
||||
del ar
|
||||
show(surface)
|
||||
|
||||
# Manipulate the image. Flip it around the y axis.
|
||||
surface = pygame.image.load(os.path.join(data_dir, "arraydemo.webp"))
|
||||
ar = pygame.PixelArray(surface)
|
||||
surface = pg.image.load(os.path.join(data_dir, "arraydemo.bmp"))
|
||||
ar = pg.PixelArray(surface)
|
||||
ar[:] = ar[:, ::-1]
|
||||
del ar
|
||||
show(surface)
|
||||
|
||||
# Flip the image around the x axis.
|
||||
ar = pygame.PixelArray(surface)
|
||||
ar = pg.PixelArray(surface)
|
||||
ar[:] = ar[::-1, :]
|
||||
del ar
|
||||
show(surface)
|
||||
|
||||
# Every second column will be made white.
|
||||
ar = pygame.PixelArray(surface)
|
||||
ar = pg.PixelArray(surface)
|
||||
ar[::2] = (255, 255, 255)
|
||||
del ar
|
||||
show(surface)
|
||||
|
||||
# Flip the image around both axes, restoring its original layout.
|
||||
ar = pygame.PixelArray(surface)
|
||||
ar = pg.PixelArray(surface)
|
||||
ar[:] = ar[::-1, ::-1]
|
||||
del ar
|
||||
show(surface)
|
||||
|
||||
# Rotate 90 degrees clockwise.
|
||||
w, h = surface.get_size()
|
||||
surface2 = pygame.Surface((h, w), surface.get_flags(), surface)
|
||||
ar = pygame.PixelArray(surface)
|
||||
ar2 = pygame.PixelArray(surface2)
|
||||
surface2 = pg.Surface((h, w), surface.get_flags(), surface)
|
||||
ar = pg.PixelArray(surface)
|
||||
ar2 = pg.PixelArray(surface2)
|
||||
ar2[...] = ar.transpose()[::-1, :]
|
||||
del ar, ar2
|
||||
show(surface2)
|
||||
|
||||
# Scale it by throwing each second pixel away.
|
||||
surface = pygame.image.load(os.path.join(data_dir, "arraydemo.webp"))
|
||||
ar = pygame.PixelArray(surface)
|
||||
surface = pg.image.load(os.path.join(data_dir, "arraydemo.bmp"))
|
||||
ar = pg.PixelArray(surface)
|
||||
sf2 = ar[::2, ::2].make_surface()
|
||||
del ar
|
||||
show(sf2)
|
||||
|
||||
# Replace anything looking like the blue color from the text.
|
||||
ar = pygame.PixelArray(surface)
|
||||
ar = pg.PixelArray(surface)
|
||||
ar.replace((60, 60, 255), (0, 255, 0), 0.06)
|
||||
del ar
|
||||
show(surface)
|
||||
|
||||
# Extract anything which might be somewhat black.
|
||||
surface = pygame.image.load(os.path.join(data_dir, "arraydemo.webp"))
|
||||
ar = pygame.PixelArray(surface)
|
||||
surface = pg.image.load(os.path.join(data_dir, "arraydemo.bmp"))
|
||||
ar = pg.PixelArray(surface)
|
||||
ar2 = ar.extract((0, 0, 0), 0.07)
|
||||
sf2 = ar2.surface
|
||||
del ar, ar2
|
||||
show(sf2)
|
||||
|
||||
# Compare two images.
|
||||
surface = pygame.image.load(os.path.join(data_dir, "alien1.gif"))
|
||||
surface2 = pygame.image.load(os.path.join(data_dir, "alien2.gif"))
|
||||
ar1 = pygame.PixelArray(surface)
|
||||
ar2 = pygame.PixelArray(surface2)
|
||||
surface = pg.image.load(os.path.join(data_dir, "alien1.gif"))
|
||||
surface2 = pg.image.load(os.path.join(data_dir, "alien2.gif"))
|
||||
ar1 = pg.PixelArray(surface)
|
||||
ar2 = pg.PixelArray(surface2)
|
||||
ar3 = ar1.compare(ar2, 0.07)
|
||||
sf3 = ar3.surface
|
||||
del ar1, ar2, ar3
|
||||
@@ -140,4 +139,4 @@ def main():
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
pygame.quit()
|
||||
pg.quit()
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.playmus
|
||||
""" pygame.examples.playmus
|
||||
|
||||
A simple music player.
|
||||
|
||||
@@ -17,110 +17,144 @@ f - fade out
|
||||
q - stop
|
||||
|
||||
"""
|
||||
|
||||
import sys
|
||||
|
||||
import pygame
|
||||
|
||||
pygame.init()
|
||||
import pygame as pg
|
||||
import pygame.freetype
|
||||
|
||||
|
||||
def write_lines(
|
||||
dest: pygame.Surface,
|
||||
text: str,
|
||||
font=pygame.Font(None, 30),
|
||||
color=(254, 231, 21, 255),
|
||||
starting_line=0,
|
||||
):
|
||||
text_surface = font.render(text, True, color)
|
||||
class Window:
|
||||
"""The application's Pygame window
|
||||
|
||||
y_offset = 0
|
||||
if starting_line >= 0:
|
||||
y_offset = font.get_height() * starting_line
|
||||
else:
|
||||
y_offset = dest.get_height() + starting_line * font.get_height()
|
||||
A Window instance manages the creation of and drawing to a
|
||||
window. It is a singleton class. Only one instance can exist.
|
||||
|
||||
dest.fill(
|
||||
(16, 24, 32, 255),
|
||||
pygame.Rect((0, y_offset), (text_surface.get_width(), dest.get_width())),
|
||||
)
|
||||
dest.blit(text_surface, (16, y_offset))
|
||||
"""
|
||||
|
||||
instance = None
|
||||
|
||||
def __new__(cls, *args, **kwds):
|
||||
"""Return an open Pygame window"""
|
||||
|
||||
if Window.instance is not None:
|
||||
return Window.instance
|
||||
self = object.__new__(cls)
|
||||
pg.display.init()
|
||||
self.screen = pg.display.set_mode((600, 400))
|
||||
Window.instance = self
|
||||
return self
|
||||
|
||||
def __init__(self, title):
|
||||
pg.display.set_caption(title)
|
||||
self.text_color = (254, 231, 21, 255)
|
||||
self.background_color = (16, 24, 32, 255)
|
||||
self.screen.fill(self.background_color)
|
||||
pg.display.flip()
|
||||
|
||||
pygame.freetype.init()
|
||||
self.font = pygame.freetype.Font(None, 20)
|
||||
self.font.origin = True
|
||||
self.ascender = int(self.font.get_sized_ascender() * 1.5)
|
||||
self.descender = int(self.font.get_sized_descender() * 1.5)
|
||||
self.line_height = self.ascender - self.descender
|
||||
|
||||
self.write_lines(
|
||||
"\nPress 'q' or 'ESCAPE' or close this window to quit\n"
|
||||
"Press 'SPACE' to play / pause\n"
|
||||
"Press 'r' to rewind to the beginning (restart)\n"
|
||||
"Press 'f' to fade music out over 5 seconds\n\n"
|
||||
"Window will quit automatically when music ends\n",
|
||||
0,
|
||||
)
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
self.close()
|
||||
return False
|
||||
|
||||
def close(self):
|
||||
pg.display.quit()
|
||||
Window.instance = None
|
||||
|
||||
def write_lines(self, text, line=0):
|
||||
w, h = self.screen.get_size()
|
||||
line_height = self.line_height
|
||||
nlines = h // line_height
|
||||
if line < 0:
|
||||
line = nlines + line
|
||||
for i, text_line in enumerate(text.split("\n"), line):
|
||||
y = i * line_height + self.ascender
|
||||
# Clear the line first.
|
||||
self.screen.fill(
|
||||
self.background_color, (0, i * line_height, w, line_height)
|
||||
)
|
||||
# Write new text.
|
||||
self.font.render_to(self.screen, (15, y), text_line, self.text_color)
|
||||
pg.display.flip()
|
||||
|
||||
|
||||
def show_usage_message():
|
||||
print(
|
||||
"Usage: python playmus.py <file>\n"
|
||||
" python -m pygame.examples.playmus <file>"
|
||||
)
|
||||
print("Usage: python playmus.py <file>")
|
||||
print(" python -m pygame.examples.playmus <file>")
|
||||
|
||||
|
||||
def main(file_path):
|
||||
"""Play an audio file with pygame.mixer.music"""
|
||||
"""Play an audio file with pg.mixer.music"""
|
||||
|
||||
screen = pygame.display.set_mode((600, 400))
|
||||
screen.fill((16, 24, 32, 255))
|
||||
with Window(file_path) as win:
|
||||
win.write_lines("Loading ...", -1)
|
||||
pg.mixer.init(frequency=44100)
|
||||
try:
|
||||
paused = False
|
||||
pg.mixer.music.load(file_path)
|
||||
|
||||
write_lines(screen, "Loading ...", starting_line=-1)
|
||||
pygame.mixer.init(frequency=44100)
|
||||
pygame.mixer.music.load(file_path)
|
||||
# Make sure the event loop ticks over at least every 0.5 seconds.
|
||||
pg.time.set_timer(pg.USEREVENT, 500)
|
||||
|
||||
pygame.display.set_caption(f"File : {file_path}")
|
||||
pg.mixer.music.play()
|
||||
win.write_lines("Playing ...\n", -1)
|
||||
|
||||
write_lines(
|
||||
screen,
|
||||
"Press 'q' or 'ESCAPE' or close this window to quit\n"
|
||||
"Press 'SPACE' to play / pause\n"
|
||||
"Press 'r' to rewind to the beginning (restart)\n"
|
||||
"Press 'f' to fade music out over 5 seconds",
|
||||
starting_line=1,
|
||||
)
|
||||
|
||||
pygame.mixer.music.play()
|
||||
write_lines(screen, "Playing ...\n", starting_line=-1)
|
||||
|
||||
running = True
|
||||
paused = False
|
||||
|
||||
while running:
|
||||
pygame.display.flip()
|
||||
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.KEYDOWN:
|
||||
key = event.key
|
||||
if key == pygame.K_SPACE:
|
||||
if paused:
|
||||
pygame.mixer.music.unpause()
|
||||
while pg.mixer.music.get_busy() or paused:
|
||||
e = pg.event.wait()
|
||||
if e.type == pg.KEYDOWN:
|
||||
key = e.key
|
||||
if key == pg.K_SPACE:
|
||||
if paused:
|
||||
pg.mixer.music.unpause()
|
||||
paused = False
|
||||
win.write_lines("Playing ...\n", -1)
|
||||
else:
|
||||
pg.mixer.music.pause()
|
||||
paused = True
|
||||
win.write_lines("Paused ...\n", -1)
|
||||
elif key == pg.K_r:
|
||||
if file_path[-3:].lower() in ("ogg", "mp3", "mod"):
|
||||
status = "Rewound."
|
||||
pg.mixer.music.rewind()
|
||||
else:
|
||||
status = "Restarted."
|
||||
pg.mixer.music.play()
|
||||
if paused:
|
||||
pg.mixer.music.pause()
|
||||
win.write_lines(status, -1)
|
||||
elif key == pg.K_f:
|
||||
win.write_lines("Fading out ...\n", -1)
|
||||
pg.mixer.music.fadeout(5000)
|
||||
# when finished get_busy() will return False.
|
||||
elif key in [pg.K_q, pg.K_ESCAPE]:
|
||||
paused = False
|
||||
write_lines(screen, "Playing ...", starting_line=-1)
|
||||
else:
|
||||
pygame.mixer.music.pause()
|
||||
paused = True
|
||||
write_lines(screen, "Paused ...", starting_line=-1)
|
||||
elif key == pygame.K_r:
|
||||
if file_path[-3:].lower() in ("ogg", "mp3", "mod"):
|
||||
status = "Rewound."
|
||||
pygame.mixer.music.rewind()
|
||||
else:
|
||||
status = "Restarted."
|
||||
pygame.mixer.music.play()
|
||||
if paused:
|
||||
pygame.mixer.music.pause()
|
||||
write_lines(screen, status, starting_line=-1)
|
||||
elif key == pygame.K_f:
|
||||
write_lines(screen, "Fading out ...", starting_line=-1)
|
||||
pygame.mixer.music.fadeout(5000)
|
||||
# when finished get_busy() will return False.
|
||||
elif key in [pygame.K_q, pygame.K_ESCAPE]:
|
||||
pg.mixer.music.stop()
|
||||
# get_busy() will now return False.
|
||||
elif e.type == pg.QUIT:
|
||||
paused = False
|
||||
pygame.mixer.music.stop()
|
||||
pg.mixer.music.stop()
|
||||
# get_busy() will now return False.
|
||||
elif event.type == pygame.QUIT:
|
||||
running = False
|
||||
|
||||
if not pygame.mixer.music.get_busy() and not paused:
|
||||
running = False
|
||||
|
||||
pygame.quit()
|
||||
pg.time.set_timer(pg.USEREVENT, 0)
|
||||
finally:
|
||||
pg.mixer.quit()
|
||||
pg.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,98 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.prevent_display_stretching
|
||||
|
||||
Prevent display stretching on Windows.
|
||||
|
||||
On some computers, the display environment can be configured to stretch
|
||||
all windows so that they will not appear too small on the screen for
|
||||
the user. This configuration is especially common on high-DPI displays.
|
||||
pygame-ce graphics appear distorted when automatically stretched by the
|
||||
display environment. This script demonstrates a technique for preventing
|
||||
this stretching and distortion.
|
||||
|
||||
Limitations:
|
||||
This script makes an API call that is only available on Windows (versions
|
||||
Vista and newer).
|
||||
|
||||
"""
|
||||
|
||||
# Ensure that the computer is running Windows Vista or newer
|
||||
import os
|
||||
import sys
|
||||
|
||||
# game constants
|
||||
TEXTCOLOR = "green"
|
||||
BACKGROUNDCOLOR = "black"
|
||||
AXISCOLOR = "white"
|
||||
|
||||
if os.name != "nt" or sys.getwindowsversion()[0] < 6:
|
||||
raise NotImplementedError("this script requires Windows Vista or newer")
|
||||
|
||||
import ctypes
|
||||
|
||||
import pygame
|
||||
|
||||
|
||||
def main():
|
||||
# Determine whether or not the user would like to prevent stretching
|
||||
if os.path.basename(sys.executable) == "pythonw.exe":
|
||||
selection = "y"
|
||||
else:
|
||||
selection = None
|
||||
while selection not in ("y", "n"):
|
||||
selection = input("Prevent stretching? (y/n): ").strip().lower()
|
||||
|
||||
if selection == "y":
|
||||
msg = "Stretching is prevented."
|
||||
else:
|
||||
msg = "Stretching is not prevented."
|
||||
|
||||
# Prevent stretching
|
||||
if selection == "y":
|
||||
user32 = ctypes.windll.user32
|
||||
user32.SetProcessDPIAware()
|
||||
|
||||
# Show screen
|
||||
pygame.display.init()
|
||||
RESOLUTION = (350, 350)
|
||||
screen = pygame.display.set_mode(RESOLUTION)
|
||||
|
||||
# Render message onto a surface
|
||||
pygame.font.init()
|
||||
font = pygame.Font(None, 36)
|
||||
msg_surf = font.render(msg, True, TEXTCOLOR)
|
||||
res_surf = font.render("Intended resolution: %ix%i" % RESOLUTION, 1, TEXTCOLOR)
|
||||
|
||||
# Control loop
|
||||
running = True
|
||||
clock = pygame.Clock()
|
||||
counter = 0
|
||||
while running:
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
running = False
|
||||
|
||||
screen.fill(BACKGROUNDCOLOR)
|
||||
|
||||
# Draw lines which will be blurry if the window is stretched
|
||||
# or clear if the window is not stretched.
|
||||
pygame.draw.line(screen, AXISCOLOR, (0, counter), (RESOLUTION[0] - 1, counter))
|
||||
pygame.draw.line(screen, AXISCOLOR, (counter, 0), (counter, RESOLUTION[1] - 1))
|
||||
|
||||
# Blit message onto screen surface
|
||||
msg_blit_rect = screen.blit(msg_surf, (0, 0))
|
||||
screen.blit(res_surf, (0, msg_blit_rect.bottom))
|
||||
|
||||
clock.tick(10)
|
||||
|
||||
pygame.display.flip()
|
||||
|
||||
counter += 1
|
||||
if counter == RESOLUTION[0]:
|
||||
counter = 0
|
||||
|
||||
pygame.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,49 +1,44 @@
|
||||
#!/usr/bin/env python
|
||||
import pygame
|
||||
import pygame as pg
|
||||
|
||||
RESOLUTION = (160, 120)
|
||||
pg.init()
|
||||
|
||||
RES = (160, 120)
|
||||
FPS = 30
|
||||
clock = pg.time.Clock()
|
||||
|
||||
screen = pg.display.set_mode(RES, pg.RESIZABLE)
|
||||
pg.display._set_autoresize(False)
|
||||
|
||||
def main():
|
||||
pygame.init()
|
||||
# MAIN LOOP
|
||||
|
||||
clock = pygame.Clock()
|
||||
done = False
|
||||
|
||||
screen = pygame.display.set_mode(RESOLUTION, pygame.RESIZABLE)
|
||||
pygame.display._set_autoresize(False)
|
||||
i = 0
|
||||
j = 0
|
||||
|
||||
# MAIN LOOP
|
||||
while not done:
|
||||
for event in pg.event.get():
|
||||
if event.type == pg.KEYDOWN and event.key == pg.K_q:
|
||||
done = True
|
||||
if event.type == pg.QUIT:
|
||||
done = True
|
||||
# if event.type==pg.WINDOWRESIZED:
|
||||
# screen=pg.display.get_surface()
|
||||
if event.type == pg.VIDEORESIZE:
|
||||
screen = pg.display.get_surface()
|
||||
i += 1
|
||||
i = i % screen.get_width()
|
||||
j += i % 2
|
||||
j = j % screen.get_height()
|
||||
|
||||
done = False
|
||||
screen.fill((255, 0, 255))
|
||||
pg.draw.circle(screen, (0, 0, 0), (100, 100), 20)
|
||||
pg.draw.circle(screen, (0, 0, 200), (0, 0), 10)
|
||||
pg.draw.circle(screen, (200, 0, 0), (160, 120), 30)
|
||||
pg.draw.line(screen, (250, 250, 0), (0, 120), (160, 0))
|
||||
pg.draw.circle(screen, (255, 255, 255), (i, j), 5)
|
||||
|
||||
i = 0
|
||||
j = 0
|
||||
|
||||
while not done:
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.KEYDOWN and event.key == pygame.K_q:
|
||||
done = True
|
||||
elif event.type == pygame.VIDEORESIZE:
|
||||
screen = pygame.display.get_surface()
|
||||
elif event.type == pygame.QUIT:
|
||||
done = True
|
||||
i += 1
|
||||
i = i % screen.get_width()
|
||||
j += i % 2
|
||||
j = j % screen.get_height()
|
||||
|
||||
screen.fill((255, 0, 255))
|
||||
pygame.draw.circle(screen, (0, 0, 0), (100, 100), 20)
|
||||
pygame.draw.circle(screen, (0, 0, 200), (0, 0), 10)
|
||||
pygame.draw.circle(screen, (200, 0, 0), (160, 120), 30)
|
||||
pygame.draw.line(screen, (250, 250, 0), (0, 120), (160, 0))
|
||||
pygame.draw.circle(screen, (255, 255, 255), (i, j), 5)
|
||||
|
||||
pygame.display.flip()
|
||||
clock.tick(FPS)
|
||||
pygame.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
pg.display.flip()
|
||||
clock.tick(FPS)
|
||||
pg.quit()
|
||||
@@ -1,78 +0,0 @@
|
||||
import math
|
||||
|
||||
import pygame
|
||||
|
||||
|
||||
def new_canvas():
|
||||
# Return a new blank canvas.
|
||||
return pygame.Surface((320, 240))
|
||||
|
||||
|
||||
def main():
|
||||
pygame.init()
|
||||
clock = pygame.Clock()
|
||||
|
||||
# Screen is a resizable window.
|
||||
screen = pygame.display.set_mode((320, 240), pygame.RESIZABLE)
|
||||
|
||||
# Canvas is the surface to draw to.
|
||||
canvas = new_canvas()
|
||||
|
||||
pygame.display.set_caption("Pygame - Retro scaling")
|
||||
|
||||
running = True
|
||||
|
||||
while running:
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
running = False
|
||||
|
||||
# A fresh canvas to work on.
|
||||
canvas = new_canvas()
|
||||
|
||||
# Fill the screen-surface with a background-color.
|
||||
screen.fill((128, 0, 0))
|
||||
|
||||
# Fill the canvas-surface with a background-color.
|
||||
canvas.fill((0, 128, 0))
|
||||
|
||||
# Render a circle to demonstrate the scaling.
|
||||
pygame.draw.circle(canvas, (255, 255, 255), (160, 120), 32)
|
||||
|
||||
# Calculate the scale-factor for the canvas-surface.
|
||||
scale_width = math.floor(screen.get_width() / canvas.get_width())
|
||||
scale_height = math.floor(screen.get_height() / canvas.get_height())
|
||||
|
||||
# Set scale to the smallest of width and height.
|
||||
scale = min(scale_width, scale_height)
|
||||
|
||||
# Set scale to a minimum of 1.
|
||||
scale = max(scale, 1)
|
||||
|
||||
# Scale the canvas-surface.
|
||||
canvas = pygame.transform.scale_by(canvas, scale)
|
||||
|
||||
# Calculate the center for the screen-surface.
|
||||
screen_center_x = math.floor(screen.get_width() / 2)
|
||||
screen_center_y = math.floor(screen.get_height() / 2)
|
||||
|
||||
# Calculate the center for the canvas-surface.
|
||||
canvas_center_x = math.floor(canvas.get_width() / 2)
|
||||
canvas_center_y = math.floor(canvas.get_height() / 2)
|
||||
|
||||
# Calculate the new canvas-position.
|
||||
canvas_x = screen_center_x - canvas_center_x
|
||||
canvas_y = screen_center_y - canvas_center_y
|
||||
|
||||
# Render the canvas-surface in the center of screen-surface.
|
||||
screen.blit(canvas, (canvas_x, canvas_y))
|
||||
|
||||
pygame.display.flip()
|
||||
|
||||
clock.tick(30)
|
||||
|
||||
pygame.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,14 +1,12 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.scaletest
|
||||
""" pygame.examples.scaletest
|
||||
|
||||
Shows an interactive image scaler.
|
||||
|
||||
"""
|
||||
|
||||
import sys
|
||||
import time
|
||||
|
||||
import pygame
|
||||
import pygame as pg
|
||||
|
||||
|
||||
def main(imagefile, convert_alpha=False, run_speed_test=False):
|
||||
@@ -21,69 +19,78 @@ def main(imagefile, convert_alpha=False, run_speed_test=False):
|
||||
"""
|
||||
|
||||
# initialize display
|
||||
pygame.display.init()
|
||||
pg.display.init()
|
||||
# load background image
|
||||
background = pygame.image.load(imagefile)
|
||||
background = pg.image.load(imagefile)
|
||||
|
||||
if run_speed_test:
|
||||
if convert_alpha:
|
||||
# convert_alpha() requires the display mode to be set
|
||||
pygame.display.set_mode((1, 1))
|
||||
pg.display.set_mode((1, 1))
|
||||
background = background.convert_alpha()
|
||||
|
||||
speed_test(background)
|
||||
SpeedTest(background)
|
||||
return
|
||||
|
||||
# start FULLSCREEN mode
|
||||
# On Windows, the fullscreen mode doesn't work properly, to fix the problem,
|
||||
# add with it pygame.SCALED flag
|
||||
screen = pygame.display.set_mode((1024, 768), pygame.FULLSCREEN | pygame.SCALED)
|
||||
# start fullscreen mode
|
||||
screen = pg.display.set_mode((1024, 768), pg.FULLSCREEN)
|
||||
if convert_alpha:
|
||||
background = background.convert_alpha()
|
||||
|
||||
# turn off the mouse pointer
|
||||
pygame.mouse.set_visible(False)
|
||||
|
||||
running = True
|
||||
cursize = [background.get_width(), background.get_height()]
|
||||
|
||||
clock = pygame.Clock()
|
||||
|
||||
pg.mouse.set_visible(0)
|
||||
# main loop
|
||||
while running:
|
||||
clock.tick(60)
|
||||
|
||||
image = pygame.transform.smoothscale(background, cursize)
|
||||
bRunning = True
|
||||
bUp = False
|
||||
bDown = False
|
||||
bLeft = False
|
||||
bRight = False
|
||||
cursize = [background.get_width(), background.get_height()]
|
||||
while bRunning:
|
||||
image = pg.transform.smoothscale(background, cursize)
|
||||
imgpos = image.get_rect(centerx=512, centery=384)
|
||||
screen.fill((255, 255, 255))
|
||||
screen.blit(image, imgpos)
|
||||
|
||||
pygame.display.flip()
|
||||
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT or (
|
||||
event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE
|
||||
pg.display.flip()
|
||||
for event in pg.event.get():
|
||||
if event.type == pg.QUIT or (
|
||||
event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE
|
||||
):
|
||||
running = False
|
||||
|
||||
pressed_keys = pygame.key.get_pressed()
|
||||
|
||||
if pressed_keys[pygame.K_UP]:
|
||||
bRunning = False
|
||||
if event.type == pg.KEYDOWN:
|
||||
if event.key == pg.K_UP:
|
||||
bUp = True
|
||||
if event.key == pg.K_DOWN:
|
||||
bDown = True
|
||||
if event.key == pg.K_LEFT:
|
||||
bLeft = True
|
||||
if event.key == pg.K_RIGHT:
|
||||
bRight = True
|
||||
if event.type == pg.KEYUP:
|
||||
if event.key == pg.K_UP:
|
||||
bUp = False
|
||||
if event.key == pg.K_DOWN:
|
||||
bDown = False
|
||||
if event.key == pg.K_LEFT:
|
||||
bLeft = False
|
||||
if event.key == pg.K_RIGHT:
|
||||
bRight = False
|
||||
if bUp:
|
||||
cursize[1] -= 2
|
||||
if cursize[1] < 1:
|
||||
cursize[1] = 1
|
||||
if pressed_keys[pygame.K_DOWN]:
|
||||
if bDown:
|
||||
cursize[1] += 2
|
||||
if pressed_keys[pygame.K_LEFT]:
|
||||
if bLeft:
|
||||
cursize[0] -= 2
|
||||
if cursize[0] < 1:
|
||||
cursize[0] = 1
|
||||
if pressed_keys[pygame.K_RIGHT]:
|
||||
if bRight:
|
||||
cursize[0] += 2
|
||||
pygame.quit()
|
||||
pg.quit()
|
||||
|
||||
|
||||
def speed_test(image):
|
||||
def SpeedTest(image):
|
||||
print(f"\nImage Scaling Speed Test - Image Size {str(image.get_size())}\n")
|
||||
|
||||
imgsize = [image.get_width(), image.get_height()]
|
||||
@@ -92,7 +99,7 @@ def speed_test(image):
|
||||
shrinkx = (imgsize[0] * i) // 128
|
||||
shrinky = (imgsize[1] * i) // 128
|
||||
start = time.time()
|
||||
tempimg = pygame.transform.smoothscale(image, (shrinkx, shrinky))
|
||||
tempimg = pg.transform.smoothscale(image, (shrinkx, shrinky))
|
||||
duration += time.time() - start
|
||||
del tempimg
|
||||
|
||||
@@ -103,7 +110,7 @@ def speed_test(image):
|
||||
expandx = (imgsize[0] * (i + 129)) // 128
|
||||
expandy = (imgsize[1] * (i + 129)) // 128
|
||||
start = time.time()
|
||||
tempimg = pygame.transform.smoothscale(image, (expandx, expandy))
|
||||
tempimg = pg.transform.smoothscale(image, (expandx, expandy))
|
||||
duration += time.time() - start
|
||||
del tempimg
|
||||
|
||||
@@ -114,7 +121,7 @@ def speed_test(image):
|
||||
shrinkx = (imgsize[0] * i) // 128
|
||||
shrinky = (imgsize[1] * i) // 128
|
||||
start = time.time()
|
||||
tempimg = pygame.transform.scale(image, (shrinkx, shrinky))
|
||||
tempimg = pg.transform.scale(image, (shrinkx, shrinky))
|
||||
duration += time.time() - start
|
||||
del tempimg
|
||||
|
||||
@@ -125,7 +132,7 @@ def speed_test(image):
|
||||
expandx = (imgsize[0] * (i + 129)) // 128
|
||||
expandy = (imgsize[1] * (i + 129)) // 128
|
||||
start = time.time()
|
||||
tempimg = pygame.transform.scale(image, (expandx, expandy))
|
||||
tempimg = pg.transform.scale(image, (expandx, expandy))
|
||||
duration += time.time() - start
|
||||
del tempimg
|
||||
|
||||
@@ -138,7 +145,7 @@ if __name__ == "__main__":
|
||||
print(f"\nUsage: {sys.argv[0]} imagefile [-t] [-convert_alpha]")
|
||||
print(" imagefile image filename (required)")
|
||||
print(" -t run speed test")
|
||||
print(" -convert_alpha use convert_alpha() on the image's surface\n")
|
||||
print(" -convert_alpha use convert_alpha() on the image's " "surface\n")
|
||||
else:
|
||||
main(
|
||||
sys.argv[1],
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.scrap_clipboard
|
||||
""" pygame.examples.scrap_clipboard
|
||||
|
||||
Demonstrates the clipboard capabilities of pygame.
|
||||
|
||||
@@ -8,66 +8,87 @@ Copy/paste!
|
||||
|
||||
Keyboard Controls
|
||||
-----------------
|
||||
v - View the current clipboard data.
|
||||
c - Copy some text into the clipboard.
|
||||
|
||||
g - get and print types in clipboard. If, image blit to screen.
|
||||
p - place some text into clipboard
|
||||
a - print types available in the clipboard
|
||||
i - put image into the clipboard
|
||||
"""
|
||||
import os
|
||||
|
||||
import pygame
|
||||
import pygame as pg
|
||||
import pygame.scrap as scrap
|
||||
|
||||
from io import BytesIO
|
||||
|
||||
|
||||
def main():
|
||||
pygame.init()
|
||||
pygame.display.set_caption("Clipboard Example")
|
||||
width, height = (960, 540)
|
||||
screen = pygame.display.set_mode((width, height))
|
||||
clock = pygame.Clock()
|
||||
font = pygame.Font(None, 30)
|
||||
|
||||
clipboard_text = ""
|
||||
running = True
|
||||
|
||||
while running:
|
||||
screen.fill("black")
|
||||
|
||||
instruction = "Keyboard Controls:\nV - View the current clipboard data.\nC - Copy some text into the clipboard.\nEscape - Quit"
|
||||
text = font.render(instruction, True, "white")
|
||||
screen.blit(text, (0, 0))
|
||||
|
||||
text = font.render(
|
||||
f"Text on the clipboard:\n{clipboard_text}", True, "white", None, width - 20
|
||||
)
|
||||
screen.blit(text, (0, 100))
|
||||
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
running = False
|
||||
|
||||
elif event.type == pygame.KEYDOWN:
|
||||
if event.key == pygame.K_v:
|
||||
# Look for any text data in the clipboard.
|
||||
print("Looking for text in the clipboard.")
|
||||
if pygame.scrap.has_text():
|
||||
print("Text found in the clipboard.")
|
||||
clipboard_text = pygame.scrap.get_text()
|
||||
else:
|
||||
print("No text in the clipboard.")
|
||||
|
||||
elif event.key == pygame.K_c:
|
||||
# put some text into the clipboard.
|
||||
print("Putting text into the clipboard.")
|
||||
|
||||
pygame.scrap.put_text(
|
||||
"Hello World! This is some text from the pygame scrap example.",
|
||||
)
|
||||
|
||||
elif event.key == pygame.K_ESCAPE:
|
||||
running = False
|
||||
|
||||
pygame.display.flip()
|
||||
clock.tick(60)
|
||||
pygame.quit()
|
||||
def usage():
|
||||
print("Press the 'g' key to get all of the current clipboard data")
|
||||
print("Press the 'p' key to put a string into the clipboard")
|
||||
print("Press the 'a' key to get a list of the currently available types")
|
||||
print("Press the 'i' key to put an image into the clipboard")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
main_dir = os.path.split(os.path.abspath(__file__))[0]
|
||||
|
||||
pg.init()
|
||||
screen = pg.display.set_mode((200, 200))
|
||||
c = pg.time.Clock()
|
||||
going = True
|
||||
|
||||
# Initialize the scrap module and use the clipboard mode.
|
||||
scrap.init()
|
||||
scrap.set_mode(pg.SCRAP_CLIPBOARD)
|
||||
|
||||
usage()
|
||||
|
||||
while going:
|
||||
for e in pg.event.get():
|
||||
if e.type == pg.QUIT or (e.type == pg.KEYDOWN and e.key == pg.K_ESCAPE):
|
||||
going = False
|
||||
|
||||
elif e.type == pg.KEYDOWN and e.key == pg.K_g:
|
||||
# This means to look for data.
|
||||
print("Getting the different clipboard data..")
|
||||
for t in scrap.get_types():
|
||||
r = scrap.get(t)
|
||||
if r and len(r) > 500:
|
||||
print(f"Type {t} : (large {len(r)} byte buffer)")
|
||||
elif r is None:
|
||||
print(f"Type {t} : None")
|
||||
else:
|
||||
print(f"Type {t} : '{r.decode('ascii', 'ignore')}'")
|
||||
if "image" in t:
|
||||
namehint = t.split("/")[1]
|
||||
if namehint in ["bmp", "png", "jpg"]:
|
||||
f = BytesIO(r)
|
||||
loaded_surf = pg.image.load(f, "." + namehint)
|
||||
screen.blit(loaded_surf, (0, 0))
|
||||
|
||||
elif e.type == pg.KEYDOWN and e.key == pg.K_p:
|
||||
# Place some text into the selection.
|
||||
print("Placing clipboard text.")
|
||||
scrap.put(pg.SCRAP_TEXT, b"Hello. This is a message from scrap.")
|
||||
|
||||
elif e.type == pg.KEYDOWN and e.key == pg.K_a:
|
||||
# Get all available types.
|
||||
print("Getting the available types from the clipboard.")
|
||||
types = scrap.get_types()
|
||||
print(types)
|
||||
if len(types) > 0:
|
||||
print(f"Contains {types[0]}: {scrap.contains(types[0])}")
|
||||
print("Contains _INVALID_: ", scrap.contains("_INVALID_"))
|
||||
|
||||
elif e.type == pg.KEYDOWN and e.key == pg.K_i:
|
||||
print("Putting image into the clipboard.")
|
||||
scrap.set_mode(pg.SCRAP_CLIPBOARD)
|
||||
fp = open(os.path.join(main_dir, "data", "liquid.bmp"), "rb")
|
||||
buf = fp.read()
|
||||
scrap.put("image/bmp", buf)
|
||||
fp.close()
|
||||
|
||||
elif e.type in (pg.KEYDOWN, pg.MOUSEBUTTONDOWN):
|
||||
usage()
|
||||
pg.display.flip()
|
||||
c.tick(40)
|
||||
pg.quit()
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.scroll
|
||||
""" pygame.examples.scroll
|
||||
|
||||
An zoomed image viewer that demonstrates Surface.scroll
|
||||
|
||||
@@ -14,16 +14,15 @@ When running click on a black triangle to move one pixel in the direction
|
||||
the triangle points. Or use the arrow keys. Close the window or press ESC
|
||||
to quit.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import os
|
||||
|
||||
import pygame
|
||||
import pygame as pg
|
||||
from pygame.transform import scale
|
||||
|
||||
main_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
# game constants
|
||||
|
||||
DIR_UP = 1
|
||||
DIR_DOWN = 2
|
||||
DIR_LEFT = 3
|
||||
@@ -32,7 +31,7 @@ DIR_RIGHT = 4
|
||||
zoom_factor = 8
|
||||
|
||||
|
||||
def draw_arrow(surf, color, posn, direction):
|
||||
def draw_arrow(surf, color, posn, direction: int):
|
||||
x, y = posn
|
||||
if direction == DIR_UP:
|
||||
pointlist = ((x - 29, y + 30), (x + 30, y + 30), (x + 1, y - 29), (x, y - 29))
|
||||
@@ -42,7 +41,7 @@ def draw_arrow(surf, color, posn, direction):
|
||||
pointlist = ((x + 30, y - 29), (x + 30, y + 30), (x - 29, y + 1), (x - 29, y))
|
||||
else:
|
||||
pointlist = ((x - 29, y - 29), (x - 29, y + 30), (x + 30, y + 1), (x + 30, y))
|
||||
pygame.draw.polygon(surf, color, pointlist)
|
||||
pg.draw.polygon(surf, color, pointlist)
|
||||
|
||||
|
||||
def add_arrow_button(screen, regions, posn, direction):
|
||||
@@ -50,8 +49,9 @@ def add_arrow_button(screen, regions, posn, direction):
|
||||
draw_arrow(regions, (direction, 0, 0), posn, direction)
|
||||
|
||||
|
||||
def scroll_view(screen, image, direction, view_rect):
|
||||
def scroll_view(screen, image: pg.Surface, direction: int, view_rect):
|
||||
src_rect = None
|
||||
dst_rect = None
|
||||
zoom_view_rect = screen.get_clip()
|
||||
image_w, image_h = image.get_size()
|
||||
if direction == DIR_UP:
|
||||
@@ -90,33 +90,34 @@ def scroll_view(screen, image, direction, view_rect):
|
||||
dst_rect = zoom_view_rect.copy()
|
||||
dst_rect.w = zoom_factor
|
||||
dst_rect.right = zoom_view_rect.right
|
||||
if src_rect is not None:
|
||||
|
||||
if src_rect is not None and dst_rect is not None:
|
||||
scale(image.subsurface(src_rect), dst_rect.size, screen.subsurface(dst_rect))
|
||||
pygame.display.update(zoom_view_rect)
|
||||
pg.display.update(zoom_view_rect)
|
||||
|
||||
|
||||
def main(image_file=None):
|
||||
if image_file is None:
|
||||
image_file = os.path.join(main_dir, "data", "arraydemo.webp")
|
||||
image_file = os.path.join(main_dir, "data", "arraydemo.bmp")
|
||||
margin = 80
|
||||
view_size = (30, 20)
|
||||
zoom_view_size = (view_size[0] * zoom_factor, view_size[1] * zoom_factor)
|
||||
win_size = (zoom_view_size[0] + 2 * margin, zoom_view_size[1] + 2 * margin)
|
||||
background_color = pygame.Color("beige")
|
||||
background_color = pg.Color("beige")
|
||||
|
||||
pygame.init()
|
||||
pygame.display.set_caption("Scroll Example")
|
||||
pg.init()
|
||||
pg.display.set_caption("Scroll Example")
|
||||
|
||||
# set up key repeating so we can hold down the key to scroll.
|
||||
old_k_delay, old_k_interval = pygame.key.get_repeat()
|
||||
pygame.key.set_repeat(500, 30)
|
||||
old_k_delay, old_k_interval = pg.key.get_repeat()
|
||||
pg.key.set_repeat(500, 30)
|
||||
|
||||
try:
|
||||
screen = pygame.display.set_mode(win_size)
|
||||
screen = pg.display.set_mode(win_size)
|
||||
screen.fill(background_color)
|
||||
pygame.display.flip()
|
||||
pg.display.flip()
|
||||
|
||||
image = pygame.image.load(image_file).convert()
|
||||
image = pg.image.load(image_file).convert()
|
||||
image_w, image_h = image.get_size()
|
||||
|
||||
if image_w < view_size[0] or image_h < view_size[1]:
|
||||
@@ -124,7 +125,7 @@ def main(image_file=None):
|
||||
print("A %i by %i or larger image is required." % zoom_view_size)
|
||||
return
|
||||
|
||||
regions = pygame.Surface(win_size, 0, 24)
|
||||
regions = pg.Surface(win_size, 0, 24)
|
||||
add_arrow_button(screen, regions, (40, win_size[1] // 2), DIR_LEFT)
|
||||
add_arrow_button(
|
||||
screen, regions, (win_size[0] - 40, win_size[1] // 2), DIR_RIGHT
|
||||
@@ -133,52 +134,53 @@ def main(image_file=None):
|
||||
add_arrow_button(
|
||||
screen, regions, (win_size[0] // 2, win_size[1] - 40), DIR_DOWN
|
||||
)
|
||||
pygame.display.flip()
|
||||
pg.display.flip()
|
||||
|
||||
screen.set_clip((margin, margin, zoom_view_size[0], zoom_view_size[1]))
|
||||
|
||||
view_rect = pygame.Rect(0, 0, view_size[0], view_size[1])
|
||||
view_rect = pg.Rect(0, 0, view_size[0], view_size[1])
|
||||
|
||||
scale(
|
||||
image.subsurface(view_rect),
|
||||
zoom_view_size,
|
||||
screen.subsurface(screen.get_clip()),
|
||||
)
|
||||
pygame.display.flip()
|
||||
pg.display.flip()
|
||||
|
||||
# the direction we will scroll in.
|
||||
direction = None
|
||||
|
||||
clock = pygame.Clock()
|
||||
clock = pg.time.Clock()
|
||||
clock.tick()
|
||||
|
||||
going = True
|
||||
|
||||
while going:
|
||||
# wait for events before doing anything.
|
||||
# events = [pygame.event.wait()] + pygame.event.get()
|
||||
events = pygame.event.get()
|
||||
# events = [pg.event.wait()] + pg.event.get()
|
||||
events = pg.event.get()
|
||||
|
||||
# During the loop, if a key is held, scroll the view.
|
||||
keys = pygame.key.get_pressed()
|
||||
if keys[pygame.K_UP]:
|
||||
keys = pg.key.get_pressed()
|
||||
if keys[pg.K_UP]:
|
||||
scroll_view(screen, image, DIR_UP, view_rect)
|
||||
if keys[pygame.K_DOWN]:
|
||||
if keys[pg.K_DOWN]:
|
||||
scroll_view(screen, image, DIR_DOWN, view_rect)
|
||||
if keys[pygame.K_LEFT]:
|
||||
if keys[pg.K_LEFT]:
|
||||
scroll_view(screen, image, DIR_LEFT, view_rect)
|
||||
if keys[pygame.K_RIGHT]:
|
||||
if keys[pg.K_RIGHT]:
|
||||
scroll_view(screen, image, DIR_RIGHT, view_rect)
|
||||
|
||||
for e in events:
|
||||
# quit if the event is quit.
|
||||
if e.type == pygame.QUIT:
|
||||
if e.type == pg.QUIT:
|
||||
going = False
|
||||
|
||||
# handle mouse button presses on arrows.
|
||||
elif e.type == pygame.MOUSEBUTTONDOWN:
|
||||
elif e.type == pg.MOUSEBUTTONDOWN:
|
||||
direction = regions.get_at(e.pos)[0]
|
||||
elif e.type == pygame.MOUSEBUTTONUP:
|
||||
|
||||
elif e.type == pg.MOUSEBUTTONUP:
|
||||
direction = None
|
||||
|
||||
if direction:
|
||||
@@ -186,13 +188,10 @@ def main(image_file=None):
|
||||
clock.tick(30)
|
||||
|
||||
finally:
|
||||
pygame.key.set_repeat(old_k_delay, old_k_interval)
|
||||
pygame.quit()
|
||||
pg.key.set_repeat(old_k_delay, old_k_interval)
|
||||
pg.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) > 1:
|
||||
image_file = sys.argv[1]
|
||||
else:
|
||||
image_file = None
|
||||
image_file = sys.argv[1] if len(sys.argv) > 1 else None
|
||||
main(image_file)
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.setmodescale
|
||||
""" pygame.examples.setmodescale
|
||||
|
||||
On high resolution displays(4k, 1080p) and tiny graphics games (640x480)
|
||||
show up very small so that they are unplayable. SCALED scales up the window
|
||||
@@ -10,82 +10,58 @@ Passing SCALED to pygame.display.set_mode means the resolution depends
|
||||
on desktop size and the graphics are scaled.
|
||||
"""
|
||||
|
||||
import sys
|
||||
import pygame as pg
|
||||
|
||||
import pygame
|
||||
pg.init()
|
||||
|
||||
RES = (160, 120)
|
||||
FPS = 30
|
||||
clock = pg.time.Clock()
|
||||
|
||||
print("desktops", pg.display.get_desktop_sizes())
|
||||
screen = pg.display.set_mode(RES, pg.SCALED | pg.RESIZABLE)
|
||||
|
||||
def main():
|
||||
pygame.init()
|
||||
# MAIN LOOP
|
||||
|
||||
clock = pygame.Clock()
|
||||
done = False
|
||||
|
||||
print("desktops", pygame.display.get_desktop_sizes())
|
||||
i = 0
|
||||
j = 0
|
||||
|
||||
do_vsync = bool("--vsync" in sys.argv)
|
||||
r_name, r_flags = pg.display._get_renderer_info()
|
||||
print("renderer:", r_name, "flags:", bin(r_flags))
|
||||
for flag, name in [
|
||||
(1, "software"),
|
||||
(2, "accelerated"),
|
||||
(4, "VSync"),
|
||||
(8, "render to texture"),
|
||||
]:
|
||||
if flag & r_flags:
|
||||
print(name)
|
||||
|
||||
if do_vsync:
|
||||
screen = pygame.display.set_mode(RES, pygame.SCALED | pygame.RESIZABLE, vsync=1)
|
||||
else:
|
||||
screen = pygame.display.set_mode(RES, pygame.SCALED | pygame.RESIZABLE)
|
||||
while not done:
|
||||
for event in pg.event.get():
|
||||
if event.type == pg.KEYDOWN and event.key == pg.K_q:
|
||||
done = True
|
||||
if event.type == pg.QUIT:
|
||||
done = True
|
||||
if event.type == pg.KEYDOWN and event.key == pg.K_f:
|
||||
pg.display.toggle_fullscreen()
|
||||
if event.type == pg.VIDEORESIZE:
|
||||
pg.display._resize_event(event)
|
||||
|
||||
# MAIN LOOP
|
||||
i += 1
|
||||
i = i % screen.get_width()
|
||||
j += i % 2
|
||||
j = j % screen.get_height()
|
||||
|
||||
done = False
|
||||
screen.fill((255, 0, 255))
|
||||
pg.draw.circle(screen, (0, 0, 0), (100, 100), 20)
|
||||
pg.draw.circle(screen, (0, 0, 200), (0, 0), 10)
|
||||
pg.draw.circle(screen, (200, 0, 0), (160, 120), 30)
|
||||
pg.draw.line(screen, (250, 250, 0), (0, 120), (160, 0))
|
||||
pg.draw.circle(screen, (255, 255, 255), (i, j), 5)
|
||||
|
||||
i = 0
|
||||
j = 0
|
||||
|
||||
r_name, r_flags = pygame.display._get_renderer_info()
|
||||
print("renderer:", r_name, "flags:", bin(r_flags))
|
||||
for flag, name in [
|
||||
(1, "software"),
|
||||
(2, "accelerated"),
|
||||
(4, "VSync"),
|
||||
(8, "render to texture"),
|
||||
]:
|
||||
if flag & r_flags:
|
||||
print(name)
|
||||
|
||||
while not done:
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.KEYDOWN and event.key == pygame.K_q:
|
||||
done = True
|
||||
if event.type == pygame.QUIT:
|
||||
done = True
|
||||
if event.type == pygame.KEYDOWN and event.key == pygame.K_f:
|
||||
pygame.display.toggle_fullscreen()
|
||||
i += 1
|
||||
i = i % screen.get_width()
|
||||
j += i % 2
|
||||
j = j % screen.get_height()
|
||||
|
||||
screen.fill((255, 0, 255))
|
||||
pygame.draw.circle(screen, (0, 0, 0), (100, 100), 20)
|
||||
pygame.draw.circle(screen, (0, 0, 200), (0, 0), 10)
|
||||
pygame.draw.circle(screen, (200, 0, 0), (160, 120), 30)
|
||||
if do_vsync:
|
||||
# vertical line that moves horizontally to make screen tearing obvious
|
||||
pygame.draw.line(screen, (250, 250, 0), (i, 0), (i, 120))
|
||||
else:
|
||||
pygame.draw.line(screen, (250, 250, 0), (0, 120), (160, 0))
|
||||
pygame.draw.circle(screen, (255, 255, 255), (i, j), 5)
|
||||
|
||||
pygame.display.set_caption("FPS:" + str(clock.get_fps()))
|
||||
if do_vsync:
|
||||
pygame.display.flip()
|
||||
# FPS should be limited by vsync, so we tick really fast
|
||||
# we only need to have the clock tick to track FPS
|
||||
clock.tick()
|
||||
else:
|
||||
clock.tick(FPS)
|
||||
pygame.display.flip()
|
||||
|
||||
pygame.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
pg.display.flip()
|
||||
clock.tick(FPS)
|
||||
pg.quit()
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.sound
|
||||
""" pygame.examples.sound
|
||||
|
||||
Playing a soundfile and waiting for it to finish. You'll need the
|
||||
pygame.mixer module for this to work. Note how in this simple example
|
||||
@@ -8,11 +8,9 @@ Just pick the mixer for sound and time for the delay function.
|
||||
|
||||
Optional command line argument: audio file name
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
import pygame
|
||||
import pygame as pg
|
||||
|
||||
main_dir = os.path.split(os.path.abspath(__file__))[0]
|
||||
|
||||
@@ -23,10 +21,10 @@ def main(file_path=None):
|
||||
:param str file_path: audio file (default data/secosmic_low.wav)
|
||||
"""
|
||||
# choose a desired audio format
|
||||
pygame.mixer.init(11025) # raises exception on fail
|
||||
pg.mixer.init(11025) # raises exception on fail
|
||||
|
||||
# load the sound
|
||||
sound = pygame.mixer.Sound(file_path)
|
||||
sound = pg.mixer.Sound(file_path)
|
||||
|
||||
# start playing
|
||||
print("Playing Sound...")
|
||||
@@ -35,9 +33,9 @@ def main(file_path=None):
|
||||
# poll until finished
|
||||
while channel.get_busy(): # still playing
|
||||
print(" ...still going...")
|
||||
pygame.time.wait(1000)
|
||||
pg.time.wait(1000)
|
||||
print("...Finished")
|
||||
pygame.quit()
|
||||
pg.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.sound_array_demos
|
||||
""" pygame.examples.sound_array_demos
|
||||
|
||||
Creates an echo effect on any Sound object.
|
||||
|
||||
@@ -13,17 +13,16 @@ version 2. changes:
|
||||
- put into a function.
|
||||
- Uses numpy by default, but falls back on Numeric.
|
||||
"""
|
||||
|
||||
import os
|
||||
import pygame as pg
|
||||
from numpy import zeros, int32, int16
|
||||
import time
|
||||
|
||||
import pygame
|
||||
from numpy import int16, int32, zeros
|
||||
|
||||
# pygame.mixer.init(44100, -16, 0)
|
||||
pygame.mixer.init()
|
||||
# pygame.mixer.init(11025, -16, 0)
|
||||
# pygame.mixer.init(11025)
|
||||
# pg.mixer.init(44100, -16, 0)
|
||||
pg.mixer.init()
|
||||
# pg.mixer.init(11025, -16, 0)
|
||||
# pg.mixer.init(11025)
|
||||
|
||||
|
||||
def make_echo(sound, samples_per_second, mydebug=True):
|
||||
@@ -31,7 +30,7 @@ def make_echo(sound, samples_per_second, mydebug=True):
|
||||
|
||||
echo_length = 3.5
|
||||
|
||||
a1 = pygame.sndarray.array(sound)
|
||||
a1 = pg.sndarray.array(sound)
|
||||
if mydebug:
|
||||
print(f"SHAPE1: {a1.shape}")
|
||||
|
||||
@@ -74,7 +73,7 @@ def make_echo(sound, samples_per_second, mydebug=True):
|
||||
if mydebug:
|
||||
print(f"SHAPE2: {myarr.shape}")
|
||||
|
||||
sound2 = pygame.sndarray.make_sound(myarr.astype(int16))
|
||||
sound2 = pg.sndarray.make_sound(myarr.astype(int16))
|
||||
|
||||
return sound2
|
||||
|
||||
@@ -87,10 +86,10 @@ def slow_down_sound(sound, rate):
|
||||
raise NotImplementedError()
|
||||
# grow_rate = 1 / rate
|
||||
# make it 1/rate times longer.
|
||||
# a1 = pygame.sndarray.array(sound)
|
||||
# surf = pygame.surfarray.make_surface(a1)
|
||||
# a1 = pg.sndarray.array(sound)
|
||||
# surf = pg.surfarray.make_surface(a1)
|
||||
# print(a1.shape[0] * grow_rate)
|
||||
# scaled_surf = pygame.transform.scale(surf, (int(a1.shape[0] * grow_rate), a1.shape[1]))
|
||||
# scaled_surf = pg.transform.scale(surf, (int(a1.shape[0] * grow_rate), a1.shape[1]))
|
||||
# print(scaled_surf)
|
||||
# print(surf)
|
||||
|
||||
@@ -98,7 +97,7 @@ def slow_down_sound(sound, rate):
|
||||
# print(a1.shape)
|
||||
# print(a2.shape)
|
||||
# print(a2)
|
||||
# sound2 = pygame.sndarray.make_sound(a2.astype(int16))
|
||||
# sound2 = pg.sndarray.make_sound(a2.astype(int16))
|
||||
# return sound2
|
||||
|
||||
|
||||
@@ -110,14 +109,14 @@ def sound_from_pos(sound, start_pos, samples_per_second=None, inplace=1):
|
||||
|
||||
# see if we want to reuse the sound data or not.
|
||||
if inplace:
|
||||
a1 = pygame.sndarray.samples(sound)
|
||||
a1 = pg.sndarray.samples(sound)
|
||||
else:
|
||||
a1 = pygame.sndarray.array(sound)
|
||||
a1 = pg.sndarray.array(sound)
|
||||
|
||||
# see if samples per second has been given. If not, query the pygame.mixer.
|
||||
# see if samples per second has been given. If not, query the pg.mixer.
|
||||
# eg. it might be set to 22050
|
||||
if samples_per_second is None:
|
||||
samples_per_second = pygame.mixer.get_init()[0]
|
||||
samples_per_second = pg.mixer.get_init()[0]
|
||||
|
||||
# figure out the start position in terms of samples.
|
||||
start_pos_in_samples = int(start_pos * samples_per_second)
|
||||
@@ -126,7 +125,7 @@ def sound_from_pos(sound, start_pos, samples_per_second=None, inplace=1):
|
||||
a2 = a1[start_pos_in_samples:]
|
||||
|
||||
# make the Sound instance from the array.
|
||||
sound2 = pygame.sndarray.make_sound(a2)
|
||||
sound2 = pg.sndarray.make_sound(a2)
|
||||
|
||||
return sound2
|
||||
|
||||
@@ -135,13 +134,13 @@ def main():
|
||||
"""play various sndarray effects"""
|
||||
|
||||
main_dir = os.path.split(os.path.abspath(__file__))[0]
|
||||
print(f"mixer.get_init {pygame.mixer.get_init()}")
|
||||
print(f"mixer.get_init {pg.mixer.get_init()}")
|
||||
|
||||
samples_per_second = pygame.mixer.get_init()[0]
|
||||
samples_per_second = pg.mixer.get_init()[0]
|
||||
|
||||
print(("-" * 30) + "\n")
|
||||
print("loading sound")
|
||||
sound = pygame.mixer.Sound(os.path.join(main_dir, "data", "car_door.wav"))
|
||||
sound = pg.mixer.Sound(os.path.join(main_dir, "data", "car_door.wav"))
|
||||
|
||||
print("-" * 30)
|
||||
print("start positions")
|
||||
@@ -153,19 +152,19 @@ def main():
|
||||
print(f"sound.get_length {sound.get_length()}")
|
||||
print(f"sound2.get_length {sound2.get_length()}")
|
||||
sound2.play()
|
||||
while pygame.mixer.get_busy():
|
||||
pygame.time.wait(200)
|
||||
while pg.mixer.get_busy():
|
||||
pg.time.wait(200)
|
||||
|
||||
print("waiting 2 seconds")
|
||||
pygame.time.wait(2000)
|
||||
pg.time.wait(2000)
|
||||
print("playing original sound")
|
||||
|
||||
sound.play()
|
||||
while pygame.mixer.get_busy():
|
||||
pygame.time.wait(200)
|
||||
while pg.mixer.get_busy():
|
||||
pg.time.wait(200)
|
||||
|
||||
print("waiting 2 seconds")
|
||||
pygame.time.wait(2000)
|
||||
pg.time.wait(2000)
|
||||
|
||||
# if 0:
|
||||
# #TODO: this is broken.
|
||||
@@ -174,8 +173,8 @@ def main():
|
||||
# rate = 0.2
|
||||
# slowed_sound = slow_down_sound(sound, rate)
|
||||
# slowed_sound.play()
|
||||
# while pygame.mixer.get_busy():
|
||||
# pygame.time.wait(200)
|
||||
# while pg.mixer.get_busy():
|
||||
# pg.time.wait(200)
|
||||
|
||||
print("-" * 30)
|
||||
print("echoing")
|
||||
@@ -187,15 +186,15 @@ def main():
|
||||
|
||||
print("original sound")
|
||||
sound.play()
|
||||
while pygame.mixer.get_busy():
|
||||
pygame.time.wait(200)
|
||||
while pg.mixer.get_busy():
|
||||
pg.time.wait(200)
|
||||
|
||||
print("echoed sound")
|
||||
sound2.play()
|
||||
while pygame.mixer.get_busy():
|
||||
pygame.time.wait(200)
|
||||
while pg.mixer.get_busy():
|
||||
pg.time.wait(200)
|
||||
|
||||
sound = pygame.mixer.Sound(os.path.join(main_dir, "data", "secosmic_lo.wav"))
|
||||
sound = pg.mixer.Sound(os.path.join(main_dir, "data", "secosmic_lo.wav"))
|
||||
|
||||
t1 = time.time()
|
||||
sound3 = make_echo(sound, samples_per_second)
|
||||
@@ -203,15 +202,15 @@ def main():
|
||||
|
||||
print("original sound")
|
||||
sound.play()
|
||||
while pygame.mixer.get_busy():
|
||||
pygame.time.wait(200)
|
||||
while pg.mixer.get_busy():
|
||||
pg.time.wait(200)
|
||||
|
||||
print("echoed sound")
|
||||
sound3.play()
|
||||
while pygame.mixer.get_busy():
|
||||
pygame.time.wait(200)
|
||||
while pg.mixer.get_busy():
|
||||
pg.time.wait(200)
|
||||
|
||||
pygame.quit()
|
||||
pg.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.sprite_texture
|
||||
""" pygame.examples.sprite_texture
|
||||
|
||||
Experimental! Uses APIs which may disappear in the next release (_sdl2 is private).
|
||||
|
||||
@@ -9,97 +9,102 @@ Hardware accelerated Image objects with pygame.sprite.
|
||||
_sdl2.video.Image is a backwards compatible way with to use Texture with
|
||||
pygame.sprite groups.
|
||||
"""
|
||||
|
||||
import os
|
||||
import pygame as pg
|
||||
|
||||
if pg.get_sdl_version()[0] < 2:
|
||||
raise SystemExit("This example requires pygame 2 and SDL2.")
|
||||
from pygame._sdl2 import Window, Texture, Image, Renderer
|
||||
|
||||
import pygame
|
||||
from pygame._sdl2 import Image, Renderer, Texture, Window
|
||||
|
||||
data_dir = os.path.join(os.path.split(os.path.abspath(__file__))[0], "data")
|
||||
|
||||
|
||||
def load_img(file):
|
||||
return pygame.image.load(os.path.join(data_dir, file))
|
||||
return pg.image.load(os.path.join(data_dir, file))
|
||||
|
||||
|
||||
def main():
|
||||
pygame.display.init()
|
||||
pygame.key.set_repeat(10, 10)
|
||||
pg.display.init()
|
||||
pg.key.set_repeat(10, 10)
|
||||
|
||||
win = Window("asdf", resizable=True)
|
||||
renderer = Renderer(win)
|
||||
tex = Texture.from_surface(renderer, load_img("alien1.gif"))
|
||||
win = Window("asdf", resizable=True)
|
||||
renderer = Renderer(win)
|
||||
tex = Texture.from_surface(renderer, load_img("alien1.gif"))
|
||||
|
||||
class Something(pygame.sprite.Sprite):
|
||||
def __init__(self, img):
|
||||
pygame.sprite.Sprite.__init__(self)
|
||||
|
||||
self.rect = img.get_rect()
|
||||
self.image = img
|
||||
class Something(pg.sprite.Sprite):
|
||||
def __init__(self, img):
|
||||
pg.sprite.Sprite.__init__(self)
|
||||
|
||||
self.rect.w *= 5
|
||||
self.rect.h *= 5
|
||||
self.rect = img.get_rect()
|
||||
self.image = img
|
||||
|
||||
img.origin = self.rect.w / 2, self.rect.h / 2
|
||||
self.rect.w *= 5
|
||||
self.rect.h *= 5
|
||||
|
||||
sprite = Something(Image(tex, (0, 0, tex.width / 2, tex.height / 2)))
|
||||
sprite.rect.x = 250
|
||||
sprite.rect.y = 50
|
||||
img.origin = self.rect.w / 2, self.rect.h / 2
|
||||
|
||||
# sprite2 = Something(Image(sprite.image))
|
||||
sprite2 = Something(Image(tex))
|
||||
sprite2.rect.x = 250
|
||||
sprite2.rect.y = 250
|
||||
sprite2.rect.w /= 2
|
||||
sprite2.rect.h /= 2
|
||||
|
||||
group = pygame.sprite.Group()
|
||||
group.add(sprite2)
|
||||
group.add(sprite)
|
||||
sprite = Something(Image(tex, (0, 0, tex.width / 2, tex.height / 2)))
|
||||
sprite.rect.x = 250
|
||||
sprite.rect.y = 50
|
||||
|
||||
import math
|
||||
# sprite2 = Something(Image(sprite.image))
|
||||
sprite2 = Something(Image(tex))
|
||||
sprite2.rect.x = 250
|
||||
sprite2.rect.y = 250
|
||||
sprite2.rect.w /= 2
|
||||
sprite2.rect.h /= 2
|
||||
|
||||
t = 0
|
||||
running = True
|
||||
clock = pygame.Clock()
|
||||
renderer.draw_color = (255, 0, 0, 255)
|
||||
group = pg.sprite.Group()
|
||||
group.add(sprite2)
|
||||
group.add(sprite)
|
||||
|
||||
while running:
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
import math
|
||||
|
||||
t = 0
|
||||
running = True
|
||||
clock = pg.time.Clock()
|
||||
renderer.draw_color = (255, 0, 0, 255)
|
||||
|
||||
while running:
|
||||
for event in pg.event.get():
|
||||
if event.type == pg.QUIT:
|
||||
running = False
|
||||
elif event.type == pg.KEYDOWN:
|
||||
if event.key == pg.K_ESCAPE:
|
||||
running = False
|
||||
elif event.type == pygame.KEYDOWN:
|
||||
if event.key == pygame.K_ESCAPE:
|
||||
running = False
|
||||
elif event.key == pygame.K_LEFT:
|
||||
sprite.rect.x -= 5
|
||||
elif event.key == pygame.K_RIGHT:
|
||||
sprite.rect.x += 5
|
||||
elif event.key == pygame.K_DOWN:
|
||||
sprite.rect.y += 5
|
||||
elif event.key == pygame.K_UP:
|
||||
sprite.rect.y -= 5
|
||||
elif event.key == pg.K_LEFT:
|
||||
sprite.rect.x -= 5
|
||||
elif event.key == pg.K_RIGHT:
|
||||
sprite.rect.x += 5
|
||||
elif event.key == pg.K_DOWN:
|
||||
sprite.rect.y += 5
|
||||
elif event.key == pg.K_UP:
|
||||
sprite.rect.y -= 5
|
||||
|
||||
renderer.clear()
|
||||
t += 1
|
||||
renderer.clear()
|
||||
t += 1
|
||||
|
||||
img = sprite.image
|
||||
img.angle += 1
|
||||
img = sprite.image
|
||||
img.angle += 1
|
||||
try:
|
||||
img.flip_x = t % 50 < 25
|
||||
img.flip_y = t % 100 < 50
|
||||
img.color[0] = int(255.0 * (0.5 + math.sin(0.5 * t + 10.0) / 2.0))
|
||||
img.alpha = int(255.0 * (0.5 + math.sin(0.1 * t) / 2.0))
|
||||
# img.draw(dstrect=(x, y, 5 * img.srcrect['w'], 5 * img.srcrect['h']))
|
||||
except AttributeError:
|
||||
# backwards compatibility for <=2.1.2
|
||||
img.flipX = t % 50 < 25
|
||||
img.flipY = t % 100 < 50
|
||||
|
||||
group.draw(renderer)
|
||||
img.color[0] = int(255.0 * (0.5 + math.sin(0.5 * t + 10.0) / 2.0))
|
||||
img.alpha = int(255.0 * (0.5 + math.sin(0.1 * t) / 2.0))
|
||||
# img.draw(dstrect=(x, y, 5 * img.srcrect['w'], 5 * img.srcrect['h']))
|
||||
|
||||
renderer.present()
|
||||
group.draw(renderer)
|
||||
|
||||
clock.tick(60)
|
||||
win.title = str(f"FPS: {clock.get_fps()}")
|
||||
renderer.present()
|
||||
|
||||
pygame.quit()
|
||||
clock.tick(60)
|
||||
win.title = str(f"FPS: {clock.get_fps()}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
pg.quit()
|
||||
@@ -1,135 +1,100 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.stars
|
||||
""" pg.examples.stars
|
||||
|
||||
We are all in the gutter,
|
||||
but some of us are looking at the stars.
|
||||
-- Oscar Wilde
|
||||
We are all in the gutter,
|
||||
but some of us are looking at the stars.
|
||||
-- Oscar Wilde
|
||||
|
||||
A simple starfield example. Note you can move the center of
|
||||
the starfield by leftclicking in the window. This example shows
|
||||
the basics of creating a window, simple pixel plotting, and event management.
|
||||
A simple starfield example. Note you can move the 'center' of
|
||||
the starfield by leftclicking in the window. This example show
|
||||
the basics of creating a window, simple pixel plotting, and input
|
||||
event management.
|
||||
"""
|
||||
|
||||
import random
|
||||
import math
|
||||
import pygame as pg
|
||||
|
||||
import pygame
|
||||
# constants
|
||||
WINSIZE = [640, 480]
|
||||
WINCENTER = [320, 240]
|
||||
NUMSTARS = 150
|
||||
|
||||
|
||||
class Particle:
|
||||
def __init__(
|
||||
self,
|
||||
pos: list[int],
|
||||
vel: pygame.Vector2,
|
||||
):
|
||||
"""
|
||||
Parameters:
|
||||
pos: Position of the particle
|
||||
vel: How far does the particle move (x, y) every frame
|
||||
"""
|
||||
def init_star(steps=-1):
|
||||
"creates new star values"
|
||||
dir = random.randrange(100000)
|
||||
steps_velocity = 1 if steps == -1 else steps * 0.09
|
||||
velmult = steps_velocity * (random.random() * 0.6 + 0.4)
|
||||
vel = [math.sin(dir) * velmult, math.cos(dir) * velmult]
|
||||
|
||||
self.pos = pos
|
||||
self.vel = vel
|
||||
self.color_list = [
|
||||
(255, 210, 125),
|
||||
(255, 163, 113),
|
||||
(166, 168, 255),
|
||||
(255, 250, 134),
|
||||
(168, 123, 255),
|
||||
]
|
||||
|
||||
def draw(self, display: pygame.Surface):
|
||||
"""
|
||||
Draws the particle on a pygame.Surface
|
||||
Parameters:
|
||||
display: The surface the particle is drawn on
|
||||
"""
|
||||
|
||||
pygame.draw.line(display, random.choice(self.color_list), self.pos, self.pos)
|
||||
|
||||
def update(self):
|
||||
"""
|
||||
Moves the particle
|
||||
"""
|
||||
|
||||
self.pos += self.vel
|
||||
if steps is None:
|
||||
return [vel, [WINCENTER[0] + (vel[0] * steps), WINCENTER[1] + (vel[1] * steps)]]
|
||||
return [vel, WINCENTER[:]]
|
||||
|
||||
|
||||
def create_particle(particle_list: list[Particle], pos: pygame.Vector2):
|
||||
"""
|
||||
Creates a new particle
|
||||
Parameters:
|
||||
particle_list: List of existing particles
|
||||
pos: The coordinates the new particle will be spawned on
|
||||
"""
|
||||
|
||||
particle_list.append(
|
||||
Particle(
|
||||
pos=pos.copy(),
|
||||
vel=pygame.Vector2(random.uniform(-5, 5), random.uniform(-5, 5)),
|
||||
)
|
||||
)
|
||||
def initialize_stars():
|
||||
"creates a new starfield"
|
||||
random.seed()
|
||||
stars = [init_star(steps=random.randint(0, WINCENTER[0])) for _ in range(NUMSTARS)]
|
||||
move_stars(stars)
|
||||
return stars
|
||||
|
||||
|
||||
def update_particles(particle_list: list[Particle], screen_rect: pygame.Rect):
|
||||
"""
|
||||
Updates the particles
|
||||
Parameters:
|
||||
particle_list: List of existing particles
|
||||
screen_rect: A pygame.Rect that represents the screen
|
||||
(used to determine whether a particle is visible on the screen)
|
||||
"""
|
||||
|
||||
for particle in particle_list:
|
||||
if not screen_rect.collidepoint(particle.pos):
|
||||
particle_list.remove(particle)
|
||||
|
||||
particle.update()
|
||||
def draw_stars(surface, stars, color):
|
||||
"used to draw (and clear) the stars"
|
||||
for _, pos in stars:
|
||||
pos = (int(pos[0]), int(pos[1]))
|
||||
surface.set_at(pos, color)
|
||||
|
||||
|
||||
def draw_particles(particle_list: list[Particle], display: pygame.Surface):
|
||||
"""
|
||||
Draws the particles
|
||||
Parameters:
|
||||
particle_list: List of existing particles
|
||||
display: The surface the particle is drawn on
|
||||
"""
|
||||
for particle in particle_list:
|
||||
particle.draw(display)
|
||||
def move_stars(stars):
|
||||
"animate the star values"
|
||||
for vel, pos in stars:
|
||||
pos[0] = pos[0] + vel[0]
|
||||
pos[1] = pos[1] + vel[1]
|
||||
if not 0 <= pos[0] <= WINSIZE[0] or not 0 <= pos[1] <= WINSIZE[1]:
|
||||
vel[:], pos[:] = init_star()
|
||||
else:
|
||||
vel[0] = vel[0] * 1.05
|
||||
vel[1] = vel[1] * 1.05
|
||||
|
||||
|
||||
def main():
|
||||
"""
|
||||
Contains the game variables and loop
|
||||
"""
|
||||
screen = pygame.display.set_mode((600, 500))
|
||||
clock = pygame.Clock()
|
||||
pygame.display.set_caption("Pygame Stars")
|
||||
particles = []
|
||||
# how many particles to spawn every frame
|
||||
particle_density = 10
|
||||
"This is the starfield code"
|
||||
# create our starfield
|
||||
stars = initialize_stars()
|
||||
|
||||
screen_rect = screen.get_rect()
|
||||
spawn_point = pygame.Vector2(screen_rect.center)
|
||||
# initialize and prepare screen
|
||||
pg.init()
|
||||
screen = pg.display.set_mode(WINSIZE)
|
||||
pg.display.set_caption("pygame Stars Example")
|
||||
white = 255, 240, 200
|
||||
black = 20, 20, 40
|
||||
screen.fill(black)
|
||||
|
||||
running = True
|
||||
while running:
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
running = False
|
||||
if event.type == pygame.MOUSEBUTTONDOWN:
|
||||
spawn_point = pygame.Vector2(event.pos)
|
||||
clock = pg.time.Clock()
|
||||
|
||||
screen.fill((20, 20, 40))
|
||||
for _ in range(particle_density):
|
||||
create_particle(particles, spawn_point)
|
||||
update_particles(particles, screen_rect)
|
||||
draw_particles(particles, screen)
|
||||
|
||||
pygame.display.flip()
|
||||
clock.tick(60)
|
||||
|
||||
pygame.quit()
|
||||
# main game loop
|
||||
done = 0
|
||||
while not done:
|
||||
draw_stars(screen, stars, black)
|
||||
move_stars(stars)
|
||||
draw_stars(screen, stars, white)
|
||||
pg.display.update()
|
||||
for e in pg.event.get():
|
||||
if e.type == pg.QUIT or (e.type == pg.KEYUP and e.key == pg.K_ESCAPE):
|
||||
done = 1
|
||||
break
|
||||
if e.type == pg.MOUSEBUTTONDOWN and e.button == 1:
|
||||
WINCENTER[:] = list(e.pos)
|
||||
clock.tick(50)
|
||||
pg.quit()
|
||||
|
||||
|
||||
# So `python -m pygame.example.stars` will work.
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
# I prefer the time of insects to the time of stars.
|
||||
#
|
||||
# -- Wisława Szymborska
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.testsprite
|
||||
""" pg.examples.testsprite
|
||||
|
||||
Like the testsprite.c that comes with libsdl, this pygame version shows
|
||||
lots of sprites moving around.
|
||||
@@ -7,15 +7,16 @@ lots of sprites moving around.
|
||||
It is an abomination of ugly code, and mostly used for testing.
|
||||
|
||||
|
||||
See pygame.examples.aliens for some prettier code.
|
||||
See pg.examples.aliens for some prettyier code.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import os
|
||||
|
||||
from random import randint
|
||||
from time import time
|
||||
from typing import List
|
||||
|
||||
import pygame
|
||||
import pygame as pg
|
||||
|
||||
main_dir = os.path.split(os.path.abspath(__file__))[0]
|
||||
data_dir = os.path.join(main_dir, "data")
|
||||
@@ -42,18 +43,22 @@ if "-layered_dirty" in sys.argv:
|
||||
|
||||
flags = 0
|
||||
if "-flip" in sys.argv:
|
||||
flags ^= pygame.DOUBLEBUF
|
||||
flags ^= pg.DOUBLEBUF
|
||||
|
||||
if "-fullscreen" in sys.argv:
|
||||
flags ^= pygame.FULLSCREEN
|
||||
flags ^= pg.FULLSCREEN
|
||||
|
||||
if "-sw" in sys.argv:
|
||||
flags ^= pygame.SWSURFACE
|
||||
flags ^= pg.SWSURFACE
|
||||
|
||||
use_rle = True
|
||||
|
||||
if "-hw" in sys.argv:
|
||||
flags ^= pg.HWSURFACE
|
||||
use_rle = False
|
||||
|
||||
if "-scaled" in sys.argv:
|
||||
flags ^= pygame.SCALED
|
||||
flags ^= pg.SCALED
|
||||
|
||||
screen_dims = [640, 480]
|
||||
|
||||
@@ -65,20 +70,37 @@ if "-width" in sys.argv:
|
||||
i = sys.argv.index("-width")
|
||||
screen_dims[0] = int(sys.argv[i + 1])
|
||||
|
||||
if "-alpha" in sys.argv:
|
||||
use_alpha = True
|
||||
else:
|
||||
use_alpha = False
|
||||
use_alpha = "-alpha" in sys.argv
|
||||
|
||||
print(screen_dims)
|
||||
|
||||
|
||||
class Thingy(pygame.sprite.DirtySprite):
|
||||
images = None
|
||||
##class Thingy(pg.sprite.Sprite):
|
||||
## images = None
|
||||
## def __init__(self):
|
||||
## pg.sprite.Sprite.__init__(self)
|
||||
## self.image = Thingy.images[0]
|
||||
## self.rect = self.image.get_rect()
|
||||
## self.rect.x = randint(0, screen_dims[0])
|
||||
## self.rect.y = randint(0, screen_dims[1])
|
||||
## #self.vel = [randint(-10, 10), randint(-10, 10)]
|
||||
## self.vel = [randint(-1, 1), randint(-1, 1)]
|
||||
##
|
||||
## def move(self):
|
||||
## for i in [0, 1]:
|
||||
## nv = self.rect[i] + self.vel[i]
|
||||
## if nv >= screen_dims[i] or nv < 0:
|
||||
## self.vel[i] = -self.vel[i]
|
||||
## nv = self.rect[i] + self.vel[i]
|
||||
## self.rect[i] = nv
|
||||
|
||||
|
||||
class Thingy(pg.sprite.DirtySprite):
|
||||
images: List[pg.Surface] = []
|
||||
|
||||
def __init__(self):
|
||||
## pygame.sprite.Sprite.__init__(self)
|
||||
pygame.sprite.DirtySprite.__init__(self)
|
||||
## pg.sprite.Sprite.__init__(self)
|
||||
pg.sprite.DirtySprite.__init__(self)
|
||||
self.image = Thingy.images[0]
|
||||
self.rect = self.image.get_rect()
|
||||
self.rect.x = randint(0, screen_dims[0])
|
||||
@@ -87,7 +109,7 @@ class Thingy(pygame.sprite.DirtySprite):
|
||||
self.vel = [randint(-1, 1), randint(-1, 1)]
|
||||
self.dirty = 2
|
||||
|
||||
def update(self):
|
||||
def update(self, *args, **kwargs):
|
||||
for i in [0, 1]:
|
||||
nv = self.rect[i] + self.vel[i]
|
||||
if nv >= screen_dims[i] or nv < 0:
|
||||
@@ -96,22 +118,22 @@ class Thingy(pygame.sprite.DirtySprite):
|
||||
self.rect[i] = nv
|
||||
|
||||
|
||||
class Static(pygame.sprite.DirtySprite):
|
||||
images = None
|
||||
class Static(pg.sprite.DirtySprite):
|
||||
images: List[pg.Surface] = []
|
||||
|
||||
def __init__(self):
|
||||
pygame.sprite.DirtySprite.__init__(self)
|
||||
pg.sprite.DirtySprite.__init__(self)
|
||||
self.image = Static.images[0]
|
||||
self.rect = self.image.get_rect()
|
||||
self.rect.x = randint(0, int(3 * screen_dims[0] / 4))
|
||||
self.rect.y = randint(0, int(3 * screen_dims[1] / 4))
|
||||
self.rect.x = randint(0, 3 * screen_dims[0] // 4)
|
||||
self.rect.y = randint(0, 3 * screen_dims[1] // 4)
|
||||
|
||||
|
||||
def main(
|
||||
update_rects=True,
|
||||
use_static=False,
|
||||
use_layered_dirty=False,
|
||||
screen_dims=[640, 480],
|
||||
screen_dims=(640, 480),
|
||||
use_alpha=False,
|
||||
flags=0,
|
||||
):
|
||||
@@ -130,35 +152,31 @@ def main(
|
||||
if use_layered_dirty:
|
||||
update_rects = True
|
||||
|
||||
pygame.init() # needed to initialise time module for get_ticks()
|
||||
pygame.display.init()
|
||||
pg.init() # needed to initialise time module for get_ticks()
|
||||
pg.display.init()
|
||||
|
||||
# if "-fast" in sys.argv:
|
||||
|
||||
screen = pygame.display.set_mode(screen_dims, flags, vsync="-vsync" in sys.argv)
|
||||
screen = pg.display.set_mode(screen_dims, flags, vsync="-vsync" in sys.argv)
|
||||
|
||||
# this is mainly for GP2X, so it can quit.
|
||||
pygame.joystick.init()
|
||||
num_joysticks = pygame.joystick.get_count()
|
||||
pg.joystick.init()
|
||||
num_joysticks = pg.joystick.get_count()
|
||||
if num_joysticks > 0:
|
||||
stick = pygame.joystick.Joystick(0)
|
||||
stick = pg.joystick.Joystick(0)
|
||||
stick.init() # now we will receive events for the joystick
|
||||
|
||||
screen.fill([0, 0, 0])
|
||||
pygame.display.flip()
|
||||
sprite_surface = pygame.image.load(os.path.join(data_dir, "asprite.bmp"))
|
||||
sprite_surface2 = pygame.image.load(os.path.join(data_dir, "static.webp"))
|
||||
pg.display.flip()
|
||||
sprite_surface = pg.image.load(os.path.join(data_dir, "asprite.bmp"))
|
||||
sprite_surface2 = pg.image.load(os.path.join(data_dir, "static.png"))
|
||||
|
||||
if use_rle:
|
||||
sprite_surface.set_colorkey(
|
||||
[0xFF, 0xFF, 0xFF], pygame.SRCCOLORKEY | pygame.RLEACCEL
|
||||
)
|
||||
sprite_surface2.set_colorkey(
|
||||
[0xFF, 0xFF, 0xFF], pygame.SRCCOLORKEY | pygame.RLEACCEL
|
||||
)
|
||||
sprite_surface.set_colorkey([0xFF, 0xFF, 0xFF], pg.SRCCOLORKEY | pg.RLEACCEL)
|
||||
sprite_surface2.set_colorkey([0xFF, 0xFF, 0xFF], pg.SRCCOLORKEY | pg.RLEACCEL)
|
||||
else:
|
||||
sprite_surface.set_colorkey([0xFF, 0xFF, 0xFF], pygame.SRCCOLORKEY)
|
||||
sprite_surface2.set_colorkey([0xFF, 0xFF, 0xFF], pygame.SRCCOLORKEY)
|
||||
sprite_surface.set_colorkey([0xFF, 0xFF, 0xFF], pg.SRCCOLORKEY)
|
||||
sprite_surface2.set_colorkey([0xFF, 0xFF, 0xFF], pg.SRCCOLORKEY)
|
||||
|
||||
if use_alpha:
|
||||
sprite_surface = sprite_surface.convert_alpha()
|
||||
@@ -180,13 +198,13 @@ def main(
|
||||
numsprites = 100
|
||||
sprites = None
|
||||
if use_layered_dirty:
|
||||
## sprites = pygame.sprite.FastRenderGroup()
|
||||
sprites = pygame.sprite.LayeredDirty()
|
||||
## sprites = pg.sprite.FastRenderGroup()
|
||||
sprites = pg.sprite.LayeredDirty()
|
||||
else:
|
||||
if update_rects:
|
||||
sprites = pygame.sprite.RenderUpdates()
|
||||
sprites = pg.sprite.RenderUpdates()
|
||||
else:
|
||||
sprites = pygame.sprite.Group()
|
||||
sprites = pg.sprite.Group()
|
||||
|
||||
for i in range(0, numsprites):
|
||||
if use_static and i % 2 == 0:
|
||||
@@ -196,7 +214,7 @@ def main(
|
||||
frames = 0
|
||||
start = time()
|
||||
|
||||
background = pygame.Surface(screen.get_size())
|
||||
background = pg.Surface(screen.get_size())
|
||||
background = background.convert()
|
||||
background.fill([0, 0, 0])
|
||||
|
||||
@@ -214,23 +232,18 @@ def main(
|
||||
|
||||
rects = sprites.draw(screen)
|
||||
if update_rects:
|
||||
pygame.display.update(rects)
|
||||
pg.display.update(rects)
|
||||
else:
|
||||
pygame.display.flip()
|
||||
pg.display.flip()
|
||||
|
||||
for event in pygame.event.get():
|
||||
if event.type in [
|
||||
pygame.QUIT,
|
||||
pygame.KEYDOWN,
|
||||
pygame.QUIT,
|
||||
pygame.JOYBUTTONDOWN,
|
||||
]:
|
||||
for event in pg.event.get():
|
||||
if event.type in [pg.QUIT, pg.KEYDOWN, pg.QUIT, pg.JOYBUTTONDOWN]:
|
||||
going = False
|
||||
|
||||
frames += 1
|
||||
end = time()
|
||||
print(f"FPS: {frames / (end - start):f}")
|
||||
pygame.quit()
|
||||
pg.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.textinput
|
||||
""" pg.examples.textinput
|
||||
|
||||
A little "console" where you can write in text.
|
||||
|
||||
Shows how to use the TEXTEDITING and TEXTINPUT events.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import os
|
||||
from typing import List
|
||||
|
||||
import pygame
|
||||
import pygame as pg
|
||||
import pygame.freetype as freetype
|
||||
|
||||
# This environment variable is important
|
||||
# If not added the candidate list will not show
|
||||
@@ -23,34 +25,28 @@ class TextInput:
|
||||
|
||||
# Add font name for each language,
|
||||
# otherwise some text can't be correctly displayed.
|
||||
FONT_NAMES = [
|
||||
"notosanscjktcregular",
|
||||
"notosansmonocjktcregular",
|
||||
"notosansregular",
|
||||
"microsoftjhenghei",
|
||||
"microsoftyahei",
|
||||
"msgothic",
|
||||
"msmincho",
|
||||
"unifont",
|
||||
"Arial",
|
||||
]
|
||||
FONT_NAMES = ",".join(
|
||||
str(x)
|
||||
for x in [
|
||||
"notosanscjktcregular",
|
||||
"notosansmonocjktcregular",
|
||||
"notosansregular,",
|
||||
"microsoftjhengheimicrosoftjhengheiuilight",
|
||||
"microsoftyaheimicrosoftyaheiuilight",
|
||||
"msgothicmsuigothicmspgothic",
|
||||
"msmincho",
|
||||
"Arial",
|
||||
]
|
||||
)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
prompt: str,
|
||||
pos: tuple[int, int],
|
||||
screen_dimensions: tuple[int, int],
|
||||
print_event: bool,
|
||||
text_color="white",
|
||||
fps: int = 50,
|
||||
self, prompt: str, pos, screen_dimensions, print_event: bool, text_color="white"
|
||||
) -> None:
|
||||
self.prompt = prompt
|
||||
self.print_event = print_event
|
||||
# position of chatlist and chatbox
|
||||
self.CHAT_LIST_POS = pygame.Rect(
|
||||
(pos[0], pos[1] + 50), (screen_dimensions[0], 400)
|
||||
)
|
||||
self.CHAT_BOX_POS = pygame.Rect(pos, (screen_dimensions[1], 40))
|
||||
self.CHAT_LIST_POS = pg.Rect((pos[0], pos[1] + 50), (screen_dimensions[0], 400))
|
||||
self.CHAT_BOX_POS = pg.Rect(pos, (screen_dimensions[1], 40))
|
||||
self.CHAT_LIST_MAXSIZE = 20
|
||||
|
||||
self._ime_editing = False
|
||||
@@ -58,197 +54,123 @@ class TextInput:
|
||||
self._ime_text_pos = 0
|
||||
self._ime_editing_text = ""
|
||||
self._ime_editing_pos = 0
|
||||
self.chat = ""
|
||||
self.chat_list: List[str] = []
|
||||
|
||||
# Freetype
|
||||
# The font name can be a comma separated list
|
||||
# of font names to search for.
|
||||
self.font_names = ",".join(self.FONT_NAMES)
|
||||
self.font = pygame.font.SysFont(self.font_names, 24)
|
||||
self.font_height = self.font.get_height()
|
||||
self.font_small = pygame.font.SysFont(self.font_names, 16)
|
||||
self.font = freetype.SysFont(self.FONT_NAMES, 24)
|
||||
self.font_small = freetype.SysFont(self.FONT_NAMES, 16)
|
||||
self.text_color = text_color
|
||||
|
||||
self.prompt_surf = self.font.render(self.prompt, True, self.text_color)
|
||||
self.prompt_rect = self.prompt_surf.get_rect(topleft=self.CHAT_BOX_POS.topleft)
|
||||
|
||||
self.fps = fps
|
||||
self.second_counter = 0
|
||||
|
||||
print("Using font: " + self.font.name)
|
||||
|
||||
def update(self, events: list[pygame.Event]) -> None:
|
||||
def update(self, events) -> None:
|
||||
"""
|
||||
Updates the text input widget
|
||||
"""
|
||||
for event in events:
|
||||
self.handle_event(event)
|
||||
if event.type == pg.KEYDOWN:
|
||||
if self.print_event:
|
||||
print(event)
|
||||
|
||||
self.second_counter += 1
|
||||
if self._ime_editing:
|
||||
if len(self._ime_editing_text) == 0:
|
||||
self._ime_editing = False
|
||||
continue
|
||||
|
||||
if self.second_counter >= self.fps:
|
||||
self.second_counter = 0
|
||||
if event.key == pg.K_BACKSPACE:
|
||||
if len(self._ime_text) > 0 and self._ime_text_pos > 0:
|
||||
self._ime_text = (
|
||||
self._ime_text[0 : self._ime_text_pos - 1]
|
||||
+ self._ime_text[self._ime_text_pos :]
|
||||
)
|
||||
self._ime_text_pos = max(0, self._ime_text_pos - 1)
|
||||
|
||||
# Check if input fits in chat box
|
||||
input_size = self.font.size(self._get_ime_text())
|
||||
while input_size[0] > self.CHAT_BOX_POS.w - self.prompt_rect.w:
|
||||
if self._ime_editing_text:
|
||||
# Don't block.
|
||||
break
|
||||
self._ime_text = self._ime_text[:-1]
|
||||
input_size = self.font.size(self._get_ime_text())
|
||||
elif event.key == pg.K_DELETE:
|
||||
self._ime_text = (
|
||||
self._ime_text[0 : self._ime_text_pos]
|
||||
+ self._ime_text[self._ime_text_pos + 1 :]
|
||||
)
|
||||
elif event.key == pg.K_LEFT:
|
||||
self._ime_text_pos = max(0, self._ime_text_pos - 1)
|
||||
elif event.key == pg.K_RIGHT:
|
||||
self._ime_text_pos = min(
|
||||
len(self._ime_text), self._ime_text_pos + 1
|
||||
)
|
||||
# Handle ENTER key
|
||||
elif event.key in [pg.K_RETURN, pg.K_KP_ENTER]:
|
||||
# Block if we have no text to append
|
||||
if len(self._ime_text) == 0:
|
||||
continue
|
||||
|
||||
def _clamp_to_text_range(self, num: int):
|
||||
return min(len(self._ime_text), max(0, num))
|
||||
# Append chat list
|
||||
self.chat_list.append(self._ime_text)
|
||||
if len(self.chat_list) > self.CHAT_LIST_MAXSIZE:
|
||||
self.chat_list.pop(0)
|
||||
self._ime_text = ""
|
||||
self._ime_text_pos = 0
|
||||
|
||||
def move_cursor_by(self, by: int):
|
||||
self._ime_text_pos = self._clamp_to_text_range(self._ime_text_pos + by)
|
||||
elif event.type == pg.TEXTEDITING:
|
||||
if self.print_event:
|
||||
print(event)
|
||||
self._ime_editing = True
|
||||
self._ime_editing_text = event.text
|
||||
self._ime_editing_pos = event.start
|
||||
|
||||
def replace_chars(
|
||||
self,
|
||||
remove_count: int = 0,
|
||||
to_insert: str = "",
|
||||
text_after_cursor: bool = False,
|
||||
):
|
||||
"""
|
||||
Removes given number of characters from the cursor location
|
||||
and adds an optional string there, then adjusts the cursor location.
|
||||
"""
|
||||
loc = self._clamp_to_text_range(remove_count + self._ime_text_pos)
|
||||
|
||||
if remove_count < 0:
|
||||
self._ime_text = (
|
||||
self._ime_text[0:loc] + to_insert + self._ime_text[self._ime_text_pos :]
|
||||
)
|
||||
|
||||
if text_after_cursor:
|
||||
self.move_cursor_by(remove_count)
|
||||
else:
|
||||
self.move_cursor_by(remove_count + len(to_insert))
|
||||
else:
|
||||
self._ime_text = (
|
||||
self._ime_text[0 : self._ime_text_pos]
|
||||
+ to_insert
|
||||
+ self._ime_text[loc:]
|
||||
)
|
||||
|
||||
# Don't move cursor if not inserting text
|
||||
# after removing the characters in front of the cursor
|
||||
if not text_after_cursor:
|
||||
self.move_cursor_by(len(to_insert))
|
||||
|
||||
def handle_event(self, event: pygame.Event):
|
||||
"""
|
||||
Handle an event
|
||||
"""
|
||||
if self.print_event:
|
||||
print(event)
|
||||
|
||||
if event.type == pygame.KEYDOWN:
|
||||
if self._ime_editing:
|
||||
if len(self._ime_editing_text) == 0:
|
||||
self._ime_editing = False
|
||||
return
|
||||
|
||||
if event.key == pygame.K_BACKSPACE:
|
||||
self.replace_chars(-1)
|
||||
|
||||
elif event.key == pygame.K_DELETE:
|
||||
self.replace_chars(1)
|
||||
|
||||
elif event.key == pygame.K_LEFT:
|
||||
self.move_cursor_by(-1)
|
||||
|
||||
elif event.key == pygame.K_RIGHT:
|
||||
self.move_cursor_by(1)
|
||||
|
||||
# Handle ENTER key
|
||||
elif event.key in (pygame.K_RETURN, pygame.K_KP_ENTER):
|
||||
# Block if we have no text to append
|
||||
if len(self._ime_text) == 0:
|
||||
return
|
||||
|
||||
# Add to chat log
|
||||
self.chat += self._ime_text + "\n"
|
||||
|
||||
chat_lines = self.chat.split("\n")
|
||||
if len(chat_lines) > self.CHAT_LIST_MAXSIZE:
|
||||
chat_lines.pop(0)
|
||||
self.chat = "\n".join(chat_lines)
|
||||
|
||||
self._ime_text = ""
|
||||
self._ime_text_pos = 0
|
||||
|
||||
elif event.type == pygame.TEXTEDITING:
|
||||
self._ime_editing = True
|
||||
self._ime_editing_text = event.text
|
||||
self._ime_editing_pos = event.start
|
||||
|
||||
elif event.type == pygame.TEXTINPUT:
|
||||
self._ime_editing = False
|
||||
self._ime_editing_text = ""
|
||||
self.replace_chars(to_insert=event.text)
|
||||
|
||||
def _get_ime_text(self):
|
||||
"""
|
||||
Returns text that is currently in input.
|
||||
"""
|
||||
if self._ime_editing_text:
|
||||
return (
|
||||
f"{self._ime_text[0 : self._ime_text_pos]}"
|
||||
f"[{self._ime_editing_text}]"
|
||||
f"{self._ime_text[self._ime_text_pos :]}"
|
||||
)
|
||||
return (
|
||||
f"{self._ime_text[0 : self._ime_text_pos]}"
|
||||
f"{self._ime_text[self._ime_text_pos :]}"
|
||||
)
|
||||
elif event.type == pg.TEXTINPUT:
|
||||
if self.print_event:
|
||||
print(event)
|
||||
self._ime_editing = False
|
||||
self._ime_editing_text = ""
|
||||
self._ime_text = (
|
||||
self._ime_text[0 : self._ime_text_pos]
|
||||
+ event.text
|
||||
+ self._ime_text[self._ime_text_pos :]
|
||||
)
|
||||
self._ime_text_pos += len(event.text)
|
||||
|
||||
def draw(self, screen: pygame.Surface) -> None:
|
||||
"""
|
||||
Draws the text input widget onto the provided surface
|
||||
"""
|
||||
|
||||
chat_list_surf = self.font_small.render(
|
||||
self.chat, True, self.text_color, wraplength=self.CHAT_LIST_POS.width
|
||||
)
|
||||
|
||||
screen.blit(chat_list_surf, self.CHAT_LIST_POS)
|
||||
# Chat List updates
|
||||
chat_height = self.CHAT_LIST_POS.height / self.CHAT_LIST_MAXSIZE
|
||||
for i, chat in enumerate(self.chat_list):
|
||||
self.font_small.render_to(
|
||||
screen,
|
||||
(self.CHAT_LIST_POS.x, self.CHAT_LIST_POS.y + i * chat_height),
|
||||
chat,
|
||||
self.text_color,
|
||||
)
|
||||
|
||||
# Chat box updates
|
||||
cursor_loc = self._ime_text_pos + self._ime_editing_pos
|
||||
ime_text = self._get_ime_text()
|
||||
|
||||
text_surf = self.font.render(
|
||||
ime_text, True, self.text_color, wraplength=self.CHAT_BOX_POS.width
|
||||
start_pos = self.CHAT_BOX_POS.copy()
|
||||
ime_text_l = self.prompt + self._ime_text[0 : self._ime_text_pos]
|
||||
ime_text_m = (
|
||||
self._ime_editing_text[0 : self._ime_editing_pos]
|
||||
+ "|"
|
||||
+ self._ime_editing_text[self._ime_editing_pos :]
|
||||
)
|
||||
ime_text_r = self._ime_text[self._ime_text_pos :]
|
||||
|
||||
text_rect = text_surf.get_rect(topleft=self.prompt_rect.topright)
|
||||
screen.blit(self.prompt_surf, self.prompt_rect)
|
||||
screen.blit(text_surf, text_rect)
|
||||
rect_text_l = self.font.render_to(
|
||||
screen, start_pos, ime_text_l, self.text_color
|
||||
)
|
||||
start_pos.x += rect_text_l.width
|
||||
|
||||
# Show blinking cursor, blink twice a second.
|
||||
if self.second_counter * 2 < self.fps:
|
||||
# Characters can have different widths,
|
||||
# so calculating the correct location for the cursor is required.
|
||||
metrics = self.font.metrics(ime_text)
|
||||
x_location = 0
|
||||
|
||||
index = 0
|
||||
for metric in metrics:
|
||||
if metric is None:
|
||||
continue
|
||||
|
||||
_, _, _, _, x_advance = metric
|
||||
|
||||
if index >= cursor_loc:
|
||||
break
|
||||
x_location += x_advance
|
||||
index += 1
|
||||
|
||||
cursor_rect = pygame.Rect(
|
||||
x_location + text_rect.x, text_rect.y, 2, self.font_height
|
||||
)
|
||||
pygame.draw.rect(screen, self.text_color, cursor_rect)
|
||||
# Editing texts should be underlined
|
||||
rect_text_m = self.font.render_to(
|
||||
screen,
|
||||
start_pos,
|
||||
ime_text_m,
|
||||
self.text_color,
|
||||
None,
|
||||
freetype.STYLE_UNDERLINE,
|
||||
)
|
||||
start_pos.x += rect_text_m.width
|
||||
self.font.render_to(screen, start_pos, ime_text_r, self.text_color)
|
||||
|
||||
|
||||
class Game:
|
||||
@@ -265,10 +187,10 @@ class Game:
|
||||
|
||||
def __init__(self, caption: str) -> None:
|
||||
# Initialize
|
||||
pygame.init()
|
||||
self.screen = pygame.display.set_mode((self.SCREEN_WIDTH, self.SCREEN_HEIGHT))
|
||||
pygame.display.set_caption(caption)
|
||||
self.clock = pygame.Clock()
|
||||
pg.init()
|
||||
self.screen = pg.display.set_mode((self.SCREEN_WIDTH, self.SCREEN_HEIGHT))
|
||||
pg.display.set_caption(caption)
|
||||
self.clock = pg.time.Clock()
|
||||
|
||||
# Text input
|
||||
# Set to true or add 'showevent' in argv to see IME and KEYDOWN events
|
||||
@@ -279,19 +201,18 @@ class Game:
|
||||
screen_dimensions=(self.SCREEN_WIDTH, self.SCREEN_HEIGHT),
|
||||
print_event=self.print_event,
|
||||
text_color="green",
|
||||
fps=self.FPS,
|
||||
)
|
||||
|
||||
def main_loop(self) -> None:
|
||||
pygame.key.start_text_input()
|
||||
input_rect = pygame.Rect(80, 80, 320, 40)
|
||||
pygame.key.set_text_input_rect(input_rect)
|
||||
pg.key.start_text_input()
|
||||
input_rect = pg.Rect(80, 80, 320, 40)
|
||||
pg.key.set_text_input_rect(input_rect)
|
||||
|
||||
while True:
|
||||
events = pygame.event.get()
|
||||
events = pg.event.get()
|
||||
for event in events:
|
||||
if event.type == pygame.QUIT:
|
||||
pygame.quit()
|
||||
if event.type == pg.QUIT:
|
||||
pg.quit()
|
||||
return
|
||||
|
||||
self.text_input.update(events)
|
||||
@@ -300,7 +221,7 @@ class Game:
|
||||
self.screen.fill(self.BG_COLOR)
|
||||
self.text_input.draw(self.screen)
|
||||
|
||||
pygame.display.update()
|
||||
pg.display.update()
|
||||
self.clock.tick(self.FPS)
|
||||
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.vgrade
|
||||
""" pg.examples.vgrade
|
||||
|
||||
This example demonstrates creating an image with numpy
|
||||
python, and displaying that through SDL. You can look at the
|
||||
method of importing numpy and pygame.surfarray. This method
|
||||
method of importing numpy and pg.surfarray. This method
|
||||
will fail 'gracefully' if it is not available.
|
||||
I've tried mixing in a lot of comments where the code might
|
||||
not be self-explanatory, nonetheless it may still seem a bit
|
||||
not be self explanatory, nonetheless it may still seem a bit
|
||||
strange. Learning to use numpy for images like this takes a
|
||||
bit of learning, but the payoff is extremely fast image
|
||||
manipulation in python.
|
||||
@@ -26,9 +26,9 @@ The window will have no border decorations.
|
||||
The code also demonstrates use of the timer events.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
import pygame
|
||||
import os
|
||||
import pygame as pg
|
||||
|
||||
try:
|
||||
import numpy as np
|
||||
@@ -40,19 +40,19 @@ timer = 0
|
||||
|
||||
|
||||
def stopwatch(message=None):
|
||||
"""simple routine to time python code"""
|
||||
"simple routine to time python code"
|
||||
global timer
|
||||
if not message:
|
||||
timer = pygame.time.get_ticks()
|
||||
timer = pg.time.get_ticks()
|
||||
return
|
||||
now = pygame.time.get_ticks()
|
||||
now = pg.time.get_ticks()
|
||||
runtime = (now - timer) / 1000.0 + 0.001
|
||||
print(f"{message} {runtime} seconds\t{(1.0 / runtime):.2f}fps")
|
||||
timer = now
|
||||
|
||||
|
||||
def vert_gradient_column(surf, topcolor, bottomcolor):
|
||||
"""creates a new 3d vertical gradient array"""
|
||||
def VertGradientColumn(surf, topcolor, bottomcolor):
|
||||
"creates a new 3d vertical gradient array"
|
||||
topcolor = np.array(topcolor, copy=False)
|
||||
bottomcolor = np.array(bottomcolor, copy=False)
|
||||
diff = bottomcolor - topcolor
|
||||
@@ -65,39 +65,37 @@ def vert_gradient_column(surf, topcolor, bottomcolor):
|
||||
# make the column a 3d image column by adding X
|
||||
column = column.astype("uint8")[np.newaxis, :, :]
|
||||
# 3d array into 2d array
|
||||
return pygame.surfarray.map_array(surf, column)
|
||||
return pg.surfarray.map_array(surf, column)
|
||||
|
||||
|
||||
def display_gradient(surf):
|
||||
"""choose random colors and show them"""
|
||||
def DisplayGradient(surf):
|
||||
"choose random colors and show them"
|
||||
stopwatch()
|
||||
colors = np_random.randint(0, 255, (2, 3))
|
||||
column = vert_gradient_column(surf, colors[0], colors[1])
|
||||
pygame.surfarray.blit_array(surf, column)
|
||||
pygame.display.flip()
|
||||
column = VertGradientColumn(surf, colors[0], colors[1])
|
||||
pg.surfarray.blit_array(surf, column)
|
||||
pg.display.flip()
|
||||
stopwatch("Gradient:")
|
||||
|
||||
|
||||
def main():
|
||||
pygame.init()
|
||||
pygame.mixer.quit() # remove ALSA underflow messages for Debian squeeze
|
||||
pg.init()
|
||||
pg.mixer.quit() # remove ALSA underflow messages for Debian squeeze
|
||||
size = 600, 400
|
||||
os.environ["SDL_VIDEO_CENTERED"] = "1"
|
||||
screen = pygame.display.set_mode(size, pygame.NOFRAME)
|
||||
screen = pg.display.set_mode(size, pg.NOFRAME, 0)
|
||||
|
||||
pygame.event.set_blocked(pygame.MOUSEMOTION) # keep our queue cleaner
|
||||
|
||||
TIMER_EVENT = pygame.event.custom_type()
|
||||
pygame.time.set_timer(TIMER_EVENT, 500)
|
||||
pg.event.set_blocked(pg.MOUSEMOTION) # keep our queue cleaner
|
||||
pg.time.set_timer(pg.USEREVENT, 500)
|
||||
|
||||
while True:
|
||||
event = pygame.event.wait()
|
||||
if event.type in (pygame.QUIT, pygame.KEYDOWN, pygame.MOUSEBUTTONDOWN):
|
||||
event = pg.event.wait()
|
||||
if event.type in (pg.QUIT, pg.KEYDOWN, pg.MOUSEBUTTONDOWN):
|
||||
break
|
||||
elif event.type == TIMER_EVENT:
|
||||
display_gradient(screen)
|
||||
elif event.type == pg.USEREVENT:
|
||||
DisplayGradient(screen)
|
||||
|
||||
pygame.quit()
|
||||
pg.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.video
|
||||
""" pg.examples.video
|
||||
|
||||
Experimental!
|
||||
|
||||
@@ -9,155 +9,150 @@ Experimental!
|
||||
* Renderer, Texture, and Image classes
|
||||
* Drawing lines, rects, and such onto Renderers.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
import pygame
|
||||
from pygame._sdl2 import Image, Renderer, Texture, Window, get_drivers
|
||||
import pygame as pg
|
||||
from pygame._sdl2 import Window, Texture, Image, Renderer, get_drivers, messagebox
|
||||
|
||||
data_dir = os.path.join(os.path.split(os.path.abspath(__file__))[0], "data")
|
||||
|
||||
|
||||
def load_img(file):
|
||||
return pygame.image.load(os.path.join(data_dir, file))
|
||||
return pg.image.load(os.path.join(data_dir, file))
|
||||
|
||||
|
||||
def main():
|
||||
pygame.display.init()
|
||||
pygame.key.set_repeat(1000, 10)
|
||||
pg.display.init()
|
||||
pg.key.set_repeat(1000, 10)
|
||||
|
||||
for driver in get_drivers():
|
||||
print(driver)
|
||||
for driver in get_drivers():
|
||||
print(driver)
|
||||
|
||||
import random
|
||||
import random
|
||||
|
||||
answer = pygame.display.message_box(
|
||||
try:
|
||||
answer = messagebox(
|
||||
"I will open two windows! Continue?",
|
||||
"Hello!",
|
||||
message_type="info",
|
||||
info=True,
|
||||
buttons=("Yes", "No", "Chance"),
|
||||
return_button=0,
|
||||
escape_button=1,
|
||||
)
|
||||
|
||||
if answer == 1 or (answer == 2 and random.random() < 0.5):
|
||||
import sys
|
||||
|
||||
sys.exit(0)
|
||||
except:
|
||||
pass
|
||||
|
||||
win = Window("asdf", resizable=True)
|
||||
renderer = Renderer(win)
|
||||
tex = Texture.from_surface(renderer, load_img("alien1.gif"))
|
||||
win = Window("asdf", resizable=True)
|
||||
renderer = Renderer(win)
|
||||
tex = Texture.from_surface(renderer, load_img("alien1.gif"))
|
||||
img = Image(tex)
|
||||
|
||||
running = True
|
||||
running = True
|
||||
|
||||
x, y = 250, 50
|
||||
clock = pygame.Clock()
|
||||
x, y = 250, 50
|
||||
clock = pg.time.Clock()
|
||||
|
||||
backgrounds = [(255, 0, 0, 255), (0, 255, 0, 255), (0, 0, 255, 255)]
|
||||
bg_index = 0
|
||||
backgrounds = [(255, 0, 0, 255), (0, 255, 0, 255), (0, 0, 255, 255)]
|
||||
bg_index = 0
|
||||
|
||||
renderer.draw_color = backgrounds[bg_index]
|
||||
|
||||
win2 = Window("2nd window", size=(256, 256), always_on_top=True)
|
||||
win2.opacity = 0.5
|
||||
win2.set_icon(load_img("bomb.gif"))
|
||||
renderer2 = Renderer(win2)
|
||||
tex2 = Texture.from_surface(renderer2, load_img("asprite.bmp"))
|
||||
renderer2.clear()
|
||||
tex2.draw()
|
||||
renderer2.present()
|
||||
del tex2
|
||||
|
||||
full = 0
|
||||
|
||||
surf = pg.Surface((64, 64))
|
||||
streamtex = Texture(renderer, (64, 64), streaming=True)
|
||||
tex_update_interval = 1000
|
||||
next_tex_update = pg.time.get_ticks()
|
||||
|
||||
|
||||
while running:
|
||||
for event in pg.event.get():
|
||||
if event.type == pg.QUIT:
|
||||
running = False
|
||||
elif getattr(event, "window", None) == win2:
|
||||
if (
|
||||
event.type == pg.KEYDOWN
|
||||
and event.key == pg.K_ESCAPE
|
||||
or event.type == pg.WINDOWCLOSE
|
||||
):
|
||||
win2.destroy()
|
||||
elif event.type == pg.KEYDOWN:
|
||||
if event.key == pg.K_ESCAPE:
|
||||
running = False
|
||||
elif event.key == pg.K_LEFT:
|
||||
x -= 5
|
||||
elif event.key == pg.K_RIGHT:
|
||||
x += 5
|
||||
elif event.key == pg.K_DOWN:
|
||||
y += 5
|
||||
elif event.key == pg.K_UP:
|
||||
y -= 5
|
||||
elif event.key == pg.K_f:
|
||||
if full == 0:
|
||||
win.set_fullscreen(True)
|
||||
full = 1
|
||||
else:
|
||||
win.set_windowed()
|
||||
full = 0
|
||||
elif event.key == pg.K_s:
|
||||
readsurf = renderer.to_surface()
|
||||
pg.image.save(readsurf, "test.png")
|
||||
|
||||
elif event.key == pg.K_SPACE:
|
||||
bg_index = (bg_index + 1) % len(backgrounds)
|
||||
renderer.draw_color = backgrounds[bg_index]
|
||||
|
||||
renderer.clear()
|
||||
|
||||
# update texture
|
||||
curtime = pg.time.get_ticks()
|
||||
if curtime >= next_tex_update:
|
||||
for x_ in range(streamtex.width // 4):
|
||||
for y_ in range(streamtex.height // 4):
|
||||
newcol = (
|
||||
random.randint(0, 255),
|
||||
random.randint(0, 255),
|
||||
random.randint(0, 255),
|
||||
255,
|
||||
)
|
||||
area = (4 * x_, 4 * y_, 4, 4)
|
||||
surf.fill(newcol, area)
|
||||
streamtex.update(surf)
|
||||
next_tex_update = curtime + tex_update_interval
|
||||
streamtex.draw(dstrect=pg.Rect(64, 128, 64, 64))
|
||||
|
||||
img.draw(dstrect=(x, y))
|
||||
|
||||
# TODO: should these be?
|
||||
# - line instead of draw_line
|
||||
# - point instead of draw_point
|
||||
# - rect(rect, width=1)->draw 1 pixel, instead of draw_rect
|
||||
# - rect(rect, width=0)->filled ? , instead of fill_rect
|
||||
#
|
||||
# TODO: should these work with pg.draw.line(renderer, ...) functions?
|
||||
renderer.draw_color = (255, 255, 255, 255)
|
||||
renderer.draw_line((0, 0), (64, 64))
|
||||
renderer.draw_line((64, 64), (128, 0))
|
||||
renderer.draw_point((72, 32))
|
||||
renderer.draw_rect(pg.Rect(0, 64, 64, 64))
|
||||
renderer.fill_rect(pg.Rect(0, 128, 64, 64))
|
||||
renderer.draw_color = backgrounds[bg_index]
|
||||
|
||||
win2 = Window("2nd window", size=(256, 256), always_on_top=True)
|
||||
win2.opacity = 0.5
|
||||
win2.set_icon(load_img("bomb.gif"))
|
||||
renderer2 = Renderer(win2)
|
||||
tex2 = Texture.from_surface(renderer2, load_img("asprite.bmp"))
|
||||
renderer2.clear()
|
||||
tex2.draw()
|
||||
renderer2.present()
|
||||
del tex2
|
||||
renderer.present()
|
||||
|
||||
full = 0
|
||||
clock.tick(60)
|
||||
win.title = str(f"FPS: {clock.get_fps()}")
|
||||
|
||||
tex = Image(tex)
|
||||
|
||||
surf = pygame.Surface((64, 64))
|
||||
streamtex = Texture(renderer, (64, 64), streaming=True)
|
||||
tex_update_interval = 1000
|
||||
next_tex_update = pygame.time.get_ticks()
|
||||
|
||||
while running:
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
running = False
|
||||
elif getattr(event, "window", None) == win2:
|
||||
if (
|
||||
event.type == pygame.KEYDOWN
|
||||
and event.key == pygame.K_ESCAPE
|
||||
or event.type == pygame.WINDOWCLOSE
|
||||
):
|
||||
win2.destroy()
|
||||
elif event.type == pygame.KEYDOWN:
|
||||
if event.key == pygame.K_ESCAPE:
|
||||
running = False
|
||||
elif event.key == pygame.K_LEFT:
|
||||
x -= 5
|
||||
elif event.key == pygame.K_RIGHT:
|
||||
x += 5
|
||||
elif event.key == pygame.K_DOWN:
|
||||
y += 5
|
||||
elif event.key == pygame.K_UP:
|
||||
y -= 5
|
||||
elif event.key == pygame.K_f:
|
||||
if full == 0:
|
||||
win.set_fullscreen(True)
|
||||
full = 1
|
||||
else:
|
||||
win.set_windowed()
|
||||
full = 0
|
||||
elif event.key == pygame.K_s:
|
||||
readsurf = renderer.to_surface()
|
||||
pygame.image.save(readsurf, "test.png")
|
||||
|
||||
elif event.key == pygame.K_SPACE:
|
||||
bg_index = (bg_index + 1) % len(backgrounds)
|
||||
renderer.draw_color = backgrounds[bg_index]
|
||||
|
||||
renderer.clear()
|
||||
|
||||
# update texture
|
||||
curtime = pygame.time.get_ticks()
|
||||
if curtime >= next_tex_update:
|
||||
for x_ in range(streamtex.width // 4):
|
||||
for y_ in range(streamtex.height // 4):
|
||||
newcol = (
|
||||
random.randint(0, 255),
|
||||
random.randint(0, 255),
|
||||
random.randint(0, 255),
|
||||
255,
|
||||
)
|
||||
area = (4 * x_, 4 * y_, 4, 4)
|
||||
surf.fill(newcol, area)
|
||||
streamtex.update(surf)
|
||||
next_tex_update = curtime + tex_update_interval
|
||||
streamtex.draw(dstrect=pygame.Rect(64, 128, 64, 64))
|
||||
|
||||
tex.draw(dstrect=(x, y))
|
||||
|
||||
# TODO: should these be?
|
||||
# - line instead of draw_line
|
||||
# - point instead of draw_point
|
||||
# - rect(rect, width=1)->draw 1 pixel, instead of draw_rect
|
||||
# - rect(rect, width=0)->filled ? , instead of fill_rect
|
||||
#
|
||||
# TODO: should these work with pygame.draw.line(renderer, ...) functions?
|
||||
renderer.draw_color = (255, 255, 255, 255)
|
||||
renderer.draw_line((0, 0), (64, 64))
|
||||
renderer.draw_line((64, 64), (128, 0))
|
||||
renderer.draw_point((72, 32))
|
||||
renderer.draw_rect(pygame.Rect(0, 64, 64, 64))
|
||||
renderer.fill_rect(pygame.Rect(0, 128, 64, 64))
|
||||
renderer.draw_color = backgrounds[bg_index]
|
||||
|
||||
renderer.present()
|
||||
|
||||
clock.tick(60)
|
||||
win.title = str(f"FPS: {clock.get_fps()}")
|
||||
|
||||
pygame.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
pg.quit()
|
||||
@@ -1,82 +0,0 @@
|
||||
"""pygame.examples.window_opengl
|
||||
|
||||
Slightly modified version of the example at https://github.com/szabolcsdombi/zengl/blob/main/examples/pygame/hello_world.py
|
||||
Modified to use Window API instead of the display module
|
||||
|
||||
Posted here with permission from https://github.com/szabolcsdombi given in the PGC discord server
|
||||
"""
|
||||
|
||||
import pygame
|
||||
import zengl
|
||||
|
||||
|
||||
def main():
|
||||
window_size = (1280, 720)
|
||||
|
||||
pygame.init()
|
||||
window = pygame.Window(size=window_size, opengl=True)
|
||||
|
||||
ctx = zengl.context()
|
||||
|
||||
image = ctx.image(window_size, "rgba8unorm", samples=4)
|
||||
|
||||
pipeline = ctx.pipeline(
|
||||
vertex_shader="""
|
||||
#version 330 core
|
||||
|
||||
out vec3 v_color;
|
||||
|
||||
vec2 vertices[3] = vec2[](
|
||||
vec2(0.0, 0.8),
|
||||
vec2(-0.6, -0.8),
|
||||
vec2(0.6, -0.8)
|
||||
);
|
||||
|
||||
vec3 colors[3] = vec3[](
|
||||
vec3(1.0, 0.0, 0.0),
|
||||
vec3(0.0, 1.0, 0.0),
|
||||
vec3(0.0, 0.0, 1.0)
|
||||
);
|
||||
|
||||
void main() {
|
||||
gl_Position = vec4(vertices[gl_VertexID], 0.0, 1.0);
|
||||
v_color = colors[gl_VertexID];
|
||||
}
|
||||
""",
|
||||
fragment_shader="""
|
||||
#version 330 core
|
||||
|
||||
in vec3 v_color;
|
||||
|
||||
layout (location = 0) out vec4 out_color;
|
||||
|
||||
void main() {
|
||||
out_color = vec4(v_color, 1.0);
|
||||
out_color.rgb = pow(out_color.rgb, vec3(1.0 / 2.2));
|
||||
}
|
||||
""",
|
||||
framebuffer=[image],
|
||||
topology="triangles",
|
||||
vertex_count=3,
|
||||
)
|
||||
|
||||
clock = pygame.Clock()
|
||||
|
||||
while True:
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
pygame.quit()
|
||||
quit()
|
||||
|
||||
ctx.new_frame()
|
||||
image.clear()
|
||||
pipeline.render()
|
||||
image.blit()
|
||||
ctx.end_frame()
|
||||
|
||||
window.flip()
|
||||
clock.tick(60)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||