#game-development

1 messages Β· Page 50 of 1

potent ice
#

That is a very hard question to answer. You have everything from game engines, game libraries and graphics libraries. Then you have different styles of game. 3D games, pixel art games etc.

#

I think whatever you start out using will teach you things that will translate to other libraries / languages / engines.

fierce wraith
#

hey @potent ice, im running into a format error with this:

self.sphere.buffer(self.buffer1, '3f8/i 3f8/i 3f8/i 1f8/i', ['planet_pos', 'planet_velocity', 'planet_force', 'planet_mass'])```
#

i think i've got the format string wrong

potent ice
#

you just need to pass in the position don't you?

fierce wraith
#

yeah but i dont use any of the other ones so dont they get optimized away anyways?

#

this way if i ever want to use the force/velocity to do some coloring i can

potent ice
#

Nah you got to map the attributes right. It only works for subsets if attributes, but they must exist

#

and I think the format string should end in /i only

fierce wraith
#

what does this mean:

It only works for subsets if attributes

potent ice
#

wait. I think you are right πŸ˜„

fierce wraith
#

the error i get is:
moderngl.error.Error: content[1][1] is an invalid format
from the render call
self.sphere.render(self.render_program, instances=self.N)

potent ice
#

'3f8 3f8 3f8 1f8/i'?

fierce wraith
#

ah just at the end?

potent ice
#

yes

#

I may have to fix that. confusing

fierce wraith
#

well atleast that part works now. bunch of other stuff doesnt!

#

hm

#

doesnt look like a sphere to me

#
#if defined VERTEX_SHADER
in vec3 in_position;
in dvec3 planet_pos;

uniform mat4 m_projection;
uniform mat4 m_camera;

void main(){
    gl_Position = m_projection * m_camera * vec4(in_position + vec3(planet_pos), 1.);
}```
#

oh well. i have a class to go to! ill try fix it later

#

ah

#

for just one planet it works

#

two or more seems to break it haha

potent ice
#

Probably wrong offset!

potent ice
#

Made an example for particle emitting in moderngl (upcoming 5.6 release that is). Method 1 steams the full buffer from python into gpu mem every frame. Method 2 only streams a smaller emit buffer every frame. Method 3 is emitting particles on the gpu. Each method are orders or magnitude faster than the previous one. I can maintain a particle system with 10M particles at 100fps in 3440 x 1440 using the last method. Particles die when leaving the screen and are emitted from the mouse position. https://github.com/moderngl/moderngl/blob/master/examples/particle_system_emit.py

#

It's just a huge mush of pixels. A lot more interesting realtime.. but I think trying to make gif anim of that is not possible

fierce wraith
#

Make a mp4

#

You can steal the convert_to_gif file from my github. It lets you convert a folder of images to a mp4/gif

potent ice
#

I did make an mp4. It looked terrible

#

Anyway. It's not that important

dawn quiver
potent ice
#

Using python api in unreal engine?

dawn quiver
#

i don't know if that is using the python api, but there is one apparently

frail dove
#

hello

olive parcel
#

Hi there!

dawn quiver
#

imagine not partnering with godot

#

