Using Pygame, draw a copy of an image in a different location - python

This is kind of a follow up to this question:
Note: This in python, using the pygame library.
I'm wanting to get some clarification on this statement which is a comment from the above question:
Another important thing, don't use the same Sprite() nor the same
Rectangle in different locations. If you want to draw another copy of
the same image in a new location make a copy of the rectangle, then
create a new Sprite() object.
I have a group of game assets and I want to pick one at random to add my
sprite group. I am currently doing this as such:
class TestSprite(pygame.sprite.Sprite):
def __init__(self, strFolder):
super(TestSprite, self).__init__()
self.image = load_image(strFolder + 'x.png'))
#....
def GetRandomAsset():
rnd = random.randrange(1, 4)
if rnd == 1:
return TestSprite('assets/A/')
elif rnd == 2:
return TestSprite('assets/B/')
elif rnd == 3:
return TestSprite('assets/C/')
else:
return TestSprite('assets/D/')
#....
my_group = pygame.sprite.Group()
my_group.add(GetRandomAsset())
#.....
#Control FPS
#Check Events
#Update State
#Clear Screen
#Draw Current State
#Update Display
Everything works as expected; Every time I run the above code, a new sprite is displayed to the screen. My problem is every time i add a sprite, im having to load it from the disk, even tho im using the same 4 images over and over again.
I imagine it would be smarter for me to store all my assets in a global list called PRELOADEDASSETS. Then whenever I need one just do: my_group.add(PRELOADEDASSETS[x])
But when I try to do that, i can only have one copy of each of my assets.
How can I preload all my assets, and then grab the stored data when needed?
Thanks!

Another important thing, don't use the same Sprite() nor the same Rectangle in different locations. If you want to draw another copy of the same image in a new location make a copy of the rectangle, then create a new Sprite() object.
This is a valid advice in this context. It's of course no problem to blit a surface multiple times to different locations (using different Rects for example), but if you use a Group to handle/simplify your drawing, you need one object for each location you want to draw your image.
To answer your actual question:
You don't need to cache the Sprite instances. Just cache the Surface instances.
This way, you can have different Sprite objects that draw the same image to different locations.
A simple cache implementation could look like this:
images = {'a': load_image('assets/A/x.png'),
'b': load_image('assets/B/x.png'),
'c': load_image('assets/C/x.png'),
'd': load_image('assets/D/x.png')}
...
class TestSprite(pygame.sprite.Sprite):
def __init__(self, image_key):
super(TestSprite, self).__init__()
self.image = images[image_key]
...
def GetRandomAsset():
image_key = random.choice(images.keys())
return TestSprite(image_key)
This will load all images upfront (may or maynot what you want); adding laziness is easy, but you probably don't want possible lags (what is best depends how many images you actually load and when).
You could even just go through all folders in your game's directory and detect and load all images automatically, but such sprees are out of scope of this answer.

Related

Blender: Rendering images and producing an animation

