Erste Version
No files matched your search
@@ -0,0 +1,145 @@
|
||||
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.
|
||||
|
||||
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)
|
||||
|
||||
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
|
||||
|
||||
audiocapture.py
|
||||
Record sound from a microphone, and play back the recorded sound.
|
||||
|
||||
blend_fill.py
|
||||
BLEND_ing colors in different ways with Surface.fill().
|
||||
|
||||
blit_blends.py
|
||||
BLEND_ing colors Surface.blit().
|
||||
|
||||
camera.py
|
||||
Basic image capturing and display using pygame.camera
|
||||
|
||||
cursors.py
|
||||
Make custom cursors :)
|
||||
|
||||
dropevent.py
|
||||
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.
|
||||
|
||||
font_viewer.py
|
||||
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
|
||||
|
||||
freetype_misc.py
|
||||
FreeType is a world famous font project.
|
||||
|
||||
glcube.py
|
||||
Using PyOpenGL and Pygame, this creates a spinning 3D multicolored cube.
|
||||
|
||||
go_over_there.py
|
||||
Demonstrates Vector.move_towards.
|
||||
|
||||
headless_no_windows_needed.py
|
||||
For using pygame in scripts.
|
||||
|
||||
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).
|
||||
|
||||
mask.py
|
||||
Single bit pixel manipulation. Fast for collision detection,
|
||||
and also good for computer vision.
|
||||
|
||||
midi.py
|
||||
For connecting pygame to musical equipment.
|
||||
|
||||
moveit.py
|
||||
A very simple example of moving stuff.
|
||||
|
||||
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.
|
||||
|
||||
pixelarray.py
|
||||
Process whole arrays of pixels at a time.
|
||||
Like numpy, but for pixels, and also built into pygame.
|
||||
|
||||
playmus.py
|
||||
Simple music playing example.
|
||||
|
||||
prevent_display_stretching.py
|
||||
A windows specific example.
|
||||
|
||||
scaletest.py
|
||||
Showing how to scale Surfaces.
|
||||
|
||||
scrap_clipboard.py
|
||||
A simple demonstration example for the clipboard support.
|
||||
|
||||
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
|
||||
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.
|
||||
|
||||
sound_array_demos.py
|
||||
Echo, delay and other array based processing of sounds.
|
||||
|
||||
sprite_texture.py
|
||||
Shows how to use hardware Image Textures with pygame.sprite.
|
||||
|
||||
stars.py
|
||||
A simple starfield example. You can change the center of
|
||||
perspective by leftclicking the mouse on the screen.
|
||||
|
||||
testsprite.py
|
||||
More of a test example. If you're interested in how to use sprites,
|
||||
then check out the aliens.py example instead.
|
||||
|
||||
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 :]
|
||||
|
||||
video.py
|
||||
It explores some new video APIs in pygame 2.
|
||||
Including multiple windows, Textures, and such.
|
||||
|
||||
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.
|
||||
@@ -0,0 +1,46 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
"""Proof of concept gfxdraw example"""
|
||||
|
||||
import pygame
|
||||
import pygame.gfxdraw
|
||||
|
||||
|
||||
def main():
|
||||
pygame.init()
|
||||
screen = pygame.display.set_mode((500, 500))
|
||||
screen.fill((255, 0, 0))
|
||||
s = pygame.Surface(screen.get_size(), pygame.SRCALPHA)
|
||||
pygame.draw.line(s, (0, 0, 0), (250, 250), (250 + 200, 250))
|
||||
|
||||
width = 1
|
||||
for a_radius in range(width):
|
||||
radius = 200
|
||||
pygame.gfxdraw.aacircle(s, 250, 250, radius - a_radius, (0, 0, 0))
|
||||
|
||||
screen.blit(s, (0, 0))
|
||||
|
||||
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():
|
||||
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()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,400 @@
|
||||
#!/usr/bin/env python
|
||||
"""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.
|
||||
* dirty rectangle optimization for processing for speed.
|
||||
* music with pygame.mixer.music, including fadeout
|
||||
* sound effects with pygame.Sound
|
||||
* event processing, keyboard handling, QUIT handling.
|
||||
* a main loop frame limited with a game clock from the pygame.time module
|
||||
* fullscreen switching.
|
||||
|
||||
|
||||
Controls
|
||||
--------
|
||||
|
||||
* Left and right arrows to move.
|
||||
* Space bar to shoot.
|
||||
* f key to toggle between fullscreen.
|
||||
|
||||
"""
|
||||
|
||||
import os
|
||||
import random
|
||||
|
||||
# import basic pygame modules
|
||||
import pygame
|
||||
|
||||
# see if we can load more than standard BMP
|
||||
if not pygame.image.get_extended():
|
||||
raise SystemExit("Sorry, extended image module required")
|
||||
|
||||
|
||||
# game constants
|
||||
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)
|
||||
SCORE = 0
|
||||
|
||||
main_dir = os.path.split(os.path.abspath(__file__))[0]
|
||||
|
||||
|
||||
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()}')
|
||||
return surface.convert()
|
||||
|
||||
|
||||
def load_sound(file):
|
||||
"""because pygame can be compiled without mixer."""
|
||||
if not pygame.mixer:
|
||||
return None
|
||||
file = os.path.join(main_dir, "data", file)
|
||||
try:
|
||||
sound = pygame.mixer.Sound(file)
|
||||
return sound
|
||||
except pygame.error:
|
||||
print(f"Warning, unable to load, {file}")
|
||||
return None
|
||||
|
||||
|
||||
# Each type of game object gets an init and an update function.
|
||||
# The update function is called once per frame, and it is when each object should
|
||||
# change its current position and state.
|
||||
#
|
||||
# The Player object actually gets a "move" function instead of update,
|
||||
# since it is passed extra information about the keyboard.
|
||||
|
||||
|
||||
class Player(pygame.sprite.Sprite):
|
||||
"""Representing the player as a moon buggy type car."""
|
||||
|
||||
speed = 10
|
||||
bounce = 24
|
||||
gun_offset = -11
|
||||
images = []
|
||||
containers = None
|
||||
|
||||
def __init__(self):
|
||||
super().__init__(self.containers)
|
||||
self.image = self.images[0]
|
||||
self.rect = self.image.get_rect(midbottom=SCREENRECT.midbottom)
|
||||
self.reloading = False
|
||||
self.origtop = self.rect.top
|
||||
self.facing = -1
|
||||
|
||||
def move(self, direction):
|
||||
if direction:
|
||||
self.facing = direction
|
||||
self.rect.move_ip(direction * self.speed, 0)
|
||||
self.rect = self.rect.clamp(SCREENRECT)
|
||||
if direction < 0:
|
||||
self.image = self.images[0]
|
||||
elif direction > 0:
|
||||
self.image = self.images[1]
|
||||
self.rect.top = self.origtop - (self.rect.left // self.bounce % 2)
|
||||
|
||||
def gunpos(self):
|
||||
pos = self.facing * self.gun_offset + self.rect.centerx
|
||||
return pos, self.rect.top
|
||||
|
||||
|
||||
class Alien(pygame.sprite.Sprite):
|
||||
"""An alien space ship. That slowly moves down the screen."""
|
||||
|
||||
speed = 13
|
||||
animcycle = 12
|
||||
images = []
|
||||
containers = None
|
||||
|
||||
def __init__(self):
|
||||
pygame.sprite.Sprite.__init__(self, self.containers)
|
||||
self.image = self.images[0]
|
||||
self.rect = self.image.get_rect()
|
||||
self.facing = random.choice((-1, 1)) * Alien.speed
|
||||
self.frame = 0
|
||||
if self.facing < 0:
|
||||
self.rect.right = SCREENRECT.right
|
||||
|
||||
def update(self):
|
||||
self.rect.move_ip(self.facing, 0)
|
||||
if not SCREENRECT.contains(self.rect):
|
||||
self.facing = -self.facing
|
||||
self.rect.top = self.rect.bottom + 1
|
||||
self.rect = self.rect.clamp(SCREENRECT)
|
||||
self.frame = self.frame + 1
|
||||
self.image = self.images[self.frame // self.animcycle % 3]
|
||||
|
||||
|
||||
class Explosion(pygame.sprite.Sprite):
|
||||
"""An explosion. Hopefully the Alien and not the player!"""
|
||||
|
||||
defaultlife = 12
|
||||
animcycle = 3
|
||||
images = []
|
||||
containers = None
|
||||
|
||||
def __init__(self, actor):
|
||||
pygame.sprite.Sprite.__init__(self, self.containers)
|
||||
self.image = self.images[0]
|
||||
self.rect = self.image.get_rect(center=actor.rect.center)
|
||||
self.life = self.defaultlife
|
||||
|
||||
def update(self):
|
||||
"""called every time around the game loop.
|
||||
|
||||
Show the explosion surface for 'defaultlife'.
|
||||
Every game tick(update), we decrease the 'life'.
|
||||
|
||||
Also we animate the explosion.
|
||||
"""
|
||||
self.life = self.life - 1
|
||||
self.image = self.images[self.life // self.animcycle % 2]
|
||||
if self.life <= 0:
|
||||
self.kill()
|
||||
|
||||
|
||||
class Shot(pygame.sprite.Sprite):
|
||||
"""a bullet the Player sprite fires."""
|
||||
|
||||
speed = -11
|
||||
images = []
|
||||
containers = None
|
||||
|
||||
def __init__(self, pos):
|
||||
pygame.sprite.Sprite.__init__(self, self.containers)
|
||||
self.image = self.images[0]
|
||||
self.rect = self.image.get_rect(midbottom=pos)
|
||||
|
||||
def update(self):
|
||||
"""called every time around the game loop.
|
||||
|
||||
Every tick we move the shot upwards.
|
||||
"""
|
||||
self.rect.move_ip(0, self.speed)
|
||||
if self.rect.top <= 0:
|
||||
self.kill()
|
||||
|
||||
|
||||
class Bomb(pygame.sprite.Sprite):
|
||||
"""A bomb the aliens drop."""
|
||||
|
||||
speed = 9
|
||||
images = []
|
||||
containers = None
|
||||
|
||||
def __init__(self, alien):
|
||||
pygame.sprite.Sprite.__init__(self, self.containers)
|
||||
self.image = self.images[0]
|
||||
self.rect = self.image.get_rect(midbottom=alien.rect.move(0, 5).midbottom)
|
||||
|
||||
def update(self):
|
||||
"""called every time around the game loop.
|
||||
|
||||
Every frame we move the sprite 'rect' down.
|
||||
When it reaches the bottom we:
|
||||
|
||||
- make an explosion.
|
||||
- remove the Bomb.
|
||||
"""
|
||||
self.rect.move_ip(0, self.speed)
|
||||
if self.rect.bottom >= 470:
|
||||
Explosion(self)
|
||||
self.kill()
|
||||
|
||||
|
||||
class Score(pygame.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)
|
||||
self.color = "white"
|
||||
self.lastscore = -1
|
||||
self.update()
|
||||
self.rect = self.image.get_rect().move(10, 450)
|
||||
|
||||
def update(self):
|
||||
"""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)
|
||||
|
||||
|
||||
def main():
|
||||
# Initialize pygame
|
||||
pygame.mixer.pre_init(44100, 32, 2, 1024)
|
||||
pygame.init()
|
||||
if pygame.mixer and not pygame.mixer.get_init():
|
||||
print("Warning, no sound")
|
||||
pygame.mixer = None
|
||||
|
||||
fullscreen = False
|
||||
# Set the display mode
|
||||
winstyle = 0 # |FULLSCREEN
|
||||
screen = pygame.display.set_mode(SCREENRECT.size, winstyle)
|
||||
|
||||
# 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)]
|
||||
img = load_image("explosion1.gif")
|
||||
Explosion.images = [img, pygame.transform.flip(img, True, True)]
|
||||
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)
|
||||
|
||||
# create the background, tile the bgd image
|
||||
bgdtile = load_image("background.gif")
|
||||
background = pygame.Surface(SCREENRECT.size)
|
||||
for x in range(0, SCREENRECT.width, bgdtile.get_width()):
|
||||
background.blit(bgdtile, (x, 0))
|
||||
pygame.display.flip()
|
||||
|
||||
# load the sound effects
|
||||
boom_sound = load_sound("boom.wav")
|
||||
shoot_sound = load_sound("car_door.wav")
|
||||
if pygame.mixer:
|
||||
music = os.path.join(main_dir, "data", "house_lo.wav")
|
||||
pygame.mixer.music.load(music)
|
||||
pygame.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
|
||||
|
||||
# Create Some Starting Values
|
||||
alienreload = ALIEN_RELOAD
|
||||
clock = pygame.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())
|
||||
|
||||
# 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:
|
||||
return
|
||||
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
|
||||
return
|
||||
elif event.type == pygame.KEYDOWN:
|
||||
if event.key == pygame.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.blit(screen_backup, (0, 0))
|
||||
else:
|
||||
print("Changing to windowed mode")
|
||||
screen_backup = screen.copy()
|
||||
screen = pygame.display.set_mode(SCREENRECT.size, winstyle)
|
||||
screen.blit(screen_backup, (0, 0))
|
||||
pygame.display.flip()
|
||||
fullscreen = not fullscreen
|
||||
|
||||
keystate = pygame.key.get_pressed()
|
||||
|
||||
# update all the sprites
|
||||
all_sprites.update()
|
||||
|
||||
# handle player input
|
||||
direction = keystate[pygame.K_RIGHT] - keystate[pygame.K_LEFT]
|
||||
player.move(direction)
|
||||
firing = keystate[pygame.K_SPACE]
|
||||
if not player.reloading and firing and len(shots) < MAX_SHOTS:
|
||||
Shot(player.gunpos())
|
||||
if pygame.mixer:
|
||||
shoot_sound.play()
|
||||
player.reloading = firing
|
||||
|
||||
# Create new alien
|
||||
if alienreload:
|
||||
alienreload = alienreload - 1
|
||||
elif not int(random.random() * ALIEN_ODDS):
|
||||
Alien()
|
||||
alienreload = ALIEN_RELOAD
|
||||
|
||||
# Drop bombs
|
||||
if lastalien and not int(random.random() * BOMB_ODDS):
|
||||
Bomb(lastalien.sprite)
|
||||
|
||||
# Detect collisions between aliens and players.
|
||||
for alien in pygame.sprite.spritecollide(player, aliens, True):
|
||||
if pygame.mixer:
|
||||
boom_sound.play()
|
||||
Explosion(alien)
|
||||
Explosion(player)
|
||||
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:
|
||||
boom_sound.play()
|
||||
Explosion(alien)
|
||||
SCORE = SCORE + 1
|
||||
|
||||
# See if alien bombs hit the player.
|
||||
for bomb in pygame.sprite.spritecollide(player, bombs, True):
|
||||
if pygame.mixer:
|
||||
boom_sound.play()
|
||||
Explosion(player)
|
||||
Explosion(bomb)
|
||||
player.kill()
|
||||
|
||||
# draw the scene
|
||||
all_sprites.draw(screen)
|
||||
pygame.display.flip()
|
||||
|
||||
# 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)
|
||||
|
||||
|
||||
# call the "main" function if running this script
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
pygame.quit()
|
||||
@@ -0,0 +1,120 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.arraydemo
|
||||
|
||||
Welcome to the arraydemo!
|
||||
|
||||
Use the numpy array package to manipulate pixels.
|
||||
|
||||
This demo will show you a few things:
|
||||
|
||||
* scale up, scale down, flip,
|
||||
* cross fade
|
||||
* soften
|
||||
* put stripes on it!
|
||||
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
import pygame
|
||||
from pygame import surfarray
|
||||
|
||||
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])
|
||||
surfarray.blit_array(screen, array_img)
|
||||
pygame.display.flip()
|
||||
pygame.display.set_caption(name)
|
||||
while True:
|
||||
e = pygame.event.wait()
|
||||
# Force application to only advance when main button is released
|
||||
if e.type == pygame.MOUSEBUTTONUP and e.button == pygame.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()
|
||||
raise SystemExit()
|
||||
|
||||
|
||||
def main():
|
||||
"""show various surfarray effects"""
|
||||
import numpy as np
|
||||
from numpy import int32, uint
|
||||
|
||||
pygame.init()
|
||||
|
||||
print("Using Numpy")
|
||||
print("Press the left mouse button to advance image.")
|
||||
print('Press the "s" key to save the current image.')
|
||||
|
||||
# allblack
|
||||
allblack = np.zeros((128, 128), int32)
|
||||
surfdemo_show(allblack, "allblack")
|
||||
|
||||
# striped
|
||||
# the element type is required for np.zeros in numpy else
|
||||
# an array of float is returned.
|
||||
striped = np.zeros((128, 128, 3), int32)
|
||||
striped[:] = (255, 0, 0)
|
||||
striped[:, ::3] = (0, 255, 255)
|
||||
surfdemo_show(striped, "striped")
|
||||
|
||||
# rgbarray
|
||||
imagename = os.path.join(main_dir, "data", "arraydemo.webp")
|
||||
imgsurface = pygame.image.load(imagename)
|
||||
rgbarray = surfarray.array3d(imgsurface)
|
||||
surfdemo_show(rgbarray, "rgbarray")
|
||||
|
||||
# flipped
|
||||
flipped = rgbarray[:, ::-1]
|
||||
surfdemo_show(flipped, "flipped")
|
||||
|
||||
# scaledown
|
||||
scaledown = rgbarray[::2, ::2]
|
||||
surfdemo_show(scaledown, "scaledown")
|
||||
|
||||
# scaleup
|
||||
# the element type is required for np.zeros in numpy else
|
||||
# an #array of floats is returned.
|
||||
shape = rgbarray.shape
|
||||
scaleup = np.zeros((shape[0] * 2, shape[1] * 2, shape[2]), int32)
|
||||
scaleup[::2, ::2, :] = rgbarray
|
||||
scaleup[1::2, ::2, :] = rgbarray
|
||||
scaleup[:, 1::2] = scaleup[:, ::2]
|
||||
surfdemo_show(scaleup, "scaleup")
|
||||
|
||||
# redimg
|
||||
redimg = np.array(rgbarray)
|
||||
redimg[:, :, 1:] = 0
|
||||
surfdemo_show(redimg, "redimg")
|
||||
|
||||
# soften
|
||||
# having factor as an array forces integer upgrade during multiplication
|
||||
# of rgbarray, even for numpy.
|
||||
factor = np.array((8,), int32)
|
||||
soften = np.array(rgbarray, int32)
|
||||
soften[1:, :] += rgbarray[:-1, :] * factor
|
||||
soften[:-1, :] += rgbarray[1:, :] * factor
|
||||
soften[:, 1:] += rgbarray[:, :-1] * factor
|
||||
soften[:, :-1] += rgbarray[:, 1:] * factor
|
||||
soften //= 33
|
||||
surfdemo_show(soften, "soften")
|
||||
|
||||
# crossfade (50%)
|
||||
src = np.array(rgbarray)
|
||||
dest = np.zeros(rgbarray.shape) # dest is float64 by default.
|
||||
dest[:] = 20, 50, 100
|
||||
diff = (dest - src) * 0.50
|
||||
xfade = src + diff.astype(uint)
|
||||
surfdemo_show(xfade, "xfade")
|
||||
|
||||
# all done
|
||||
pygame.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,82 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.audiocapture
|
||||
|
||||
A pygame 2 experiment.
|
||||
|
||||
* record sound from a microphone
|
||||
* play back the recorded sound
|
||||
"""
|
||||
|
||||
import time
|
||||
|
||||
import pygame
|
||||
from pygame._sdl2 import (
|
||||
AUDIO_ALLOW_FORMAT_CHANGE,
|
||||
AUDIO_F32,
|
||||
AudioDevice,
|
||||
get_audio_device_names,
|
||||
)
|
||||
from pygame._sdl2.mixer import set_post_mix
|
||||
|
||||
sounds = []
|
||||
sound_chunks = []
|
||||
|
||||
|
||||
def callback(audiodevice, audiomemoryview):
|
||||
"""This is called in the sound thread.
|
||||
|
||||
Note, that the frequency and such you request may not be what you get.
|
||||
"""
|
||||
# print(type(audiomemoryview), len(audiomemoryview))
|
||||
# print(audiodevice)
|
||||
sound_chunks.append(bytes(audiomemoryview))
|
||||
|
||||
|
||||
def postmix_callback(postmix, audiomemoryview):
|
||||
"""This is called in the sound thread.
|
||||
|
||||
At the end of mixing we get this data.
|
||||
"""
|
||||
print(type(audiomemoryview), len(audiomemoryview))
|
||||
print(postmix)
|
||||
|
||||
|
||||
def main():
|
||||
pygame.mixer.pre_init(44100, 32, 2, 512)
|
||||
pygame.init()
|
||||
|
||||
# init_subsystem(INIT_AUDIO)
|
||||
names = get_audio_device_names(True)
|
||||
print(names)
|
||||
|
||||
set_post_mix(postmix_callback)
|
||||
|
||||
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()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,115 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.blend_fill
|
||||
|
||||
BLEND_ing colors in different ways with Surface.fill().
|
||||
|
||||
Keyboard Controls:
|
||||
|
||||
* Press R, G, B to increase the color channel values,
|
||||
* 1-9 to set the step range for the increment,
|
||||
* A - ADD, S- SUB, M- MULT, - MIN, + MAX to change the blend modes
|
||||
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
import pygame
|
||||
from pygame import K_1, K_2, K_3, K_4, K_5, K_6, K_7, K_8, K_9
|
||||
|
||||
|
||||
def usage():
|
||||
print("Press R, G, B to increase the color channel values,")
|
||||
print("1-9 to set the step range for the increment,")
|
||||
print("A - ADD, S- SUB, M- MULT, - MIN, + MAX")
|
||||
print(" to change the blend modes")
|
||||
|
||||
|
||||
main_dir = os.path.split(os.path.abspath(__file__))[0]
|
||||
data_dir = os.path.join(main_dir, "data")
|
||||
|
||||
|
||||
def main():
|
||||
color = [0, 0, 0]
|
||||
changed = False
|
||||
blendtype = 0
|
||||
step = 5
|
||||
|
||||
pygame.init()
|
||||
screen = pygame.display.set_mode((640, 480))
|
||||
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()
|
||||
screen.blit(image, (10, 10))
|
||||
screen.blit(blendimage, (200, 10))
|
||||
|
||||
pygame.display.flip()
|
||||
pygame.key.set_repeat(500, 30)
|
||||
usage()
|
||||
|
||||
going = True
|
||||
while going:
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
going = False
|
||||
|
||||
if event.type == pygame.KEYDOWN:
|
||||
usage()
|
||||
|
||||
if event.key == pygame.K_ESCAPE:
|
||||
going = False
|
||||
|
||||
if event.key == pygame.K_r:
|
||||
color[0] += step
|
||||
if color[0] > 255:
|
||||
color[0] = 0
|
||||
changed = True
|
||||
|
||||
elif event.key == pygame.K_g:
|
||||
color[1] += step
|
||||
if color[1] > 255:
|
||||
color[1] = 0
|
||||
changed = True
|
||||
|
||||
elif event.key == pygame.K_b:
|
||||
color[2] += step
|
||||
if color[2] > 255:
|
||||
color[2] = 0
|
||||
changed = True
|
||||
|
||||
elif event.key == pygame.K_a:
|
||||
blendtype = pygame.BLEND_ADD
|
||||
changed = True
|
||||
elif event.key == pygame.K_s:
|
||||
blendtype = pygame.BLEND_SUB
|
||||
changed = True
|
||||
elif event.key == pygame.K_m:
|
||||
blendtype = pygame.BLEND_MULT
|
||||
changed = True
|
||||
elif event.key == pygame.K_PLUS:
|
||||
blendtype = pygame.BLEND_MAX
|
||||
changed = True
|
||||
elif event.key == pygame.K_MINUS:
|
||||
blendtype = pygame.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):
|
||||
step = int(event.unicode)
|
||||
|
||||
if changed:
|
||||
screen.fill((100, 100, 100))
|
||||
screen.blit(image, (10, 10))
|
||||
blendimage.blit(image, (0, 0))
|
||||
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()
|
||||
|
||||
pygame.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,203 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.blit_blends
|
||||
|
||||
Blending colors in different ways with different blend modes.
|
||||
|
||||
It also shows some tricks with the surfarray.
|
||||
Including how to do additive blending.
|
||||
|
||||
|
||||
Keyboard Controls
|
||||
-----------------
|
||||
|
||||
* R, G, B - add a bit of Red, Green, or Blue.
|
||||
* A - Add blend mode
|
||||
* S - Subtractive blend mode
|
||||
* M - Multiply blend mode
|
||||
* = key BLEND_MAX blend mode.
|
||||
* - key BLEND_MIN blend mode.
|
||||
* 1, 2, 3, 4 - use different images.
|
||||
|
||||
"""
|
||||
|
||||
import os
|
||||
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
|
||||
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))
|
||||
|
||||
im1 = pygame.Surface(screen.get_size())
|
||||
# im1= im1.convert()
|
||||
im1.fill((100, 0, 0))
|
||||
|
||||
im2 = pygame.Surface(screen.get_size())
|
||||
im2.fill((0, 50, 0))
|
||||
# we make a srcalpha copy of it.
|
||||
# im3= im2.convert(SRCALPHA)
|
||||
im3 = im2
|
||||
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"))
|
||||
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
|
||||
|
||||
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"
|
||||
|
||||
screen.blit(im1, (0, 0))
|
||||
pygame.display.flip()
|
||||
clock = pygame.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:
|
||||
going = False
|
||||
if event.type == pygame.KEYDOWN:
|
||||
usage()
|
||||
|
||||
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
|
||||
going = False
|
||||
|
||||
elif event.type == pygame.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():
|
||||
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])
|
||||
t2 = time.time()
|
||||
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]:
|
||||
for bkey in blits.keys():
|
||||
t1 = time.time()
|
||||
|
||||
for x in range(300):
|
||||
im1.blit(img_to_blit, (0, 0), None, blits[bkey])
|
||||
|
||||
t2 = time.time()
|
||||
|
||||
# show which key we're doing...
|
||||
onedoing = blitsn[bkey]
|
||||
print(f"time to do :{onedoing}: is :{t2 - t1}:")
|
||||
|
||||
elif event.type == pygame.KEYDOWN and event.key in [pygame.K_o]:
|
||||
t1 = time.time()
|
||||
# blits is a dict keyed with key -> blit flag. eg BLEND_ADD.
|
||||
im1.blit(iaa, (0, 0))
|
||||
t2 = time.time()
|
||||
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:
|
||||
# this additive blend without clamp two surfaces.
|
||||
# im1.set_alpha(127)
|
||||
# im1.blit(im1, (0,0))
|
||||
# im1.set_alpha(255)
|
||||
t1 = time.time()
|
||||
|
||||
im1p = pygame.surfarray.pixels2d(im1)
|
||||
im2p = pygame.surfarray.pixels2d(im2)
|
||||
im1p += im2p
|
||||
del im1p
|
||||
del im2p
|
||||
t2 = time.time()
|
||||
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]:
|
||||
t1 = time.time()
|
||||
im1p = pygame.surfarray.pixels3d(im1)
|
||||
im2p = pygame.surfarray.pixels3d(im2)
|
||||
im1p16 = im1p.astype(numpy.uint16)
|
||||
im2p16 = im1p.astype(numpy.uint16)
|
||||
im1p16 += im2p16
|
||||
im1p16 = numpy.minimum(im1p16, 255)
|
||||
pygame.surfarray.blit_array(im1, im1p16)
|
||||
|
||||
del im1p
|
||||
del im2p
|
||||
t2 = time.time()
|
||||
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,
|
||||
]:
|
||||
# this adds one to each pixel.
|
||||
colmap = {}
|
||||
colmap[pygame.K_r] = 0x10000
|
||||
colmap[pygame.K_g] = 0x00100
|
||||
colmap[pygame.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:
|
||||
print("one pixel is:%s:" % [im1.get_at((0, 0))])
|
||||
|
||||
elif event.type == pygame.KEYDOWN and event.key == pygame.K_f:
|
||||
# this additive blend without clamp two surfaces.
|
||||
|
||||
t1 = time.time()
|
||||
im1.set_alpha(127)
|
||||
im1.blit(im2, (0, 0))
|
||||
im1.set_alpha(255)
|
||||
|
||||
t2 = time.time()
|
||||
print("one pixel is:%s:" % [im1.get_at((0, 0))])
|
||||
print(f"time to do:{t2 - t1}:")
|
||||
|
||||
screen.blit(im1, (0, 0))
|
||||
pygame.display.flip()
|
||||
|
||||
pygame.quit()
|
||||
|
||||
|
||||
def usage():
|
||||
print("press keys 1-5 to change image to blit.")
|
||||
print("A - ADD, S- SUB, M- MULT, - MIN, + MAX")
|
||||
print("T - timing test for special blend modes.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
usage()
|
||||
main()
|
||||
@@ -0,0 +1,124 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.camera
|
||||
|
||||
Basic image capturing and display using pygame.camera
|
||||
|
||||
Keyboard controls
|
||||
-----------------
|
||||
|
||||
- 0, start camera 0.
|
||||
- 1, start camera 1.
|
||||
- 9, start camera 9.
|
||||
- 10, start camera... wait a minute! There's not 10 key!
|
||||
"""
|
||||
|
||||
import pygame
|
||||
import pygame.camera
|
||||
|
||||
|
||||
class VideoCapturePlayer:
|
||||
size = (640, 480)
|
||||
|
||||
def __init__(self, **argd):
|
||||
self.__dict__.update(**argd)
|
||||
super().__init__(**argd)
|
||||
|
||||
# create a display surface. standard pygame stuff
|
||||
self.display = pygame.display.set_mode(self.size)
|
||||
self.init_cams(0)
|
||||
|
||||
def init_cams(self, which_cam_idx):
|
||||
# gets a list of available cameras.
|
||||
self.clist = pygame.camera.list_cameras()
|
||||
|
||||
# ensure a camera exists
|
||||
if not self.clist:
|
||||
raise ValueError("Sorry, no cameras detected.")
|
||||
|
||||
# check to see if the camera id exists. If not, default to the first one in the list.
|
||||
try:
|
||||
cam_id = self.clist[which_cam_idx]
|
||||
except IndexError:
|
||||
cam_id = self.clist[0]
|
||||
|
||||
# creates the camera of the specified size and in RGB colorspace
|
||||
self.camera = pygame.camera.Camera(cam_id, self.size, "RGB")
|
||||
|
||||
# starts the camera
|
||||
self.camera.start()
|
||||
|
||||
self.clock = pygame.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)
|
||||
# return the name of the camera being used, to be included in the window name
|
||||
return cam_id
|
||||
|
||||
def get_and_flip(self):
|
||||
# if you don't want to tie the framerate to the camera, you can check and
|
||||
# see if the camera has an image ready. note that while this works
|
||||
# on most cameras, some will never return true.
|
||||
|
||||
self.snapshot = self.camera.get_image(self.display)
|
||||
|
||||
# if 0 and self.camera.query_image():
|
||||
# # capture an image
|
||||
|
||||
# self.snapshot = self.camera.get_image(self.snapshot)
|
||||
|
||||
# if 0:
|
||||
# self.snapshot = self.camera.get_image(self.snapshot)
|
||||
# # self.snapshot = self.camera.get_image()
|
||||
|
||||
# # blit it to the display surface. simple!
|
||||
# self.display.blit(self.snapshot, (0, 0))
|
||||
# else:
|
||||
|
||||
# self.snapshot = self.camera.get_image(self.display)
|
||||
# # self.display.blit(self.snapshot, (0,0))
|
||||
|
||||
pygame.display.flip()
|
||||
|
||||
def main(self):
|
||||
# get the camera list. If there are no cameras, raise a value error.
|
||||
clist = pygame.camera.list_cameras()
|
||||
if not clist:
|
||||
raise ValueError("Sorry, no cameras detected.")
|
||||
# get the first camera, as this is the default. We want the display to contain the name of the camera.
|
||||
camera = clist[0]
|
||||
|
||||
# create a list of options for the user to easily understand.
|
||||
print(
|
||||
"\nPress the associated number for the desired camera to see that display!"
|
||||
)
|
||||
print("(Selecting a camera that does not exist will default to camera 0)")
|
||||
for index, cam in enumerate(clist):
|
||||
print(f"[{index}]: {cam}")
|
||||
|
||||
going = True
|
||||
while going:
|
||||
events = pygame.event.get()
|
||||
for e in events:
|
||||
if e.type == pygame.QUIT or (
|
||||
e.type == pygame.KEYDOWN and e.key == pygame.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)
|
||||
|
||||
self.get_and_flip()
|
||||
self.clock.tick()
|
||||
pygame.display.set_caption(f"{camera} ({self.clock.get_fps():.2f} FPS)")
|
||||
|
||||
|
||||
def main():
|
||||
pygame.init()
|
||||
pygame.camera.init()
|
||||
VideoCapturePlayer().main()
|
||||
pygame.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,200 @@
|
||||
#!/usr/bin/env python
|
||||
"""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.
|
||||
Note there are comments here, but for the full explanation,
|
||||
follow along in the tutorial.
|
||||
"""
|
||||
|
||||
# Import Modules
|
||||
import os
|
||||
|
||||
import pygame
|
||||
|
||||
if not pygame.font:
|
||||
print("Warning, fonts disabled")
|
||||
if not pygame.mixer:
|
||||
print("Warning, sound disabled")
|
||||
|
||||
main_dir = os.path.split(os.path.abspath(__file__))[0]
|
||||
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 = image.convert()
|
||||
|
||||
image = pygame.transform.scale_by(image, scale)
|
||||
|
||||
if colorkey is not None:
|
||||
if colorkey == -1:
|
||||
colorkey = image.get_at((0, 0))
|
||||
image.set_colorkey(colorkey, pygame.RLEACCEL)
|
||||
return image, image.get_rect()
|
||||
|
||||
|
||||
def load_sound(name):
|
||||
class NoneSound:
|
||||
def play(self):
|
||||
pass
|
||||
|
||||
if not pygame.mixer.get_init():
|
||||
return NoneSound()
|
||||
|
||||
fullname = os.path.join(data_dir, name)
|
||||
sound = pygame.mixer.Sound(fullname)
|
||||
|
||||
return sound
|
||||
|
||||
|
||||
# classes for our game objects
|
||||
class Fist(pygame.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)
|
||||
self.fist_offset = (-235, -80)
|
||||
self.punching = False
|
||||
|
||||
def update(self):
|
||||
"""move the fist based on the mouse position"""
|
||||
pos = pygame.mouse.get_pos()
|
||||
self.rect.topleft = pos
|
||||
self.rect.move_ip(self.fist_offset)
|
||||
if self.punching:
|
||||
self.rect.move_ip(15, 25)
|
||||
|
||||
def punch(self, target):
|
||||
"""returns true if the fist collides with the target"""
|
||||
if not self.punching:
|
||||
self.punching = True
|
||||
hitbox = self.rect.inflate(-5, -5)
|
||||
return hitbox.colliderect(target.rect)
|
||||
|
||||
def unpunch(self):
|
||||
"""called to pull the fist back"""
|
||||
self.punching = False
|
||||
|
||||
|
||||
class Chimp(pygame.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()
|
||||
self.area = screen.get_rect()
|
||||
self.rect.topleft = 10, 90
|
||||
self.move = 18
|
||||
self.dizzy = False
|
||||
|
||||
def update(self):
|
||||
"""walk or spin, depending on the monkeys state"""
|
||||
if self.dizzy:
|
||||
self._spin()
|
||||
else:
|
||||
self._walk()
|
||||
|
||||
def _walk(self):
|
||||
"""move the monkey across the screen, and turn at the ends"""
|
||||
newpos = self.rect.move((self.move, 0))
|
||||
if not self.area.contains(newpos):
|
||||
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.rect = newpos
|
||||
|
||||
def _spin(self):
|
||||
"""spin the monkey image"""
|
||||
center = self.rect.center
|
||||
self.dizzy = self.dizzy + 12
|
||||
if self.dizzy >= 360:
|
||||
self.dizzy = False
|
||||
self.image = self.original
|
||||
else:
|
||||
rotate = pygame.transform.rotate
|
||||
self.image = rotate(self.original, self.dizzy)
|
||||
self.rect = self.image.get_rect(center=center)
|
||||
|
||||
def punched(self):
|
||||
"""this will cause the monkey to start spinning"""
|
||||
if not self.dizzy:
|
||||
self.dizzy = True
|
||||
self.original = self.image
|
||||
|
||||
|
||||
def main():
|
||||
"""this function is called when the program starts.
|
||||
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)
|
||||
|
||||
# Create The Background
|
||||
background = pygame.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)
|
||||
|
||||
# Display The Background
|
||||
screen.blit(background, (0, 0))
|
||||
pygame.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()
|
||||
|
||||
# Main Loop
|
||||
going = True
|
||||
while going:
|
||||
clock.tick(60)
|
||||
|
||||
# Handle Input Events
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
going = False
|
||||
elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
|
||||
going = False
|
||||
elif event.type == pygame.MOUSEBUTTONDOWN:
|
||||
if fist.punch(chimp):
|
||||
punch_sound.play() # punch
|
||||
chimp.punched()
|
||||
else:
|
||||
whiff_sound.play() # miss
|
||||
elif event.type == pygame.MOUSEBUTTONUP:
|
||||
fist.unpunch()
|
||||
|
||||
all_sprites.update()
|
||||
|
||||
# Draw Everything
|
||||
screen.blit(background, (0, 0))
|
||||
all_sprites.draw(screen)
|
||||
pygame.display.flip()
|
||||
|
||||
pygame.quit()
|
||||
|
||||
|
||||
# Game Over
|
||||
|
||||
|
||||
# this calls the 'main' function when this script is executed
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,256 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.cursors
|
||||
Click a button and the cursor will change.
|
||||
This example will show you:
|
||||
*The different types of cursors that exist
|
||||
*How to create a cursor
|
||||
*How to set a cursor
|
||||
*How to make a simple button
|
||||
"""
|
||||
|
||||
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
|
||||
|
||||
|
||||
# Create a color cursor
|
||||
|
||||
surf = pygame.Surface((40, 40))
|
||||
surf.fill((120, 50, 50))
|
||||
color_cursor = pygame.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.get_width() // 2, image.get_height() // 2), image
|
||||
)
|
||||
|
||||
|
||||
# Create a bitmap cursor from simple strings
|
||||
|
||||
# sized 24x24
|
||||
thickarrow_strings = (
|
||||
"XX ",
|
||||
"XXX ",
|
||||
"XXXX ",
|
||||
"XX.XX ",
|
||||
"XX..XX ",
|
||||
"XX...XX ",
|
||||
"XX....XX ",
|
||||
"XX.....XX ",
|
||||
"XX......XX ",
|
||||
"XX.......XX ",
|
||||
"XX........XX ",
|
||||
"XX........XXX ",
|
||||
"XX......XXXXX ",
|
||||
"XX.XXX..XX ",
|
||||
"XXXX XX..XX ",
|
||||
"XX XX..XX ",
|
||||
" XX..XX ",
|
||||
" XX..XX ",
|
||||
" XX..XX ",
|
||||
" XXXX ",
|
||||
" XX ",
|
||||
" ",
|
||||
" ",
|
||||
" ",
|
||||
)
|
||||
|
||||
bitmap_cursor1 = pygame.cursors.Cursor(
|
||||
(24, 24),
|
||||
(0, 0),
|
||||
*pygame.cursors.compile(thickarrow_strings, black="X", white=".", xor="o"),
|
||||
)
|
||||
|
||||
|
||||
# Create a bitmap cursor from premade simple strings
|
||||
|
||||
bitmap_cursor2 = pygame.cursors.diamond
|
||||
|
||||
|
||||
# Calculate if mouse position is inside circle
|
||||
def check_circle(mouse_pos_x, mouse_pos_y, center_x, center_y, radius):
|
||||
return (mouse_pos_x - center_x) ** 2 + (mouse_pos_y - center_y) ** 2 < radius**2
|
||||
|
||||
|
||||
def main():
|
||||
pygame.init()
|
||||
pygame.display.set_caption("Cursors Example")
|
||||
|
||||
pygame.font.init()
|
||||
font = pygame.Font(None, 30)
|
||||
font1 = pygame.Font(None, 24)
|
||||
|
||||
bg = pygame.display.set_mode((500, 400))
|
||||
bg.fill((183, 201, 226))
|
||||
|
||||
# Initialize circles
|
||||
radius1 = 40
|
||||
radius2 = 40
|
||||
radius3 = 40
|
||||
radius4 = 40
|
||||
radius5 = 40
|
||||
radius6 = 40
|
||||
radius7 = 40
|
||||
|
||||
pos_x1 = 82
|
||||
pos_x2 = 138
|
||||
pos_x3 = 194
|
||||
pos_x4 = 250
|
||||
pos_x5 = 306
|
||||
pos_x6 = 362
|
||||
pos_x7 = 418
|
||||
|
||||
pos_y1 = 140
|
||||
pos_y2 = 220
|
||||
pos_y3 = 140
|
||||
pos_y4 = 220
|
||||
pos_y5 = 140
|
||||
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)
|
||||
|
||||
# Initialize button
|
||||
button_text = font1.render("Click here to change cursor", True, (0, 0, 0))
|
||||
button = pygame.draw.rect(
|
||||
bg,
|
||||
(180, 180, 180),
|
||||
(139, 300, button_text.get_width() + 5, button_text.get_height() + 50),
|
||||
)
|
||||
button_text_rect = button_text.get_rect(center=button.center)
|
||||
bg.blit(button_text, button_text_rect)
|
||||
|
||||
pygame.display.update()
|
||||
|
||||
cursors = [
|
||||
system_cursor1,
|
||||
color_cursor,
|
||||
system_cursor2,
|
||||
image_cursor,
|
||||
system_cursor3,
|
||||
bitmap_cursor1,
|
||||
bitmap_cursor2,
|
||||
]
|
||||
|
||||
index = 0
|
||||
pygame.mouse.set_cursor(cursors[index])
|
||||
|
||||
was_pressed = False
|
||||
clock = pygame.Clock()
|
||||
|
||||
while True:
|
||||
clock.tick(50)
|
||||
|
||||
mouse_x, mouse_y = pygame.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)
|
||||
else:
|
||||
circle1 = pygame.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)
|
||||
else:
|
||||
circle2 = pygame.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)
|
||||
else:
|
||||
circle3 = pygame.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)
|
||||
else:
|
||||
circle4 = pygame.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)
|
||||
else:
|
||||
circle5 = pygame.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)
|
||||
else:
|
||||
circle6 = pygame.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)
|
||||
else:
|
||||
circle7 = pygame.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)
|
||||
)
|
||||
text_rect1 = text1.get_rect(center=(bg.get_width() / 2, 40))
|
||||
bg.blit(text1, text_rect1)
|
||||
|
||||
button = pygame.draw.rect(
|
||||
bg,
|
||||
(100, 149, 240),
|
||||
(139, 300, button_text.get_width() + 5, button_text.get_height() + 50),
|
||||
)
|
||||
bg.blit(button_text, button_text_rect)
|
||||
|
||||
# Check if button was clicked and change cursor
|
||||
if button.collidepoint(mouse_x, mouse_y):
|
||||
button = pygame.draw.rect(
|
||||
bg,
|
||||
(60, 100, 255),
|
||||
(
|
||||
139,
|
||||
300,
|
||||
button_text.get_width() + 5,
|
||||
button_text.get_height() + 50,
|
||||
),
|
||||
)
|
||||
bg.blit(button_text, button_text_rect)
|
||||
|
||||
if pygame.mouse.get_pressed()[0] and not was_pressed:
|
||||
button = pygame.draw.rect(
|
||||
bg,
|
||||
(0, 0, 139),
|
||||
(
|
||||
139,
|
||||
300,
|
||||
button_text.get_width() + 5,
|
||||
button_text.get_height() + 50,
|
||||
),
|
||||
)
|
||||
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)
|
||||
|
||||
was_pressed = pygame.mouse.get_pressed()[0]
|
||||
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
pygame.quit()
|
||||
raise SystemExit
|
||||
|
||||
pygame.display.update()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
After Width: | Height: | Size: 244 B |
|
After Width: | Height: | Size: 3.7 KiB |
|
After Width: | Height: | Size: 3.0 KiB |
|
After Width: | Height: | Size: 3.4 KiB |
|
After Width: | Height: | Size: 3.7 KiB |
|
After Width: | Height: | Size: 3.4 KiB |
|
After Width: | Height: | Size: 3.7 KiB |
|
After Width: | Height: | Size: 3.4 KiB |
|
After Width: | Height: | Size: 39 KiB |
|
After Width: | Height: | Size: 38 KiB |
|
After Width: | Height: | Size: 578 B |
@@ -0,0 +1,7 @@
|
||||
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
|
||||
|
After Width: | Height: | Size: 8.9 KiB |
|
After Width: | Height: | Size: 84 B |
|
After Width: | Height: | Size: 1.1 KiB |
|
After Width: | Height: | Size: 170 B |
|
After Width: | Height: | Size: 622 B |
|
After Width: | Height: | Size: 143 B |
@@ -0,0 +1,5 @@
|
||||
P6
|
||||
# CREATOR: GIMP PNM Filter Version 1.1
|
||||
32 32
|
||||
255
|
||||
ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<ワ<
|
||||
|
After Width: | Height: | Size: 960 B |
|
After Width: | Height: | Size: 6.4 KiB |
|
After Width: | Height: | Size: 47 KiB |
|
After Width: | Height: | Size: 124 B |
|
After Width: | Height: | Size: 253 B |
|
After Width: | Height: | Size: 1.8 KiB |
|
After Width: | Height: | Size: 9.3 KiB |
|
After Width: | Height: | Size: 3.4 KiB |
@@ -0,0 +1,36 @@
|
||||
/* XPM */
|
||||
static char * C:\Users\Kristof\Documents\purple_xpm[] = {
|
||||
"32 32 1 1",
|
||||
" c #FF00FF",
|
||||
" ",
|
||||
" ",
|
||||
" ",
|
||||
" ",
|
||||
" ",
|
||||
" ",
|
||||
" ",
|
||||
" ",
|
||||
" ",
|
||||
" ",
|
||||
" ",
|
||||
" ",
|
||||
" ",
|
||||
" ",
|
||||
" ",
|
||||
" ",
|
||||
" ",
|
||||
" ",
|
||||
" ",
|
||||
" ",
|
||||
" ",
|
||||
" ",
|
||||
" ",
|
||||
" ",
|
||||
" ",
|
||||
" ",
|
||||
" ",
|
||||
" ",
|
||||
" ",
|
||||
" ",
|
||||
" ",
|
||||
" "};
|
||||
|
After Width: | Height: | Size: 1.2 KiB |
|
After Width: | Height: | Size: 82 B |
|
After Width: | Height: | Size: 129 B |
|
After Width: | Height: | Size: 580 B |
@@ -0,0 +1,9 @@
|
||||
<svg width="32" height="32" xmlns="http://www.w3.org/2000/svg">
|
||||
<title>teal</title>
|
||||
|
||||
<g>
|
||||
<title>Layer 1</title>
|
||||
<rect fill="#fff" stroke="#000" x="0" y="0" width="32" height="32" id="svg_1"/>
|
||||
<rect stroke-width="0" id="svg_2" height="32" width="32" y="0" x="0" stroke="#000" fill="#008080"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 313 B |
|
After Width: | Height: | Size: 3.0 KiB |
@@ -0,0 +1,79 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.dropfile
|
||||
|
||||
Drag and drop an image on here.
|
||||
|
||||
Uses these events:
|
||||
|
||||
* DROPBEGIN
|
||||
* DROPCOMPLETE
|
||||
* DROPTEXT
|
||||
* DROPFILE
|
||||
"""
|
||||
|
||||
import pygame
|
||||
|
||||
pygame.init()
|
||||
|
||||
|
||||
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()
|
||||
|
||||
spr_file_text = font.render("Feed me some file or image!", True, (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)
|
||||
print("File drop begin!")
|
||||
elif event.type == pygame.DROPCOMPLETE:
|
||||
print(event)
|
||||
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
|
||||
)
|
||||
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
|
||||
)
|
||||
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:]
|
||||
if filetype in ["png", "bmp", "jpg"]:
|
||||
spr_file_image = pygame.image.load(event.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:
|
||||
surf.blit(spr_file_image, spr_file_image_rect)
|
||||
|
||||
pygame.display.flip()
|
||||
clock.tick(30)
|
||||
|
||||
pygame.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,183 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.eventlist
|
||||
|
||||
Learn about pygame events and input.
|
||||
|
||||
At the top of the screen are the state of several device values,
|
||||
and a scrolling list of events are displayed on the bottom.
|
||||
|
||||
"""
|
||||
|
||||
usage = """
|
||||
Mouse Controls
|
||||
==============
|
||||
|
||||
- 1st button on mouse (left click) to toggle events 'grabbed'.
|
||||
- 3rd button on mouse (right click) to toggle mouse visible.
|
||||
- The window can be resized.
|
||||
- Mouse the mouse around to see mouse events.
|
||||
- If events grabbed and mouse invisible show virtual mouse coords.
|
||||
|
||||
|
||||
Keyboard Joystick Controls
|
||||
==========================
|
||||
|
||||
- press keys up an down to see events.
|
||||
- you can see joystick events if any are plugged in.
|
||||
"""
|
||||
|
||||
import pygame
|
||||
|
||||
try:
|
||||
import pygame._sdl2.controller
|
||||
|
||||
pygame._sdl2.controller.init()
|
||||
SDL2 = True
|
||||
except ImportError:
|
||||
SDL2 = False
|
||||
|
||||
img_on_off = []
|
||||
font = None
|
||||
last_key = None
|
||||
|
||||
# these are a running counter of mouse.get_rel() calls.
|
||||
virtual_x = 0
|
||||
virtual_y = 0
|
||||
|
||||
|
||||
def showtext(win, pos, text, color, bgcolor):
|
||||
textimg = font.render(text, 1, color, bgcolor)
|
||||
win.blit(textimg, pos)
|
||||
return pos[0] + textimg.get_width() + 5, pos[1]
|
||||
|
||||
|
||||
def drawstatus(win):
|
||||
global virtual_x, virtual_y
|
||||
bgcolor = 50, 50, 50
|
||||
win.fill(bgcolor, (0, 0, 640, 120))
|
||||
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)
|
||||
|
||||
pos = showtext(
|
||||
win, (pos[0] + 50, pos[1]), "Mouse visible", (255, 255, 255), bgcolor
|
||||
)
|
||||
win.blit(img_on_off[pygame.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)
|
||||
|
||||
pos = showtext(win, (10, 60), "Mouse Position(rel)", (255, 255, 255), bgcolor)
|
||||
rel = pygame.mouse.get_rel()
|
||||
virtual_x += rel[0]
|
||||
virtual_y += rel[1]
|
||||
|
||||
mouse_data = tuple(list(pygame.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))
|
||||
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)
|
||||
|
||||
is_virtual_mouse = pygame.event.get_grab() and not pygame.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:
|
||||
p = f"{virtual_x}, {virtual_y}"
|
||||
showtext(win, (pos[0] + 50, pos[1]), p, bgcolor, (255, 255, 55))
|
||||
|
||||
|
||||
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))
|
||||
|
||||
|
||||
def draw_usage_in_history(history, text):
|
||||
for line in text.split("\n"):
|
||||
if "===" not in line and line != "":
|
||||
history.append(line)
|
||||
|
||||
|
||||
def main():
|
||||
pygame.init()
|
||||
print(usage)
|
||||
|
||||
win = pygame.display.set_mode((640, 480), pygame.RESIZABLE)
|
||||
pygame.display.set_caption("Mouse Focus Workout. h key for help")
|
||||
|
||||
global font
|
||||
font = pygame.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
|
||||
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):
|
||||
c = pygame._sdl2.controller.Controller(x)
|
||||
txt = f"Enabled controller: {c.name}"
|
||||
else:
|
||||
j = pygame.joystick.Joystick(x)
|
||||
txt = f"Enabled joystick: {j.get_name()}"
|
||||
|
||||
history.append(txt)
|
||||
|
||||
if not pygame.joystick.get_count():
|
||||
history.append("No Joysticks to Initialize")
|
||||
|
||||
going = True
|
||||
while going:
|
||||
for e in pygame.event.get():
|
||||
if e.type == pygame.KEYDOWN:
|
||||
if e.key == pygame.K_ESCAPE:
|
||||
going = False
|
||||
else:
|
||||
global last_key
|
||||
last_key = e.key
|
||||
if e.key == pygame.K_h:
|
||||
draw_usage_in_history(history, usage)
|
||||
|
||||
if e.type == pygame.MOUSEBUTTONDOWN and e.button == 1:
|
||||
pygame.event.set_grab(not pygame.event.get_grab())
|
||||
|
||||
if e.type == pygame.MOUSEBUTTONDOWN and e.button == 3:
|
||||
pygame.mouse.set_visible(not pygame.mouse.get_visible())
|
||||
|
||||
if e.type != pygame.MOUSEMOTION:
|
||||
txt = f"{pygame.event.event_name(e.type)}: {e.dict}"
|
||||
history.append(txt)
|
||||
history = history[-13:]
|
||||
|
||||
if e.type == pygame.VIDEORESIZE:
|
||||
win = pygame.display.set_mode(e.size, pygame.RESIZABLE)
|
||||
|
||||
if e.type == pygame.QUIT:
|
||||
going = False
|
||||
|
||||
drawstatus(win)
|
||||
drawhistory(win, history)
|
||||
|
||||
pygame.display.flip()
|
||||
pygame.time.wait(10)
|
||||
|
||||
pygame.quit()
|
||||
raise SystemExit
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,286 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.font_viewer
|
||||
Scroll through your system fonts from a list of surfaces or one huge buffer.
|
||||
|
||||
This example exhibits:
|
||||
* iterate over available fonts using font.get_fonts and font.SysFont()
|
||||
* click and drag using mouse input
|
||||
* scrolling with the scroll wheel
|
||||
* save a surface to disk
|
||||
* work with a very large surface
|
||||
* simple mouse and keyboard scroll speed acceleration
|
||||
|
||||
By default this example uses the fonts returned by pygame.font.get_fonts()
|
||||
and opens them using pygame.font.SysFont().
|
||||
Alternatively, you may pass a path to the command line. The TTF files found
|
||||
in that directory will be used instead.
|
||||
|
||||
Mouse Controls:
|
||||
* Use the mouse wheel or click and drag to scroll
|
||||
|
||||
Keyboard Controls:
|
||||
* Press up or down to scroll
|
||||
* Press escape to exit
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
import pygame
|
||||
|
||||
use_big_surface = False # draw into large buffer and save png file
|
||||
|
||||
|
||||
class FontViewer:
|
||||
"""
|
||||
This example is encapsulated by the fontviewer class
|
||||
It initializes the pygame window, handles input, and draws itself
|
||||
to the screen.
|
||||
"""
|
||||
|
||||
KEY_SCROLL_SPEED = 10
|
||||
MOUSE_SCROLL_SPEED = 50
|
||||
|
||||
def __init__(self):
|
||||
pygame.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
|
||||
|
||||
self.clock = pygame.Clock()
|
||||
self.y_offset = 0
|
||||
self.grabbed = False
|
||||
self.render_fonts("&N abcDEF789")
|
||||
|
||||
if use_big_surface or "big" in sys.argv:
|
||||
self.render_surface()
|
||||
self.display_surface()
|
||||
self.save_png()
|
||||
else:
|
||||
self.display_fonts()
|
||||
|
||||
def get_font_list(self):
|
||||
"""
|
||||
Generate a font list using font.get_fonts() for system fonts or
|
||||
from a path from the command line.
|
||||
"""
|
||||
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
|
||||
|
||||
def render_fonts(self, text="A display of font &N"):
|
||||
"""
|
||||
Build a list that includes a surface and the running total of their
|
||||
height for each font in the font list. Store the largest width and
|
||||
other variables for later use.
|
||||
"""
|
||||
font_size = self.font_size
|
||||
color = (255, 255, 255)
|
||||
instruction_color = (255, 255, 0)
|
||||
self.back_color = (0, 0, 0)
|
||||
|
||||
fonts, path = self.get_font_list()
|
||||
font_surfaces = []
|
||||
total_height = 0
|
||||
max_width = 0
|
||||
|
||||
load_font = pygame.Font if path else pygame.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"
|
||||
)
|
||||
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())
|
||||
|
||||
# render all the fonts and store them with the total height
|
||||
for name in sorted(fonts):
|
||||
try:
|
||||
font = load_font(path + name, font_size)
|
||||
except OSError:
|
||||
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:
|
||||
print(e)
|
||||
break
|
||||
|
||||
max_width = max(max_width, surf.get_width())
|
||||
font_surfaces.append((surf, total_height))
|
||||
total_height += surf.get_height()
|
||||
|
||||
# store variables for later usage
|
||||
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()
|
||||
|
||||
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()
|
||||
center = display.get_width() // 2
|
||||
|
||||
while True:
|
||||
# draw visible surfaces
|
||||
display.fill(self.back_color)
|
||||
for surface, top in self.font_surfaces:
|
||||
bottom = top + surface.get_height()
|
||||
if (
|
||||
bottom >= self.y_offset
|
||||
and top <= self.y_offset + display.get_height()
|
||||
):
|
||||
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()
|
||||
clock.tick(30)
|
||||
|
||||
def render_surface(self):
|
||||
"""
|
||||
Note: this method uses twice the memory and is only called if
|
||||
big_surface is set to true or big is added to the command line.
|
||||
|
||||
Optionally generates one large buffer to draw all the font surfaces
|
||||
into. This is necessary to save the display to a png file and may
|
||||
be useful for testing large surfaces.
|
||||
"""
|
||||
|
||||
large_surface = pygame.surface.Surface(
|
||||
(self.max_width, self.total_height)
|
||||
).convert()
|
||||
large_surface.fill(self.back_color)
|
||||
print("scrolling surface created")
|
||||
|
||||
# display the surface size and memory usage
|
||||
byte_size = large_surface.get_bytesize()
|
||||
total_size = byte_size * (self.max_width * self.total_height)
|
||||
print(
|
||||
"Surface Size = {}x{} @ {}bpp: {:,.3f}mb".format(
|
||||
self.max_width, self.total_height, byte_size, total_size / 1000000.0
|
||||
)
|
||||
)
|
||||
|
||||
y = 0
|
||||
center = int(self.max_width / 2)
|
||||
for surface, top in self.font_surfaces:
|
||||
w = surface.get_width()
|
||||
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.surface = large_surface
|
||||
|
||||
def display_surface(self, time=10):
|
||||
"""
|
||||
Display the large surface created by the render_surface method. Scrolls
|
||||
based on the y_offset value(set in handle_events) and the height of the
|
||||
pygame window.
|
||||
"""
|
||||
screen = pygame.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(
|
||||
0,
|
||||
0,
|
||||
self.surface.get_width(),
|
||||
min(self.surface.get_height(), screen.get_height()),
|
||||
)
|
||||
|
||||
x = int((screen.get_width() - self.surface.get_width()) / 2)
|
||||
going = True
|
||||
while going:
|
||||
if not self.handle_events():
|
||||
going = False
|
||||
screen.fill(self.back_color)
|
||||
rect.top = self.y_offset
|
||||
screen.blit(self.surface, (x, 0), rect)
|
||||
pygame.display.flip()
|
||||
self.clock.tick(20)
|
||||
|
||||
def save_png(self, name="font_viewer.png"):
|
||||
pygame.image.save(self.surface, name)
|
||||
file_size = os.path.getsize(name) // 1024
|
||||
print(f"font surface saved to {name}\nsize: {file_size:,}Kb")
|
||||
|
||||
def handle_events(self):
|
||||
"""
|
||||
This method handles user input. It returns False when it receives
|
||||
a pygame.QUIT event or the user presses escape. The y_offset is
|
||||
changed based on mouse and keyboard input. display_fonts() and
|
||||
display_surface() use the y_offset to scroll display.
|
||||
"""
|
||||
events = pygame.event.get()
|
||||
for e in events:
|
||||
if e.type == pygame.QUIT:
|
||||
return False
|
||||
elif e.type == pygame.KEYDOWN:
|
||||
if e.key == pygame.K_ESCAPE:
|
||||
return False
|
||||
elif e.type == pygame.MOUSEWHEEL:
|
||||
self.y_offset += e.y * self.MOUSE_SCROLL_SPEED * -1
|
||||
elif e.type == pygame.MOUSEBUTTONDOWN:
|
||||
# enter dragging mode on mouse down
|
||||
self.grabbed = True
|
||||
pygame.event.set_grab(True)
|
||||
elif e.type == pygame.MOUSEBUTTONUP:
|
||||
# exit drag mode on mouse up
|
||||
self.grabbed = False
|
||||
pygame.event.set_grab(False)
|
||||
|
||||
# allow simple accelerated scrolling with the keyboard
|
||||
keys = pygame.key.get_pressed()
|
||||
if keys[pygame.K_UP]:
|
||||
self.key_held += 1
|
||||
self.y_offset -= int(self.KEY_SCROLL_SPEED * (self.key_held // 10))
|
||||
elif keys[pygame.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]
|
||||
if y and self.grabbed:
|
||||
self.y_offset -= y
|
||||
|
||||
self.y_offset = min((max(self.y_offset, 0), self.max_y))
|
||||
return True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
viewer = FontViewer()
|
||||
pygame.quit()
|
||||
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.fonty
|
||||
|
||||
Here we load a .TTF True Type font file, and display it in
|
||||
a basic pygame window.
|
||||
|
||||
Demonstrating several Font object attributes.
|
||||
|
||||
- basic window, event, and font management.
|
||||
"""
|
||||
|
||||
import pygame
|
||||
|
||||
|
||||
def main():
|
||||
# initialize
|
||||
pygame.init()
|
||||
resolution = 400, 200
|
||||
screen = pygame.display.set_mode(resolution)
|
||||
|
||||
## pygame.mouse.set_cursor(*pygame.cursors.diamond)
|
||||
|
||||
fg = 250, 240, 230
|
||||
bg = 5, 5, 5
|
||||
wincolor = 40, 40, 90
|
||||
|
||||
# fill background
|
||||
screen.fill(wincolor)
|
||||
|
||||
# load font, prepare values
|
||||
font = pygame.Font(None, 80)
|
||||
text = "Fonty"
|
||||
size = font.size(text)
|
||||
|
||||
# no AA, no transparency, normal
|
||||
ren = font.render(text, 0, fg, bg)
|
||||
screen.blit(ren, (10, 10))
|
||||
|
||||
# no AA, transparency, underline
|
||||
font.set_underline(1)
|
||||
ren = font.render(text, 0, fg)
|
||||
screen.blit(ren, (10, 40 + size[1]))
|
||||
font.set_underline(0)
|
||||
|
||||
a_sys_font = pygame.font.SysFont("Arial", 60)
|
||||
|
||||
# AA, no transparency, bold
|
||||
a_sys_font.set_bold(1)
|
||||
ren = a_sys_font.render(text, 1, fg, bg)
|
||||
screen.blit(ren, (30 + size[0], 10))
|
||||
a_sys_font.set_bold(0)
|
||||
|
||||
# AA, transparency, italic
|
||||
a_sys_font.set_italic(1)
|
||||
ren = a_sys_font.render(text, 1, fg)
|
||||
screen.blit(ren, (30 + size[0], 40 + size[1]))
|
||||
a_sys_font.set_italic(0)
|
||||
|
||||
# Get some metrics.
|
||||
print(f"Font metrics for 'Fonty': {a_sys_font.metrics(text)}")
|
||||
ch = "\u3060"
|
||||
msg = f"Font metrics for '{ch}': {a_sys_font.metrics(ch)}"
|
||||
print(msg)
|
||||
|
||||
## #some_japanese_unicode = u"\u304b\u3070\u306b"
|
||||
##some_japanese_unicode = unicode_('%c%c%c') % (0x304b, 0x3070, 0x306b)
|
||||
|
||||
# AA, transparency, italic
|
||||
##ren = a_sys_font.render(some_japanese_unicode, 1, fg)
|
||||
##screen.blit(ren, (30 + size[0], 40 + size[1]))
|
||||
|
||||
# show the surface and await user quit
|
||||
pygame.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,
|
||||
):
|
||||
break
|
||||
pygame.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,163 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.freetype_misc
|
||||
|
||||
|
||||
Miscellaneous (or misc) means:
|
||||
"consisting of a mixture of various things that are not
|
||||
usually connected with each other"
|
||||
Adjective
|
||||
|
||||
|
||||
All those words you read on computers, magazines, books, and such over the years?
|
||||
Probably a lot of them were constructed with...
|
||||
|
||||
The FreeType Project: a free, high-quality and portable Font engine.
|
||||
https://freetype.org
|
||||
|
||||
Next time you're reading something. Think of them.
|
||||
|
||||
|
||||
Herein lies a *BOLD* demo consisting of a mixture of various things.
|
||||
|
||||
Not only is it a *BOLD* demo, it's an
|
||||
italics demo,
|
||||
a rotated demo,
|
||||
it's a blend,
|
||||
and is sized to go nicely with a cup of tea*.
|
||||
|
||||
* also goes well with coffee.
|
||||
|
||||
Enjoy!
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
import pygame
|
||||
import pygame.freetype as freetype
|
||||
|
||||
|
||||
def run():
|
||||
pygame.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.fill("gray")
|
||||
|
||||
font.underline_adjustment = 0.5
|
||||
font.pad = True
|
||||
font.render_to(
|
||||
screen,
|
||||
(32, 32),
|
||||
"Hello World",
|
||||
"red3",
|
||||
"dimgray",
|
||||
size=64,
|
||||
style=freetype.STYLE_UNDERLINE | freetype.STYLE_OBLIQUE,
|
||||
)
|
||||
font.pad = False
|
||||
|
||||
font.render_to(
|
||||
screen,
|
||||
(32, 128),
|
||||
"abcdefghijklm",
|
||||
"dimgray",
|
||||
"green3",
|
||||
size=64,
|
||||
)
|
||||
|
||||
font.vertical = True
|
||||
font.render_to(screen, (32, 200), "Vertical?", "blue3", None, size=32)
|
||||
font.vertical = False
|
||||
|
||||
font.render_to(screen, (64, 190), "Let's spin!", "red3", None, size=48, rotation=55)
|
||||
|
||||
font.render_to(
|
||||
screen, (160, 290), "All around!", "green3", None, size=48, rotation=-55
|
||||
)
|
||||
|
||||
font.render_to(screen, (250, 220), "and BLEND", (255, 0, 0, 128), None, size=64)
|
||||
|
||||
font.render_to(screen, (265, 237), "or BLAND!", (0, 0xCC, 28, 128), None, size=64)
|
||||
|
||||
# Some pinwheels
|
||||
font.origin = True
|
||||
for angle in range(0, 360, 45):
|
||||
font.render_to(screen, (150, 420), ")", "black", size=48, rotation=angle)
|
||||
font.vertical = True
|
||||
for angle in range(15, 375, 30):
|
||||
font.render_to(screen, (600, 400), "|^*", "orange", size=48, rotation=angle)
|
||||
font.vertical = False
|
||||
font.origin = False
|
||||
|
||||
utext = "I \u2665 Unicode"
|
||||
font.render_to(screen, (298, 320), utext, (0, 0xCC, 0xDD), None, size=64)
|
||||
|
||||
utext = "\u2665"
|
||||
font.render_to(screen, (480, 32), utext, "gray", "red3", size=148)
|
||||
|
||||
font.render_to(
|
||||
screen,
|
||||
(380, 380),
|
||||
"...yes, this is an SDL surface",
|
||||
"black",
|
||||
None,
|
||||
size=24,
|
||||
style=freetype.STYLE_STRONG,
|
||||
)
|
||||
|
||||
font.origin = True
|
||||
r = font.render_to(
|
||||
screen,
|
||||
(100, 530),
|
||||
"stretch",
|
||||
"red3",
|
||||
None,
|
||||
size=(24, 24),
|
||||
style=freetype.STYLE_NORMAL,
|
||||
)
|
||||
font.render_to(
|
||||
screen,
|
||||
(100 + r.width, 530),
|
||||
" VERTICAL",
|
||||
"red3",
|
||||
None,
|
||||
size=(24, 48),
|
||||
style=freetype.STYLE_NORMAL,
|
||||
)
|
||||
|
||||
r = font.render_to(
|
||||
screen,
|
||||
(100, 580),
|
||||
"stretch",
|
||||
"blue3",
|
||||
None,
|
||||
size=(24, 24),
|
||||
style=freetype.STYLE_NORMAL,
|
||||
)
|
||||
font.render_to(
|
||||
screen,
|
||||
(100 + r.width, 580),
|
||||
" HORIZONTAL",
|
||||
"blue3",
|
||||
None,
|
||||
size=(48, 24),
|
||||
style=freetype.STYLE_NORMAL,
|
||||
)
|
||||
|
||||
pygame.display.flip()
|
||||
|
||||
while True:
|
||||
if pygame.event.wait().type in (
|
||||
pygame.QUIT,
|
||||
pygame.KEYDOWN,
|
||||
pygame.MOUSEBUTTONDOWN,
|
||||
):
|
||||
break
|
||||
|
||||
pygame.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run()
|
||||
@@ -0,0 +1,607 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.glcube
|
||||
|
||||
Draw a cube on the screen.
|
||||
|
||||
|
||||
|
||||
Amazing.
|
||||
|
||||
Every frame we orbit the camera around a small amount
|
||||
creating the illusion of a spinning object.
|
||||
|
||||
First we setup some points of a multicolored cube. Then we then go through
|
||||
a semi-unoptimized loop to draw the cube points onto the screen.
|
||||
|
||||
OpenGL does all the hard work for us. :]
|
||||
|
||||
|
||||
Keyboard Controls
|
||||
-----------------
|
||||
|
||||
* ESCAPE key to quit
|
||||
* f key to toggle fullscreen.
|
||||
|
||||
"""
|
||||
|
||||
import ctypes
|
||||
import math
|
||||
|
||||
import pygame
|
||||
|
||||
try:
|
||||
import OpenGL.GL as GL
|
||||
import OpenGL.GLU as GLU
|
||||
except ImportError:
|
||||
print("pyopengl missing. The GLCUBE example requires: pyopengl numpy")
|
||||
raise SystemExit
|
||||
|
||||
try:
|
||||
from numpy import array, dot, eye, float32, uint32, zeros
|
||||
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
|
||||
|
||||
# Some simple data for a colored cube here we have the 3D point position
|
||||
# and color for each corner. A list of indices describes each face, and a
|
||||
# list of indices describes each edge.
|
||||
|
||||
CUBE_POINTS = (
|
||||
(0.5, -0.5, -0.5),
|
||||
(0.5, 0.5, -0.5),
|
||||
(-0.5, 0.5, -0.5),
|
||||
(-0.5, -0.5, -0.5),
|
||||
(0.5, -0.5, 0.5),
|
||||
(0.5, 0.5, 0.5),
|
||||
(-0.5, -0.5, 0.5),
|
||||
(-0.5, 0.5, 0.5),
|
||||
)
|
||||
|
||||
# colors are 0-1 floating values
|
||||
CUBE_COLORS = (
|
||||
(1, 0, 0),
|
||||
(1, 1, 0),
|
||||
(0, 1, 0),
|
||||
(0, 0, 0),
|
||||
(1, 0, 1),
|
||||
(1, 1, 1),
|
||||
(0, 0, 1),
|
||||
(0, 1, 1),
|
||||
)
|
||||
|
||||
CUBE_QUAD_VERTS = (
|
||||
(0, 1, 2, 3),
|
||||
(3, 2, 7, 6),
|
||||
(6, 7, 5, 4),
|
||||
(4, 5, 1, 0),
|
||||
(1, 5, 7, 2),
|
||||
(4, 0, 3, 6),
|
||||
)
|
||||
|
||||
CUBE_EDGES = (
|
||||
(0, 1),
|
||||
(0, 3),
|
||||
(0, 4),
|
||||
(2, 1),
|
||||
(2, 3),
|
||||
(2, 7),
|
||||
(6, 3),
|
||||
(6, 4),
|
||||
(6, 7),
|
||||
(5, 1),
|
||||
(5, 4),
|
||||
(5, 7),
|
||||
)
|
||||
|
||||
|
||||
def translate(matrix, x=0.0, y=0.0, z=0.0):
|
||||
"""
|
||||
Translate (move) a matrix in the x, y and z axes.
|
||||
|
||||
:param matrix: Matrix to translate.
|
||||
:param x: direction and magnitude to translate in x axis. Defaults to 0.
|
||||
:param y: direction and magnitude to translate in y axis. Defaults to 0.
|
||||
:param z: direction and magnitude to translate in z axis. Defaults to 0.
|
||||
:return: The translated matrix.
|
||||
"""
|
||||
translation_matrix = array(
|
||||
[
|
||||
[1.0, 0.0, 0.0, x],
|
||||
[0.0, 1.0, 0.0, y],
|
||||
[0.0, 0.0, 1.0, z],
|
||||
[0.0, 0.0, 0.0, 1.0],
|
||||
],
|
||||
dtype=matrix.dtype,
|
||||
).T
|
||||
matrix[...] = dot(matrix, translation_matrix)
|
||||
return matrix
|
||||
|
||||
|
||||
def frustum(left, right, bottom, top, znear, zfar):
|
||||
"""
|
||||
Build a perspective matrix from the clipping planes, or camera 'frustrum'
|
||||
volume.
|
||||
|
||||
:param left: left position of the near clipping plane.
|
||||
:param right: right position of the near clipping plane.
|
||||
:param bottom: bottom position of the near clipping plane.
|
||||
:param top: top position of the near clipping plane.
|
||||
:param znear: z depth of the near clipping plane.
|
||||
:param zfar: z depth of the far clipping plane.
|
||||
|
||||
:return: A perspective matrix.
|
||||
"""
|
||||
perspective_matrix = zeros((4, 4), dtype=float32)
|
||||
perspective_matrix[0, 0] = +2.0 * znear / (right - left)
|
||||
perspective_matrix[2, 0] = (right + left) / (right - left)
|
||||
perspective_matrix[1, 1] = +2.0 * znear / (top - bottom)
|
||||
perspective_matrix[3, 1] = (top + bottom) / (top - bottom)
|
||||
perspective_matrix[2, 2] = -(zfar + znear) / (zfar - znear)
|
||||
perspective_matrix[3, 2] = -2.0 * znear * zfar / (zfar - znear)
|
||||
perspective_matrix[2, 3] = -1.0
|
||||
return perspective_matrix
|
||||
|
||||
|
||||
def perspective(fovy, aspect, znear, zfar):
|
||||
"""
|
||||
Build a perspective matrix from field of view, aspect ratio and depth
|
||||
planes.
|
||||
|
||||
:param fovy: the field of view angle in the y axis.
|
||||
:param aspect: aspect ratio of our view port.
|
||||
:param znear: z depth of the near clipping plane.
|
||||
:param zfar: z depth of the far clipping plane.
|
||||
|
||||
:return: A perspective matrix.
|
||||
"""
|
||||
h = math.tan(fovy / 360.0 * math.pi) * znear
|
||||
w = h * aspect
|
||||
return frustum(-w, w, -h, h, znear, zfar)
|
||||
|
||||
|
||||
def rotate(matrix, angle, x, y, z):
|
||||
"""
|
||||
Rotate a matrix around an axis.
|
||||
|
||||
:param matrix: The matrix to rotate.
|
||||
:param angle: The angle to rotate by.
|
||||
:param x: x of axis to rotate around.
|
||||
:param y: y of axis to rotate around.
|
||||
:param z: z of axis to rotate around.
|
||||
|
||||
:return: The rotated matrix
|
||||
"""
|
||||
angle = math.pi * angle / 180
|
||||
c, s = math.cos(angle), math.sin(angle)
|
||||
n = math.sqrt(x * x + y * y + z * z)
|
||||
x, y, z = x / n, y / n, z / n
|
||||
cx, cy, cz = (1 - c) * x, (1 - c) * y, (1 - c) * z
|
||||
rotation_matrix = array(
|
||||
[
|
||||
[cx * x + c, cy * x - z * s, cz * x + y * s, 0],
|
||||
[cx * y + z * s, cy * y + c, cz * y - x * s, 0],
|
||||
[cx * z - y * s, cy * z + x * s, cz * z + c, 0],
|
||||
[0, 0, 0, 1],
|
||||
],
|
||||
dtype=matrix.dtype,
|
||||
).T
|
||||
matrix[...] = dot(matrix, rotation_matrix)
|
||||
return matrix
|
||||
|
||||
|
||||
class Rotation:
|
||||
"""
|
||||
Data class that stores rotation angles in three axes.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.theta = 20
|
||||
self.phi = 40
|
||||
self.psi = 25
|
||||
|
||||
|
||||
def drawcube_old():
|
||||
"""
|
||||
Draw the cube using the old open GL methods pre 3.2 core context.
|
||||
"""
|
||||
allpoints = list(zip(CUBE_POINTS, CUBE_COLORS))
|
||||
|
||||
GL.glBegin(GL.GL_QUADS)
|
||||
for face in CUBE_QUAD_VERTS:
|
||||
for vert in face:
|
||||
pos, color = allpoints[vert]
|
||||
GL.glColor3fv(color)
|
||||
GL.glVertex3fv(pos)
|
||||
GL.glEnd()
|
||||
|
||||
GL.glColor3f(1.0, 1.0, 1.0)
|
||||
GL.glBegin(GL.GL_LINES)
|
||||
for line in CUBE_EDGES:
|
||||
for vert in line:
|
||||
pos, color = allpoints[vert]
|
||||
GL.glVertex3fv(pos)
|
||||
|
||||
GL.glEnd()
|
||||
|
||||
|
||||
def init_gl_stuff_old():
|
||||
"""
|
||||
Initialise open GL, prior to core context 3.2
|
||||
"""
|
||||
GL.glEnable(GL.GL_DEPTH_TEST) # use our zbuffer
|
||||
|
||||
# setup the camera
|
||||
GL.glMatrixMode(GL.GL_PROJECTION)
|
||||
GL.glLoadIdentity()
|
||||
GLU.gluPerspective(45.0, 640 / 480.0, 0.1, 100.0) # setup lens
|
||||
GL.glTranslatef(0.0, 0.0, -3.0) # move back
|
||||
GL.glRotatef(25, 1, 0, 0) # orbit higher
|
||||
|
||||
|
||||
def init_gl_modern(display_size):
|
||||
"""
|
||||
Initialise open GL in the 'modern' open GL style for open GL versions
|
||||
greater than 3.1.
|
||||
|
||||
:param display_size: Size of the window/viewport.
|
||||
"""
|
||||
|
||||
# Create shaders
|
||||
# --------------------------------------
|
||||
vertex_code = """
|
||||
|
||||
#version 150
|
||||
uniform mat4 model;
|
||||
uniform mat4 view;
|
||||
uniform mat4 projection;
|
||||
|
||||
uniform vec4 color_mul;
|
||||
uniform vec4 color_add;
|
||||
|
||||
in vec4 vertex_color; // vertex color in
|
||||
in vec3 vertex_position;
|
||||
|
||||
out vec4 vertex_color_out; // vertex color out
|
||||
void main()
|
||||
{
|
||||
vertex_color_out = (color_mul * vertex_color) + color_add;
|
||||
gl_Position = projection * view * model * vec4(vertex_position, 1.0);
|
||||
}
|
||||
|
||||
"""
|
||||
|
||||
fragment_code = """
|
||||
#version 150
|
||||
in vec4 vertex_color_out; // vertex color from vertex shader
|
||||
out vec4 fragColor;
|
||||
void main()
|
||||
{
|
||||
fragColor = vertex_color_out;
|
||||
}
|
||||
"""
|
||||
|
||||
program = GL.glCreateProgram()
|
||||
vertex = GL.glCreateShader(GL.GL_VERTEX_SHADER)
|
||||
fragment = GL.glCreateShader(GL.GL_FRAGMENT_SHADER)
|
||||
GL.glShaderSource(vertex, vertex_code)
|
||||
GL.glCompileShader(vertex)
|
||||
|
||||
# this logs issues the shader compiler finds.
|
||||
log = GL.glGetShaderInfoLog(vertex)
|
||||
if isinstance(log, bytes):
|
||||
log = log.decode()
|
||||
for line in log.split("\n"):
|
||||
print(line)
|
||||
|
||||
GL.glAttachShader(program, vertex)
|
||||
GL.glShaderSource(fragment, fragment_code)
|
||||
GL.glCompileShader(fragment)
|
||||
|
||||
# this logs issues the shader compiler finds.
|
||||
log = GL.glGetShaderInfoLog(fragment)
|
||||
if isinstance(log, bytes):
|
||||
log = log.decode()
|
||||
for line in log.split("\n"):
|
||||
print(line)
|
||||
|
||||
GL.glAttachShader(program, fragment)
|
||||
GL.glValidateProgram(program)
|
||||
GL.glLinkProgram(program)
|
||||
|
||||
GL.glDetachShader(program, vertex)
|
||||
GL.glDetachShader(program, fragment)
|
||||
GL.glUseProgram(program)
|
||||
|
||||
# Create vertex buffers and shader constants
|
||||
# ------------------------------------------
|
||||
|
||||
# Cube Data
|
||||
vertices = zeros(8, [("vertex_position", float32, 3), ("vertex_color", float32, 4)])
|
||||
|
||||
vertices["vertex_position"] = [
|
||||
[1, 1, 1],
|
||||
[-1, 1, 1],
|
||||
[-1, -1, 1],
|
||||
[1, -1, 1],
|
||||
[1, -1, -1],
|
||||
[1, 1, -1],
|
||||
[-1, 1, -1],
|
||||
[-1, -1, -1],
|
||||
]
|
||||
|
||||
vertices["vertex_color"] = [
|
||||
[0, 1, 1, 1],
|
||||
[0, 0, 1, 1],
|
||||
[0, 0, 0, 1],
|
||||
[0, 1, 0, 1],
|
||||
[1, 1, 0, 1],
|
||||
[1, 1, 1, 1],
|
||||
[1, 0, 1, 1],
|
||||
[1, 0, 0, 1],
|
||||
]
|
||||
|
||||
filled_cube_indices = array(
|
||||
[
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
0,
|
||||
2,
|
||||
3,
|
||||
0,
|
||||
3,
|
||||
4,
|
||||
0,
|
||||
4,
|
||||
5,
|
||||
0,
|
||||
5,
|
||||
6,
|
||||
0,
|
||||
6,
|
||||
1,
|
||||
1,
|
||||
6,
|
||||
7,
|
||||
1,
|
||||
7,
|
||||
2,
|
||||
7,
|
||||
4,
|
||||
3,
|
||||
7,
|
||||
3,
|
||||
2,
|
||||
4,
|
||||
7,
|
||||
6,
|
||||
4,
|
||||
6,
|
||||
5,
|
||||
],
|
||||
dtype=uint32,
|
||||
)
|
||||
|
||||
outline_cube_indices = array(
|
||||
[0, 1, 1, 2, 2, 3, 3, 0, 4, 7, 7, 6, 6, 5, 5, 4, 0, 5, 1, 6, 2, 7, 3, 4],
|
||||
dtype=uint32,
|
||||
)
|
||||
|
||||
shader_data = {"buffer": {}, "constants": {}}
|
||||
|
||||
GL.glBindVertexArray(GL.glGenVertexArrays(1)) # Have to do this first
|
||||
|
||||
shader_data["buffer"]["vertices"] = GL.glGenBuffers(1)
|
||||
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, shader_data["buffer"]["vertices"])
|
||||
GL.glBufferData(GL.GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL.GL_DYNAMIC_DRAW)
|
||||
|
||||
stride = vertices.strides[0]
|
||||
offset = ctypes.c_void_p(0)
|
||||
|
||||
loc = GL.glGetAttribLocation(program, "vertex_position")
|
||||
GL.glEnableVertexAttribArray(loc)
|
||||
GL.glVertexAttribPointer(loc, 3, GL.GL_FLOAT, False, stride, offset)
|
||||
|
||||
offset = ctypes.c_void_p(vertices.dtype["vertex_position"].itemsize)
|
||||
|
||||
loc = GL.glGetAttribLocation(program, "vertex_color")
|
||||
GL.glEnableVertexAttribArray(loc)
|
||||
GL.glVertexAttribPointer(loc, 4, GL.GL_FLOAT, False, stride, offset)
|
||||
|
||||
shader_data["buffer"]["filled"] = GL.glGenBuffers(1)
|
||||
GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, shader_data["buffer"]["filled"])
|
||||
GL.glBufferData(
|
||||
GL.GL_ELEMENT_ARRAY_BUFFER,
|
||||
filled_cube_indices.nbytes,
|
||||
filled_cube_indices,
|
||||
GL.GL_STATIC_DRAW,
|
||||
)
|
||||
|
||||
shader_data["buffer"]["outline"] = GL.glGenBuffers(1)
|
||||
GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, shader_data["buffer"]["outline"])
|
||||
GL.glBufferData(
|
||||
GL.GL_ELEMENT_ARRAY_BUFFER,
|
||||
outline_cube_indices.nbytes,
|
||||
outline_cube_indices,
|
||||
GL.GL_STATIC_DRAW,
|
||||
)
|
||||
|
||||
shader_data["constants"]["model"] = GL.glGetUniformLocation(program, "model")
|
||||
GL.glUniformMatrix4fv(shader_data["constants"]["model"], 1, False, eye(4))
|
||||
|
||||
shader_data["constants"]["view"] = GL.glGetUniformLocation(program, "view")
|
||||
view = translate(eye(4), z=-6)
|
||||
GL.glUniformMatrix4fv(shader_data["constants"]["view"], 1, False, view)
|
||||
|
||||
shader_data["constants"]["projection"] = GL.glGetUniformLocation(
|
||||
program, "projection"
|
||||
)
|
||||
GL.glUniformMatrix4fv(shader_data["constants"]["projection"], 1, False, eye(4))
|
||||
|
||||
# This color is multiplied with the base vertex color in producing
|
||||
# the final output
|
||||
shader_data["constants"]["color_mul"] = GL.glGetUniformLocation(
|
||||
program, "color_mul"
|
||||
)
|
||||
GL.glUniform4f(shader_data["constants"]["color_mul"], 1, 1, 1, 1)
|
||||
|
||||
# This color is added on to the base vertex color in producing
|
||||
# the final output
|
||||
shader_data["constants"]["color_add"] = GL.glGetUniformLocation(
|
||||
program, "color_add"
|
||||
)
|
||||
GL.glUniform4f(shader_data["constants"]["color_add"], 0, 0, 0, 0)
|
||||
|
||||
# Set GL drawing data
|
||||
# -------------------
|
||||
GL.glClearColor(0, 0, 0, 0)
|
||||
GL.glPolygonOffset(1, 1)
|
||||
GL.glEnable(GL.GL_LINE_SMOOTH)
|
||||
GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA)
|
||||
GL.glDepthFunc(GL.GL_LESS)
|
||||
GL.glHint(GL.GL_LINE_SMOOTH_HINT, GL.GL_NICEST)
|
||||
GL.glLineWidth(1.0)
|
||||
|
||||
projection = perspective(45.0, display_size[0] / float(display_size[1]), 2.0, 100.0)
|
||||
GL.glUniformMatrix4fv(shader_data["constants"]["projection"], 1, False, projection)
|
||||
|
||||
return shader_data, filled_cube_indices, outline_cube_indices
|
||||
|
||||
|
||||
def draw_cube_modern(shader_data, filled_cube_indices, outline_cube_indices, rotation):
|
||||
"""
|
||||
Draw a cube in the 'modern' Open GL style, for post 3.1 versions of
|
||||
open GL.
|
||||
|
||||
:param shader_data: compile vertex & pixel shader data for drawing a cube.
|
||||
:param filled_cube_indices: the indices to draw the 'filled' cube.
|
||||
:param outline_cube_indices: the indices to draw the 'outline' cube.
|
||||
:param rotation: the current rotations to apply.
|
||||
"""
|
||||
|
||||
GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
|
||||
|
||||
# Filled cube
|
||||
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.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, shader_data["buffer"]["filled"])
|
||||
GL.glDrawElements(
|
||||
GL.GL_TRIANGLES, len(filled_cube_indices), GL.GL_UNSIGNED_INT, None
|
||||
)
|
||||
|
||||
# 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.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.psi += 1.0 # degrees
|
||||
model = eye(4, dtype=float32)
|
||||
# rotate(model, rotation.theta, 0, 0, 1)
|
||||
rotate(model, rotation.phi, 0, 1, 0)
|
||||
rotate(model, rotation.psi, 1, 0, 0)
|
||||
GL.glUniformMatrix4fv(shader_data["constants"]["model"], 1, False, model)
|
||||
|
||||
|
||||
def main():
|
||||
"""run the demo"""
|
||||
|
||||
# initialize pygame-ce and setup an opengl display
|
||||
|
||||
pygame.init()
|
||||
clock = pygame.time.Clock()
|
||||
|
||||
gl_version = (3, 0) # GL Version number (Major, Minor)
|
||||
if USE_MODERN_GL:
|
||||
gl_version = (3, 2) # GL Version number (Major, Minor)
|
||||
|
||||
# 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
|
||||
)
|
||||
|
||||
# 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
|
||||
)
|
||||
|
||||
if USE_MODERN_GL:
|
||||
gpu, f_indices, o_indices = init_gl_modern(display_size)
|
||||
rotation = Rotation()
|
||||
else:
|
||||
init_gl_stuff_old()
|
||||
|
||||
delta_time = 0
|
||||
going = True
|
||||
while going:
|
||||
# check for quit'n events
|
||||
events = pygame.event.get()
|
||||
for event in events:
|
||||
if event.type == pygame.QUIT or (
|
||||
event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE
|
||||
):
|
||||
going = False
|
||||
|
||||
elif event.type == pygame.KEYDOWN and event.key == pygame.K_f:
|
||||
if not pygame.display.is_fullscreen():
|
||||
print("Changing to FULLSCREEN")
|
||||
pygame.display.set_mode(
|
||||
display_size,
|
||||
pygame.OPENGL | pygame.DOUBLEBUF | pygame.FULLSCREEN,
|
||||
)
|
||||
else:
|
||||
print("Changing to windowed mode")
|
||||
pygame.display.set_mode(
|
||||
display_size, pygame.OPENGL | pygame.DOUBLEBUF
|
||||
)
|
||||
|
||||
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)
|
||||
drawcube_old()
|
||||
|
||||
pygame.display.flip()
|
||||
if pygame.display.is_vsync():
|
||||
delta_time = clock.tick()
|
||||
else:
|
||||
delta_time = clock.tick(60)
|
||||
|
||||
pygame.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,92 @@
|
||||
"""pygame.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.
|
||||
|
||||
Mouse Controls:
|
||||
* Use the mouse to click on a new target position
|
||||
|
||||
Keyboard Controls:
|
||||
* Press R to restart the demo
|
||||
"""
|
||||
|
||||
import random
|
||||
|
||||
import pygame
|
||||
|
||||
MIN_SPEED = 0.25
|
||||
MAX_SPEED = 5
|
||||
MAX_BALLS = 1600
|
||||
SCREEN_SIZE = pygame.Vector2(1000, 600)
|
||||
CIRCLE_RADIUS = 5
|
||||
|
||||
target_position = None
|
||||
balls = []
|
||||
|
||||
|
||||
class Ball:
|
||||
def __init__(self, position, speed):
|
||||
self.position = position
|
||||
self.speed = speed
|
||||
|
||||
|
||||
def reset():
|
||||
global balls
|
||||
global target_position
|
||||
|
||||
target_position = None
|
||||
balls = []
|
||||
for x in range(MAX_BALLS):
|
||||
pos = pygame.Vector2(
|
||||
random.randint(0, int(SCREEN_SIZE.x)), random.randint(0, int(SCREEN_SIZE.y))
|
||||
)
|
||||
speed = random.uniform(MIN_SPEED, MAX_SPEED)
|
||||
|
||||
b = Ball(pos, speed)
|
||||
balls.append(b)
|
||||
|
||||
|
||||
def main():
|
||||
global target_position
|
||||
global balls
|
||||
|
||||
pygame.init()
|
||||
screen = pygame.display.set_mode(SCREEN_SIZE)
|
||||
clock = pygame.Clock()
|
||||
|
||||
reset()
|
||||
delta_time = 0
|
||||
running = True
|
||||
while running:
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
running = False
|
||||
|
||||
if event.type == pygame.MOUSEBUTTONUP:
|
||||
target_position = pygame.mouse.get_pos()
|
||||
|
||||
if event.type == pygame.KEYUP:
|
||||
if event.key == pygame.K_ESCAPE:
|
||||
running = False
|
||||
|
||||
if event.key == pygame.K_r:
|
||||
reset()
|
||||
|
||||
screen.fill((31, 143, 65))
|
||||
|
||||
for o in balls:
|
||||
if target_position is not None:
|
||||
o.position.move_towards_ip(target_position, o.speed * delta_time)
|
||||
pygame.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)}"
|
||||
)
|
||||
|
||||
pygame.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,48 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.headless_no_windows_needed
|
||||
|
||||
How to use pygame-ce 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
|
||||
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
import pygame
|
||||
|
||||
# set SDL to use the NULL video driver,
|
||||
# so it doesn't need a windowing system.
|
||||
os.environ["SDL_VIDEODRIVER"] = pygame.NULL_VIDEODRIVER
|
||||
|
||||
|
||||
# Some platforms need to init the display for some parts of pygame.
|
||||
pygame.display.init()
|
||||
screen = pygame.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)
|
||||
|
||||
|
||||
def main(fin, fout, w, h):
|
||||
"""smoothscale image file named fin as fout with new size (w,h)"""
|
||||
scaleit(fin, fout, w, h)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if "-scale" in sys.argv:
|
||||
fin, fout, w, h = sys.argv[2:]
|
||||
w, h = map(int, [w, h])
|
||||
main(fin, fout, w, h)
|
||||
else:
|
||||
print(usage)
|
||||
@@ -0,0 +1,141 @@
|
||||
import pygame
|
||||
|
||||
pygame.init()
|
||||
|
||||
|
||||
def indent(text, indentation_level=0):
|
||||
return (" " * indentation_level) + text
|
||||
|
||||
|
||||
def main():
|
||||
# Set the size of the screen (width, height), and name the window.
|
||||
size = (500, 700)
|
||||
screen = pygame.display.set_mode(size)
|
||||
pygame.display.set_caption("Joystick example")
|
||||
|
||||
# Used to manage how fast the screen updates.
|
||||
clock = pygame.Clock()
|
||||
|
||||
# Get ready to print.
|
||||
font = pygame.font.SysFont(None, 25)
|
||||
wraplength = size[0] - 20
|
||||
|
||||
# This dict can be left as-is, since pygame-ce will generate a
|
||||
# pygame.JOYDEVICEADDED event for every joystick connected
|
||||
# at the start of the program.
|
||||
joysticks = {}
|
||||
|
||||
done = False
|
||||
while not done:
|
||||
# Event processing step.
|
||||
# Possible joystick events: JOYAXISMOTION, JOYBALLMOTION, JOYBUTTONDOWN,
|
||||
# JOYBUTTONUP, JOYHATMOTION, JOYDEVICEADDED, JOYDEVICEREMOVED
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
done = True # Flag that we are done so we exit this loop.
|
||||
|
||||
if event.type == pygame.JOYBUTTONDOWN:
|
||||
print("Joystick button pressed.")
|
||||
if event.button == 0:
|
||||
joystick = joysticks[event.instance_id]
|
||||
if joystick.rumble(0, 0.7, 500):
|
||||
print(f"Rumble effect played on joystick {event.instance_id}")
|
||||
|
||||
if event.type == pygame.JOYBUTTONUP:
|
||||
print("Joystick button released.")
|
||||
|
||||
# Handle hotplugging
|
||||
if event.type == pygame.JOYDEVICEADDED:
|
||||
# This event will be generated when the program starts for every
|
||||
# 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")
|
||||
|
||||
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"
|
||||
)
|
||||
|
||||
# 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 = []
|
||||
|
||||
# Get count of joysticks.
|
||||
joystick_count = pygame.joystick.get_count()
|
||||
lines.append(indent(f"Number of joysticks: {joystick_count}", indentation))
|
||||
indentation += 1
|
||||
|
||||
# For each joystick:
|
||||
for joystick in joysticks.values():
|
||||
jid = joystick.get_instance_id()
|
||||
|
||||
lines.append(indent(f"Joystick {jid}", indentation))
|
||||
indentation += 1
|
||||
|
||||
# Get the name from the OS for the controller/joystick.
|
||||
name = joystick.get_name()
|
||||
lines.append(indent(f"Joystick name: {name}", indentation))
|
||||
|
||||
guid = joystick.get_guid()
|
||||
lines.append(indent(f"GUID: {guid}", indentation))
|
||||
|
||||
power_level = joystick.get_power_level()
|
||||
lines.append(indent(f"Joystick's power level: {power_level}", indentation))
|
||||
|
||||
# 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
|
||||
|
||||
for i in range(axes):
|
||||
axis = joystick.get_axis(i)
|
||||
lines.append(indent(f"Axis {i} value: {axis:>6.3f}", indentation))
|
||||
indentation -= 1
|
||||
|
||||
buttons = joystick.get_numbuttons()
|
||||
lines.append(indent(f"Number of buttons: {buttons}", indentation))
|
||||
indentation += 1
|
||||
|
||||
for i in range(buttons):
|
||||
button = joystick.get_button(i)
|
||||
lines.append(indent(f"Button {i:>2} value: {button}", indentation))
|
||||
indentation -= 1
|
||||
|
||||
hats = joystick.get_numhats()
|
||||
lines.append(indent(f"Number of hats: {hats}", indentation))
|
||||
indentation += 1
|
||||
|
||||
# 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
|
||||
|
||||
# draw the accumulated text
|
||||
screen.blit(
|
||||
font.render("\n".join(lines), True, "black", "white", wraplength), (10, 10)
|
||||
)
|
||||
|
||||
# Go ahead and update the screen with what we've drawn.
|
||||
pygame.display.flip()
|
||||
|
||||
# Limit to 30 frames per second.
|
||||
clock.tick(30)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
# If you forget this line, the program will 'hang'
|
||||
# on exit if running from IDLE.
|
||||
pygame.quit()
|
||||
@@ -0,0 +1,93 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.liquid
|
||||
|
||||
This example demonstrates a simplish water effect of an
|
||||
image. It attempts to create a hardware display surface that
|
||||
can use pageflipping for faster updates. Note that the colormap
|
||||
from the loaded GIF image is copied to the colormap for the
|
||||
display surface.
|
||||
|
||||
This is based on the demo named F2KWarp by Brad Graham of Freedom2000
|
||||
done in BlitzBasic. I was just translating the BlitzBasic code to
|
||||
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 os
|
||||
from math import sin
|
||||
|
||||
import pygame
|
||||
|
||||
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)
|
||||
|
||||
# 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)
|
||||
|
||||
# get the image and screen in the same format
|
||||
if screen.get_bitsize() == 8:
|
||||
screen.set_palette(bitmap.get_palette())
|
||||
else:
|
||||
bitmap = bitmap.convert()
|
||||
|
||||
# prep some variables
|
||||
anim = 0.0
|
||||
|
||||
# mainloop
|
||||
xblocks = range(0, 640, 20)
|
||||
yblocks = range(0, 480, 20)
|
||||
stop_events = pygame.QUIT, pygame.KEYDOWN, pygame.MOUSEBUTTONDOWN
|
||||
|
||||
clock = pygame.Clock()
|
||||
|
||||
while True:
|
||||
clock.tick(60)
|
||||
|
||||
for event in pygame.event.get():
|
||||
if event.type in stop_events:
|
||||
return
|
||||
|
||||
anim = anim + 0.02
|
||||
for x in xblocks:
|
||||
xpos = (x + (sin(anim + x * 0.01) * 15)) + 20
|
||||
for y in yblocks:
|
||||
ypos = (y + (sin(anim + y * 0.01) * 15)) + 20
|
||||
screen.blit(bitmap, (x, y), (xpos, ypos, 20, 20))
|
||||
|
||||
pygame.display.flip()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
pygame.quit()
|
||||
|
||||
|
||||
"""BTW, here is the code from the BlitzBasic example this was derived
|
||||
from. i've snipped the sound and text stuff out.
|
||||
-----------------------------------------------------------------
|
||||
; Brad@freedom2000.com
|
||||
|
||||
; Load a bmp pic (800x600) and slice it into 1600 squares
|
||||
Graphics 640,480
|
||||
SetBuffer BackBuffer()
|
||||
bitmap$="f2kwarp.bmp"
|
||||
pic=LoadAnimImage(bitmap$,20,15,0,1600)
|
||||
|
||||
; use SIN to move all 1600 squares around to give liquid effect
|
||||
Repeat
|
||||
f=0:w=w+10:If w=360 Then w=0
|
||||
For y=0 To 599 Step 15
|
||||
For x = 0 To 799 Step 20
|
||||
f=f+1:If f=1600 Then f=0
|
||||
DrawBlock pic,(x+(Sin(w+x)*40))/1.7+80,(y+(Sin(w+y)*40))/1.7+60,f
|
||||
Next:Next:Flip:Cls
|
||||
Until KeyDown(1)
|
||||
"""
|
||||
@@ -0,0 +1,202 @@
|
||||
#!/usr/bin/env python
|
||||
"""
|
||||
pygame.examples.mask
|
||||
|
||||
A pygame.mask collision detection production.
|
||||
|
||||
|
||||
|
||||
|
||||
Brought
|
||||
|
||||
to
|
||||
you
|
||||
by
|
||||
|
||||
the
|
||||
|
||||
pixels
|
||||
0000000000000
|
||||
and
|
||||
111111
|
||||
|
||||
|
||||
This is 32 bits:
|
||||
11111111111111111111111111111111
|
||||
|
||||
There are 32 or 64 bits in a computer 'word'.
|
||||
Rather than using one word for a pixel,
|
||||
the mask module represents 32 or 64 pixels in one word.
|
||||
As you can imagine, this makes things fast, and saves memory.
|
||||
|
||||
Compute intensive things like collision detection,
|
||||
and computer vision benefit greatly from this.
|
||||
|
||||
|
||||
This module can also be run as a stand-alone program, excepting
|
||||
one or more image file names as command line arguments.
|
||||
"""
|
||||
|
||||
import os
|
||||
import random
|
||||
import sys
|
||||
|
||||
import pygame
|
||||
|
||||
|
||||
class Sprite:
|
||||
"""
|
||||
Moving Sprite demonstrating pixel-perfect collisions between pygame.mask.Mask objects
|
||||
"""
|
||||
|
||||
def __init__(self, pos, vel, surface, mask=None):
|
||||
"""
|
||||
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)
|
||||
"""
|
||||
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.pos = pygame.Vector2(pos)
|
||||
self.vel = pygame.Vector2(vel)
|
||||
|
||||
def collide(self, sprite):
|
||||
"""
|
||||
Test if the sprites are colliding and
|
||||
resolve the collision in this case.
|
||||
|
||||
Positional arguments:
|
||||
sprite: other sprite to test for collisions
|
||||
"""
|
||||
offset = [int(x) for x in sprite.pos - self.pos]
|
||||
overlap = self.mask.overlap_area(sprite.mask, offset)
|
||||
if overlap == 0:
|
||||
return
|
||||
# Calculate collision normal
|
||||
|
||||
# Number of collisions
|
||||
n_collisions = pygame.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])),
|
||||
# y axis
|
||||
self.mask.overlap_area(sprite.mask, (offset[0], offset[1] + 1))
|
||||
- self.mask.overlap_area(sprite.mask, (offset[0], offset[1] - 1)),
|
||||
)
|
||||
if n_collisions.x == 0 and n_collisions.y == 0:
|
||||
# One sprite is inside another
|
||||
return
|
||||
|
||||
delta_vel = sprite.vel - self.vel
|
||||
j = delta_vel * n_collisions / (2 * n_collisions * n_collisions)
|
||||
if j > 0:
|
||||
# Can scale up to 2*j here to get bouncy collisions
|
||||
j *= 1.9
|
||||
self.vel += [n_collisions.x * j, n_collisions.y * j]
|
||||
sprite.vel += [-j * n_collisions.x, -j * n_collisions.y]
|
||||
|
||||
# # Separate the sprites
|
||||
# c1 = -overlap / (n_collisions * n_collisions)
|
||||
# c2 = -c1 / 2
|
||||
# self.pos += [c2 * n_collisions.x, c2 * n_collisions.y]
|
||||
# sprite.pos += [(c1 + c2) * n_collisions.x, (c1 + c2) * n_collisions.y]
|
||||
|
||||
def update(self):
|
||||
"""
|
||||
Move the sprite
|
||||
"""
|
||||
self.pos += self.vel
|
||||
|
||||
|
||||
def main(*args):
|
||||
"""
|
||||
Display multiple images bounce off each other using collision detection
|
||||
|
||||
Positional arguments:
|
||||
one or more image file names.
|
||||
|
||||
This pygame.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()
|
||||
|
||||
screen_size = (640, 480)
|
||||
screen = pygame.display.set_mode(screen_size)
|
||||
clock = pygame.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]))
|
||||
|
||||
sprites = []
|
||||
for i in range(20):
|
||||
j = i % len(images)
|
||||
sprite = Sprite(
|
||||
pos=(
|
||||
random.uniform(0, screen_size[0]),
|
||||
random.uniform(0, screen_size[1]),
|
||||
),
|
||||
vel=(
|
||||
random.uniform(-5, 5),
|
||||
random.uniform(-5, 5),
|
||||
),
|
||||
surface=images[j],
|
||||
mask=masks[j],
|
||||
)
|
||||
sprites.append(sprite)
|
||||
|
||||
while True:
|
||||
for event in pygame.event.get():
|
||||
if event.type in (pygame.QUIT, pygame.KEYDOWN):
|
||||
return
|
||||
|
||||
screen.fill((240, 220, 100))
|
||||
|
||||
for sprite_index, sprite in enumerate(sprites):
|
||||
for other_sprite in sprites[sprite_index + 1 :]:
|
||||
sprite.collide(other_sprite)
|
||||
|
||||
sprite.update()
|
||||
|
||||
# If the sprite is outside of the screen on the left
|
||||
if sprite.pos.x < -sprite.width:
|
||||
sprite.pos.x = screen_size[0]
|
||||
# right
|
||||
elif sprite.pos.x > screen_size[0]:
|
||||
sprite.pos.x = -sprite.width
|
||||
# top
|
||||
if sprite.pos.y < -sprite.height:
|
||||
sprite.pos.y = screen_size[1]
|
||||
# down
|
||||
elif sprite.pos.y > screen_size[1]:
|
||||
sprite.pos.y = -sprite.height
|
||||
|
||||
screen.blit(sprite.surface, sprite.pos)
|
||||
|
||||
clock.tick(30)
|
||||
pygame.display.flip()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) < 2:
|
||||
print("Usage: mask.py <IMAGE> [<IMAGE> ...]")
|
||||
print("Let many copies of IMAGE(s) bounce against each other")
|
||||
print("Press any key to quit")
|
||||
main_dir = os.path.split(os.path.abspath(__file__))[0]
|
||||
main(os.path.join(main_dir, "data", "alien1.png"))
|
||||
|
||||
else:
|
||||
main(*sys.argv[1:])
|
||||
pygame.quit()
|
||||
@@ -0,0 +1,877 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.midi
|
||||
|
||||
midi input, and a separate example of midi output.
|
||||
|
||||
By default it runs the output example.
|
||||
|
||||
python -m pygame.examples.midi --output
|
||||
python -m pygame.examples.midi --input
|
||||
python -m pygame.examples.midi --input
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
import pygame
|
||||
import pygame.midi
|
||||
|
||||
# black and white piano keys use b/w color values directly
|
||||
BACKGROUNDCOLOR = "slategray"
|
||||
|
||||
|
||||
def print_device_info():
|
||||
pygame.midi.init()
|
||||
_print_device_info()
|
||||
pygame.midi.quit()
|
||||
|
||||
|
||||
def _print_device_info():
|
||||
for i in range(pygame.midi.get_count()):
|
||||
r = pygame.midi.get_device_info(i)
|
||||
(interf, name, input, output, opened) = r
|
||||
|
||||
in_out = ""
|
||||
if input:
|
||||
in_out = "(input)"
|
||||
if output:
|
||||
in_out = "(output)"
|
||||
|
||||
print(
|
||||
"%2i: interface :%s:, name :%s:, opened :%s: %s"
|
||||
% (i, interf, name, opened, in_out)
|
||||
)
|
||||
|
||||
|
||||
def input_main(device_id=None):
|
||||
pygame.init()
|
||||
|
||||
pygame.midi.init()
|
||||
|
||||
_print_device_info()
|
||||
|
||||
if device_id is None:
|
||||
input_id = pygame.midi.get_default_input_id()
|
||||
else:
|
||||
input_id = device_id
|
||||
|
||||
print(f"using input_id :{input_id}:")
|
||||
i = pygame.midi.Input(input_id)
|
||||
|
||||
pygame.display.set_mode((1, 1))
|
||||
|
||||
going = True
|
||||
while going:
|
||||
events = pygame.event.get()
|
||||
for e in events:
|
||||
if e.type in [pygame.QUIT]:
|
||||
going = False
|
||||
if e.type in [pygame.KEYDOWN]:
|
||||
going = False
|
||||
if e.type in [pygame.midi.MIDIIN]:
|
||||
print(e)
|
||||
|
||||
if i.poll():
|
||||
midi_events = i.read(10)
|
||||
# convert them into pygame events.
|
||||
midi_evs = pygame.midi.midis2events(midi_events, i.device_id)
|
||||
|
||||
for m_e in midi_evs:
|
||||
pygame.event.post(m_e)
|
||||
|
||||
del i
|
||||
pygame.midi.quit()
|
||||
|
||||
|
||||
def output_main(device_id=None):
|
||||
"""Execute a musical keyboard example for the Church Organ instrument
|
||||
|
||||
This is a piano keyboard example, with a two octave keyboard, starting at
|
||||
note F3. Left mouse down over a key starts a note, left up stops it. The
|
||||
notes are also mapped to the computer keyboard keys, assuming an American
|
||||
English PC keyboard (sorry everyone else, but I don't know if I can map to
|
||||
absolute key position instead of value.) The white keys are on the second
|
||||
row, TAB to BACKSLASH, starting with note F3. The black keys map to the top
|
||||
row, '1' to BACKSPACE, starting with F#3. 'r' is middle C. Close the
|
||||
window or press ESCAPE to quit the program. Key velocity (note
|
||||
amplitude) varies vertically on the keyboard image, with minimum velocity
|
||||
at the top of a key and maximum velocity at bottom.
|
||||
|
||||
Default Midi output, no device_id given, is to the default output device
|
||||
for the computer.
|
||||
|
||||
"""
|
||||
|
||||
# A note to new pygamers:
|
||||
#
|
||||
# All the midi module stuff is in this function. It is unnecessary to
|
||||
# understand how the keyboard display works to appreciate how midi
|
||||
# messages are sent.
|
||||
|
||||
# The keyboard is drawn by a Keyboard instance. This instance maps Midi
|
||||
# notes to musical keyboard keys. A regions surface maps window position
|
||||
# to (Midi note, velocity) pairs. A key_mapping dictionary does the same
|
||||
# for computer keyboard keys. Midi sound is controlled with direct method
|
||||
# calls to a pygame.midi.Output instance.
|
||||
#
|
||||
# Things to consider when using pygame.midi:
|
||||
#
|
||||
# 1) Initialize the midi module with a to pygame.midi.init().
|
||||
# 2) Create a midi.Output instance for the desired output device port.
|
||||
# 3) Select instruments with set_instrument() method calls.
|
||||
# 4) Play notes with note_on() and note_off() method calls.
|
||||
# 5) Call pygame.midi.Quit() when finished. Though the midi module tries
|
||||
# to ensure that midi is properly shut down, it is best to do it
|
||||
# explicitly. A try/finally statement is the safest way to do this.
|
||||
#
|
||||
|
||||
# GRAND_PIANO = 0
|
||||
CHURCH_ORGAN = 19
|
||||
|
||||
instrument = CHURCH_ORGAN
|
||||
# instrument = GRAND_PIANO
|
||||
start_note = 53 # F3 (white key note), start_note != 0
|
||||
n_notes = 24 # Two octaves (14 white keys)
|
||||
|
||||
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,
|
||||
],
|
||||
start_note,
|
||||
)
|
||||
|
||||
pygame.init()
|
||||
pygame.midi.init()
|
||||
|
||||
_print_device_info()
|
||||
|
||||
if device_id is None:
|
||||
port = pygame.midi.get_default_output_id()
|
||||
else:
|
||||
port = device_id
|
||||
|
||||
print(f"using output_id :{port}:")
|
||||
|
||||
midi_out = pygame.midi.Output(port, 0)
|
||||
try:
|
||||
midi_out.set_instrument(instrument)
|
||||
keyboard = Keyboard(start_note, n_notes)
|
||||
|
||||
screen = pygame.display.set_mode(keyboard.rect.size)
|
||||
screen.fill(BACKGROUNDCOLOR)
|
||||
pygame.display.flip()
|
||||
|
||||
background = pygame.Surface(screen.get_size())
|
||||
background.fill(BACKGROUNDCOLOR)
|
||||
dirty_rects = []
|
||||
keyboard.draw(screen, background, dirty_rects)
|
||||
pygame.display.update(dirty_rects)
|
||||
|
||||
regions = pygame.Surface(screen.get_size()) # initial color (0,0,0)
|
||||
keyboard.map_regions(regions)
|
||||
|
||||
pygame.event.set_blocked(pygame.MOUSEMOTION)
|
||||
mouse_note = 0
|
||||
on_notes = set()
|
||||
while True:
|
||||
e = pygame.event.wait()
|
||||
if e.type == pygame.MOUSEBUTTONDOWN:
|
||||
mouse_note, velocity, __, __ = regions.get_at(e.pos)
|
||||
if mouse_note and mouse_note not in on_notes:
|
||||
keyboard.key_down(mouse_note)
|
||||
midi_out.note_on(mouse_note, velocity)
|
||||
on_notes.add(mouse_note)
|
||||
else:
|
||||
mouse_note = 0
|
||||
elif e.type == pygame.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:
|
||||
break
|
||||
elif e.type == pygame.KEYDOWN:
|
||||
if e.key == pygame.K_ESCAPE:
|
||||
break
|
||||
try:
|
||||
note, velocity = key_mapping[e.key]
|
||||
except KeyError:
|
||||
pass
|
||||
else:
|
||||
if note not in on_notes:
|
||||
keyboard.key_down(note)
|
||||
midi_out.note_on(note, velocity)
|
||||
on_notes.add(note)
|
||||
elif e.type == pygame.KEYUP:
|
||||
try:
|
||||
note, __ = key_mapping[e.key]
|
||||
except KeyError:
|
||||
pass
|
||||
else:
|
||||
if note in on_notes and note != mouse_note:
|
||||
keyboard.key_up(note)
|
||||
midi_out.note_off(note, 0)
|
||||
on_notes.remove(note)
|
||||
|
||||
dirty_rects = []
|
||||
keyboard.draw(screen, background, dirty_rects)
|
||||
pygame.display.update(dirty_rects)
|
||||
finally:
|
||||
del midi_out
|
||||
pygame.midi.quit()
|
||||
|
||||
|
||||
def make_key_mapping(keys, start_note):
|
||||
"""Return a dictionary of (note, velocity) by computer keyboard key code"""
|
||||
mapping = {}
|
||||
for i, key in enumerate(keys):
|
||||
mapping[key] = (start_note + i, 127)
|
||||
return mapping
|
||||
|
||||
|
||||
class NullKey:
|
||||
"""A null 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.
|
||||
|
||||
"""
|
||||
|
||||
def _right_white_down(self):
|
||||
pass
|
||||
|
||||
def _right_white_up(self):
|
||||
pass
|
||||
|
||||
def _right_black_down(self):
|
||||
pass
|
||||
|
||||
def _right_black_up(self):
|
||||
pass
|
||||
|
||||
|
||||
null_key = NullKey()
|
||||
|
||||
|
||||
def key_class(updates, image_strip, image_rects, is_white_key=True):
|
||||
"""Return a keyboard key widget class
|
||||
|
||||
Arguments:
|
||||
updates - a set into which a key instance adds itself if it needs
|
||||
redrawing.
|
||||
image_strip - The surface containing the images of all key states.
|
||||
image_rects - A list of Rects giving the regions within image_strip that
|
||||
are relevant to this key class.
|
||||
is_white_key (default True) - Set false if this is a black key.
|
||||
|
||||
This function automates the creation of a key widget class for the
|
||||
three basic key types. A key has two basic states, up or down (
|
||||
depressed). Corresponding up and down images are drawn for each
|
||||
of these two states. But to give the illusion of depth, a key
|
||||
may have shadows cast upon it by the adjacent keys to its right.
|
||||
These shadows change depending on the up/down state of the key and
|
||||
its neighbors. So a key may support multiple images and states
|
||||
depending on the shadows. A key type is determined by the length
|
||||
of image_rects and the value of is_white.
|
||||
|
||||
"""
|
||||
|
||||
# Naming convention: Variables used by the Key class as part of a
|
||||
# closure start with 'c_'.
|
||||
|
||||
# State logic and shadows:
|
||||
#
|
||||
# A key may cast a shadow upon the key to its left. A black key casts a
|
||||
# shadow on an adjacent white key. The shadow changes depending of whether
|
||||
# the black or white key is depressed. A white key casts a shadow on the
|
||||
# white key to its left if it is up and the left key is down. Therefore
|
||||
# a keys state, and image it will draw, is determined entirely by its
|
||||
# itself and the key immediately adjacent to it on the right. A white key
|
||||
# is always assumed to have an adjacent white key.
|
||||
#
|
||||
# There can be up to eight key states, representing all permutations
|
||||
# of the three fundamental states of self up/down, adjacent white
|
||||
# right up/down, adjacent black up/down.
|
||||
#
|
||||
down_state_none = 0
|
||||
down_state_self = 1
|
||||
down_state_white = down_state_self << 1
|
||||
down_state_self_white = down_state_self | down_state_white
|
||||
down_state_black = down_state_white << 1
|
||||
down_state_self_black = down_state_self | down_state_black
|
||||
down_state_white_black = down_state_white | down_state_black
|
||||
down_state_all = down_state_self | down_state_white_black
|
||||
|
||||
# Some values used in the class.
|
||||
#
|
||||
c_down_state_initial = down_state_none
|
||||
c_down_state_rect_initial = image_rects[0]
|
||||
c_updates = updates
|
||||
c_image_strip = image_strip
|
||||
c_width, c_height = image_rects[0].size
|
||||
|
||||
# A key propagates its up/down state change to the adjacent white key on
|
||||
# the left by calling the adjacent key's _right_black_down or
|
||||
# _right_white_down method.
|
||||
#
|
||||
if is_white_key:
|
||||
key_color = "white"
|
||||
else:
|
||||
key_color = "black"
|
||||
c_notify_down_method = f"_right_{key_color}_down"
|
||||
c_notify_up_method = f"_right_{key_color}_up"
|
||||
|
||||
# Images:
|
||||
#
|
||||
# A black key only needs two images, for the up and down states. Its
|
||||
# appearance is unaffected by the adjacent keys to its right, which cast no
|
||||
# shadows upon it.
|
||||
#
|
||||
# A white key with a no adjacent black to its right only needs three
|
||||
# images, for self up, self down, and both self and adjacent white down.
|
||||
#
|
||||
# A white key with both a black and white key to its right needs six
|
||||
# images: self up, self up and adjacent black down, self down, self and
|
||||
# adjacent white down, self and adjacent black down, and all three down.
|
||||
#
|
||||
# Each 'c_event' dictionary maps the current key state to a new key state,
|
||||
# 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 = {
|
||||
down_state_none: (down_state_none, None),
|
||||
down_state_self: (down_state_self, None),
|
||||
}
|
||||
c_event_right_white_up = c_event_right_white_down.copy()
|
||||
c_event_right_black_down = c_event_right_white_down.copy()
|
||||
c_event_right_black_up = c_event_right_white_down.copy()
|
||||
if len(image_rects) > 2:
|
||||
c_event_down[down_state_white] = (down_state_self_white, image_rects[2])
|
||||
c_event_up[down_state_self_white] = (down_state_white, image_rects[0])
|
||||
c_event_right_white_down[down_state_none] = (down_state_white, None)
|
||||
c_event_right_white_down[down_state_self] = (
|
||||
down_state_self_white,
|
||||
image_rects[2],
|
||||
)
|
||||
c_event_right_white_up[down_state_white] = (down_state_none, None)
|
||||
c_event_right_white_up[down_state_self_white] = (
|
||||
down_state_self,
|
||||
image_rects[1],
|
||||
)
|
||||
c_event_right_black_down[down_state_white] = (down_state_white, None)
|
||||
c_event_right_black_down[down_state_self_white] = (down_state_self_white, None)
|
||||
c_event_right_black_up[down_state_white] = (down_state_white, None)
|
||||
c_event_right_black_up[down_state_self_white] = (down_state_self_white, None)
|
||||
if len(image_rects) > 3:
|
||||
c_event_down[down_state_black] = (down_state_self_black, image_rects[4])
|
||||
c_event_down[down_state_white_black] = (down_state_all, image_rects[5])
|
||||
c_event_up[down_state_self_black] = (down_state_black, image_rects[3])
|
||||
c_event_up[down_state_all] = (down_state_white_black, image_rects[3])
|
||||
c_event_right_white_down[down_state_black] = (down_state_white_black, None)
|
||||
c_event_right_white_down[down_state_self_black] = (
|
||||
down_state_all,
|
||||
image_rects[5],
|
||||
)
|
||||
c_event_right_white_up[down_state_white_black] = (down_state_black, None)
|
||||
c_event_right_white_up[down_state_all] = (down_state_self_black, image_rects[4])
|
||||
c_event_right_black_down[down_state_none] = (down_state_black, image_rects[3])
|
||||
c_event_right_black_down[down_state_self] = (
|
||||
down_state_self_black,
|
||||
image_rects[4],
|
||||
)
|
||||
c_event_right_black_down[down_state_white] = (
|
||||
down_state_white_black,
|
||||
image_rects[3],
|
||||
)
|
||||
c_event_right_black_down[down_state_self_white] = (
|
||||
down_state_all,
|
||||
image_rects[5],
|
||||
)
|
||||
c_event_right_black_up[down_state_black] = (down_state_none, image_rects[0])
|
||||
c_event_right_black_up[down_state_self_black] = (
|
||||
down_state_self,
|
||||
image_rects[1],
|
||||
)
|
||||
c_event_right_black_up[down_state_white_black] = (
|
||||
down_state_white,
|
||||
image_rects[0],
|
||||
)
|
||||
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
|
||||
|
||||
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
|
||||
|
||||
|
||||
def key_images():
|
||||
"""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.
|
||||
|
||||
This function encapsulates the constants relevant to the keyboard image
|
||||
file. There are five key types. One is the black key. The other four
|
||||
white keys are determined by the proximity of the black keys. The plain
|
||||
white key has no black key adjacent to it. A white-left and white-right
|
||||
key has a black key to the left or right of it respectively. A white-center
|
||||
key has a black key on both sides. A key may have up to six related
|
||||
images depending on the state of adjacent keys to its right.
|
||||
|
||||
"""
|
||||
|
||||
my_dir = os.path.split(os.path.abspath(__file__))[0]
|
||||
strip_file = os.path.join(my_dir, "data", "midikeys.webp")
|
||||
white_key_width = 42
|
||||
white_key_height = 160
|
||||
black_key_width = 22
|
||||
black_key_height = 94
|
||||
strip = pygame.image.load(strip_file)
|
||||
names = [
|
||||
"black none",
|
||||
"black self",
|
||||
"white none",
|
||||
"white self",
|
||||
"white self-white",
|
||||
"white-left none",
|
||||
"white-left self",
|
||||
"white-left black",
|
||||
"white-left self-black",
|
||||
"white-left self-white",
|
||||
"white-left all",
|
||||
"white-center none",
|
||||
"white-center self",
|
||||
"white-center black",
|
||||
"white-center self-black",
|
||||
"white-center self-white",
|
||||
"white-center all",
|
||||
"white-right none",
|
||||
"white-right self",
|
||||
"white-right self-white",
|
||||
]
|
||||
rects = {}
|
||||
for i in range(2):
|
||||
rects[names[i]] = pygame.Rect(
|
||||
i * white_key_width, 0, black_key_width, black_key_height
|
||||
)
|
||||
for i in range(2, len(names)):
|
||||
rects[names[i]] = pygame.Rect(
|
||||
i * white_key_width, 0, white_key_width, white_key_height
|
||||
)
|
||||
return strip, rects
|
||||
|
||||
|
||||
class Keyboard:
|
||||
"""Musical keyboard widget
|
||||
|
||||
Constructor arguments:
|
||||
start_note: midi note value of the starting note on the keyboard.
|
||||
n_notes: number of notes (keys) on the keyboard.
|
||||
|
||||
A Keyboard instance draws the musical keyboard and maintains the state of
|
||||
all the keyboard keys. Individual keys can be in a down (depressed) or
|
||||
up (released) state.
|
||||
|
||||
"""
|
||||
|
||||
_image_strip, _rects = key_images()
|
||||
|
||||
white_key_width, white_key_height = _rects["white none"].size
|
||||
black_key_width, black_key_height = _rects["black none"].size
|
||||
|
||||
_updates = set()
|
||||
|
||||
# There are five key classes, representing key shape:
|
||||
# black key (BlackKey), plain white key (WhiteKey), white key to the left
|
||||
# of a black key (WhiteKeyLeft), white key between two black keys
|
||||
# (WhiteKeyCenter), and white key to the right of a black key
|
||||
# (WhiteKeyRight).
|
||||
BlackKey = key_class(
|
||||
_updates, _image_strip, [_rects["black none"], _rects["black self"]], False
|
||||
)
|
||||
WhiteKey = key_class(
|
||||
_updates,
|
||||
_image_strip,
|
||||
[_rects["white none"], _rects["white self"], _rects["white self-white"]],
|
||||
)
|
||||
WhiteKeyLeft = key_class(
|
||||
_updates,
|
||||
_image_strip,
|
||||
[
|
||||
_rects["white-left none"],
|
||||
_rects["white-left self"],
|
||||
_rects["white-left self-white"],
|
||||
_rects["white-left black"],
|
||||
_rects["white-left self-black"],
|
||||
_rects["white-left all"],
|
||||
],
|
||||
)
|
||||
WhiteKeyCenter = key_class(
|
||||
_updates,
|
||||
_image_strip,
|
||||
[
|
||||
_rects["white-center none"],
|
||||
_rects["white-center self"],
|
||||
_rects["white-center self-white"],
|
||||
_rects["white-center black"],
|
||||
_rects["white-center self-black"],
|
||||
_rects["white-center all"],
|
||||
],
|
||||
)
|
||||
WhiteKeyRight = key_class(
|
||||
_updates,
|
||||
_image_strip,
|
||||
[
|
||||
_rects["white-right none"],
|
||||
_rects["white-right self"],
|
||||
_rects["white-right self-white"],
|
||||
],
|
||||
)
|
||||
|
||||
def __init__(self, start_note, n_notes):
|
||||
"""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):
|
||||
"""Populate the keyboard with key instances
|
||||
|
||||
Set the _keys and rect attributes.
|
||||
|
||||
"""
|
||||
|
||||
# Keys are entered in a list, where index is Midi note. Since there are
|
||||
# only 128 possible Midi notes the list length is manageable. Unassigned
|
||||
# note positions should never be accessed, so are set None to ensure
|
||||
# the bug is quickly detected.
|
||||
#
|
||||
key_map = [None] * 128
|
||||
|
||||
start_note = self._start_note
|
||||
end_note = self._end_note
|
||||
black_offset = self.black_key_width // 2
|
||||
prev_white_key = None
|
||||
x = y = 0
|
||||
if is_white_key(start_note):
|
||||
is_prev_white = True
|
||||
else:
|
||||
x += black_offset
|
||||
is_prev_white = False
|
||||
for note in range(start_note, end_note + 1):
|
||||
ident = note # For now notes uniquely identify keyboard keys.
|
||||
if is_white_key(note):
|
||||
if is_prev_white:
|
||||
if note == end_note or is_white_key(note + 1):
|
||||
key = self.WhiteKey(ident, (x, y), prev_white_key)
|
||||
else:
|
||||
key = self.WhiteKeyLeft(ident, (x, y), prev_white_key)
|
||||
else:
|
||||
if note == end_note or is_white_key(note + 1):
|
||||
key = self.WhiteKeyRight(ident, (x, y), prev_white_key)
|
||||
else:
|
||||
key = self.WhiteKeyCenter(ident, (x, y), prev_white_key)
|
||||
is_prev_white = True
|
||||
x += self.white_key_width
|
||||
prev_white_key = key
|
||||
else:
|
||||
key = self.BlackKey(ident, (x - black_offset, y), prev_white_key)
|
||||
is_prev_white = False
|
||||
key_map[note] = key
|
||||
self._keys = key_map
|
||||
|
||||
kb_width = key_map[self._end_note].rect.right
|
||||
kb_height = self.white_key_height
|
||||
self.rect = pygame.Rect(0, 0, kb_width, kb_height)
|
||||
|
||||
def map_regions(self, regions):
|
||||
"""Draw the key regions onto surface regions.
|
||||
|
||||
Regions must have at least 3 byte pixels. Each pixel of the keyboard
|
||||
rectangle is set to the color (note, velocity, 0). The regions surface
|
||||
must be at least as large as (0, 0, self.rect.left, self.rect.bottom)
|
||||
|
||||
"""
|
||||
|
||||
# First draw the white key regions. Then add the overlapping
|
||||
# black key regions.
|
||||
#
|
||||
cutoff = self.black_key_height
|
||||
black_keys = []
|
||||
for note in range(self._start_note, self._end_note + 1):
|
||||
key = self._keys[note]
|
||||
if 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)
|
||||
|
||||
def draw(self, surf, background, dirty_rects):
|
||||
"""Redraw all altered keyboard keys"""
|
||||
|
||||
changed_keys = self._updates
|
||||
while changed_keys:
|
||||
changed_keys.pop().draw(surf, background, dirty_rects)
|
||||
|
||||
def key_down(self, note):
|
||||
"""Signal a key down event for note"""
|
||||
|
||||
self._keys[note].down()
|
||||
|
||||
def key_up(self, note):
|
||||
"""Signal a key up event for note"""
|
||||
|
||||
self._keys[note].up()
|
||||
|
||||
|
||||
def fill_region(regions, note, rect, cutoff):
|
||||
"""Fill the region defined by rect with a (note, velocity, 0) color
|
||||
|
||||
The velocity varies from a small value at the top of the region to
|
||||
127 at the bottom. The vertical region 0 to cutoff is split into
|
||||
three parts, with velocities 42, 84 and 127. Everything below cutoff
|
||||
has velocity 127.
|
||||
|
||||
"""
|
||||
|
||||
x, y, width, height = rect
|
||||
if cutoff is None:
|
||||
cutoff = height
|
||||
delta_height = cutoff // 3
|
||||
regions.fill((note, 42, 0), (x, y, width, delta_height))
|
||||
regions.fill((note, 84, 0), (x, y + delta_height, width, delta_height))
|
||||
regions.fill(
|
||||
(note, 127, 0), (x, y + 2 * delta_height, width, height - 2 * delta_height)
|
||||
)
|
||||
|
||||
|
||||
def is_white_key(note):
|
||||
"""True if note is represented by a white key"""
|
||||
|
||||
key_pattern = [
|
||||
True,
|
||||
False,
|
||||
True,
|
||||
True,
|
||||
False,
|
||||
True,
|
||||
False,
|
||||
True,
|
||||
True,
|
||||
False,
|
||||
True,
|
||||
False,
|
||||
]
|
||||
return key_pattern[(note - 21) % len(key_pattern)]
|
||||
|
||||
|
||||
def usage():
|
||||
print("--input [device_id] : Midi message logger")
|
||||
print("--output [device_id] : Midi piano keyboard")
|
||||
print("--list : list available midi devices")
|
||||
|
||||
|
||||
def main(mode="output", device_id=None):
|
||||
"""Run a Midi example
|
||||
|
||||
Arguments:
|
||||
mode - if 'output' run a midi keyboard output example
|
||||
'input' run a midi event logger input example
|
||||
'list' list available midi devices
|
||||
(default 'output')
|
||||
device_id - midi device number; if None then use the default midi input or
|
||||
output device for the system
|
||||
|
||||
"""
|
||||
|
||||
if mode == "input":
|
||||
input_main(device_id)
|
||||
elif mode == "output":
|
||||
output_main(device_id)
|
||||
elif mode == "list":
|
||||
print_device_info()
|
||||
else:
|
||||
raise ValueError(f"Unknown mode option '{mode}'")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
device_id = int(sys.argv[-1])
|
||||
except ValueError:
|
||||
device_id = None
|
||||
|
||||
if "--input" in sys.argv or "-i" in sys.argv:
|
||||
input_main(device_id)
|
||||
|
||||
elif "--output" in sys.argv or "-o" in sys.argv:
|
||||
output_main(device_id)
|
||||
elif "--list" in sys.argv or "-l" in sys.argv:
|
||||
print_device_info()
|
||||
else:
|
||||
usage()
|
||||
|
||||
pygame.quit()
|
||||
@@ -0,0 +1,120 @@
|
||||
#!/usr/bin/env python
|
||||
"""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
|
||||
them on the screen.
|
||||
|
||||
It also has a separate player character that can be controlled with arrow keys.
|
||||
|
||||
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
|
||||
|
||||
main_dir = os.path.split(os.path.abspath(__file__))[0]
|
||||
|
||||
# Height and Width of screen
|
||||
WIDTH = 640
|
||||
HEIGHT = 480
|
||||
# Height and width of the sprite
|
||||
SPRITE_WIDTH = 80
|
||||
SPRITE_HEIGHT = 60
|
||||
|
||||
|
||||
# our game object class
|
||||
class GameObject:
|
||||
def __init__(self, image, height, speed):
|
||||
self.speed = speed
|
||||
self.image = image
|
||||
self.pos = image.get_rect().move(0, height)
|
||||
|
||||
# move the object.
|
||||
def move(self, up=False, down=False, left=False, right=False):
|
||||
if right:
|
||||
self.pos.right += self.speed
|
||||
if left:
|
||||
self.pos.right -= self.speed
|
||||
if down:
|
||||
self.pos.top += self.speed
|
||||
if up:
|
||||
self.pos.top -= self.speed
|
||||
|
||||
# controls the object such that it cannot leave the screen's viewpoint
|
||||
if self.pos.right > WIDTH:
|
||||
self.pos.left = 0
|
||||
if self.pos.top > HEIGHT - SPRITE_HEIGHT:
|
||||
self.pos.top = 0
|
||||
if self.pos.right < SPRITE_WIDTH:
|
||||
self.pos.right = WIDTH
|
||||
if self.pos.top < 0:
|
||||
self.pos.top = HEIGHT - SPRITE_HEIGHT
|
||||
|
||||
|
||||
# quick function to load an image
|
||||
def load_image(name):
|
||||
path = os.path.join(main_dir, "data", name)
|
||||
return pygame.image.load(path).convert()
|
||||
|
||||
|
||||
# here's the full code
|
||||
def main():
|
||||
pygame.init()
|
||||
clock = pygame.Clock()
|
||||
screen = pygame.display.set_mode((WIDTH, HEIGHT))
|
||||
|
||||
player = load_image("player1.gif")
|
||||
entity = load_image("alien1.gif")
|
||||
background = load_image("liquid.webp")
|
||||
|
||||
# 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)
|
||||
|
||||
screen.blit(background, (0, 0))
|
||||
|
||||
objects = []
|
||||
p = GameObject(player, 10, 3)
|
||||
for x in range(10):
|
||||
o = GameObject(entity, x * 40, x)
|
||||
objects.append(o)
|
||||
|
||||
pygame.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]:
|
||||
p.move(up=True)
|
||||
if keys[pygame.K_DOWN]:
|
||||
p.move(down=True)
|
||||
if keys[pygame.K_LEFT]:
|
||||
p.move(left=True)
|
||||
if keys[pygame.K_RIGHT]:
|
||||
p.move(right=True)
|
||||
|
||||
# Draw the background
|
||||
screen.blit(background, (0, 0))
|
||||
for e in pygame.event.get():
|
||||
# quit upon screen exit
|
||||
if e.type == pygame.QUIT:
|
||||
return
|
||||
for o in objects:
|
||||
screen.blit(background, o.pos, o.pos)
|
||||
for o in objects:
|
||||
o.move(right=True)
|
||||
screen.blit(o.image, o.pos)
|
||||
screen.blit(p.image, p.pos)
|
||||
pygame.display.update()
|
||||
clock.tick(60)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
pygame.quit()
|
||||
@@ -0,0 +1,157 @@
|
||||
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()
|
||||
@@ -0,0 +1,242 @@
|
||||
#!/usr/bin/env python
|
||||
"""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
|
||||
Music files passed from the commandline are played
|
||||
Music files and filenames are played when drag and dropped onto the pygame window
|
||||
Polls the clipboard and plays music files if it finds one there
|
||||
|
||||
Keyboard Controls:
|
||||
* Press space or enter to pause music playback
|
||||
* Press up or down to change the music volume
|
||||
* Press left or right to seek 5 seconds into the track
|
||||
* Press escape to quit
|
||||
* Press any other button to skip to the next music file in the list
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
import pygame
|
||||
|
||||
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):
|
||||
"""
|
||||
This function will check if filename exists and is a music file
|
||||
If it is the file will be added to a list of music files(even if already there)
|
||||
Type checking is by the extension of the file, not by its contents
|
||||
We can only discover if the file is valid when we mixer.music.load() it later
|
||||
|
||||
It looks in the file directory and its data subdirectory
|
||||
"""
|
||||
if filename.rpartition(".")[2].lower() not in music_file_types:
|
||||
print(f"{filename} not added to file list")
|
||||
print("only these files types are allowed: ", music_file_types)
|
||||
return False
|
||||
elif os.path.exists(filename):
|
||||
music_file_list.append(filename)
|
||||
elif os.path.exists(os.path.join(main_dir, filename)):
|
||||
music_file_list.append(os.path.join(main_dir, filename))
|
||||
elif os.path.exists(os.path.join(data_dir, filename)):
|
||||
music_file_list.append(os.path.join(data_dir, filename))
|
||||
else:
|
||||
print("file not found")
|
||||
return False
|
||||
print(f"{filename} added to file list")
|
||||
return True
|
||||
|
||||
|
||||
def play_file(filename):
|
||||
"""
|
||||
This function will call add_file and play it if successful
|
||||
The music will fade in during the first 4 seconds
|
||||
set_endevent is used to post a MUSIC_DONE event when the song finishes
|
||||
The main loop will call play_next() when the MUSIC_DONE event is received
|
||||
"""
|
||||
global starting_pos
|
||||
|
||||
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:
|
||||
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)
|
||||
|
||||
if filename.rpartition(".")[2].lower() in music_can_seek:
|
||||
print("file supports seeking")
|
||||
starting_pos = 0
|
||||
else:
|
||||
print("file does not support seeking")
|
||||
starting_pos = -1
|
||||
pygame.mixer.music.set_endevent(MUSIC_DONE)
|
||||
|
||||
|
||||
def play_next():
|
||||
"""
|
||||
This function will play the next song in music_file_list
|
||||
It uses pop(0) to get the next song and then appends it to the end of the list
|
||||
The song will fade in during the first 4 seconds
|
||||
"""
|
||||
|
||||
global starting_pos
|
||||
if len(music_file_list) > 1:
|
||||
nxt = music_file_list.pop(0)
|
||||
|
||||
try:
|
||||
pygame.mixer.music.load(nxt)
|
||||
except pygame.error as e:
|
||||
print(e)
|
||||
print(f"{nxt} removed from file list")
|
||||
|
||||
music_file_list.append(nxt)
|
||||
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)
|
||||
|
||||
if nxt.rpartition(".")[2].lower() in music_can_seek:
|
||||
starting_pos = 0
|
||||
else:
|
||||
starting_pos = -1
|
||||
|
||||
|
||||
def change_music_position(amount):
|
||||
"""
|
||||
Changes current playback position by amount seconds.
|
||||
This only works with OGG and MP3 files.
|
||||
music.get_pos() returns how many milliseconds the song has played, not
|
||||
the current position in the file. We must track the starting position
|
||||
ourselves. music.set_pos() will set the position in seconds.
|
||||
"""
|
||||
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
|
||||
old_pos = starting_pos + played_for
|
||||
starting_pos = old_pos + amount
|
||||
pygame.mixer.music.play(start=starting_pos)
|
||||
print(f"jumped from {old_pos} to {starting_pos}")
|
||||
|
||||
|
||||
def main():
|
||||
global font # this will be used by the draw_text_line function
|
||||
global volume, starting_pos
|
||||
global screen
|
||||
running = True
|
||||
paused = False
|
||||
|
||||
# we will be polling for key up and key down events
|
||||
# users should be able to change the volume by holding the up and down arrows
|
||||
# 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()
|
||||
|
||||
clipped = ""
|
||||
if pygame.scrap.has_text():
|
||||
clipped = pygame.scrap.get_text()
|
||||
|
||||
# add the command line arguments to the music_file_list
|
||||
for arg in sys.argv[1:]:
|
||||
add_file(arg)
|
||||
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!
|
||||
|
||||
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:
|
||||
running = False
|
||||
elif ev.type == pygame.DROPTEXT:
|
||||
play_file(ev.text)
|
||||
elif ev.type == pygame.DROPFILE:
|
||||
play_file(ev.file)
|
||||
elif ev.type == MUSIC_DONE:
|
||||
play_next()
|
||||
elif ev.type == pygame.KEYDOWN:
|
||||
if ev.key == pygame.K_ESCAPE:
|
||||
running = False # exit loop
|
||||
elif ev.key in (pygame.K_SPACE, pygame.K_RETURN):
|
||||
if paused:
|
||||
pygame.mixer.music.unpause()
|
||||
paused = False
|
||||
else:
|
||||
pygame.mixer.music.pause()
|
||||
paused = True
|
||||
elif ev.key == pygame.K_UP:
|
||||
change_volume = VOLUME_CHANGE_AMOUNT
|
||||
elif ev.key == pygame.K_DOWN:
|
||||
change_volume = -VOLUME_CHANGE_AMOUNT
|
||||
elif ev.key == pygame.K_RIGHT:
|
||||
change_music_position(+5)
|
||||
elif ev.key == pygame.K_LEFT:
|
||||
change_music_position(-5)
|
||||
|
||||
else:
|
||||
play_next()
|
||||
|
||||
elif ev.type == pygame.KEYUP:
|
||||
if ev.key in (pygame.K_UP, pygame.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)
|
||||
print("volume:", volume)
|
||||
|
||||
if pygame.scrap.has_text():
|
||||
new_text = pygame.scrap.get_text()
|
||||
if new_text != clipped:
|
||||
clipped = new_text
|
||||
play_file(clipped)
|
||||
|
||||
pygame.display.flip()
|
||||
clock.tick(9) # keep CPU use down by updating screen less often
|
||||
|
||||
pygame.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,164 @@
|
||||
#!/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()
|
||||
@@ -0,0 +1,143 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.pixelarray
|
||||
|
||||
PixelArray does array processing of pixels.
|
||||
Sort of like another array processor called 'numpy' - But for pixels.
|
||||
|
||||
Flip it,
|
||||
stripe it,
|
||||
rotate it.
|
||||
|
||||
Controls
|
||||
--------
|
||||
|
||||
To see different effects - press a key or click a mouse.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
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.fill((255, 255, 255))
|
||||
screen.blit(image, (0, 0))
|
||||
pygame.display.flip()
|
||||
while True:
|
||||
event = pygame.event.wait()
|
||||
if event.type == pygame.QUIT:
|
||||
pygame.quit()
|
||||
raise SystemExit
|
||||
if event.type in [pygame.MOUSEBUTTONDOWN, pygame.KEYDOWN]:
|
||||
break
|
||||
|
||||
|
||||
def main():
|
||||
pygame.init()
|
||||
|
||||
pygame.display.set_mode((255, 255))
|
||||
surface = pygame.Surface((255, 255))
|
||||
|
||||
pygame.display.flip()
|
||||
|
||||
# Create the PixelArray.
|
||||
ar = pygame.PixelArray(surface)
|
||||
|
||||
# Do some easy gradient effect.
|
||||
for y in range(255):
|
||||
r, g, b = y, y, y
|
||||
ar[:, y] = (r, g, b)
|
||||
del ar
|
||||
show(surface)
|
||||
|
||||
# We have made some gradient effect, now flip it.
|
||||
ar = pygame.PixelArray(surface)
|
||||
ar[:] = ar[:, ::-1]
|
||||
del ar
|
||||
show(surface)
|
||||
|
||||
# Every second column will be made blue
|
||||
ar = pygame.PixelArray(surface)
|
||||
ar[::2] = (0, 0, 255)
|
||||
del ar
|
||||
show(surface)
|
||||
|
||||
# Every second row will be made green
|
||||
ar = pygame.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)
|
||||
ar[:] = ar[:, ::-1]
|
||||
del ar
|
||||
show(surface)
|
||||
|
||||
# Flip the image around the x axis.
|
||||
ar = pygame.PixelArray(surface)
|
||||
ar[:] = ar[::-1, :]
|
||||
del ar
|
||||
show(surface)
|
||||
|
||||
# Every second column will be made white.
|
||||
ar = pygame.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[:] = 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)
|
||||
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)
|
||||
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.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)
|
||||
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)
|
||||
ar3 = ar1.compare(ar2, 0.07)
|
||||
sf3 = ar3.surface
|
||||
del ar1, ar2, ar3
|
||||
show(sf3)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
pygame.quit()
|
||||
@@ -0,0 +1,131 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.playmus
|
||||
|
||||
A simple music player.
|
||||
|
||||
Use pygame.mixer.music to play an audio file.
|
||||
|
||||
A window is created to handle keyboard events for playback commands.
|
||||
|
||||
|
||||
Keyboard Controls
|
||||
-----------------
|
||||
|
||||
space - play/pause toggle
|
||||
r - rewind
|
||||
f - fade out
|
||||
q - stop
|
||||
|
||||
"""
|
||||
|
||||
import sys
|
||||
|
||||
import pygame
|
||||
|
||||
pygame.init()
|
||||
|
||||
|
||||
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)
|
||||
|
||||
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()
|
||||
|
||||
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))
|
||||
|
||||
|
||||
def show_usage_message():
|
||||
print(
|
||||
"Usage: python playmus.py <file>\n"
|
||||
" python -m pygame.examples.playmus <file>"
|
||||
)
|
||||
|
||||
|
||||
def main(file_path):
|
||||
"""Play an audio file with pygame.mixer.music"""
|
||||
|
||||
screen = pygame.display.set_mode((600, 400))
|
||||
screen.fill((16, 24, 32, 255))
|
||||
|
||||
write_lines(screen, "Loading ...", starting_line=-1)
|
||||
pygame.mixer.init(frequency=44100)
|
||||
pygame.mixer.music.load(file_path)
|
||||
|
||||
pygame.display.set_caption(f"File : {file_path}")
|
||||
|
||||
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()
|
||||
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]:
|
||||
paused = False
|
||||
pygame.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()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Check the only command line argument, a file path
|
||||
if len(sys.argv) != 2:
|
||||
show_usage_message()
|
||||
else:
|
||||
main(sys.argv[1])
|
||||
@@ -0,0 +1,98 @@
|
||||
#!/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()
|
||||
@@ -0,0 +1,49 @@
|
||||
#!/usr/bin/env python
|
||||
import pygame
|
||||
|
||||
RESOLUTION = (160, 120)
|
||||
FPS = 30
|
||||
|
||||
|
||||
def main():
|
||||
pygame.init()
|
||||
|
||||
clock = pygame.Clock()
|
||||
|
||||
screen = pygame.display.set_mode(RESOLUTION, pygame.RESIZABLE)
|
||||
pygame.display._set_autoresize(False)
|
||||
|
||||
# MAIN LOOP
|
||||
|
||||
done = False
|
||||
|
||||
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()
|
||||
@@ -0,0 +1,78 @@
|
||||
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()
|
||||
@@ -0,0 +1,147 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.scaletest
|
||||
|
||||
Shows an interactive image scaler.
|
||||
|
||||
"""
|
||||
|
||||
import sys
|
||||
import time
|
||||
|
||||
import pygame
|
||||
|
||||
|
||||
def main(imagefile, convert_alpha=False, run_speed_test=False):
|
||||
"""show an interactive image scaler
|
||||
|
||||
Args:
|
||||
imagefile - name of source image (required)
|
||||
convert_alpha - use convert_alpha() on the surf (default False)
|
||||
run_speed_test - (default False)
|
||||
"""
|
||||
|
||||
# initialize display
|
||||
pygame.display.init()
|
||||
# load background image
|
||||
background = pygame.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))
|
||||
background = background.convert_alpha()
|
||||
|
||||
speed_test(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)
|
||||
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()
|
||||
|
||||
# main loop
|
||||
while running:
|
||||
clock.tick(60)
|
||||
|
||||
image = pygame.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
|
||||
):
|
||||
running = False
|
||||
|
||||
pressed_keys = pygame.key.get_pressed()
|
||||
|
||||
if pressed_keys[pygame.K_UP]:
|
||||
cursize[1] -= 2
|
||||
if cursize[1] < 1:
|
||||
cursize[1] = 1
|
||||
if pressed_keys[pygame.K_DOWN]:
|
||||
cursize[1] += 2
|
||||
if pressed_keys[pygame.K_LEFT]:
|
||||
cursize[0] -= 2
|
||||
if cursize[0] < 1:
|
||||
cursize[0] = 1
|
||||
if pressed_keys[pygame.K_RIGHT]:
|
||||
cursize[0] += 2
|
||||
pygame.quit()
|
||||
|
||||
|
||||
def speed_test(image):
|
||||
print(f"\nImage Scaling Speed Test - Image Size {str(image.get_size())}\n")
|
||||
|
||||
imgsize = [image.get_width(), image.get_height()]
|
||||
duration = 0.0
|
||||
for i in range(128):
|
||||
shrinkx = (imgsize[0] * i) // 128
|
||||
shrinky = (imgsize[1] * i) // 128
|
||||
start = time.time()
|
||||
tempimg = pygame.transform.smoothscale(image, (shrinkx, shrinky))
|
||||
duration += time.time() - start
|
||||
del tempimg
|
||||
|
||||
print(f"Average transform.smoothscale shrink time: {duration / 128 * 1000:.4f} ms.")
|
||||
|
||||
duration = 0.0
|
||||
for i in range(128):
|
||||
expandx = (imgsize[0] * (i + 129)) // 128
|
||||
expandy = (imgsize[1] * (i + 129)) // 128
|
||||
start = time.time()
|
||||
tempimg = pygame.transform.smoothscale(image, (expandx, expandy))
|
||||
duration += time.time() - start
|
||||
del tempimg
|
||||
|
||||
print(f"Average transform.smoothscale expand time: {duration / 128 * 1000:.4f} ms.")
|
||||
|
||||
duration = 0.0
|
||||
for i in range(128):
|
||||
shrinkx = (imgsize[0] * i) // 128
|
||||
shrinky = (imgsize[1] * i) // 128
|
||||
start = time.time()
|
||||
tempimg = pygame.transform.scale(image, (shrinkx, shrinky))
|
||||
duration += time.time() - start
|
||||
del tempimg
|
||||
|
||||
print(f"Average transform.scale shrink time: {duration / 128 * 1000:.4f} ms.")
|
||||
|
||||
duration = 0.0
|
||||
for i in range(128):
|
||||
expandx = (imgsize[0] * (i + 129)) // 128
|
||||
expandy = (imgsize[1] * (i + 129)) // 128
|
||||
start = time.time()
|
||||
tempimg = pygame.transform.scale(image, (expandx, expandy))
|
||||
duration += time.time() - start
|
||||
del tempimg
|
||||
|
||||
print(f"Average transform.scale expand time: {duration / 128 * 1000:.4f} ms.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# check input parameters
|
||||
if len(sys.argv) < 2:
|
||||
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")
|
||||
else:
|
||||
main(
|
||||
sys.argv[1],
|
||||
convert_alpha="-convert_alpha" in sys.argv,
|
||||
run_speed_test="-t" in sys.argv,
|
||||
)
|
||||
@@ -0,0 +1,73 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.scrap_clipboard
|
||||
|
||||
Demonstrates the clipboard capabilities of pygame.
|
||||
|
||||
Copy/paste!
|
||||
|
||||
|
||||
Keyboard Controls
|
||||
-----------------
|
||||
v - View the current clipboard data.
|
||||
c - Copy some text into the clipboard.
|
||||
|
||||
"""
|
||||
|
||||
import pygame
|
||||
|
||||
|
||||
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()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,198 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.scroll
|
||||
|
||||
An zoomed image viewer that demonstrates Surface.scroll
|
||||
|
||||
This example shows a scrollable image that has a zoom factor of eight.
|
||||
It uses the Surface.scroll function to shift the image on the display
|
||||
surface. A clip rectangle protects a margin area. If called as a function,
|
||||
the example accepts an optional image file path. If run as a program
|
||||
it takes an optional file path command line argument. If no file
|
||||
is provided a default image file is used.
|
||||
|
||||
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 pygame
|
||||
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
|
||||
DIR_RIGHT = 4
|
||||
|
||||
zoom_factor = 8
|
||||
|
||||
|
||||
def draw_arrow(surf, color, posn, direction):
|
||||
x, y = posn
|
||||
if direction == DIR_UP:
|
||||
pointlist = ((x - 29, y + 30), (x + 30, y + 30), (x + 1, y - 29), (x, y - 29))
|
||||
elif direction == DIR_DOWN:
|
||||
pointlist = ((x - 29, y - 29), (x + 30, y - 29), (x + 1, y + 30), (x, y + 30))
|
||||
elif direction == DIR_LEFT:
|
||||
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)
|
||||
|
||||
|
||||
def add_arrow_button(screen, regions, posn, direction):
|
||||
draw_arrow(screen, "black", posn, direction)
|
||||
draw_arrow(regions, (direction, 0, 0), posn, direction)
|
||||
|
||||
|
||||
def scroll_view(screen, image, direction, view_rect):
|
||||
src_rect = None
|
||||
zoom_view_rect = screen.get_clip()
|
||||
image_w, image_h = image.get_size()
|
||||
if direction == DIR_UP:
|
||||
if view_rect.top > 0:
|
||||
screen.scroll(dy=zoom_factor)
|
||||
view_rect.move_ip(0, -1)
|
||||
src_rect = view_rect.copy()
|
||||
src_rect.h = 1
|
||||
dst_rect = zoom_view_rect.copy()
|
||||
dst_rect.h = zoom_factor
|
||||
elif direction == DIR_DOWN:
|
||||
if view_rect.bottom < image_h:
|
||||
screen.scroll(dy=-zoom_factor)
|
||||
view_rect.move_ip(0, 1)
|
||||
src_rect = view_rect.copy()
|
||||
src_rect.h = 1
|
||||
src_rect.bottom = view_rect.bottom
|
||||
dst_rect = zoom_view_rect.copy()
|
||||
dst_rect.h = zoom_factor
|
||||
dst_rect.bottom = zoom_view_rect.bottom
|
||||
elif direction == DIR_LEFT:
|
||||
if view_rect.left > 0:
|
||||
screen.scroll(dx=zoom_factor)
|
||||
view_rect.move_ip(-1, 0)
|
||||
src_rect = view_rect.copy()
|
||||
src_rect.w = 1
|
||||
dst_rect = zoom_view_rect.copy()
|
||||
dst_rect.w = zoom_factor
|
||||
elif direction == DIR_RIGHT:
|
||||
if view_rect.right < image_w:
|
||||
screen.scroll(dx=-zoom_factor)
|
||||
view_rect.move_ip(1, 0)
|
||||
src_rect = view_rect.copy()
|
||||
src_rect.w = 1
|
||||
src_rect.right = view_rect.right
|
||||
dst_rect = zoom_view_rect.copy()
|
||||
dst_rect.w = zoom_factor
|
||||
dst_rect.right = zoom_view_rect.right
|
||||
if src_rect is not None:
|
||||
scale(image.subsurface(src_rect), dst_rect.size, screen.subsurface(dst_rect))
|
||||
pygame.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")
|
||||
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")
|
||||
|
||||
pygame.init()
|
||||
pygame.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)
|
||||
|
||||
try:
|
||||
screen = pygame.display.set_mode(win_size)
|
||||
screen.fill(background_color)
|
||||
pygame.display.flip()
|
||||
|
||||
image = pygame.image.load(image_file).convert()
|
||||
image_w, image_h = image.get_size()
|
||||
|
||||
if image_w < view_size[0] or image_h < view_size[1]:
|
||||
print("The source image is too small for this example.")
|
||||
print("A %i by %i or larger image is required." % zoom_view_size)
|
||||
return
|
||||
|
||||
regions = pygame.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
|
||||
)
|
||||
add_arrow_button(screen, regions, (win_size[0] // 2, 40), DIR_UP)
|
||||
add_arrow_button(
|
||||
screen, regions, (win_size[0] // 2, win_size[1] - 40), DIR_DOWN
|
||||
)
|
||||
pygame.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])
|
||||
|
||||
scale(
|
||||
image.subsurface(view_rect),
|
||||
zoom_view_size,
|
||||
screen.subsurface(screen.get_clip()),
|
||||
)
|
||||
pygame.display.flip()
|
||||
|
||||
# the direction we will scroll in.
|
||||
direction = None
|
||||
|
||||
clock = pygame.Clock()
|
||||
clock.tick()
|
||||
|
||||
going = True
|
||||
|
||||
while going:
|
||||
# wait for events before doing anything.
|
||||
# events = [pygame.event.wait()] + pygame.event.get()
|
||||
events = pygame.event.get()
|
||||
|
||||
# During the loop, if a key is held, scroll the view.
|
||||
keys = pygame.key.get_pressed()
|
||||
if keys[pygame.K_UP]:
|
||||
scroll_view(screen, image, DIR_UP, view_rect)
|
||||
if keys[pygame.K_DOWN]:
|
||||
scroll_view(screen, image, DIR_DOWN, view_rect)
|
||||
if keys[pygame.K_LEFT]:
|
||||
scroll_view(screen, image, DIR_LEFT, view_rect)
|
||||
if keys[pygame.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:
|
||||
going = False
|
||||
|
||||
# handle mouse button presses on arrows.
|
||||
elif e.type == pygame.MOUSEBUTTONDOWN:
|
||||
direction = regions.get_at(e.pos)[0]
|
||||
elif e.type == pygame.MOUSEBUTTONUP:
|
||||
direction = None
|
||||
|
||||
if direction:
|
||||
scroll_view(screen, image, direction, view_rect)
|
||||
clock.tick(30)
|
||||
|
||||
finally:
|
||||
pygame.key.set_repeat(old_k_delay, old_k_interval)
|
||||
pygame.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) > 1:
|
||||
image_file = sys.argv[1]
|
||||
else:
|
||||
image_file = None
|
||||
main(image_file)
|
||||
@@ -0,0 +1,91 @@
|
||||
#!/usr/bin/env python
|
||||
"""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
|
||||
for you. The game thinks it's a 640x480 window, but really it can be bigger.
|
||||
Mouse events are scaled for you, so your game doesn't need to do it.
|
||||
|
||||
Passing SCALED to pygame.display.set_mode means the resolution depends
|
||||
on desktop size and the graphics are scaled.
|
||||
"""
|
||||
|
||||
import sys
|
||||
|
||||
import pygame
|
||||
|
||||
RES = (160, 120)
|
||||
FPS = 30
|
||||
|
||||
|
||||
def main():
|
||||
pygame.init()
|
||||
|
||||
clock = pygame.Clock()
|
||||
|
||||
print("desktops", pygame.display.get_desktop_sizes())
|
||||
|
||||
do_vsync = bool("--vsync" in sys.argv)
|
||||
|
||||
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)
|
||||
|
||||
# MAIN LOOP
|
||||
|
||||
done = False
|
||||
|
||||
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()
|
||||
@@ -0,0 +1,47 @@
|
||||
#!/usr/bin/env python
|
||||
"""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
|
||||
we don't even bother loading all of the pygame package.
|
||||
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
|
||||
|
||||
main_dir = os.path.split(os.path.abspath(__file__))[0]
|
||||
|
||||
|
||||
def main(file_path=None):
|
||||
"""Play an audio file as a buffered sound sample
|
||||
|
||||
:param str file_path: audio file (default data/secosmic_low.wav)
|
||||
"""
|
||||
# choose a desired audio format
|
||||
pygame.mixer.init(11025) # raises exception on fail
|
||||
|
||||
# load the sound
|
||||
sound = pygame.mixer.Sound(file_path)
|
||||
|
||||
# start playing
|
||||
print("Playing Sound...")
|
||||
channel = sound.play()
|
||||
|
||||
# poll until finished
|
||||
while channel.get_busy(): # still playing
|
||||
print(" ...still going...")
|
||||
pygame.time.wait(1000)
|
||||
print("...Finished")
|
||||
pygame.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) > 1:
|
||||
main(sys.argv[1])
|
||||
else:
|
||||
main(os.path.join(main_dir, "data", "secosmic_lo.wav"))
|
||||
@@ -0,0 +1,218 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.sound_array_demos
|
||||
|
||||
Creates an echo effect on any Sound object.
|
||||
|
||||
Uses sndarray and numpy to create offset faded copies of the
|
||||
original sound. Currently it just uses hardcoded values for the
|
||||
number of echos and the delay. Easy for you to recreate as
|
||||
needed.
|
||||
|
||||
version 2. changes:
|
||||
- Should work with different sample rates now.
|
||||
- put into a function.
|
||||
- Uses numpy by default, but falls back on Numeric.
|
||||
"""
|
||||
|
||||
import os
|
||||
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)
|
||||
|
||||
|
||||
def make_echo(sound, samples_per_second, mydebug=True):
|
||||
"""returns a sound which is echoed of the last one."""
|
||||
|
||||
echo_length = 3.5
|
||||
|
||||
a1 = pygame.sndarray.array(sound)
|
||||
if mydebug:
|
||||
print(f"SHAPE1: {a1.shape}")
|
||||
|
||||
length = a1.shape[0]
|
||||
|
||||
# myarr = zeros(length+12000)
|
||||
myarr = zeros(a1.shape, int32)
|
||||
|
||||
if len(a1.shape) > 1:
|
||||
# mult = a1.shape[1]
|
||||
size = (a1.shape[0] + int(echo_length * a1.shape[0]), a1.shape[1])
|
||||
# size = (a1.shape[0] + int(a1.shape[0] + (echo_length * 3000)), a1.shape[1])
|
||||
else:
|
||||
# mult = 1
|
||||
size = (a1.shape[0] + int(echo_length * a1.shape[0]),)
|
||||
# size = (a1.shape[0] + int(a1.shape[0] + (echo_length * 3000)),)
|
||||
|
||||
if mydebug:
|
||||
print(int(echo_length * a1.shape[0]))
|
||||
myarr = zeros(size, int32)
|
||||
|
||||
if mydebug:
|
||||
print(f"size {size}")
|
||||
print(myarr.shape)
|
||||
myarr[:length] = a1
|
||||
# print(myarr[3000:length+3000])
|
||||
# print(a1 >> 1)
|
||||
# print("a1.shape %s" % (a1.shape,))
|
||||
# c = myarr[3000:length+(3000*mult)]
|
||||
# print("c.shape %s" % (c.shape,))
|
||||
|
||||
incr = int(samples_per_second / echo_length)
|
||||
gap = length
|
||||
|
||||
myarr[incr : gap + incr] += a1 >> 1
|
||||
myarr[incr * 2 : gap + (incr * 2)] += a1 >> 2
|
||||
myarr[incr * 3 : gap + (incr * 3)] += a1 >> 3
|
||||
myarr[incr * 4 : gap + (incr * 4)] += a1 >> 4
|
||||
|
||||
if mydebug:
|
||||
print(f"SHAPE2: {myarr.shape}")
|
||||
|
||||
sound2 = pygame.sndarray.make_sound(myarr.astype(int16))
|
||||
|
||||
return sound2
|
||||
|
||||
|
||||
def slow_down_sound(sound, rate):
|
||||
"""returns a sound which is a slowed down version of the original.
|
||||
rate - at which the sound should be slowed down. eg. 0.5 would be half speed.
|
||||
"""
|
||||
|
||||
raise NotImplementedError()
|
||||
# grow_rate = 1 / rate
|
||||
# make it 1/rate times longer.
|
||||
# a1 = pygame.sndarray.array(sound)
|
||||
# surf = pygame.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]))
|
||||
# print(scaled_surf)
|
||||
# print(surf)
|
||||
|
||||
# a2 = a1 * rate
|
||||
# print(a1.shape)
|
||||
# print(a2.shape)
|
||||
# print(a2)
|
||||
# sound2 = pygame.sndarray.make_sound(a2.astype(int16))
|
||||
# return sound2
|
||||
|
||||
|
||||
def sound_from_pos(sound, start_pos, samples_per_second=None, inplace=1):
|
||||
"""returns a sound which begins at the start_pos.
|
||||
start_pos - in seconds from the beginning.
|
||||
samples_per_second -
|
||||
"""
|
||||
|
||||
# see if we want to reuse the sound data or not.
|
||||
if inplace:
|
||||
a1 = pygame.sndarray.samples(sound)
|
||||
else:
|
||||
a1 = pygame.sndarray.array(sound)
|
||||
|
||||
# see if samples per second has been given. If not, query the pygame.mixer.
|
||||
# eg. it might be set to 22050
|
||||
if samples_per_second is None:
|
||||
samples_per_second = pygame.mixer.get_init()[0]
|
||||
|
||||
# figure out the start position in terms of samples.
|
||||
start_pos_in_samples = int(start_pos * samples_per_second)
|
||||
|
||||
# cut the beginning off the sound at the start position.
|
||||
a2 = a1[start_pos_in_samples:]
|
||||
|
||||
# make the Sound instance from the array.
|
||||
sound2 = pygame.sndarray.make_sound(a2)
|
||||
|
||||
return sound2
|
||||
|
||||
|
||||
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()}")
|
||||
|
||||
samples_per_second = pygame.mixer.get_init()[0]
|
||||
|
||||
print(("-" * 30) + "\n")
|
||||
print("loading sound")
|
||||
sound = pygame.mixer.Sound(os.path.join(main_dir, "data", "car_door.wav"))
|
||||
|
||||
print("-" * 30)
|
||||
print("start positions")
|
||||
print("-" * 30)
|
||||
|
||||
start_pos = 0.1
|
||||
sound2 = sound_from_pos(sound, start_pos, samples_per_second)
|
||||
|
||||
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)
|
||||
|
||||
print("waiting 2 seconds")
|
||||
pygame.time.wait(2000)
|
||||
print("playing original sound")
|
||||
|
||||
sound.play()
|
||||
while pygame.mixer.get_busy():
|
||||
pygame.time.wait(200)
|
||||
|
||||
print("waiting 2 seconds")
|
||||
pygame.time.wait(2000)
|
||||
|
||||
# if 0:
|
||||
# #TODO: this is broken.
|
||||
# print(("-" * 30) + "\n")
|
||||
# print("Slow down the original sound.")
|
||||
# rate = 0.2
|
||||
# slowed_sound = slow_down_sound(sound, rate)
|
||||
# slowed_sound.play()
|
||||
# while pygame.mixer.get_busy():
|
||||
# pygame.time.wait(200)
|
||||
|
||||
print("-" * 30)
|
||||
print("echoing")
|
||||
print("-" * 30)
|
||||
|
||||
t1 = time.time()
|
||||
sound2 = make_echo(sound, samples_per_second)
|
||||
print("time to make echo %i" % (time.time() - t1,))
|
||||
|
||||
print("original sound")
|
||||
sound.play()
|
||||
while pygame.mixer.get_busy():
|
||||
pygame.time.wait(200)
|
||||
|
||||
print("echoed sound")
|
||||
sound2.play()
|
||||
while pygame.mixer.get_busy():
|
||||
pygame.time.wait(200)
|
||||
|
||||
sound = pygame.mixer.Sound(os.path.join(main_dir, "data", "secosmic_lo.wav"))
|
||||
|
||||
t1 = time.time()
|
||||
sound3 = make_echo(sound, samples_per_second)
|
||||
print("time to make echo %i" % (time.time() - t1,))
|
||||
|
||||
print("original sound")
|
||||
sound.play()
|
||||
while pygame.mixer.get_busy():
|
||||
pygame.time.wait(200)
|
||||
|
||||
print("echoed sound")
|
||||
sound3.play()
|
||||
while pygame.mixer.get_busy():
|
||||
pygame.time.wait(200)
|
||||
|
||||
pygame.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,105 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.sprite_texture
|
||||
|
||||
Experimental! Uses APIs which may disappear in the next release (_sdl2 is private).
|
||||
|
||||
|
||||
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
|
||||
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))
|
||||
|
||||
|
||||
def main():
|
||||
pygame.display.init()
|
||||
pygame.key.set_repeat(10, 10)
|
||||
|
||||
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
|
||||
|
||||
self.rect.w *= 5
|
||||
self.rect.h *= 5
|
||||
|
||||
img.origin = self.rect.w / 2, self.rect.h / 2
|
||||
|
||||
sprite = Something(Image(tex, (0, 0, tex.width / 2, tex.height / 2)))
|
||||
sprite.rect.x = 250
|
||||
sprite.rect.y = 50
|
||||
|
||||
# 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)
|
||||
|
||||
import math
|
||||
|
||||
t = 0
|
||||
running = True
|
||||
clock = pygame.Clock()
|
||||
renderer.draw_color = (255, 0, 0, 255)
|
||||
|
||||
while running:
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
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
|
||||
|
||||
renderer.clear()
|
||||
t += 1
|
||||
|
||||
img = sprite.image
|
||||
img.angle += 1
|
||||
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']))
|
||||
|
||||
group.draw(renderer)
|
||||
|
||||
renderer.present()
|
||||
|
||||
clock.tick(60)
|
||||
win.title = str(f"FPS: {clock.get_fps()}")
|
||||
|
||||
pygame.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,135 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.stars
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
import random
|
||||
|
||||
import pygame
|
||||
|
||||
|
||||
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
|
||||
"""
|
||||
|
||||
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
|
||||
|
||||
|
||||
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 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_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 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
|
||||
|
||||
screen_rect = screen.get_rect()
|
||||
spawn_point = pygame.Vector2(screen_rect.center)
|
||||
|
||||
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)
|
||||
|
||||
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()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,237 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.examples.testsprite
|
||||
|
||||
Like the testsprite.c that comes with libsdl, this pygame version shows
|
||||
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.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from random import randint
|
||||
from time import time
|
||||
|
||||
import pygame
|
||||
|
||||
main_dir = os.path.split(os.path.abspath(__file__))[0]
|
||||
data_dir = os.path.join(main_dir, "data")
|
||||
|
||||
|
||||
# use this to use update rects or not.
|
||||
# If the screen is mostly full, then update rects are not useful.
|
||||
update_rects = True
|
||||
if "-update_rects" in sys.argv:
|
||||
update_rects = True
|
||||
if "-noupdate_rects" in sys.argv:
|
||||
update_rects = False
|
||||
|
||||
use_static = False
|
||||
if "-static" in sys.argv:
|
||||
use_static = True
|
||||
|
||||
|
||||
use_layered_dirty = False
|
||||
if "-layered_dirty" in sys.argv:
|
||||
update_rects = True
|
||||
use_layered_dirty = True
|
||||
|
||||
|
||||
flags = 0
|
||||
if "-flip" in sys.argv:
|
||||
flags ^= pygame.DOUBLEBUF
|
||||
|
||||
if "-fullscreen" in sys.argv:
|
||||
flags ^= pygame.FULLSCREEN
|
||||
|
||||
if "-sw" in sys.argv:
|
||||
flags ^= pygame.SWSURFACE
|
||||
|
||||
use_rle = True
|
||||
|
||||
if "-scaled" in sys.argv:
|
||||
flags ^= pygame.SCALED
|
||||
|
||||
screen_dims = [640, 480]
|
||||
|
||||
if "-height" in sys.argv:
|
||||
i = sys.argv.index("-height")
|
||||
screen_dims[1] = int(sys.argv[i + 1])
|
||||
|
||||
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
|
||||
|
||||
print(screen_dims)
|
||||
|
||||
|
||||
class Thingy(pygame.sprite.DirtySprite):
|
||||
images = None
|
||||
|
||||
def __init__(self):
|
||||
## pygame.sprite.Sprite.__init__(self)
|
||||
pygame.sprite.DirtySprite.__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)]
|
||||
self.dirty = 2
|
||||
|
||||
def update(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 Static(pygame.sprite.DirtySprite):
|
||||
images = None
|
||||
|
||||
def __init__(self):
|
||||
pygame.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))
|
||||
|
||||
|
||||
def main(
|
||||
update_rects=True,
|
||||
use_static=False,
|
||||
use_layered_dirty=False,
|
||||
screen_dims=[640, 480],
|
||||
use_alpha=False,
|
||||
flags=0,
|
||||
):
|
||||
"""Show lots of sprites moving around
|
||||
|
||||
Optional keyword arguments:
|
||||
update_rects - use the RenderUpdate sprite group class (default True)
|
||||
use_static - include non-moving images (default False)
|
||||
use_layered_dirty - Use the FastRenderGroup sprite group (default False)
|
||||
screen_dims - Pygame window dimensions (default [640, 480])
|
||||
use_alpha - use alpha blending (default False)
|
||||
flags - additional display mode flags (default no additional flags)
|
||||
|
||||
"""
|
||||
|
||||
if use_layered_dirty:
|
||||
update_rects = True
|
||||
|
||||
pygame.init() # needed to initialise time module for get_ticks()
|
||||
pygame.display.init()
|
||||
|
||||
# if "-fast" in sys.argv:
|
||||
|
||||
screen = pygame.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()
|
||||
if num_joysticks > 0:
|
||||
stick = pygame.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"))
|
||||
|
||||
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
|
||||
)
|
||||
else:
|
||||
sprite_surface.set_colorkey([0xFF, 0xFF, 0xFF], pygame.SRCCOLORKEY)
|
||||
sprite_surface2.set_colorkey([0xFF, 0xFF, 0xFF], pygame.SRCCOLORKEY)
|
||||
|
||||
if use_alpha:
|
||||
sprite_surface = sprite_surface.convert_alpha()
|
||||
sprite_surface2 = sprite_surface2.convert_alpha()
|
||||
else:
|
||||
sprite_surface = sprite_surface.convert()
|
||||
sprite_surface2 = sprite_surface2.convert()
|
||||
|
||||
Thingy.images = [sprite_surface]
|
||||
if use_static:
|
||||
Static.images = [sprite_surface2]
|
||||
|
||||
if len(sys.argv) > 1:
|
||||
try:
|
||||
numsprites = int(sys.argv[-1])
|
||||
except Exception:
|
||||
numsprites = 100
|
||||
else:
|
||||
numsprites = 100
|
||||
sprites = None
|
||||
if use_layered_dirty:
|
||||
## sprites = pygame.sprite.FastRenderGroup()
|
||||
sprites = pygame.sprite.LayeredDirty()
|
||||
else:
|
||||
if update_rects:
|
||||
sprites = pygame.sprite.RenderUpdates()
|
||||
else:
|
||||
sprites = pygame.sprite.Group()
|
||||
|
||||
for i in range(0, numsprites):
|
||||
if use_static and i % 2 == 0:
|
||||
sprites.add(Static())
|
||||
sprites.add(Thingy())
|
||||
|
||||
frames = 0
|
||||
start = time()
|
||||
|
||||
background = pygame.Surface(screen.get_size())
|
||||
background = background.convert()
|
||||
background.fill([0, 0, 0])
|
||||
|
||||
going = True
|
||||
while going:
|
||||
if not update_rects:
|
||||
screen.fill([0, 0, 0])
|
||||
|
||||
## for sprite in sprites:
|
||||
## sprite.move()
|
||||
|
||||
if update_rects:
|
||||
sprites.clear(screen, background)
|
||||
sprites.update()
|
||||
|
||||
rects = sprites.draw(screen)
|
||||
if update_rects:
|
||||
pygame.display.update(rects)
|
||||
else:
|
||||
pygame.display.flip()
|
||||
|
||||
for event in pygame.event.get():
|
||||
if event.type in [
|
||||
pygame.QUIT,
|
||||
pygame.KEYDOWN,
|
||||
pygame.QUIT,
|
||||
pygame.JOYBUTTONDOWN,
|
||||
]:
|
||||
going = False
|
||||
|
||||
frames += 1
|
||||
end = time()
|
||||
print(f"FPS: {frames / (end - start):f}")
|
||||
pygame.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(update_rects, use_static, use_layered_dirty, screen_dims, use_alpha, flags)
|
||||
@@ -0,0 +1,314 @@
|
||||
#!/usr/bin/env python
|
||||
"""pygame.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 pygame
|
||||
|
||||
# This environment variable is important
|
||||
# If not added the candidate list will not show
|
||||
os.environ["SDL_IME_SHOW_UI"] = "1"
|
||||
|
||||
|
||||
class TextInput:
|
||||
"""
|
||||
A simple TextInput class that allows you to receive inputs in pygame.
|
||||
"""
|
||||
|
||||
# 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",
|
||||
]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
prompt: str,
|
||||
pos: tuple[int, int],
|
||||
screen_dimensions: tuple[int, int],
|
||||
print_event: bool,
|
||||
text_color="white",
|
||||
fps: int = 50,
|
||||
) -> 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_MAXSIZE = 20
|
||||
|
||||
self._ime_editing = False
|
||||
self._ime_text = ""
|
||||
self._ime_text_pos = 0
|
||||
self._ime_editing_text = ""
|
||||
self._ime_editing_pos = 0
|
||||
self.chat = ""
|
||||
|
||||
# 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.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:
|
||||
"""
|
||||
Updates the text input widget
|
||||
"""
|
||||
for event in events:
|
||||
self.handle_event(event)
|
||||
|
||||
self.second_counter += 1
|
||||
|
||||
if self.second_counter >= self.fps:
|
||||
self.second_counter = 0
|
||||
|
||||
# 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())
|
||||
|
||||
def _clamp_to_text_range(self, num: int):
|
||||
return min(len(self._ime_text), max(0, num))
|
||||
|
||||
def move_cursor_by(self, by: int):
|
||||
self._ime_text_pos = self._clamp_to_text_range(self._ime_text_pos + by)
|
||||
|
||||
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 :]}"
|
||||
)
|
||||
|
||||
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 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
|
||||
)
|
||||
|
||||
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)
|
||||
|
||||
# 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)
|
||||
|
||||
|
||||
class Game:
|
||||
"""
|
||||
A class that handles the game's events, mainloop etc.
|
||||
"""
|
||||
|
||||
# CONSTANTS
|
||||
# Frames per second, the general speed of the program
|
||||
FPS = 50
|
||||
# Size of window
|
||||
SCREEN_WIDTH, SCREEN_HEIGHT = 640, 480
|
||||
BG_COLOR = "black"
|
||||
|
||||
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()
|
||||
|
||||
# Text input
|
||||
# Set to true or add 'showevent' in argv to see IME and KEYDOWN events
|
||||
self.print_event = "showevent" in sys.argv
|
||||
self.text_input = TextInput(
|
||||
prompt="> ",
|
||||
pos=(0, 20),
|
||||
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)
|
||||
|
||||
while True:
|
||||
events = pygame.event.get()
|
||||
for event in events:
|
||||
if event.type == pygame.QUIT:
|
||||
pygame.quit()
|
||||
return
|
||||
|
||||
self.text_input.update(events)
|
||||
|
||||
# Screen updates
|
||||
self.screen.fill(self.BG_COLOR)
|
||||
self.text_input.draw(self.screen)
|
||||
|
||||
pygame.display.update()
|
||||
self.clock.tick(self.FPS)
|
||||
|
||||
|
||||
# Main loop process
|
||||
def main():
|
||||
game = Game("Text Input Example")
|
||||
game.main_loop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||