:(

fierce wraith
#

hmm @potent ice really dont know what i could be doing wrong here:

self.sphere = sphere(radius=.001)
self.sphere.buffer(self.buffer1, '3f8 3f8 3f8 1f8/i', ['planet_pos', 'planet_velocity', 'planet_force', 'planet_mass'])
...
self.sphere.render(self.render_program, instances=self.N)```
#
#version 430

#if defined VERTEX_SHADER
in vec3 in_position;
in dvec3 planet_pos;

uniform mat4 m_projection;
uniform mat4 m_camera;

void main(){
    gl_Position = m_projection * m_camera * vec4(in_position + vec3(planet_pos), 1.);
}
#endif```
#

just doesnt work somehow hah

potent ice
#

code in repo?

fierce wraith
#

no not yet

#

but thats all there is

fierce wraith
#

ok ive tried to add balls to my compute shader example and i also pushed the code

#

@potent ice its as simple as it gets but it doesnt work 😦

potent ice
#

Looking at it. Might be a bug!

thick niche
#

ok, so, i need help big time with how to make colision with lets say platforms

potent ice
#

What libraries are you currently using?

thick niche
#

pygame

potent ice
thick niche
#

thats not really helping me too much

mortal bridge
#

well, then maybe ask a more specific questionΒ πŸ˜„

thick niche
#

first i need to make a rect over a sprite i have, and make it so that when i jump up into it it pushes me away, and if i jump onto it it keeps me ontop of it

mortal bridge
#

well, it's usually a bit more complex than that, as you'll have lateral collisions, as well, and sometime your sprite will only partially standing on the block, etc, in my game the solution was to have something like 8 collision points around the character (like a very low precision ellipse), and test them all against the various rectangles, and depending on which collided, i would push the character in the opposite direction until it didn't collide anymore, and motions were directed by vectors, one for gravity always applied in the direction of the ground, and user input would just add acceleration to the character, that would be then reduced by opposing forces like friction with the ground and air, etc

thick niche
#

ok im having dificulty with that, i cant make my player fall at all, like im trying to make their y be y - vel and i have them defined but it keeps saying i cant do that

#

anyone here able to join a call and i can share what im trying to do rather than try and explain it

potent ice
#

That is a lot to ask for. Try to break down the problem into smaller parts?

foggy python
frozen knoll
#

Arcade 2.2.4 is out. Main improvement is a 20% efficiency improvement in the time to move, rotate, scale, color a sprite through the use of array.array instead of numpy.

Numpy may be removed as a dependency in the future.

night coral
#

what would replace it? inbuilt c implementation?

frozen knoll
#

Arcade used/uses numpy to create a block of native values (like float, double, int) as a block of memory to send to the GPU. I updated the sprite code to use Python's array class and that sped things up.

#

I'm hoping I can speed up the non-sprite drawing commands too. Those are pretty slow.

jovial fable
#

A pretty cool one

frozen knoll
#

Agreed. Not only is the article well-written, I think their artwork is pretty cool as well.

potent ice
#

It's also super-nice when someone other than the library creator makes guides πŸ™‚

frozen knoll
#

No kidding.

#

Today I was able to speed drawing primitives 71%, except I have one unit test that throws an OpenGL error. Not when I run the unit test individually, but only when I run all the unit tests together. And only on Linux. That's going to be fun to chase down.

potent ice
#

Nice! Static or dynamic ones? (except for the error)

#

nvm. I can look at commit log

frozen knoll
#

Not sure what you mean, but the dynamic ones I'm guessing. Specifically the if statement on line 445 will cache the shader so I only create one per program run, rather than each time I draw an item:

potent ice
#

hmm. I am surprised that array.array() is twice as fast when building a list first compared to using a generator. It's even slightly faster than np.fromiter with a generator.

#
list         5.291297500000001
generator    11.442588
np.fromiter  6.746506999999998
#

and it's on par with struck.pack. Maybe even a tad faster.

fierce wraith
#

@potent ice maybe you can explain why this is happening.
so i add this buffer to my sphere VAO:
self.ball.buffer(self.buffer1, '4f 4f 4f/i', ['ball_position', 'ball_velocity', 'ball_color'])
and then in the shader if i just set the color to a fixed color it bugs out

#

but if i set the color differently for every ball it works fine...

#
#version 430

#if defined VERTEX_SHADER
in vec3 in_position;
in vec4 ball_position;
in vec4 ball_velocity;

uniform mat4 m_projection;
uniform mat4 m_camera;

out vec4 color;

void main(){
    color = vec4(1,0,0,1);
    gl_Position = m_projection * m_camera * vec4(in_position + ball_position.xyz, 1.);
}


#elif defined FRAGMENT_SHADER

out vec4 fragColor;
in vec4 color;

void main() {
    fragColor = color;
}
#endif
#

that breaks

potent ice
#

It's a bug. My bug 😦

fierce wraith
#

but if i add in vec4 ball_color;

#

and color = ball_color; it works

#

do you know what causes the bug?

potent ice
#

Yeah it's a bug in the VAO wrapper not calculating the right padding and stride for the buffer.

#

If you use all the attributes it will work.

fierce wraith
#

hmm

#

but if i leave out the velocity it still works

potent ice
#

oh well. Pure luck then? πŸ˜„

fierce wraith
#

haha

#

ill take it!

potent ice
#

I made an issue for it

#

Should be fixed in 2.1

fierce wraith
#

ok awesome!

potent ice
#

You can also build your own VertexArray manually to solve it. It's just the VAO that doesn't handle it well

#

The VAO is getting very complicated πŸ˜…

fierce wraith
#

hahah

#

but it makes life sooo much easier

#

i really love it

potent ice
#

It definitely makes life easier. Might even move it into moderngl core soon

fierce wraith
#

oooohh!

#

hm, im kind of suprised that i cant have 500k balls bouncing around the scene at 60 fps..

#

it goes down to 9fps

potent ice
#

500k spheres instanced?

fierce wraith
#

yeah

#

dont really know if the instanced rendering or the compute shader is tanking performance

potent ice
#

How do you create the sphere?

fierce wraith
#

self.ball = sphere(radius=.01)

#

ah probably dont need that a that high res sphere

#

probably like 8 sectors and 4 rings is enough

#

or 4 each

#

hahahah yup

#

60 fps πŸ™‚

potent ice
#

yay πŸ™‚

fierce wraith
#

1mil still 60 fps!

#

but now generating the arrays takes for ever..

#

wow 10mil at 16 fps!

#

but it took like 2 min to generate the initial conditions

potent ice
#

Try specifying dtype when creating the np arrays instead of using astype() after

fierce wraith
#

ok let me try that

#

i just tried to time my function to create the data

#

haha

#

pycharm has stopped responding

#

4GB or ram already hehe

potent ice
#

Often it's actually faster to use generators and consume the data with np.fromiter.

#

Very often method 3 in that article is faster than doing fancy stuff with numpy. It's even more readable for most people.

#

And you minimize the amount of memory allocated.

fierce wraith
#

so should i use random.random in the generator?

#

so to generate 2 vec4 with random x,y,z values and 1 as the w value i would do this?

def gen(N):
    for _ in range(N):
        yield random.random()
        yield random.random()
        yield random.random()
        yield 1.
        yield random.random()
        yield random.random()
        yield random.random()
        yield 1.```
potent ice
#

Give it a try

#

I haven't profiled np's random and python random

fierce wraith
#

its a lot slower

potent ice
#

really?

fierce wraith
#

i think

#

wait

potent ice
#

Don't run in debug mode

fierce wraith
#

hm?

potent ice
#

You mean the random methods or generating the data?

fierce wraith
#

generating the data

#

havent tested the random methods

#

my numpy solution:
%timeit generate_data(10_000_000) 2.15 s Β± 96 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)
using fromiter:
%timeit np.fromiter(gen(10_000_000), count=10_000_000 * 8, dtype=np.float32) 11.3 s Β± 304 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)

#

np.random just getting called once is 4.5x slower than random.random

#
%timeit np.random.random()
450 ns Β± 12.6 ns per loop (mean Β± std. dev. of 7 runs, 1000000 loops each)
%timeit random.random()
99 ns Β± 5.58 ns per loop (mean Β± std. dev. of 7 runs, 10000000 loops each)```
potent ice
#

... but is the entire initialisation slower in practice using generators?

fierce wraith
#

yeah

#

11.3 sec vs 2.15

#

my generator might just be bad though

potent ice
#

ok. I guess random is the the problem.

fierce wraith
#

yeah

#

but numpy is slower for single calls so you cant just replace it with np

#

but it probably doesnt matter too much for smaller data sizes

potent ice
#

You could pre-generate an np array with random values and yield those

fierce wraith
#

doesnt cuda have something for generating random numbers?

potent ice
fierce wraith
#

but how would i generate that stuff into a buffer?

#

and is that still faster?

potent ice
#

You can use transform feedback to generate the initial buffer with a vertex shader

fierce wraith
#

hmm good idea

#

ah slight problem

#

i moved the color to a different buffer

#

now it all breaks because im not using the velocity part

#

but i dont need the velocity, can i tell the compiler to not optimize it away?

potent ice
#

Just pad it

fierce wraith
#

how?

potent ice
#

hmm. Do it with VertexArray.

fierce wraith
#

ah ok

frozen knoll
#

@fierce wraith Are you using the compute shader to move the balls?

fierce wraith
#

yup πŸ™‚

#

and to bounce them off the walls of a box they are in

#

i would show you, but i just broke it haha

frozen knoll
#

I'd love to see it when you un-break it.

potent ice
fierce wraith
#

thanks!!

potent ice
#

I don't think it can be any simpler. There are plenty of resources out there doing gpu noise. Don't use the built in glsl noise functions. They are not implemented by most vendors.

fierce wraith
#

yeah

potent ice
#

Maybe not super-important to optimize the initialization, but playing with this technique is very useful

#

I haven't had time to play with empty vao-rendering. You can do a lot of amazing stuff like voxel rendering.

fierce wraith
frozen knoll
#

Oooh, very cool. I've got to learn how to do that.

fierce wraith
#

thats just 256 balls, but i can go up to 10mil at 60 fps πŸ™‚

frozen knoll
#

Thats....a lot.

fierce wraith
#

@potent ice turns out what I had broke, was switching from vec4 to vec3. Apparently they dont pad correctly either.... now its a bunch of floats haha

potent ice
#

aha

#

You only need to pad between each struct entry (aligned with the biggest datatype in the struct), so it's not that horrible. Still when dealing with this much data.. packing it tight with floats is probably a good idea.

#

@fierce wraith did you push the changes?

#

NOPE πŸ˜„

fierce wraith
#

Nope

#

At the doctor now

#

@potent ice its just two vec3

#

Thats it

#

Till breaks

#

Still

near wedge
#

I wonder if 32 byte aligned vertex data is still a good thing to do, or if tighter packing is preferred now-a-days. I know AMD cards really liked 32byte aligned vertex data, but that advice was probably from before GCN. It might have even been advice for ATI cards =/

potent ice
#

For vertex data I don't really know how it work today. I know some Intel and amd integrated don't like 3-component float32 textures. That's the only thing I've stumbled over.

#

I'm pretty sure alignment still matters to some degree, but considering how insanely powerful gpus are today.. I have never really needed to profile it.

#

Alignment can matter for buffer streaming. That's the only case I've looked at.

#

.. but the biggest bottlenecks when rendering with python is python itself πŸ˜„

#

(That applies to any higher level language)

#

Still, there are many clever tricks to render things with near C performance

fierce wraith
#

@potent ice puuuuusssshhhheeeedd!

potent ice
#

nice. You need to make a ball1 and ball2 to make it render smooth

#

Now it only updates every second frame

#

because buffer1 is only the target buffer every second frame.

fierce wraith
#

and ball2 has buffer2?

potent ice
#

y

#

I guess every frame end up with data in ball2, so that's the one you render

#

Swap around ball vaos in the end self.ball1, self.ball2 = self.ball2, self.ball1

fierce wraith
#

yeah

#

hmm. how do i create a function that tells me how many rings/sectors the spheres should have based on their size?

potent ice
#

are the balls big enough for that to matter?

fierce wraith
#

yeah if i have N down below 500

potent ice
#

You should add simple lighting to these spheres. Otherwise they might as well be points or quads rendered with frag shader.

fierce wraith
#

i have no idea of lighting hah

#

i've always put it off

potent ice
#

nice hack in balls.glsl btw πŸ˜„

fierce wraith
#

to use the velocity? yeah hahaah

potent ice
#

Makes them look like balls ```glsl
#version 430

#if defined VERTEX_SHADER
in vec3 in_position;
in vec3 in_normal;
in vec3 ball_position;
in vec3 ball_velocity;
in vec4 ball_color;

uniform mat4 m_projection;
uniform mat4 m_camera;

out vec4 color;
out vec3 vel;
out vec3 pos;
out vec3 normal;

void main(){
color = ball_color;
vel = ball_velocity;
vec4 p = m_camera * vec4(in_position + ball_position, 1.);
gl_Position = m_projection * p;
pos = p.xyz;
normal = inverse(transpose(mat3(m_camera))) * in_normal;
}

#elif defined FRAGMENT_SHADER

out vec4 fragColor;
in vec4 color;
in vec3 vel;
in vec3 pos;
in vec3 normal;

void main() {
float l = dot(normalize(-pos), normalize(normal));
float _ = length(vel);
fragColor = color * _ / _ * l;
}
#endif

fierce wraith
#

thanks!

potent ice
#

Might be a bit more heavy, but you'll see

fierce wraith
#

ok pushed the dynamic rescaling/resolution πŸ™‚

potent ice
#

Nice. The new shader will work great when N is low

#

But not when N is high

#

fragColor = color * _ / _ * (l + 0.25) needed to add some ambient

fierce wraith
#

oh wow those look nice!

#

i have quite a few constants now to play with, should i create a config file?

#

nah its fine

#

haha

potent ice
#

yeah. python is the config file πŸ˜›

fierce wraith
#

wow

#

im gonna push something real quick

#

just let it run for a few min

#

ok pushed

#

hm maybe its just a optical illusion or sniping tool makes too low res screenshots

#

you can kinda see the border of the cube thru the cube

potent ice
#

You have blending enabled for some reason

#

Is that is intended, at least add self.ctx.enable(moderngl.BLEND | moderngl.CULL_FACE)

fierce wraith
#

wasnt really intended hah

potent ice
#

so the gpu don't have to deal with back faces

#

self.ctx.enable(moderngl.DEPTH_TEST | moderngl.CULL_FACE) is probably even faster

fierce wraith
#

oh wow that looks completely different

#

dont know what i like more haha

#

with blending enabled you could kinda see the density of the balls

potent ice
#

whatever looks better. culling is a minimum

frosty stag
#

i have question about uploading to app store

#

so when i try to upload it says that i need to pay 25$
but my credit card uses another currency
will i still be able to make the transaction

potent ice
#

Should be no problem with that as far as I know. There will probably be a currency conversion somewhere down the line.

frosty stag
#

thanks alot man

frozen knoll
#

Ok, just found this problem before going to bed. While I'm updating the position of my sprites, I'm not updating the angle. A quick test:

potent ice
#

hm ok?

frozen knoll
#

Oh, nvm. Just had to post the question to find the answer.

#

Need to get a stuffed animal to explain the problem to first I guess.

potent ice
#

πŸ˜„

#

I did something way worse today it that's helps

manic quartz
#

Need some help related to Pygame, I am trying to place a sprite into our code but I am having trouble doing so, can anyone help? I'm using a template as well. Here's the code, and I will show what parts I want to try and replace with a sprite.

fierce wraith
#

hey @potent ice how would i go about reducing the python overhead?

#

like what are some easy to implement tricks

potent ice
#

@manic quartz Post the code in a code block

#

!codeblock

frank fieldBOT
#

Discord has support for Markdown, which allows you to post code with full syntax highlighting. Please use these whenever you paste code, as this helps improve the legibility and makes it easier for us to help you.

To do this, use the following method:

```python
print('Hello world!')
```

Note:
β€’ These are backticks, not quotes. Backticks can usually be found on the tilde key.
β€’ You can also use py as the language instead of python
β€’ The language must be on the first line next to the backticks with no space between them

This will result in the following:

print('Hello world!')
manic quartz
#

alrighty

potent ice
#

That image is very hard to read! πŸ˜„

manic quartz
#

yeah sorry haha

potent ice
#

And please state what library you are using etc.

manic quartz
#
import pygame
import random
import os




WIDTH = 360
HEIGHT = 480
FPS = 30

# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

# initialize pygame and create window
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("My Game")
clock = pygame.time.Clock()

all_sprites = pygame.sprite.Group()



class Bullet(pygame.sprite.Sprite):
    
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((50, 50))
        self.image.fill(GREEN)
        self.rect = self.image.get_rect()
        self.rect.center = (0, 0)
        
    def update(self):
        self.rect.x += 3
        self.rect.y += 1
        
        if self.rect.left > WIDTH:
            self.rect.right = 0
            
        if self.rect.top > HEIGHT:
            self.rect.bottom = 0
        
        
for i in range(10):    
        first_bullet = Bullet()
        all_sprites.add(first_bullet)

# Game loop
running = True
while running:
    
    clock.tick(FPS)
    # Process input (events)
    for event in pygame.event.get():
        
        if event.type == pygame.QUIT:
            
            running = False

    # Update
    all_sprites.update()

    # Draw / render
    screen.fill(BLACK)
    all_sprites.draw(screen)
    # *after* drawing everything, flip the display
    pygame.display.flip()

pygame.quit()```
#

yeah ill try

potent ice
#

pygame?

manic quartz
#

yeah

#

I am using pygame

potent ice
#

Not completely understanding what the problem is

manic quartz
#

it’s not a problem really it’s just like

#

i explained above

#

I want to replace the rectangle there with like a sprite or image

potent ice
#

ah

manic quartz
#

yeah

potent ice
#

So I guess the image needs to be replaced with something you load from disk

manic quartz
#

hmm

#

yeah that works

#

thanks man

#

appreciate the help

potent ice
#

Pygame have a lot of resources. Examples in the git repo and lots of tutorials on their site

#

so you can always learn by looking around there

#

@fierce wraith That entirely depends on the code. I guess the normal culprit is memory allocations.

#

For the visualization stuff I don't there there are much to optimize

#

Other than using better algorithms on the cpu and gpu

fierce wraith
#

i think the part taking up the most time is actually calling the render function in python

#

not the compute shader being executed

potent ice
#

What code are you talking about?

fierce wraith
#

the N-Body code

#

but i guess you might as well use the compute shader example

frozen knoll
potent ice
#

You are calculating the camera matrix every frame. You don't ever move the camera, so it can go in init

fierce wraith
#

n body or compute shader?

potent ice
#

compute

fierce wraith
#

hm i rotate it

potent ice
#

Other than that it should already be near C performance

#

oh ignore me there. What you have is already perfect

fierce wraith
#

haha

#

ok, in the nbody sim i dont need to actually render the result every frame, i only need to execute the compute shader

#

can i somehow execute the compute shader a couple times without using python to loop?

potent ice
#

You can make your compute shader do multiple steps?

fierce wraith
#

not really, because i split it into too compute shaders

#

i have to once calculate all the updated forces and then apply them

potent ice
#

ah right. otherwise it goes heywire

#

Doesn't it already run pretty fast?

fierce wraith
#

yeah but i want moooore speeeeed! hah

#

it runs at like 2.5kfps

#

but i dont actually need to update the screen that many times, i just need to do the calculation

potent ice
#

I don't know. Start with crack or something or optimize the shaders πŸ˜„

fierce wraith
#

hahaa

potent ice
#

Or do the same in python to compare speed.

fierce wraith
#

haha yeah compared to python its waaayy faster

potent ice
#

I'm sure you could study glsl optimzing as well. I knew that well 10 years ago, but times have changed. I don't think it's worth it unless you are REALLY interested or actually need the speed for some real world problems.

fierce wraith
#

hm no dont really need speed that much

potent ice
#

Better to focus on algorithms. Getting the good old quad tree working in compute shaders should be awesome for example.

fierce wraith
#

puh haha

#

quadtrees are waay to hard haha

potent ice
#

I don't think it's that hard, but there might be easier methods as well

#

Most common pitfalls is using astype() and tobytes() on np arrays in render code

#

and doing way to much matrix math on the python side

#

uniform.write(matrix.astype('f4').tobytes()) is terrible πŸ˜„

fierce wraith
#

oh yikes

#

hmm, all i have is swapping buffers and executing the compute shader

potent ice
#

If your np array is already an f4 you can pass it directly because it supports the buffer protocil. uniform.write(matrix) done

#

so instead of converting then using them, np has dtype parameter in create methods normally

#

Same with pyrr. ```python
Matrix44.identity(dtype='f4')
matrix44.create_identity(dtype='f4')
... etc

#

Also Matrix44 is 5x slower than matrix44

fierce wraith
#

yikes

potent ice
#

Because of that decorator, remember?

#

I think you profiled that originally

fierce wraith
#

yeah

#

have you fixed the VAO bug with instanced rendering?

#

and can i pull that somewhere? hehe

potent ice
#

Not yet. It needs some planning or that whole class will have a meltdown

fierce wraith
#

hah ok

#

what did you say i could do to fix it?

#

create a vertexarray?

potent ice
#

Yeah use plain moderngl.VertexArray or make sure you use all the attributes I guess?

fierce wraith
#

i really dont need any for the display, im only using them in the compute shader

#

but if i used a vertex array i would have to build the sphere myself right?

potent ice
#

Yeah, or you can steal the buffers from a VAO

#

.. created by geometry module

fierce wraith
#

yeah

potent ice
#

vao.get_buffer_by_name('in_position').buffer I think, because that method returns a BufferInfo object

#

Then slap that into the content parameter with format and attrib name(s)... then add your instanced buffer.

#

I have a laundry list if things to fix in that VAO class like support for replacing buffers. Then it would destroy all the internal vertex arrays so you start from scratch

#

And VAO.merge is also nice

#

Merge together lots of VAOs so you can batch render many objects

#

Works great for static things when you can't use instancing

fierce wraith
#

well i got this far:

self.ball = self.ctx.vertex_array(self.render_program,
          [
              (my_sphere.get_buffer_by_name('in_position').buffer, '3f', 'in_position'),
              (self.buffer1, '3f8 3f8 3f8 1f8/i', 'planet_pos', 'planet_velocity', 'planet_force', 'planet_mass'),
              (self.color_buffer, '4f/i', 'in_color')
          ])
#

@potent ice what does this mean:
moderngl.error.Error: content[1][3] must be an attribute not NoneType?

#

its complaining about the color buffer part

#

i think

potent ice
#

hmm

#

I guess it can't find the attribute in the shader

#

I should reword that error

fierce wraith
#

oh does a vertex_array not drop unused attr?

potent ice
#

It does not

fierce wraith
#

urgh

potent ice
#

but you can pad in the format string.

#

Not a problem

fierce wraith
#

can i somehow bind the buffer containing position, velocity, force and mass to a shader even though im only using the pos

#

ah

#

something like 3x8 for a dvec3?

#

it works!

#

but i need to steal the index buffer from the vao aswell haha

#

@potent ice whats the buffer name for the index_buffer? is it just index_buffer?

potent ice
#

yes, doesn't show up in auto complete? πŸ˜„

fierce wraith
#

no, i mean the get_buffer_by_name thing

#

what name do i give it to steal the index buffer

potent ice
#

oh. hmm yeah. _index_buffer should work.

fierce wraith
#

returns none 😦

potent ice
#

It's the sphere?

fierce wraith
#

yeah

#

ah you mean sphere._index_buffer

potent ice
#

It doesn't have index buffer. Passing None is fine as well

fierce wraith
#

huh

potent ice
#

never mind. It does have index buffer

#

Jesus.. wrote that a long time ago

fierce wraith
#

sphere._index_buffer is a VAO, does it just have one buffer?

potent ice
#

yes. only one index buffer

fierce wraith
#

what is its name?

potent ice
#

sphere._index_buffer

fierce wraith
#

ah yeah ofc

potent ice
#

It's not pretty, I know

fierce wraith
#

but _index_buffer is a VAO not a buffer

#

sphere._index_buffer.index_buffer?

#

nvm pycharm is just messing with me

#

yaaay works!

potent ice
#

Yeah it should be a moderngl.Buffer πŸ™‚

#

nice!

#

The shitty part with the basic VertexArray is that its tied to a program.

fierce wraith
#

dont you mean that it is tied to a program?

#

and thats fine for me, im only ever gonna use it with one program haha

potent ice
#

yes. phone typing

#

no = now

fierce wraith
#

hahah

potent ice
#

I have one minor knitpick. Not all your entrypoints are called main.py.

fierce wraith
#

yeah i tried to rename them to the folder names so i dont get confused as to what im executing

potent ice
#

ahh

fierce wraith
#

but i just havent done so with the newer projects haha. i always wait until everything is unreadable and then i go through and start reformatting...

potent ice
#

well. If you run them from the root, it should be easy to separate them?

fierce wraith
#

i guess i could count how many mains i have run haha

potent ice
#

oh. lol

fierce wraith
#

yeah I end up just rightclicking the file and selecting run because i forget what main (5) is haha

#

do i need to do some fancy uv unwrapping to fit a planet texture onto the sphere?

fierce wraith
#

@potent ice whats the buffer that stores the uvs called? in_texcoord_0 or uv or in_uv?

potent ice
fierce wraith
#

ahhh thank you!

#

now i can look it all up

potent ice
#

You can pass in your own variant in geometry methods if needed

fierce wraith
#

whats textcoord1?

potent ice
#

for a second layer of textures. It's based on the gltf standard

#

You could have a in_texcoord_15 if you wanted I guess

fierce wraith
#

haha

potent ice
#

There you go. Make shaders unreadable πŸ™‚ ```python
class MyAttrNames(AttributeNames):
POISTION = 'bob'
NORMAL = 'harry'
TEXCOORD_0 = 'lucy'

geometry.sphere(attr_names=MyAttrNames)

#
in vec3 bob; // position
in vec3 harry; // normal
in vec2 lucy; // uv
fierce wraith
#

haha looks good to me!

potent ice
#

There's of course a drawback with fixed standard attributes, but I think the benefits outweighs the disadvantages.

fierce wraith
#

would you suggest a texture array to store the different planets textures? @potent ice

#

what are the drawbacks for fixed standard attributes?

potent ice
#

yeah because you can't change texture binding during a render call

#

But you can use the gl_InstanceID to fetch from a different layer

#

That's how you draw different tiles in 2d tilemaps as well in one draw call

#

Each tile contains a material_id in the vertex data specifying what layer to fetch from.

#

Same with a minecraft type chunk of cubes

#

If you want to keep it simple just stack 9 256x256 planet textures vertically in a png and load it as a texture array

frozen knoll
#

Not really game related, but I have a script that scans my files and produces a quick-index of available commands.

#

Kind of like it.

potent ice
#

It generates an rst file?

#

yep. it does. That's actually an awesome index

frozen knoll
#

I wish there was a way to make something like this easier to read:

#

For new programmers, that is very hard to figure out. Heck, for me that's hard to figure out and I wrote it.

olive hornet
#

it would be easier of you somehow split it between lines and on each line added a comment about which does what?

tawny stratus
#

I've written the Game of Life in Kivy. But updates are fairly slow (~1s per update) . My implementation of the logic is fairly slow, creating a new grid each time. Is the thing thats slowing it down likely to be my rubbish logic, the unnecessary setting of RGB values, or is Kivy just not gonna like updating 200x200 cells each update?

class Cell(Widget):
    r, g, b, a = NumericProperty(1), NumericProperty(0), NumericProperty(0), NumericProperty(0)


class PongGame(Widget):
    w, h = 200, 200
    life = Life(w, h) # Where I implement GOL poorly
    cells = []

    def start(self):
        for i in range(self.w):
            r = []
            self.cells.append(r)
            for j in range(self.h):
                w = Cell(pos=(i * 5, j * 5))
                self.add_widget(w) # Don't know if this is the right way to add widgets, but I had a lot of problems trying to get it to work, so just went for this dumb double for loop way
                r.append(w)

    def render(self, _):
        self.life.update()
        for i in range(self.w):
            for j in range(self.h):
                # Setting this each time isn't necessary
                # But I don't think it should affect performance
                if self.life.current_state[i][j]:
                    self.cells[i][j].r = 1
                else:
                    if self.life.has_been_alive[i][j]:
                        self.cells[i][j].r = 0.1
                    else:
                        self.cells[i][j].r = 0


class LifeApp(App):
    def build(self):
        game = PongGame()
        game.start()
        Clock.schedule_interval(game.render, 0.1 / 60.0)
        return game


if __name__ == '__main__':
    LifeApp().run()

Sorry if this isn't the right place to ask

frozen knoll
#

I don't do Kivy, but recreating 200 x 200 = 40,000 each time is going to take a while.

#

If I were advising how to do it in Arcade, I'd generate 40,000 sprites. Then flip the color or texture on the sprites you want to change. Then you are just changing the color, and not resending to the graphics card all that data.

potent ice
tawny stratus
#

I think what I am doing is just changing the colour based on the current state, rather than re rendering an entire widget - but I do it for every widget irregardless of whether the state has changed

#

and I'll check it out, thanks Einarf

#

Closest thing I can find is from salt-die doing it with numpy, and his version of the logic is probably infinitely faster than mine - I just want to understand where the slowness is coming from, whether bad graphics implementation, bad logic implementation, or just inherent slowness

potent ice
#

ah yep. That's it I guess

#

You can speed up things with numpy

tawny stratus
#

Well, at the moment I'm generating and throwing away a 200x200 list each time, so I'd guess just switching to not doing that would be enough to give me a big speed up in terms of logic. I'll do that and see how much of a difference it makes

potent ice
#

He's updating a texture instead

#

Just feeding it with new pixels every frame

#

Then using nearest interpolation to make sure it scales up pixelated

#

I think this example is still relevant.

tawny stratus
#

Godammit, salt-die's stuff is so cool, and so far out of my league at the moment

potent ice
#

Or reduce the resolution

tawny stratus
#

although I think I can learn from his maze stuff at least

potent ice
#

You could use numpy.convolve to quickly calculate neighbours

#

just with 1 weights

tawny stratus
#

I only just noticed that I forgot to change the name of my app away from PongGame - hah

potent ice
#

I was going through the same tutorial. Totally did not notice πŸ˜„

potent ice
frozen knoll
#

I've had students want to do space invaders before, but don't know how to get sprites to move in a group. Making an example show that, and how to do shields.

#

Oh, and get only the bottom row of enemies to fire bullets

fierce wraith
#

@potent ice will compute shaders support uniform vars at some point? or is that a opengl problem not a moderngl issue

olive parcel
#

I don't know about ModernGL, but compute shaders are no different than other shaders with regards to uniform vars.

#

In Panda3D you can certainly have uniform vars with compute shaders.

potent ice
#

@fierce wraith It should support uniforms like any other shader.

#

Uniforms and uniform blocks

#

and I guess even subroutines

fierce wraith
#

oh even though it has its own class?

#

just wondering because i had to implement my own loader, so i thought it probably wouldnt have uniforms

#

iirc i didnt see anything about uniforms in the computeshader class, but i might have just missed it

potent ice
#

Yup. They are merged in 6.0. The loader was just missing from moderngl-window, but it's in 2.1 (unreleased)

fierce wraith
#

oh awesome

#

i cant wait for 6.0!

#

so many awesome fixes and features!

potent ice
#

That's going to take a while. 5.6 will get a lot of new stuff.

#

I think 6 could possibly be next year. 5.x has a lot more to give.

fierce wraith
#

oh wow thats far away 😦

#

why are you only merging them in 6.0?

potent ice
#

Think if 5.6 as the first transition version towards 6

fierce wraith
#

ah

potent ice
#

5.6 will have most of the stuff in 6.0

#

The main difference in 6 is that we remove the python wrappers over the objects created in C++

#

That bypasses a function call per instruction

fierce wraith
#

oh wow, wont that make it a lot faster?

potent ice
#

It will be faster at least

fierce wraith
#

ill take it haha

potent ice
#

Main focus is brining 5.x up to speed moving to towards 6.0 and improve docs and tutorials

#

Especially the last part.

frozen knoll
#

Yay for docs.

potent ice
#

A new user shouldn't necessarily need to know opengl to start using moderngl.

#

Right now that is not really the case. moderngl makes opengl easier to reason with, but you still need to know some opengl to use it. That needs to change.

#

@fierce wraith If you have any input on doc improvements, please poke me and I will add to list

#

or anyone..

fierce wraith
#

will do!

potent ice
#

or make issue on github

potent ice
#

Really well done.

#

except that they use the old attribute instead of in because they are using #version 120 shaders.

slow cloak
#

Question, I have this little alien ship that moves around in my Pygame window, and it only moves when I move the left and right arrow button, which is what it's supposed to do. For it to move, I have to move my mouse just slightly then all the movement takes place. It's like it's waiting for my mouse to move just a little for the movements to all take place. Is their some way around this because I have no idea why it's doing that.

potent ice
#

How do you process the input events?

#

That's usually where the problem is

#

oh my god. wasted 30 minutes on kivy render example because my attribute names was strings, not bytes

slow cloak
#

I fixed it @potent ice , thanks for the help though!

potent ice
#

@slow cloak Care to share when the problem was? πŸ™‚

slow cloak
#

I think it was input events, I just moved the if statements up, and that solved it.

potent ice
#

Yep it processes all event from the same queue, so it's easy to mess up the conditions

slow cloak
#

Yah

potent ice
#

I would recommend adding some prints if you get in trouble

slow cloak
#

Ok, thanks for the help!

potent ice
#

No problem

slow cloak
#

Actually @potent ice while I have you here, do you know if it's possible to create multiple circles, and all have them falling? I made an Alien Ship and when he fires I can't get all of the circles to keep moving down at once, and I was curious if there was a way.

#

I know with rects you can do something like rect.center_y or something like that, but I don't know if it's possible with circles

potent ice
#

No idea. I've just used pygame.draw.circle πŸ™‚

#

I'm not well versed on sprites and whatnot in pygame, but I do know the windowing and event system well

slow cloak
#

Hmnm ok

potent ice
#

There could possibly be some examples out there. Pygame does have a lot

#

Need to learn more about that myself. Think I need to make a simple game soon

fierce wraith
#

@potent ice are you working on getting kivy to run with moderngl?

#

or just kivy for fun

potent ice
#

kivy for fun first

#

I think it would work, but only on win and linux

#

It all depend if it's a good idea πŸ˜„

#

Could do it for fun, but I don't know if it has any real world value. That is the big question.

#

You can already do pretty nice things with shaders in kivy

#

.. and it will work across platforms.

#

So in theory adding moderngl into the equation will break compatibility and hugely complicate distribution of the app

fierce wraith
#

yeah fair enough

potent ice
#

Would be a "for fun" thing I guess.

#

If bump to gles3 in the future.. then maybe. Not holding my breath for that πŸ˜„

#

I don't think that has a high pri, and it probably shouldn't

potent ice
#

so.. when setting uniforms in kivy, make sure you send in the right datatype. ```
self.canvas['size'] = float(self.width), float(self.height)

works with

uniform vec2 size;

#

but setting the integers directly doesn't work self.width, self.height

quaint fog
#

what is the best video or website for learning pygame

frozen knoll
#

@foggy python has a lot of more advanced tutorials PyGame out there too, if you've had some programming already.

foggy python
quaint fog
#

ok thank u

quaint fog
#

but @foggy python i dont want to pay i just want a free tutorial

#

@foggy python i would like some of your tutorials

foggy python
#

if you want mine, you can google them

quaint fog
#

OK

#

they are very good videos btw

#

yo guys not sure if pygame has changed but isnt this how you get the code running

#


import pygame,sys
from pygame.locals import * 
pygame.init() 
WINDOW_SIZE = pygame.display.set_mode((250,250))
#

it alway give me this error

#

No module named 'pygame.locals'; 'pygame' is not a package

#

maybe ```py
pygame.locals

#

doesent exist anymore

quaint fog
#

discard the issue it works

blissful oar
#

ive tried learning python myself but i only know the very basics

#

message me if intrested

flint pecan
#

!rules 6

frank fieldBOT
#

6. No spamming or unapproved advertising, including requests for paid work. Open-source projects can be showcased in #show-your-projects.

flint pecan
#

@blissful oar We do not allow for requests for paid work here.

blissful oar
#

ahh bummer, any idea where i should go to find what im looking for

flint pecan
#

Not clue, maybe fiverr?

mortal bridge
#

@potent ice maybe it would be fine to allow gl3 on android now, and win/linux would certainly be fine, but not sure about ios/osx 😬

#

Gles2.0 is still 20% on android though, but i'm sure it wasn't more than 80% when we did the initial port, so… maybe

quartz cedar
#

is there a good lib for python to make a simple videogame?

#

apart from pygame

fierce wraith
#

arcade!

#

made by @frozen knoll

olive parcel
#

@quartz cedar And if you want to make a 3D game, I recommend panda3d Panda3D

mortal bridge
#

For simple videogames, although it's not the lib objective, as opposed to panda3d, arcade or pygame, kivy is fine, too

blazing edge
#

Can anyone help me install pygame? I keep on getting a missing dependencies error.

olive parcel
#

I'm afraid we can't help you unless you specify which error message you are getting. πŸ™‚

#

If you could paste the error message, that'd be great.

blazing edge
#

WARNING, No "Setup" File Exists, Running "buildconfig/config.py"
Using UNIX configuration...

Hunting dependencies...
SDL     : found 1.2.15
FONT    : not found
IMAGE   : not found
MIXER   : not found
PNG     : found
JPEG    : found
SCRAP   : found
PORTMIDI: not found
PORTTIME: not found
FREETYPE: found 23.1.17
Missing dependencies
#

I am running Linux Manjaro

#

And Using Pycharm with the Python 3.8 interpreter

olive parcel
#

@blazing edge Isn't Manjaro based on ArchLinux? If so, I recommend installing pygame using sudo pacman -S python-pygame

blazing edge
#

Cool! I ran it and it seemed to work. Any advice installing it to pycharm?

olive parcel
#

@blazing edge I don't have experience with PyCharm, but I would assume that PyCharm simply uses your system Python installation, and if so, it should be able to pick up PyGame automatically.

blazing edge
#

It seemed to. I apparently needed to restart the program

#

Thanks so much though!

potent ice
#

You might also want to check out 2.0.0-dev6 of pygame based on sdl2. It's pretty stable now.

potent ice
#

FYI: pyglet 1.4.10 is out. It's the last release in 1.4. Next release is 1.5, a pure python 3 version with mountains of old cruft removed. It will keep getting patches for a long time (including the experimental 2.0 version)

olive parcel
#

If it removes so much cruft and isn't a compatible upgrade, shouldn't 1.5 be numbered 2.0?

manic quartz
#

Hey, so I'm trying to make an interactive button in Pygame and I am having trouble changing the Y position so the button changes black when I hover over it. What it does currently is change black when I hover over the bottom area of it, which is what I don't want.

#

Here's my game code: ```print ("WARNING: PLEASE INSTALL SAN FRANCISCO FONT FROM DEVELOPER.APPLE.COM/FONTS BEFORE STARTING THIS GAME OR ELSE IT WILL NOT FUNCTION PROPERLY.")

import pygame

Define some colors

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)