I am new to Blender and I’m having a bit of a tough time understanding its key concepts. I am using Blender 2.82 and working with Python scripting. My project consists of using Python to do the following:
Move object slightly.
Take picture with camera 1, camera 2, camera 3, and camera 4.
Repeat.
I had a script that did that. However, I wanted to save the position of my object (a sphere) every time I changed it during the loop in an animation, so I could later see what I did. When trying to insert keyframes for animation in my loop, it seems as if my sphere didn’t move. Below is my code. When I remove the lines that include frame_set and keyframe_insert, my sphere moves as I can see from my rendered images. I think I am confusing some kind of concept… Any help would be appreciated. The goal of this is to produce the images I would obtain from four cameras placed around an object, that is moving, so as to simulate a mocap system.
Why does inserting a keyframe change all of the images being rendered?
import bpy, bgl, blf,sys
import numpy as np
from bpy import data, ops, props, types, context
cameraNames=''
# Loop all command line arguments and try to find "cameras=east" or similar
for arg in sys.argv:
words=arg.split('=')
if ( words[0] == 'cameras'):
cameraNames = words[1]
sceneKey = bpy.data.scenes.keys()[0]
# Loop all objects and try to find Cameras
bpy.data.scenes[sceneKey].render.image_settings.file_format = 'JPEG'
bpy.data.scenes[sceneKey].cycles.max_bounces=12
bpy.data.scenes[sceneKey].render.tile_x=8
bpy.data.scenes[sceneKey].render.tile_y=8
bpy.data.scenes[sceneKey].cycles.samples = 16
bpy.data.scenes[sceneKey].cycles.caustics_reflective = False
bpy.data.scenes[sceneKey].cycles.caustics_refractive = False
bpy.data.objects['Sphere'].location=[1,1,1]
frame_num=0
for i in range(0,2): #nframes
bpy.context.scene.frame_set(frame_num)
for obj in bpy.data.objects:
# Find cameras that match cameraNames
if ( obj.type =='CAMERA') and ( cameraNames == '' or obj.name.find(cameraNames) != -1) :
# Set Scenes camera and output filename
bpy.data.scenes[sceneKey].camera = obj
bpy.data.scenes[sceneKey].render.filepath = '//'+obj.name+"_"+str(i)
# Render Scene and store the scene
bpy.ops.render.render( write_still=True )
bpy.data.objects['Sphere'].keyframe_insert(data_path="location",index=-1)
frame_num+=1
bpy.data.objects['Sphere'].location=[2,2,1]
I have no knowledge of python, but you can try to do key frame animation manually and make a script which will render the pictures after a set of key frames(whenever the object has moved to a new location)
It is not too hard (I'm talking about only the animation), just press the circle button near the play animation button on the timeline. This will turn on auto key framing and you just have to go to the desired key frame and move the object according to your need.

I need assistance regarding my function and game

def death_en():
death = pygame.Surface.blit(pygame.image.load('tombstone.png'))
if x + (WarriorSize_x * .8) == x_en:
screenDisplay.blit(death, (x_en, y_en))
I'm new to Python and over all programing. I have started learning about pygame and I'm trying to create a game. What I want this function to do is to put another image on top of the enemy that was killed, though nothing happens when I get close enough to it with the main character. I now I haven't assigned a y-axis, but want to make sure this works first. I could send the whole code if it's necessary.
Thanks in advance.
To check for collisions use the PyGame Rect Class. Keep a rectangle for your player, and a rectangle for each enemy, updating the position of the rect whenever the item it tracks changes position. Also, when an enemy or the player moves, use the function Rect.colliderect() to determine if the two items have intersected on-screen.
This might be something like:
tombstone_image = pygame.image.load('tombstone.png')
...
# Inside main loop
# Have there been any collisions?
for e_rect in all_enemy_rects:
if ( e_rect.colliderect( player_rect ) ):
screenDisplay.blit( tombstone_image, e_rect )
# TODO: remove enemy from game

trying to draw over sprite or change picture pyglet

I am trying to learn pyglet and practice some python coding with a questionnaire thing, but I am unable to find a way to make the background picture be removed or drawn on top of or something for 10 seconds. I am new and am lacking in a lot of the knowledge I would need, thank you for helping!
import pyglet
from pyglet.window import Window
from pyglet.window import key
from pyglet import image
import time
card1 = False
cat_image = pyglet.image.load("cat.png")
dog_image = pyglet.image.load("dog.png")
image = pyglet.image.load("backg.png")
background_sprite = pyglet.sprite.Sprite(image)
cat = pyglet.sprite.Sprite(cat_image)
dog = pyglet.sprite.Sprite(dog_image)
window = pyglet.window.Window(638, 404, "Life")
mouse_pos_x = 0
mouse_pos_y = 0
catmeme = pyglet.image.load("catmeme.png")
sprite_catmeme = pyglet.sprite.Sprite(catmeme)
#window.event
def on_draw():
window.clear()
background_sprite.draw()
card_draw1(63, 192, 385, 192)
def card1():
while time.time() < (time.time() + 10):
window.clear()
sprite_catmeme.draw()
#window.event
def card_draw1(x1, y1, x2, y2):
cat.set_position(x1, y1)
dog.set_position(x2, y2)
cat.draw()
dog.draw()
def card_draw2():
pass
#window.event
def on_mouse_press(x, y, button, modifiers):
if x > cat.x and x < (cat.x + cat.width):
if y > cat.y and y < (cat.y + cat.height):
card1()
game = True
while game:
on_draw()
pyglet.app.run()
There's a few flaws in the order and in which you do things.
I will try my best to describe them and give you a piece of code that might work better for what your need is.
I also think your description of the problem is a bit of an XY Problem which is quite common when asking for help on complex matters where you think you're close to a solution, so you're asking for help on the solution you've come up with and not the problem.
I'm assuming you want to show a "Splash screen" for 10 seconds, which happens to be your background? And then present the cat.png and dog.png ontop of it, correct?
If that's the case, here's where you probably need to change things in order for it to work:
The draw() function
It doesn't really update the screen much, it simply adds things to the graphical memory. What updates the screen is you or something telling the graphics library that you're done adding things to the screen and it's time to update everything you've .draw()'n. So the last thing you need in the loop would be window.flip() in order for the things you've drawn to actually show.
Your things might show if you try to wiggle the window around, it should trigger a re-draw of the scene because of how the internal mechanics of pyglet work..
If you don't call .flip() - odds are probable that the redraw() call will never occur - which again, is a internal mechanism of Pyglet/GL that tells the graphics card that something has been updated, we're done updating and it's time to redraw the scene.
a scene
This is the word most commonly used for what the user is seeing.
I'll probably throw this around a lot in my text, so it's good to know that this is what the user is seeing, not what you've .draw()'n or what's been deleted, it's the last current rendering of the graphics card to the monitor.
But because of how graphical buffers work we've might have removed or added content to the memory without actually drawing it yet. Keep this in mind.
The pyglet.app.run() call
This is a never ending loop in itself, so having that in a while game: loop doesn't really make sense because .run() will "hang" your entire application, any code you want to execute needs to be in def on_draw or an event that is generated from within the graphical code itself.
To better understand this, have a look at my code, i've pasted it around a couple of times here on SO over the years and it's a basic model of two custom classes that inherits the behavior of Pyglet but lets you design your own classes to behave slightly differently.
And most of the functionality is under on_??? functions, which is almost always a function used to catch Events. Pyglet has a lot of these built in, and we're going to override them with our own (but the names must be the same)
import pyglet
from pyglet.gl import *
key = pyglet.window.key
class CustomSprite(pyglet.sprite.Sprite):
def __init__(self, texture_file, x=0, y=0):
## Must load the texture as a image resource before initializing class:Sprite()
self.texture = pyglet.image.load(texture_file)
super(CustomSprite, self).__init__(self.texture)
self.x = x
self.y = y
def _draw(self):
self.draw()
class MainScreen(pyglet.window.Window):
def __init__ (self):
super(MainScreen, self).__init__(800, 600, fullscreen = False)
self.x, self.y = 0, 0
self.bg = CustomSprite('bg.jpg')
self.sprites = {}
self.alive = 1
def on_draw(self):
self.render()
def on_close(self):
self.alive = 0
def on_key_press(self, symbol, modifiers):
if symbol == key.ESCAPE: # [ESC]
self.alive = 0
elif symbol == key.C:
print('Rendering cat')
self.sprites['cat'] = CustomSprite('cat.png', x=10, y=10)
elif symbol == key.D:
self.sprites['dog'] = CustomSprite('dog.png', x=100, y=100)
def render(self):
self.clear()
self.bg.draw()
for sprite_name, sprite_obj in self.sprites.items():
sprite_obj._draw()
self.flip()
def run(self):
while self.alive == 1:
self.render()
# -----------> This is key <----------
# This is what replaces pyglet.app.run()
# but is required for the GUI to not freeze
#
event = self.dispatch_events()
x = MainScreen()
x.run()
Now, this code is kept simple on purpose, the full code I usually paste on SO can be found at Torxed/PygletGui, the gui.py is where most of this comes from and it's the main loop.
What I do here is simply replace the Decorators by using "actual" functions inside a class. The class itself inherits the functions from a traditional pyglet.window.Window, and as soon as you name the functions the same as the inherited onces, you replace the core functionality of Window() with whatever you decide.. In this case, i mimic the same functions but add a few of my own.
on_key_press
One such example is on_key_press(), which normally just contain a pass call and does nothing, here, we check if key.C is pressed, and if so - we add a item to self.sprites.. self.sprites just so happen to be in our render() loop, anything in there will be rendered ontop of a background.
Here's the pictures I used:
(named bg.jpg, cat.png, dog.png - note the different file endings)
class:CustomSprite
CustomSprite is a very simple class designed to make your life easier at this point, nothing else. It's very limited in functionality but the little it do is awesome.
It's soul purpose is to take a file name, load it as an image and you can treat the object like a traditional pyglet.sprite.Sprite, meaning you can move it around and manipulate it in many ways.
It saves a few lines of code having to load all the images you need and as you can see in gui_classes_generic.py you can add a heap of functions that's "invisible" and normally not readily availbale to a normal sprite class.
I use this a bunch! But the code gets complicated real fast so I kept this post simple on purpose.
the flip function
Even in my class, I still need to use flip() in order to update the contents of the screen. This is because .clear() clears the window as you would expect, that also triggers a redraw of the scene.
bg.draw() might in some cases trigger a redraw if the data is big enough or if something else happens, for instance you move the window.
but calling .flip() will tell the GL backend to force a redraw.
Further optimizations
There's a thing called batched rendering, basically the graphic card is designed to take enormous ammounts of data and render it in one go, so calling .draw() on several items will only clog the CPU before the GPU even gets a chance to shine. Read more about Batched rendering and graphics! It will save you a lot of frame rates.
Another thing is to keep as little functionality as possible in the render() loop and use the event triggers as your main source of coding style.
Pyglet does a good job of being fast, especially if you only do things on event driven tasks.
Try to avoid timers, but if you really do need to use time for things, such as removing cat.png after a certain ammount of time, use the clock/time event to call a function that removes the cat. Do not try to use your own t = time() style of code unless you know where you're putting it and why. There's a good timer, I rarely use it.. But you should if you're starting off.
This has been one hell of a wall of text, I hope it educated you some what in the life of graphics and stuff. Keep going, it's a hurdle to get into this kind of stuff but it's quite rewarding once you've mastered it (I still haven't) :)