pygame.init()

Set the width and height of the screen [width, height]

size = (700, 500)
screen = pygame.display.set_mode(size)

pygame.display.set_caption("My Game")

Loop until the user clicks the close button.

done = False

Used to manage how fast the screen updates

clock = pygame.time.Clock()

SanFran = pygame.font.SysFont('.SF Pro Display Light',28, True, False)

-------- Main Program Loop -----------

while not done:
# --- Main event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True

# --- Game logic should go here

# --- Screen-clearing code goes here

# Here, we clear the screen to white. Don't put other drawing commands
# above this, or they will be erased with this command.

# If you want a background image, replace this clear with blit'ing the
# background image.
screen.fill(WHITE)

# --- Drawing code should go here
wording = SanFran.render("our game haha", True, BLACK)
screen.blit(wording, [30, 130])

mouse = pygame.mouse.get_pos()

if 150+100 > mouse[0] > 150 and 90+300 > mouse[1] > 300:
    pygame.draw.rect(screen, BLACK, (90, 170, 300, 100))
else:
    pygame.draw.rect(screen, RED,(90,170,300,100))
wording = SanFran.render("play me", True, BLACK)
screen.blit(wording, [90, 170])  
pygame.display.update()
clock.tick(15)
# --- Go ahead and update the screen with what we've drawn.
pygame.display.flip()

# --- Limit to 60 frames per second
clock.tick(60)

Close the window and quit.

pygame.quit()```

quaint fog
#

how would you add coins in a scrolling platformer

#

with pygame

potent ice
#

@olive parcel pyglet 2.x is gl 3.3 core. pyglet 1.x is GL 2.1 πŸ™‚

quaint fog
#

@potent ice do you know how to add coins in pygame

olive parcel
#

@potent ice I would've then suggested that 1.5 be 2.0, and 2.x be 3.x

potent ice
#

Yeah but there's already a 2.0 released πŸ˜„

olive parcel
#

Ah.

potent ice
#

Long side project..

quaint fog
#

@potent ice do you know how to add coins in pygame

potent ice
#

coins?

quaint fog
#

yes

#

maybe theres a documentation on it

#

i coudlnt find a video

potent ice
#

There are tons of examples drawing textures rectangles and sprites

quaint fog
#

where

#

is there an official documentation of this module?

potent ice
quaint fog
#

ok thanks

potent ice
#

everything is there

#

guides, docs, examples.. tons

quaint fog
#

ok

#

thank u

potent ice
#

no problem. That should be much faster than searching for random videos πŸ˜‰

urban cipher
#

In pygame (which is a package in python) can I just upload the gif itself and get it to show all the pics of the gif or do I need to take every one of the pics in the gif and upload them together (not as a gif)?

#

I mean I'm pretty sure the answer is no but I just wanna make sure

grand imp
#

if therese no baked in support you might be able to cobble it together with pillow

foggy python
#

chances are, someone has written a library for that

#

although yeah, it'd be pretty easy to do yourself

potent ice
#

yeah not that hard to convert to separate images or a vertical/horizontal stack of frames

#

Worst case you learn more about Pillow.

slow ingot
#

i made game multiplayer game with python (pygame, sockets, threading) now i want to run them on other pc's, is it possible to just install the game to pc, or i need to install python on every pc and every libary, and then run the scripts to play the game

potent ice
#

There are projects like pyinstaller that makes executables, but never played with it much

#

There are a couple of other projects as well. Not too familiar with what project works best

mortal bridge
#

i've had decent experiences with pyinstaller, kind of a pain to declare the dependencies it misses, and then to make sure it works on a PC that didn't have all the things you have installed, so it bundles all the actual dependencies, but once you got that working, it works well on other people's desktop

#

i didn't use the onefile mode ever, it always seemed more troublesome than needed, i used the onedir mode, which produces a dir full of files, and you have to give all that, so i used innosetup to create a setup.exe from this directory, and give that to people

#

i didn't try cx_freeze because for years i though it was just an older thing than pyinstaller, but i've recently learned it's actively maintained and it could be a very decent alternative to pyinstaller

slow ingot
#

thanks for tips guys

near wedge
#

+1 for PyInstaller

late bronze
#

Boys im having some issues in my pygame with hit detection with a bullet and a player!

round swan
#

could you give more information, like the code you've tried?

foggy python
#

the downside to cx_freeze is that it only works on Windows afaik

brazen mauve
#

anyone know how to run a python script, from unity c#, on an android device?

#

iron python seems like it might be the way to go, but its not updated for python 3+ yet.

mortal bridge
#

Hm, i don't know how unity interact with python, but you can package cpython for android using python for android.

dawn quiver
#

pygame isn't working for vscode or pycharm

#

anyone know how to fix

near wedge
#

@dawn quiver Some specifics on what is not working would be useful.

dawn quiver
#

it says "No module pygame found" even though I downloaded it

#

I downloaded the 32 bit version and I have a 32 bit version of python

olive parcel
#

How did you download and install it? Do you have the right version of Python? Do you have multiple copies of Python on your system?

dawn quiver
#

I used pip

#

pip instal pygame

#

I only have 1 version of python

#

3.8.1

#

@olive parcel

potent ice
#

@dawn quiver It depends what platform you are on. Pygame 1.x has some issues. You can try the 2.0.0-dev6 version as well. It's pretty stable.

#

Or maybe you have issues with your virtualenv?

#

I can't get pygame 1.x to work properly on os x for example

foggy python
#

I think there are more known issues with Pygame 2 than 1

#

idk what the state of Pygame's support for 3.8.x is

#

I've tried everything from 3.3.x to 3.7.x

potent ice
#

@foggy python 2.0.0-dev6 supports python 3.8

#

But they also added py38 wheels for 1.9.6 in november

foggy python
#

ah

potent ice
#

BUT there are platform specific issues with 1.x

#

so some people have to use 2.0

potent ice
#

When 2.0 is deemed stable pygame will be in good shape again I think. There are also things in sdl2 that provides speedups for certain operations.

near wedge
#

@dawn quiver Does another pip-installed module work? I'm guessing this has more to do with PYTHONPATH or other environment stuff than pygame specifically.

tired dune
#

(Pygame) I have a class named Bird and a method under it named draw_bird

#

but I cant get the bird to display on the screen :/

#

first time user of classes

ember glade
#

The Bird bird thing shouldn't conflict

tired dune
#

okay

ember glade
#

Case matters in Python

#

So those are two different names in its eyes

#

!paste can you toss your code onto our hastebin? Will be easier to get an idea of what's going on with more context

frank fieldBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

tired dune
#

will do

#

Warning there is some commented out functions+variables

ember glade
#

No worries

tired dune
#

I removed the bird in update after as well

ember glade
#

Did the error give you a line number?

#

Or any more detail than what you mentioned?

#

Ohhhhh oh ohoh oh

#

Oh

#

Hold on

#

So the screen itself isn't being updated or flipped

#

That's what's going on

tired dune
#

...

#

p.display.flip()

#

right

#

im a little stupid

ember glade
#

No, it's an easy thing to overlook

#

Like I said, graphical stuff is a pain in the ass

tired dune
#

um

#

its still giving the same error

ember glade
#

Right, one sec

#

So from what I'm gathering, it's not seeing the bird object in the main function. global is a bit tricky like that

crystal walrus
#

I don’t get it, doesn’t bird.update() work?

#

lowercase bird

ember glade
#

It doesn't because the object isn't in scope

#

I think

crystal walrus
#

it raises an error about args

#

not NameError

ember glade
#

True

#

But it is saying self isn't being passed

#

So I'm unsure

crystal walrus
#

nah, it’s fine

#

just checked that global magic

#

it works

tired dune
#

Bird is the class

#

bird is the object

crystal walrus
#

yes

ember glade
#

And it should work with bird.update(). And you're sure you're saving it before running it when you change it to that?

#

I know I'm asking basic stuff, but I'm just trying to be thorough

tired dune
#

It opens with a blank canvas

ember glade
#

Okay, that's what we should expect

#

And this is because we're still not updating the screen itself to account for the object being tacked onto it

#

(I think)

tired dune
#

updated code

#

still not working from what I can see

#

maybe I still did something wrong

ember glade
#

Looking further into it on my end

tired dune
#

It is probably something very simple that I am overlooking

ember glade
#

I'll have to investigate in a moment. Currently dealing with a database issue at work

#

Sorry, with tax season looming, it's hectic here

tired dune
#

np

ember glade
#

Got it

#

@tired dune figured it out

#

You need to add global bird just under where you have global screen at the top of your code

#

I mean it crashed, but it at least drew the circle

#

@tired dune Toss your updated code here

tired dune
#

will do

#

Im cutting the code down

#

so it is only the part that isnt working

ember glade
#

Oh no you can't stack the globals together like that

#

Has to be:

global screen
global bird
tired dune
#

ohhhh

#

why does that not work?

ember glade
#

It's just not how the syntax works for that particular keyword

#

Just how they implemented it

tired dune
#

so i've been doing global var, var1, etc

#

and it doesnt work

ember glade
#

And honestly, if you can help it, limit using globals. They tend to get messy, and like you've seen, getting them to properly appear where you want them to can be a chore

#

!globals

#

!global

frank fieldBOT
#

When adding functions or classes to a program, it can be tempting to reference inaccessible variables by declaring them as global. Doing this can result in code that is harder to read, debug and test. Instead of using globals, pass variables or objects as parameters and receive return values.

Instead of writing

def update_score():
    global score, roll
    score = score + roll
update_score()

do this instead

def update_score(score, roll):
    return score + roll
score = update_score(score, roll)

For in-depth explanations on why global variables are bad news in a variety of situations, see this Stack Overflow answer.

ember glade
#

There it is

tired dune
#

it still isnt working for me

ember glade
#

Looking at your current version now

tired dune
#

k

ember glade
#

So it shows the white screen with the yellow circle on my screen but then it hangs and crashes

#

I'm going back over the tutorials to remind myself about all this, see if I can track down where the issue is

tired dune
#

so I got rid of the while loop

#

and that semmed to make the circle show up at least

#

but then it closes

ember glade
#

Yep, since it does it once, sees it has no other commands to run, then closes

tired dune
#

but then the second I use the while loop

#

it doesnt work

ember glade
#

Yeah, I think I know why, but I'm trying to figure it out

#

Ah theeeeeere it is

#

The event loop part

#

So 2 things I added. First I added import sys to the top of the file

#

Then I changed the main() function to be this:

def main():
    setup()
    maxFPS = 60  # FPS of the screen
    clock = p.time.Clock()  # Ticks frames of the screen
    bird = Bird(28, "Yellow", 150, 250)
    running = True
    while running:
        for event in p.event.get():
            if event.type == p.QUIT:
                sys.exit()
        screen.fill(p.Color("White"))
        bird.update()
        p.display.flip()
#

I knew there was something that was missing, I just couldn't put my finger on it

tired dune
#

So pygame requires events in order to function

#

thats good to know

#

and also what does the sys library do?

ember glade
#

It just adds some system functions. Like exiting the program and that kind of jazz

#

So every key press and anything else you could do in pygame is considered an event

#

Events are always happening in it. But since they were never checked, they were piling up and just crashing it

#

(That's my guess, at any rate)

tired dune
#

Ah okay

#

Major thanks

#

I would have been stumbling for a while

ember glade
tired dune
#

πŸ‘

ember glade
#

A lot of it is in Python 2, but the differences are minimal

#

print vs print() and what not

#

Not to mention it has a very helpful section on blitting, which is key for making pygame run smoothly

frozen knoll
ember glade
#

Snagged and bookmarked

foggy python
#

I made a 3D cube

#

with Pygame

dawn quiver
#

nice, now make a 4d cube πŸ™‚

potent ice
#

Nice. The good old way of drawing a cube. Lines and sin/cos rotations I guess.

foggy python
#

yeah

#

although it's written to work with any shape

urban cipher
#

Does anyone know where I can get a 2d character pics for my game? (I mean a web or something like this)

#

I want to make an animation

olive parcel
urban cipher
#

Thanks

mortal bridge
potent ice
#

Just make sure you include attributions. I do that even if the license don't require it.

frozen knoll
#

Kenney has 6 spritesheets that are awesome for creating character animations out of.

#

See here for an example of how I did it, if you are interested:

tired dune
#

How did you go about 3D shapes with pygame

potent ice
#

With commands drawing to surfaces?

#

I mean.. you can use pygame as a window for opengl as well

#

But I assume you mean software rendering with surfaces. You can start drawing some points and apply manual rotations to them

#

Good old sin/cos stuff

#

Do it without perspective division first, so drop the z axis (or drop it fully)

steep tapir
#

nice, now make a 4d cube πŸ™‚
@dawn quiver lmao spoken like an asian mother

dawn quiver
#

lol

grand imp
#

would emulator/interpreter dev also go here?

#

also @tired dune idk if 3d is really pygame's thing exactly

#

you might need to start using other libraries

#

you can certainly implement 3d operations in python yourself and you might learn a lot, but that'll run pretty slowly

foggy python
#

it can make for some pretty interesting effects in a 2D context still (and it performs fine in that context)

#

as long as you aren't doing full 3D, it's fine

potent ice
#

@grand imp You can createa an opengl window/context with pygame if needed. It's even even possible to mix pygame surfaces and opengl stuff. Lots of interesting things can be done.

surreal furnace
#

@foggy python that looks epic

#

i feel dumb for asking this now, but should i quit trying to do a platformer type attack system and start a turn based one? i'm really struggling with the former

foggy python
#

a lot of people have a hard time with combat from a game design perspective

#

in general, turn based is less work and easier conceptually

surreal furnace
#

it just does it backeards when i try to do melee, no matter what direction i'm facing, even if the code is identical for each orientation, it does it backwards for that direction

#

so i tried to make a homing type projectile, and that's bugging like heck, and doesn't work properly. i also really hate the concept of it

iron galleon
#

hey @foggy python what was your website again?

foggy python
#

homing projectiles take some trig to do nicely

iron galleon
#

thanks

surreal furnace
#

can you help me figure out a melee combat system? i was basing it off the x and y of the images i'm using, since i don't know how to use hitboxes

#

@foggy python this

foggy python
#

my tutorials cover hitboxes

surreal furnace
#

you have tutorials?

#

epic

foggy python
#

google dafluffypotato

surreal furnace
#

ok

foggy python
#

the first few are rough audio-wise

surreal furnace
#

got it

#

though i fear my code's messiness might be beyond that

#

i'll have a look ayway

foggy python
#

mine is messy aswell

surreal furnace
#

ok

#

do u only do platformers? cuz mine's not so i don't know if they would mesh well

#

i'll send u a clip of what i have so far

foggy python
#

a lot of the concepts are applicable

#

just take out gravity

surreal furnace
#

i'll take a look at your videos

#

are there any specific ones for my problem?

#

@foggy python this

foggy python
#

oh, you meant just following

#

what's the issue there?

#

@surreal furnace

surreal furnace
#

it dissappers instantly.

foggy python
#

oh, is the attack supposed to be homing?

surreal furnace
#

it's also a really bad early game mechanic in my opinion, and 'hitting demons from beneath' is just to cover up an attack bug

#

welcome to 700 lines of buggy nightmares, friend

foggy python
#

why do you have like 50 global variables

surreal furnace
#

i honestly have no idea

#

otherwise it gives a ton of errors

foggy python
#

._.

#

so the player's attacks are supposed to be homing, right?

surreal furnace
#

i'd like to see if i can implement a melee attack, but since the x and y are in the top left corner, that makes it really hard

foggy python
#

you can do it by center

#

it just takes some math

surreal furnace
#

how

foggy python
#

well

#

center_x = width / 2 + pos_x

#

just transform that formula to whatever you need and you can work by center

surreal furnace
#

interesting

#

thank u! i'll be sure to bug you some more when i inevitably stuff it up

foggy python
#

you really need to learn a bit more python before stepping into Pygame

surreal furnace
#

idiot is my middle name

foggy python
#

start by working out all those globals

surreal furnace
#

how? if i don't have them there then the definition can't use them

foggy python
#

you can return values you need back

#

and you can pass values into the function as a parameter

#

look up how functions work

surreal furnace
#

can do

foggy python
#

also, you may want to use a class for the fireball, not a function

#

or just don't use either

surreal furnace
#

yeah, i made it a function cuz i stuffed up with class and i didn't know why. i just now figured out it was because i wrote python class atk(): code goes here instead of python class atk: bleh bleh

#

also, how do i find the width?

foggy python
#

of what

#

an image?

#

.get_size()[0] or .get_width()

#

otherwise, you define it yourself

surreal furnace
#

ok

#

still not working. here's what i'm using: ```python
class atk:
def melee(damage, x, y, ex, ey, width, attack):
global facing
center_ex = 30 / 2 + ex
center_ey = 30 / 2 + ey
center_x = 15 / 2 + x
center_y = 15 / 2 + y
if attack:
if facing == -1:
if center_ex < center_x and center_ex > center_x - 50:
#if center_ey < center_y + 15 and center_ey > center_y - 15:
print('damaged')
elif facing == 1:
d = 3 #placeholder to prevent errors