Python and Pygame: Avoiding creating display surface twice

Heyo, this is a bit of an extension of the "Imports within imports" question asked earlier by me, so moderators feel free to merge the 2.
I have 2 files: A.py and B.py
#A.py
import pygame
import B
pygame.init()
tv = pygame.display.set_mode((256, 256))
tv.blit(<some surface here>)
#B.py
import pygame
pygame.init()
tv.blit()??? <--- I need to blit to tv, but how do I do it here?
I've tried making a blank file called Globe and assigning global values to it, but most of the time I've found it just makes my code look clunky and hard to write.
As well.. I don't want to init pygame twice either.
Is there any 'Pythonic' way to do it?
This question could really apply to any structured python application.
An executable python script is going to have an entry-point. This is the script that you call to start the application. Within this script, it can import library modules to reuse extended functionality.
Your application needs to have a single entry point. Lets assume it will be A.py.
B.py would be a library module that you will import and use its functions. It should not have to expect a global tv variable to operate on. Instead, it should have, at the very least, functions that take arguments. Or even, a class that is instantiated with a surface to use. The benefit of this approach is that your B module is now reusable and not dependent on some executable main script providing a global surface always called tv
B.py
def blitSpecial(surf):
surf.blit()
A.py
import B
tv = pygame.display.set_mode((256, 256))
B.blitSpecial(tv)
This is a good habit to get into. If all your modules depend on global objects from a main script, they will be far less reusable.
Specifically for your pygame situation, everything with the screen surface should be happening in A.py which is using all of the other modules for custom classes and utility functions.
You can write functions that take pygame.Surface objects as parameters:
class TV():
def __init__(self):
self.img = ...
### insert code to load image here
self.rect = self.img.get_rect()
def draw(self, surface):
surface.blit(self.img, self.rect.topleft)
def erase(self, surface, background):
surface.blit(background, self.rect)
I don't personally know how fast/slow this is compared to other sprite-based engines, but it's a very quick way to build out a class that can draw/erase itself.
To use it, just create a display screen and a TV object.
screen = pygame.display.set_mode((256, 256))
background = pygame.Surface((0,0),(256,256))
background.fill(pygame.Color(0,0,0))
screen.fill(pygame.Color(0,0,0))
myTVobj = TV()
Every time you want to draw a copy of the TV onto the screen you call
myTVobj.draw(screen)
To erase the object, use
myTVobj.erase(screen, background)
Then you can do fun stuff later with objects created from the TV class, like stick them in a list.
tv_list = []
tv_list.append(myTVobj)
You can add a whole bunch of TVs to a list and draw all of them at the same time.
tv_list = []
tv_list.append(myTVobj)
tv_list.append(myTVobj)
tv_list.append(myTVobj)
for tv in tv_list:
tv.draw(screen)
Or you can erase them all just by changing one line
for tv in tv_list:
tv.erase(screen)
Finally, you can add one more function to your TV class that lets you move it around. If you treat the .rect member as a 'position marker', all you have to do is fiddle with its members (hehe) to change your object's onscreen update location.
def move(self, move_amount=(1,0):
self.rect.move_ip(move_amount[0], move_amount[1])
You only need to call pygame.init() once, so I think your code should look something like this:
#A.py
import pygame
import B
def setup():
pygame.init()
tv = pygame.display.set_mode((256, 256))
...
mysurface = ...
tv.blit(mysurface)
return tv
#B.py
import pygame
def mydraw(surface):
...
surface.blit()
# In whatever file you like :)
if __name__ == '__main__':
surface_A = B.setup() # Do this first
mydraw(surface_A)

top down friction in pymunk

Been struggling with this for a couple of days, hard to find code examples on the net.
I'm making a topdown game and having trouble getting the player to move on key press. At the moment i'm using add_force or add_impulse to move the player in a direction, but the player doesn't stop.
I've read about using surface friction between the space and the player to simulate friction and here is how it's done in the tank.c demo.
However I don't understand the API enough to port this code from chipmunk into pymunk.
cpConstraint *pivot = cpSpaceAddConstraint(space, cpPivotJointNew2(tankControlBody, tankBody, cpvzero, cpvzero));
So far, I have something that looks like this:
class Player(PhysicalObject):
BASE_SPEED = 5
VISIBLE_RANGE = 400
def __init__(self, image, position, world, movementType=None):
PhysicalObject.__init__(self, image, position, world)
self.mass = 100
self.CreateBody()
self.controlBody = pymunk.Body(pymunk.inf, pymunk.inf)
self.joint = pymunk.PivotJoint(self.body, self.controlBody, (0,0))
self.joint.max_force = 100
self.joint.bias_coef = 0
world.space.add(self.joint)
I don't know how to add the constraint of the space/player to the space.
(Need someone with 1500+ rep to create a pymunk tag for this question).
Joe crossposted the question to the Chipmunk/pymunk forum, and it got a couple of more answers there. http://www.slembcke.net/forums/viewtopic.php?f=1&t=1450&start=0&st=0&sk=t&sd=a
Ive pasted/edited in parts of my answer from the forum below:
#As pymunk is python and not C, the constructor to PivotJoint is defined as
def __init__(self, a, b, *args):
pass
#and the straight conversion from c to python is
pivot1 = PivotJoint(tankControlBody, tankBody, Vec2d.zero(), Vec2d.zero())
# but ofc it works equally well with 0 tuples instead of the zero() methods:
pivot2 = PivotJoint(tankControlBody, tankBody, (0,0), (0,0))
mySpace.add(pivot1, pivot2)
Depending on if you send in one or two arguments to args, it will either use the cpPivotJointNew or cpPivotJointNew2 method in the C interface to create the joint. The difference between these two methods is that cpPivotJointNew want one pivot point as argument, and the cpPivotJointNew2 want two anchor points. So, if you send in one Vec2d pymunk will use cpPivotJointNew, but if you send in two Vec2d it will use cpPivotJointNew2.
Full PivotJoint constructor documentation is here: PivotJoint constructor docs
I'm not familiar with either system you've mentioned, but some basic game ideas that may relate are:
If you add a force (or impulse) which affects movement, for the entity to stop, you must also take it away. In my games if I had a function AddImpulse()/AddForce() I would have a corresponding one such as Apply_Friction() which would reverse the effect by however much you want (based on terrain?) until movespeed is zero or less. I personally wouldn't bother with this method for movement unless needed for gameplay since it can add more computations that its worth each update.
There should be some way to track KeyPressed and/or KeyPosition and then using those x/y coordinates are incrememnted based on player speed. Without knowing what you've tried or how much the API does for you, it's hard to really say more.
Hope this helps. If this is stuff you already knew kindly ignore it.

Categories