foggy python
#

you need to look up Pygame’s Rect class

surreal furnace
#

that's ok, i made it work from the center_x thingo

#

to annoy you, i willnow send you a clip of it working

potent ice
#

@surreal furnace You should really re-think the structure of that project πŸ™‚

surreal furnace
#

what do you mean by that

foggy python
#

uh

surreal furnace
#

as in code or concept

foggy python
#

code

surreal furnace
#

oh

#

yeah, that's fair

foggy python
#

like I mentioned before, the globals and the use of functions are the main offenders

#

I’m no expert on code structure tho

surreal furnace
#

says the youtuber that does coding tutorials

foggy python
#

I don’t teach structure

#

I teach fundamentals to Pygame

surreal furnace
#

fair enough

potent ice
#

I'd start by putting all the non-code stuff into a data or resources directory with subfolders organizing things

foggy python
#

that too

surreal furnace
#

ok. um did you see the first 35 lines

foggy python
#

I forgot about that by the time I read the code itself

surreal furnace
#

i'm honestly way too lazy at this point to do that. but i will later

#

also, i don't know how clean ~700 lines of code is supposed to be, ok

foggy python
#

That game could easily be 300-350

#

maybe even less

#

also, by organization of files, we were talking about the files themselves

potent ice
#

If you are planning to keep expanding it, you at least need to do something πŸ™‚

foggy python
#

Not just how they’re handled in the code

surreal furnace
#

ok, but.. in my defense i only learnt python 4 - 5 days ago, so my optimisation skills are not the best

foggy python
#

You probably shouldn’t have done Pygame so early

potent ice
#

It's a perfect opportunity to learn actually

#

Step back and re-organize. Ask for help if needed

surreal furnace
#

@foggy python impatience is my other middle name

foggy python
#

Also, taking a look at how other people did it will help get you in better habits

#

Learning Python’s fundamentals will save you time

surreal furnace
#

ok

foggy python
#

A lot of time

potent ice
#

Work for laziness in the future πŸ˜„

foggy python
#

And btw

#

This is coming from someone who didn’t figure out why lists were useful until after around a year of using Python

potent ice
#

Hard work pays off in the future. Laziness pays off now.

surreal furnace
#

@foggy python i only think they're useful for animation (that's also the only thing i've used them for)

foggy python
#

uh

#

Your events are a list

#

Your enemies are in a list I think too

#

Or wait

#

Maybe not

surreal furnace
#

those are the sprites FOR the animation

foggy python
#

I’m on mobile so I can’t read the code atm

surreal furnace
#

ah, ok

foggy python
#

Lists are useful for a lot of things btw

#

Look up dictionaries too

surreal furnace
#

aren't dictionarys the thing you used to make a text map of the level in your video?

foggy python
#

I used lists and dictionaries I think

#

Depends on the video

#

I’m pretty sure I used dicts in the infinite worlds one

surreal furnace
#

yeah, that's the one

surreal furnace
#

@foggy python i'm going to try my hand at 'top down' infinite terrien gen (via your video, of course)

#

y'know what? i just realised that my game mechanics are WAY too far off from what is required for an infinite gen game, soooo i'll just make it levels

cyan geyser
#

Oh baby, when i understood that all game code is in one file, i knew i'm in for a treat!

grand imp
#

@potent ice thats still technically not using python to do the actual 3d operations, but hardware/software libs. It's still good to mention to @tired dune though

frozen knoll
ember glade
#

Man you're working your tail off on that

gray stump
#

anyone here, knows python and willing to work with me on a 3D game

olive parcel
#

@gray stump out of curiosity, what are you using for 3D in Python? Panda3D?

gray stump
#

pyglet

#

and pycharm

frozen knoll
#

@ember glade I'm on sabbatical from teaching this semester, so finally getting to poor a lot of effort into it.

gray stump
#

Please don't judge me but i wanna maka a voxel engine.

#

scifi game

#

@olive parcel

#

Wanna join?

olive parcel
#

No thanks.

jovial fable
#

@frozen knoll the release date of 2.2.0 and other in december are set in 2020

#

If i'm reading it right

frozen knoll
#

Where, on the release notes?

jovial fable
#

Yeah on the link you pasted

frozen knoll
#

Oooh, right. That's not right.

#

Well, doesn't make any more sense than what I just wrote in the line above. Thanks. I'll correct.

jovial fable
#

o7

surreal furnace
#

@cyan geyser yes! another person with a green default icon! join my in my quest for domination!

surreal furnace
#

@foggy python i remembered what you said about clutter in my code, and decided to make the rest of the game in another file, which i import with ```python
from gamefiles import Game

#

(it's a class)

cyan geyser
#

@surreal furnace BTW, check out SOLID principles. While not all are applicable to python (like interface segregation), single responsibility principle will make the code much more readable

surreal furnace
#

ok, thanks

lunar jetty
#

I was considering making an indie game in Python, something a'la Cave Story
any tips on getting started with that?

#

other than getting more people than myself on the team, all I can handle by myself theoretically is code and soundtrack

fervent rose
#

Firstly, you should choose which library you want to use

#

I'd suggest Arcade, or you can build your own engine using almost any graphical library (we made a retro pixelated game for the code jam using kivy)

lunar jetty
#

Oh yeah speaking of which, which should I use? PyGame? Kivy? Try them both and see which suits you better?

jovial fable
#

i have a preference for arcade because it's simple and fun to use, and the creator hangs out around here

#

try it out for like 2 screen of platformer/shooter

lunar jetty
#

alrighty, I'll take a look and see what I can learn

frozen knoll
#

I'm also happy to answer any Arcade questions you might have. Just ping me.

fierce wraith
#

@frozen knoll so i've never used arcade, but ive been using a lot of moderngl recently. im trying to port a project of mine from moderngl to arcade, just because doing everything from scratch gets kind of annoying haha

#

like i had to do the text rendering from scratch etc

#

is something like the image i posted easy to do in arcade?

frozen knoll
#

Ah, tile-based games.

#

See 2048 created in Arcade:

fierce wraith
#

im gonna be using waaay larger grids than this too

frozen knoll
#

For creating tiles, I used the Pillow library to put text on an image, and then used the image as a Sprite.

fierce wraith
#

isnt that really slow?

frozen knoll
#

No. I generate the image when the program starts.

fierce wraith
#

ah fair enough

frozen knoll
#

Then just re-use it as needed.

#

This creates the textures:

fierce wraith
#

hm but ill need numbers 0 to maybe 500

#

isnt that a lot of sprites?