#game-development
1 messages · Page 107 of 1
Oh man I always loved gravity puzzles
They are like truly the best
I'm planning on creating a game related to space and time
insane
thank uu!! and oo sounds fun u should!(:
might be too late now, but you should ask for user input, and use if statements and some math to produce results.
an example:
money = 4850
level = 1
question = ask for user input
if (question == "yes")and(money>=200):
while (question == "yes")and(money>=200):
money = money-200
level = +1
print("Level is now", level)
print("Gold left:", money)
question = ask for user input
if question == "no":
quit
Now, this most likely isint the most efficient, and if you are looking for perfect efficiency with no possibility of anything going wrong, there are better ways that this. however, this should work 👍
Hello! I'm currently rebuilding an ECS project of mine with the intention of significantly enhancing the codebase's stability and ease of use. I wanted to get some input on what I'm currently thinking about how the interface for the package should work.
The basic idea is that entity and component setup should be simple and accessible. In the past, I had enabled the user to access a component on an entity by passing in either a string corresponding to the component's class name, or by passing in the component's class symbol itself.
For this version, I wanted to make this simpler and much more robust, so I have the following initialization patterns supported:
engine = Engine()
world = engine.create_world()
zombie = world.create_entity()
zombie[Position] = Position(10, 10)
zombie[Velocity] = { 'x': 10, 'y': 10 }
zombie.add(Health, { 'maximum': 100 })
zombie.add(Name(value = 'Bob'))
Does this sound reasonable? And/or are there any obvious drawbacks to any of these methods? I'm happy to provide implementation details as well.
Note that once components are added to the entity, they can be retrieved either through the class symbol (e.g. zombie.get(Position) or zombie[Position]) or through a string corresponding to the class name (e.g. zombie.get('position') or zombie['PoSITiOn'], etc.)
is zombie[Health] = 100 valid for your ecs api ?
No, you would define methods for manipulating component state.
I see
Components are defined ahead of time, inheriting from a component base class
and zombie[Health] = zombie.add(Health, {'maximum': 100}) is valid I'm assuming ?
add doesn't return anything, so no. That could be implemented though, probably
is this on github?
Not yet, but I'll be putting it up soon
Looks great to me, that dictionary usage for coordinates pokes my heart though 😛
Also it specifiy says Velocity type.. unless that was an alias for a dictionary, which I dont think works with esper (what I use) so I may have just found it unnatural
I have been messing around with some ECS
https://github.com/blankRiot96/ecs-pygame
Ahh yeah - esper is nice, though my components have a bit more going on in terms of configuring properties and making serialization easier
https://github.com/krummja/ECStremity/
ECStremity is the previous ECS that I developed. I'm using it as a basis for the new ECS, which should be a significant improvement over some of the messier pieces of its predecessor.
Oh neat
hi 👋 could anyone help me with my hangman game
So basically I'm not quite sure how to ouput the letters in thepygame windows
like the the length of the word
as well as a list that handles all the letters that have been used
also idk how to make my buttons work i dont quite get it
I've only managed figure out the exit button
anyone here know how PyQt5 works
cause I need help with my QGraphicsScene not showing up
ping me when u respond to me
https://github.com/krummja/PECS
Still a lot of work to do to get it up to a workable state before publishing on PyPI, but this is where the new ECS library will be if you're interested
@grim abyss Wanted to ping you as well since you asked about it being on github earlier
cool, gonna check it out there buddy
might even contrib...
flex those pecs...
haha
@orchid zinc On the installation subheader you could include pip install git+https://github.com/krummja/PECS to install with pip
The code looks great! 😄
PyGame question @ #help-potato please thanks
if i were to make a menu for my game, which library can do it in a more fancy way?
What library are you using for your game?
Oh are you asking what library to use for your game based on what can make a fancy menu
In this tutorial, you will be able to make 2d flud dimension with simplified Navier Stokes equation, in Pyhton with Harfang.
With a small example, you will be ready to use HarfangHighLevel in your project.
HARFANG®️ High Level is a set of simple functions that allow you to code faster, and to achieve results without needing to become familiar ...
somewhat yes
i am using pygame but i didnt really like how it makes the menu
PyGame doesn't make a menu for you, you use it to make one
I made one recently
2 actually
yes but the way its made isnt really nice
show show
maybe i am the one who isnt really using pygame as its supposed to then
Oops that jumps into the gameplay too fast
I'll take new recordings give me a second
oooo that looks really nice
the menu is really clean
if you can, could u explain how you made the menu
The other one I made
Thanks 
That's a very big task, and I don't feel it would help you either
What I do feel will help you is looking into pygame_gui
https://pygame-gui.readthedocs.io/en/latest/
It is what I used for the second menu, also a lot of this just comes with repeated usage and familiarity, so consistent usage will be the most helpful asset among anything else here
ok
looks like there are a lot of things i need to learn to continue work on my game
With the limit, would it be best to go by CPU/RAM limitation, or set a hard limit?
I'm assuming the landscape is procedurally generated?
are you storing unloaded chunks somewhere, or just regenerating them from the same seed each time they get loaded?
I'd recommend you do the latter, although if you want the terrain to be editable, you'll need to store modified chunks
You could just store the voxel data for modified chunks, but if you're only expecting a relatively small amount of voxels to change, you could try storing a diff between the 'base state' (what the procedural generation algorithm spits out for that chunk) and the modified state
I think he did more or less that
the world is procedurally generated from a function that returns a block ID from a world position
so at first there is not need for any storage and the world is potentially unlimited
then he will start to store "user blocks" in a sparse matrix
and each time a chunk gets "dirty" the mesh is reevaluated
maybe @lyric pawn could tell us more 🙂
ok so long message time
this channel is for game dev related stuff, you can ask this in off topic channel
I’m not TOO advanced in python, like i know enough to program what i have but I’m not the best. I’ve been programming a text-based battle system where the user can face off against enemies with multiple party members who have differing menu options and stuff, so basically i was just wondering if i send the code later (currently implementing something), if people could give feedback on how to improve the code and make it more efficient/less complicated?
ello
!paste
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.pythondiscord.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.
Sure, go ahead and send it :)
alright i will, stopped coding a bit ago but once i finish will send
this might be a bit since I’m currently in the process of quite a big overhaul
also it requires external files (just a couple txts), should i substitute in placeholder data or something?
Hello anyone want to help me with code in pygame?
Making a repository and sending a link to that might be cleanest
alright
The world is procedurally generated and as @snow hill said, I store modified blocks and loaded chunks in a sparse matrix (in Python it’s actually just a dictionnary class with a tuple (x, y, z) as key and I reload a chunk whenever a block is removed/added inside of it
That's pretty much how I do it as well. I keep track of dirty / modified chunks and save them in a fixed interval and on exit
I did use a json format initially to make things easier to debug, but changed to a simple binary format. I can convert between them anyway, so it's not aproblem.
Yup, keeping track of dirty chunks in a dict is a great way to do it!
Are you generating the chunks in python?
I'm generating chunk data in shaders currently to speed things up a lot. My chunks have 65_536 blocks so it can be a bit time consuming in python. To be fair.. it can be done in subprocesses. I just liked the speed when using shaders since I can pretty much re-generate the entire world in less than a second.
for game you would probably want an UI provided with game engine, eg pygame_gui in pygame, or direct in Panda3D, also tkinter may not be the best choice on mobile or web
I want to make a word based game but you can press buttons
looks 2D so i'd say pygame
[pygame] AttributeError: 'pygame.Rect' object has no attribute 'kill'
class PlayerBullet(Sprite):
def __init__(self, x, y, w, h, Mx, My):
super(PlayerBullet, self).__init__()
self.rect = pygame.Rect(x, y, w, h)
self.x = x
self.y = y
self.w = w
self.h = h
self.Mx = Mx
self.My = My
self.speed = 5
self.angle = math.atan2(y-My, x-Mx)
self.x_vel = math.cos(self.angle) * self.speed
self.y_vel = math.sin(self.angle) * self.speed
self.c = False
def main(self, display):
self.rect = pygame.Rect(self.x, self.y, self.w, self.h)
self.x -= int(self.x_vel)
self.y -= int(self.y_vel)
pos = pygame.mouse.get_pos()
angle = 360-math.atan2(pos[1]-self.y,pos[0]-self.x)*180/math.pi
rot_img = pygame.transform.rotate(blt, angle)
display.blit(rot_img,(self.x, self.y))
# pygame.draw.rect(sc, (255,0,0), self.rect, 2)
for z in zombies:
self.c = self.rect.colliderect(z.rect)
if self.c:
break
else:
pass
if self.c:
self.kill()
def kill(self):
self.rect.kill()
Sprite.kill(self)```
what i'm trying to do here is to kill the bullet right when the bullet collide with zombie, but i got that error, why
It would make more sense to remove the player bullet from whatever container you are storing it in
We have a good example on this
https://github.com/Matiiss/pygame_examples/blob/main/pgex/examples/projectile_to_position/projectile.py#L11-#L39
pgex/examples/projectile_to_position/projectile.py line 11
class Projectile(pygame.sprite.Sprite):```
how to make tap on the button(example 1) --> sth happened instead of input the text --> sth happened
maybe its possible with if or while
example :
print('u tap 1')```
or
```if tap_2:
print('u tap 2')```
or even
```while u_tap_1:
sth happened always while u clamp 1```
hmm.....
is it possible in Python ?? ?!?!?!?!!?!?!??!!?
What GUI framework are you using
ok, my solution is to just redraw over it, but the rect is still there, how to remove the rect?
PyCharm
ok, i found a solution, using list to remember what bullet rect has collide and wont detect it anymore :)
def gameloop(running = True):
shooter = pygame.image.load('shooter.png')
bullet = pygame.image.load('bullet.png')
x = 275
y = 300
bullet_x = 200
bullet_y = 200
x_vel = 5
y_vel = 5
win.fill((255, 255, 255))
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x -= 5
if event.key == pygame.K_RIGHT:
x += 5
if event.key == pygame.K_SPACE:
while not keys[pygame.KEYUP]:
win.blit(bullet, (bullet_x, bullet_y))
bullet_x += 5
win.fill((255, 255, 255))
win.blit(shooter, (x, y))
pygame.display.update()
Here, I am trying to make a shooting mechanism in my way. While, I'm pressing the space button it blits the bullet image and increases it's x to move (not necessarily x). But the problem here is it fills the screen white after it blits and moves. But I need to fill the screen white because I have a shooter image which I also want to move. Is there a way to not change anything but blit and move the bullet image while I'm pressing space?
Fill the screen, then blit the bullet, then update the display.
Can you show in code
win.fill((255, 255, 255))
win.blit(bullet, (bullet_x, bullet_y))
win.blit(shooter, (x, y))
pygame.display.update()
1. clear screen
2. draw stuff on it
3. flip the display buffer (update)
okk
1. Get Input.
2. Act (on input and as time passes).
3. Render / Draw (this has the three previous steps in it).
def _process_keydown(self, ev):
attrname = f"_process_{pygame.key.name(ev.key)}"
if hasattr(self, attrname):
getattr(self, attrname)()
else:
self._process_other(ev)
def _process_delete(self):
self.right = self.right[1:]
def _process_backspace(self):
self.left = self.left[:-1]
def _process_right(self):
self.cursor_pos += 1
def _process_left(self):
self.cursor_pos -= 1
def _process_end(self):
self.cursor_pos = len(self.value)
def _process_home(self):
self.cursor_pos = 0
def _process_return(self):
pass
def _process_other(self, event):
self.left += event.unicode
for all my pygame fellas
Hi, need developers to test out PandaEditor, it's a level / scene editor for panda3d game engine, currently except for scene saving all other core systems are implemented. You can write python scripts to define object behaviors... to extend the editor with custom features there is support for editor plugins too. If you like it give it a star on GitHub, you can support it on patreon too, it would really help to speed up the development. https://github.com/barbarian77/PandaEditor
hello guys, i would like to put my .py file into .exe, but i have an error.
Actually I know it failed when i do : fond = ('freesansbold.ttf',15') but idk how to fix it
by the way i m using pyinstaller
seems to be because you passed in the wrong argument
Hey guys. I’m developing a game for a school assignment and it’s almost done. I’m looking for someone who can help me to create a start menu for my game. Can anyone help me please?
Might want to share that here : https://discord.gg/UyepRMm
Hey guys. I’m developing a game for a school assignment and it’s almost done. I’m looking for someone who can help me to create a start menu for my game. Can anyone help me please?
Might be a little to much to ask. Smaller questions are better here like specific issues you have with the menu system or how to approach it.
guys can i get some help
win=True
bot_input = random.randint(0, 2)
rule = {'paper': 0, 'scissors': 1, 'rock': 2}
if abs(bot_input - input) == 2:
if bot_input == 0:
win = False
if bot_input== 2:
win= True
if bot_input - input == 1:
win= False
if bot_input - input== -1:
win=True
print(f'Bot:{list(rule.keys())[bot_input]}')
if bot_input == input:
pygame.draw(tie,975,300)
else:
pygame.draw(won,975,300) if win else pygame.draw(lose,975,300)```
its not drawing out the image
and it has that yellow back ground
idk how to fix it
in pygame u can't just say pygame.draw because ur just accessing the module. Pygame can draw primitive shapes(circle, rectangle, line...). Or polygons defined by point coordinates. Or images/text. I think ur trying to draw text to the screen. For that u 1. have to call pygame.font.init() to create an instance of the font module. 2. load in a font by calling font = pygame.font.SysFont({ur font}, {font size}). 3. create a surface with the font and text u want by saying text_surface = font.render("win", True, {font colour}). 4. draw the text surface to the screen by saying screen.blit(text_surface, (x, y)). Hope this helped
oh
i did this but
Can someone help me, I usually know how to do basic python coding but this is difficult for me and I can't seen to complete it/do it right. Thanks in advance
Might not be the right channel for this problem. The best way to approach the problem is probably breaking the problems into smaller parts. What have you written so far? Where exactly are you stuck?
A lot more people are willing to help with smaller problems. You are presenting a whole assignment here. Almost no one have time in their busy life to cover every question you have in one session. Break things down into smaller questions. Something that doesn't involve the screenshot, but is simple enough to explain in one sentence.
hello people i made a game called Shiftania for the metroidvania month game jam, and it's kind of a cool original little game. make sure to mute the music when you play, and please leave a nice rating! https://itch.io/jam/metroidvania-month-16/rate/1576796
Should i make 3d game or 2d game?
= 3d
= 2d
Pick whatever you are comfortable with.
College Physics Project : https://youtu.be/d28lbsqOJ-8
For my Physics project I was teamed up with one of my classmate where I had the task to code a simulation of the Magnus Effect.
Thanks to the Pyglet Discord as well as Github and other forums I was able to make a working simulation.
[-------------------------]
Song used : Dark Souls - Menu Theme
Look at Ursina and Arcade maybe?
They are fairly high level game libraries.
That looks nice. What are the white points? They don't seem to be tracking the ball's trajectory.
i agree
They were supposed to but since I was restricted in time I couldn't polish the feature enough to do so.
2d, recommend using pygame
Pygame is solid and you can't go wrong but I'm a huge Arcade fan for all my 2D games 😉
First you need to ask a question
Does anyone here use Ursina?
Definitely. There is also an Ursina discord server.
anyone wanna help me derive the appropriate conditions for keeping particles in the region between these two boxes? it's really stumping me rn. the straight vertical sections on the left and right, as well as the straight horizontal sections on top and bottom aren't an issue, it's the corners of the region that have me scratching my head.
this is in c++ btw, but doesn't matter since it's only a group of if statements. this is what i've got so far (written as if it were python):
if (particle.position.x < 250):
particle.position.x = 250
particle.velocity.x *= -1
if (particle.position.x > 950):
particle.position.x = 950
particle.velocity.x *= -1
if (particle.position.y < 100):
particle.position.y = 100
particle.velocity.y *= -1
if (particle.position.y > 800):
particle.position.y = 800
particle.velocity.y *= -1
this handles the extreme outer-wall collisions.
What is the shape of your particles?
If they are round they should hit no more than one or two sides (and of the same box) if they are round shaped
@lunar venture circular particles, this is with only the outer bounds applied. just need to restrict them from ever entering the inner box
And what's stopping you from doing something like this for the inner border?
@lunar venture this is the behavior that's throwing me off. this is the code added.
if (p.position.y > 150 and p.position.y < 750):
if (p.position.x > 300 and p.position.x < 900):
p.position.x = 300
p.velocity.x *= -1
You are setting their position to 300 in both conditions
so ignoring the right side of the region for now and just looking at the left side where the particles are at in the gif, their x-position should always be set back to 300 if they ever exceed that, as long as their y-position is between 150 and 750, i.e. not within the top or bottom gaps
but in the gif, because there's no collision detection for when the particles' y-positions exceed 150 when in the top horizontal section, they jump back to 300 instead of just bouncing off that bottom wall. my problem is having conditions that distinguish those two
I think instead of setting it back to 300 it should be updated accordingly with the velocity so they won't stick there
Unless you mean to dampen their velocity once they hit walls
no I do not intend on damping anything. i guess it'd help to point out that the goal of this bounding region is to emulate a wire, and the particles are charged particles. I'm trying to simulate a circuit in the end, so the only "damping" will be the loss in electrical potential, no kinematic business
I think you can have two ifs and instead of setting their position attribute to a set position value, update it according to their velocity so it looks like they bounced off in a direction
I want to try doing particle physics myself now lol
it's a lot of fun. interesting to see how they behave. this is the result of just spawning a bunch of positive charges. 30 fps framerate limit on the gif capture makes it look bad but it's really smooth. interesting to see them always orient themselves such that potential energy is at a minimum
I've tried doing something in JavaScript and in C#
The C# one has VSync problems I think
Now I'm gonna be doing it in C for the heck of it
Gonna be using WinAPI and GDI32
I think it's okay
I do it in C++ with SFML. though i've had to write basically everything myself since SFML is very limited, just use it for the window and drawing shapes. I'm sure there's much better ways of going about it
hey guys, can someone take a look at this and help me with the problem? i know its some mathematical thing but i really cant seem to figure it out :/ the yellow car is supposed to go to the red dot
i can send a zip file of the code n everything if someone can help
is the car trying to turn around and go back to the first red dot once it reaches the second red dot?
right, i assume that's the intended behavior. but does the car distinguish the first red dot from the third red dot once it reaches the second red dot?
it does, i realized that whenever the dot is on the right of the car its fine but when its of the left of the car the issue occurs
wait let me take another recording
should i dm you the zip file?
yea i could look at it
Hello guys, I am working on a game and the game creates files but I would like the created files go in the folder desk, and I would like it works on every computer, any ideas?
As in, save files to desktop? (depending on what "folder desk" means)
>>> from pathlib import Path
>>> Path.home()
WindowsPath('C:/Users/einarf')
Yes it was why I needed !
That should work cross platform to get the user home directory
Thank u very much
i'm beginning to think it's impossible to contain a particle in this region. unless there's a method im straight up overlooking
nvm got it
If you care about the collision being correct then this method is not correct. It's ok for a video game though because you don't really care about it being correct. For simulation and more advanced games it can matter.
The reason why is because it's moving the particle to the wrong position. The correct thing is to move the particle back to where the collision happened.
The method currently used does this when hitting a right side border:
The correct place to move the particle to would be the intersection between the particle's path and the border.
if (particle.position.x > 950):
particle.position.x = 950
particle.velocity.x *= -1
``` The position correcting does not take into account both x and y.
You mean interpolate backwards in time? This is just for simulation of current in a wire, the collisions with the walls aren't important, just that they remain inside the "wire". The energy loss/gain from imprecise collisions would be negligible compared to the energy supplied by a voltage source and the following electric field interactions. I get what you're saying though, it could definitely be improved on
Yes. But it does not seem to matter for your case.
thats why charges in wire propagates only on wire surface
hey guys, i just wanna ask, how can i implement a pause function for a game in pygame?
You can have a variable initially false, e.g. paused = False. Then you can check for the pause button being pressed, and if it is, set paused = True. Then, before you update the animation you can check if not paused: ...
how can i fill the screen with say white?
keys = pygame.key.get_pressed()
pause = False
if pause == False:
botcar = BotCar(3,10,TRAIL)
elif keys[pygame.K_p]:
pause = True
botcar = BotCar(0,0,TRAIL)
centertext(WIN,MAINF,"Paused")
if keys[pygame.K_SPACE]:
pause = False```
this doesnt work :( can you help?
the centertext is a function i made to display text in the middle
pygame.display.get_surface().fill((255, 255, 255))
Or just
screen.fill((255, 255, 255))
if you have a screen variable already defined
You need to be setting the initial pause value outside the game loop, but checking for pauses inside the game loop
so i make a while loop?
Your game should already have a while loop if it was working before you tried to add a pause function?
yeah it does
so i set the pause boolean inside?
Set the pause Boolean to False before the while loop, then inside the while loop check for pauses
Hi, I'm relative new to python and my first posting here.
I'm using pygame and have two sprite groups with around 2000 sprites in one group and around 500 in the second group. Now I need to find the nearest neighbors in the first group for every sprite in the second group. For that I want to use a kd-tree, more specific the cKDTree from scipy.spatial. I have to rebuild the trees every x frames when there are new sprites in group one and/or movement in group two.
How would you call the cKDTree in this case? The cKDTree expects the x, y coords of the sprites as a list of (x, y) values.
Would you copy all (x, y) tupels to a new list to call the cKDTree with it, or is there a faster way to call the cKDTree with the original sprite group? How would that be done?
At last, HARFANG Studio (0.8.0 for Windows 64) is available!
https://www.harfang3d.com/en_US/studio
Sample projects can be download here :
https://github.com/harfang3d/sample-projects/releases
It is a simple 3D editor for creating your 3D scenes. It can import FBX, GLTF, OBJ files.
The content will run in HARFANG Python
❤️ 
can anyone recommend a tutorial on ursina?
this one seems exciting
A basic tutorial on how to create Minecraft in Python by using the Ursina Game Engine. This also includes a general introduction to the engine itself.
Timestamps:
0:00 - Intro
1:24 - The basics of Ursina
15:49 - Creating Minecraft style blocks
35:25 - Creating a sky, a hand and adding sounds
Project files are available here:
https://github.co...
im having a bit of a problem with pygame
currently this is what I have (attached) and here is the code for a bullet
class PlayerBullet:
def __init__(self, x, y, mousex, mousey):
self.x = x
self.y = y
self.width = 5
self.height = 5
self.speed = 15
self.angle = math.atan2(y-mousey, x-mousex)
self.xvel = math.cos(self.angle) * self.speed
self.yvel = math.sin(self.angle) * self.speed
self.cooldowncount = 0
def cooldown(self):
if self.cooldowncount >= 100:
self.cooldowncount = 0
elif self.cooldowncount > 0:
self.cooldowncount += 1
def main(self, display):
self.x -= int(self.xvel)
self.y -= int(self.yvel)
pygame.draw.circle(display, (0, 0, 0), (self.x+40, self.y+45), 5)
and here is the bandit script
class bandit:
def __init__(self, x, y):
self.x = x
self.y = y
self.image = pygame.image.load("pixil-frame-1.png")
self.offset_x = random.randrange(-300, 300)
self.offset_y = random.randrange(-300, 300)
self.reset_offset = 0
def main(self, display):
if self.reset_offset == 0:
self.offset_x = random.randrange(-300, 300)
self.offset_y = random.randrange(-300, 300)
self.reset_offset = random.randrange(120, 150)
else:
self.reset_offset -= 1
if player.x + self.offset_x > self.x - display_scroll[0]:
self.x += 1
elif player.x + self.offset_x < self.x - display_scroll[0]:
self.x -= 1
if player.y + self.offset_y > self.y - display_scroll[1]:
self.y += 1
elif player.y + self.offset_y < self.y - display_scroll[1]:
self.y -= 1
display.blit(pygame.transform.scale(self.image, (50, 70)), (self.x-display_scroll[0], self.y-display_scroll[1]))
I don't know how to detect collisions with pygame between a circle and a
sprite
so i dont know where to go from there
i would appreciate any help
Hi, im new to python and im trying to make a gambling game basically but its not with real money, currently in this game you can only bet $1 each turn but im trying to so that the user can choose how much money they wanna bet each round
Here is my repl:
https://replit.com/join/smvmjjvxeg-jacknguyen17
Help!!! How do I balance prices in an economy game
Let’s say right now, the best item is 10,000,000. The richest player only have 7,000,000 right now. How do I prevent those items from becoming cheap when players hit 100,000,000?
To a certain degree you can't
I mean, you could scale the prices so they're always high relative to a given player, but if they can accumulate infinite money then there's nothing you can really do to make an item not eventually become cheap
The only things you can really do is limit account balances or impose external costs that ensure they can't make enough money to make something cheap
There’s no equations to set prices? For example, I was thinking of setting some items to a % of the total economy, but that would only hurt the poor players, right?
I wonder if an equation like x/15(e)^x/15
Would work
Or something like an exponential function
Nope, nevermind. Once you hit a point the player couldn't afford it
.bm
just introduce inflation :p
still practically useless if they’re ultra rich tho
you could try and do something similar to a marginal tax rate system except instead of tax you apply it on prices
I think you'll always end up having inflation. Especially if there's no cap on what a player can earn over time.
Some games use several currencies to combat this. There's for example a daily cap, but that's more MMOish
Adding tax on trade/auction house and other areas also helps
Yeah, was thinking about this. Although it would be a little tedious to code a tax bracket
anybody?
is it possible to set a map with ursina? like a vmf file
You could get the bounding box of the sprite and check if any of the corners of the bounds overlap with the circle. Pretty easy to find out if they do bcuz you can just do
if self.x - bullet.x <= (self.bounds.width/2) + bullet.radius: self.freaking die
Oh and check the same thing but with y and bounds height
thanks
i love the self.freaking die
you could basically make a function that runs in background that detects whether a bullet is in the same place (field) that the sprite is
Hi everyone, I wanted to make a chess in python but a don't know how to continue. If someone think that is able to help me shot a DM pls (without complex graphic interface)
just pythons prints
you can do pseudo graphic with text see https://github.com/Textualize/textual
RN graphic isn't the problem, the problem are the logical functions
for logic better grab books maybe have a look there https://pythonbooks.revolunet.com
PythonBooks showcase the bests free ebooks about the Python programming language. The easiest way to learn Python for free!
Hey @dawn quiver!
It looks like you tried to attach file type(s) that we do not allow (.mkv). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.
Feel free to ask in #community-meta if you think this is a mistake.
for any of u here who have used pygame before, is there a way for me to make an object have a circular rect ? every object in pygame when u make a rect on it, the rect is a square around the image
yk what i mean, but can i make the rect be a circle around the image ?
trying to make a simulation for gravity :/
bruh
just check if the distance between the center points of the 2 circles is less then the radius of both added together
def dist(x1, y1, x2, y2):
return (((x2-x1)**2)+((y2-y1)**2))**(0.5)
if dist(self.x, self.y, moon.x, moon.y) <= (self.radius + moon.radius):
#call collide function
print("collide")
print("built in syntax highlighting is fun")
mm okay thanks, ill see what i can do with that
yea
appreciate it
np
Did you code en passant?
[pygame] ok, how to unlock surface when i .pixelArray it
so basically i wanna make a line trace for parabolic movement, and when i searching on
i get a code that need pixelArray to do it. And when i paste it, boom pygame.error: pygame_Blit: Surfaces must not be locked during blit shows up. i alr try screen.unlock() after pixelArray, but still not work, how to unlock it?
no, vmf is a proprietary format for levels made with Hammer
If you can export to obj or something similar, you can use it
Hi everyone, which one of library or python framework use to build a GUI desktop? I want to create a game "Hit the Mole". But I don't know what library is better to use for it
This is the example for website
you could use pygame_gui or simpleguics2pygame, btw they work on web too
hey guys! Me and my friend are working on a super cool game with python and pygame! we needed a bit of help with some things in the code and art, if anyone is willing to help, please dm!
here's a scr of wat we have till now
btw we're using the zelda character for now we'll change it when we're ready with our own character
thx
from ursina.prefabs.first_person_controller import FirstPersonController
class Voxel(Button):
def __init__(self, position = (0, 0, 0)):
super().__init__(
parent = scene,
position = position,
model = "cube",
origin_y = 0.5,
texture = "white_cube",
color = color.white,
highlight_color = color.lime)
def input(self,key):
if self.hovered:
if key == "left mouse down":
voxel = Voxel(position = self.position + mouse.normal)
app = Ursina()
for z in range(20):
for x in range(20):
voxel = Voxel(position = (x,0,z))
player = FirstPersonController()
app.run()```
Guys a voxel doesnt spawn when I press left click, is there anyway you guys can fix it or help me?
it looks like replit
Never heard of that. Looked it up and I think ur right
how do I make everyone turn?
you can add them to a list and iterate through it
Theme Select Thread.
https://blenderartists.org/t/bgmc-37-theme-thread/1387304
Blender Game Making Challenge.
BGMC will take place from June 27 to July 4th!!!
if pygame.draw.rect isn't working anymore then how to fix it?
@fallen nymph remember to call pygame.display.update() ?
HARFANG Studio editor, using a character created in Adobe Mixamo
next step, animate the character in Python using this kind of code snippet : https://github.com/harfang3d/tutorials-hg2/blob/master/scene_instances.py
it's replit
Yep
for the colab
Someone else already told me
oo ok
How would I fix this? (I'm using tkinter).
hi does anyone know how to make a timer in python that closes the game after 15 seconds?
idk how to do it but imo if you search for python countdown timer u will get results
and maybe multi threading so the game runs at the same time with the timer
I’ve searched for some
https://replit.com/@Spike3y/riddle-rpg-struggle?v=1/
hey guys feel free to tell me any ways to improve on this
Hey everyone. I am working on a text adventure game atm and want to to get some feedback from it. Also I am doing a competition for something called YTAC and need people to play my game and click on the link. Don't need to join and hope you like my game!
https://replit.com/@BonkDuck/Dragon-Side?v=1
You could make a function that presents a riddle and check the response from the user so you can reuse code.
Let's say you had 100 riddles loaded from file
That is fair 🙂
alot of help from friends was needed
2 min mockup ```py
RIDDLES = [
("What is the capital of France?", "paris"),
("What is the capital of Germany?", "berlin"),
("What is the capital of Italy?", "rome"),
]
hitpoints = 2
def ask_riddle(question, corect_answer) -> bool:
print(question)
user_answer = input("Your answer: ")
if user_answer.lower() == corect_answer:
print("Correct!")
return True
print("Wrong!")
return False
for riddle in RIDDLES:
question, answer = riddle
if(ask_riddle(question, answer)):
hitpoints += 1
else:
hitpoints -= 1
if hitpoints <= 0:
print("You lost!")
break
It shows using a function with a return value
You have to answer at least 2 questions right
bro i shoulda asked for help when the other competition was still going thats what i was trying too do lol
i think i understand this
It's an array of tuples with a question and the correct answer
We can "unpack" those values into two separate variables ```py
for riddle in RIDDLES:
question, answer = riddle
There are other ways to do it of course, but at least you need some list of questions/answers
Can also pick a random question ```py
import random
random.choice(RIDDLES)
That assignment is actually pretty nice for learning some programming
I forgot to add a win condition, but that should be easy to fix
Even the example I made above can be improved a lot, but it depends on the use case
what would be the best lib for making games, mostly 2d or pixel
Pygame
Subjective
I'd recommend pygame from prior experience
^
if you want to run on mobile and web : pygame
wbt like macos and windows ?
it can be the same code if that's you want to know
but can i still make games with pygame for windows and macos ?
sure
see https://pmp-p.itch.io/stuntcat , it can work on web, ios, android, windows macos linux bsd and probably others with the same code archive ( nb it's pygame 2 which uses SDL 2)
in pygame, how can i make an object be attracted to a point ?
i can move rectangles 50 pixels on the x axis or 50 pixels on the y axis but can i make a rectangle move to a certain point ?
for example, making a circle move towards the center of another circle

i need some help, how do i make it so that this error gets ignored?
i remember fixing it by typing "#" and some word after it
The easiest way would be to use some vector math. Subtract the body's position from the target's position - that's the vector from the body to the target. Rescale that vector to a length equal to how much you want to move per tick. Move the body by that vector.
okay, ill do a bit of research into vectors
thanks for the suggestions ill look into that as well
whats bounds
use lerp
pygame.math.Vector2.lerp
does anyone know if pygame has a button.just_pressed() function or something like that
?
why exactly lerp ?
lerp is short for linear interpolation and is meant for exactly this, interpolating from a to b
Hey everyone. I am working on a text adventure game atm and want to get some feedback from it. Also, I am doing a competition for something called YTAC and need people to play my game and click on the link. Don't need to join and hope you like my game! https://replit.com/@BonkDuck/Dragon-Side?v=1
The source code can be found with the Replit.
It works pretty nicely. One obvious improvement here should be to put all the player attributes into an object or class so you don't have to rely on global. Whenever you hare forced to use global it's a sign that there is a better way.
Maybe also the same for an enemy that has a set of properties 🙂
It’s very interesting
I also think if you defined long strings like this the source could be more readable ```py
lookCave = (
"As you look around you start to feel a sense of danger. The cave is creepy "
"and illuminated by a couple of torches and natural light. You can also see a sleeping bear "
" and the [cave exit]. Maybe you should [attack the bear]? "
)
This will turn into a single string and will not break the indentation making the game code much cleaner to read since you can follow the indentation to quickly see the blocks / structure.
In theory it would also possible to make the game more data driven to avoid making custom functions for each step.
That's at least two simple things + one larger thing that could be done to improve it 😄
To be a knit picker: Python style is "snake case" so we use lower case function and variable names like def scroll_text(text) and look_burning_tower. Classes can title case like Player.
You have still managed to use functions to greatly reduce the amount of code, so that's great work. This is pretty complex code if you are a beginner.
@vagrant quest I think that's all I'm going to say right now, but be free to ask if needed.
Thanks so much for the advice. Made in two days for competition and hadn't really used classes before so
definitely want to try some of that.
hey, i am currently learning the fundamentals of 3d rendering and currently learning how to multiply matrixes. short question, is it correct that you need to following ```
A B
[ 1 2 ] [ 2 3 ]
[ 4 3 ] [ 2 3 ]
step 1: 12, 22
step 2: 43, 33
REALLY new to this please don't judge, i never had this in math or in school general
what do i do next? i only have the first column of the result, 6 and 14
nvm i am dumb
okay, other question: how do you multiply multiple matrixes? i mean more then 2
You just keep multiplying them. Just remember that matrix operations are not commutative, meaning A x B will not give the same result as B x A. Multiplication order matters.
There are plenty of resources on how do do the actual multiplication math. Just make sure you don't confuse rows and columns
Matrixes come in two flavors. Stick to one of them: https://en.wikipedia.org/wiki/Row-_and_column-major_order
In computing, row-major order and column-major order are methods for storing multidimensional arrays in linear storage such as random access memory.
The difference between the orders lies in which elements of an array are contiguous in memory. In row-major order, the consecutive elements of a row reside next to each other, whereas the same hold...
Hello.
We maintain a pretty good example for that.
In 2.1.3+ you can use pygame.Vector2.move_towards
But this example assumes you use a lower version (since only the dev versions of 2.1.3 are out so far)
We have two related examples actually.
https://github.com/Matiiss/pygame_examples/tree/main/pgex/examples/projectile_to_position
https://github.com/Matiiss/pygame_examples/tree/main/pgex/examples/move_towards_mouse
Just a bunch of pygame examples (https://github.com/Matiiss/pygame_examples/tree/main/pgex/examples) - pygame_examples/pgex/examples/move_towards_mouse at main · Matiiss/pygame_examples
Panda is soon rolling out support for Vulkan.
I was talking about going low level in that instance, and yes I know panda is going vulkan 🙂
You need to share a lot more information about this app and how it's related to game development. Preferably also link a public repository with code.
I'm trying to draw a WWE ring but I'm having SUCH a hard time with the X and Y coordinates input and output.
Pygame, basic shapes.
What have you tried so far? I also think most people don't know what a "WWE ring" is.
.... It's a professional wrestling ring.
@potent ice I'm suffering with guessing coordinates!
0, 0 is in the upper left corner if that helps
I get that.
I think pen and paper can solve that problem.
There are techniques for drawing things in perspective by using perspective lines. You could look that up. The idea is to get a few rough control points. That can be done without graphing paper
If you have a ruler you can also get the main points from an existing image
or you can use pixel location in an image with mspaint
That might be much easier
I wonder why I haven't learned about this!
windows paint use same coordinates as pygame, so that should be super easy 😄
@ionic plume
So if you scale/crop the image to your window size, you are good to go
AHHHHH WHY HAVEN'T I LEARNED THIS FROM MY PYTHON BOOKS!! 😭😭😭💔
It's all about being creative finding good solutions. Open your mind 😄
I thought I just had to... Read books.
It's probably a bit too specific to be covered in a book 😄
You're amazing! You're my hero!!
Can I DM you if I need more help? 🥺😭
It's all part of general creativity when solving problems. It's something you can get better at over time.
I don't do DMs, keep questions here
Okay with me.
But my goodness you, really helped me leap a giant foot forward!
Thank you again!
I would've continued to suffer so much with no avail.
And you're right, MS Paint really DOES measure your pixels, I would've never thought of MSPain in a million years.
I have one more problem. I need help with.
It has to do with moving a square on my screen
is there anything representing pygame.Vector2.move_towards in version below 2.1.3 ?
No
mm okay
thanks a lot for the examples btw
they are already helping
respect
any clues to when 2.1.3 will release btw ?
This one basically just implements move_towards specifically for this
https://github.com/Matiiss/pygame_examples/blob/main/pgex/examples/move_towards_mouse/vector2.py#L12
You could use that instead
pgex/examples/move_towards_mouse/vector2.py line 12
class Vector2:```
Soon, they are trying to get it out as fast as possible
will look into it rn
hope it comes out soon
oh
i was trying to see if there are any updates for it but there werent
but this works ?
huh
perfect
any downsides or ?
just bugs
i assume
Stability maybe, but the contributors think otherwise
mm okay
Some things could be subject to change in the actual 2.1.3 for sure
alright
yeah im gonna tell u head on, 1 month is not enough to make a whole game engine
and pyglet for gra^hics
u need at least years
i mean ur still learning the fundementals
currently I want to switch
panda3d or pyvulkan
ah
if u are really really ON about making games, i recommend trying to learn C# instead
look
u can still use python sure, but C# comes with lots of ways to make games, unity game engine for example is one
I challenged my self to make it in 3 months only
a game engine ?
3 months
isn't realistic
yes
yes its not enough u need way more time
I named it Gold engine
thousands of llines of code
it's gonna be buggy and 3d
lines
currently the graphics.py
has a lot of lines
don't worry I'm using numba for performance
cuz python is little slow
Ok, good luck mate
thx @plain junco
u need to learn insanely more to make a whole game engine, get a solid grip of classes , solid grip of the whole logic of how programming works , make a few side projects here and there, interesting things that are challenging like for example visualizing a sorting algorithm or simulating gravity, or making something like a small game with interesting and unique stuff in it, u cant just go from nothing to a game engine
gold engine currently
don't have even collision
but
it can draw
.fbx and .obj and .egg
3d models
if u want 2d
then go with other version
yeah
big dreams, but small PP
nah
look
big dreams and big pp i respect u for trying man, almost no one would try such things
I really love c++
C++ is good yeah
but python was the challenge
we choose c++ just for performance and good graphics Libs
I tryed unity
I liked Godot
godot is good
GDScript
simliar to python
yep
gimme a second
really similar to python actually
why not try using godot ? to get a grip of how making games works
u dont copy code from github and shite like that right
Guys can you make a good game using pygame precisely a top down game .
This feels very much like an advertisement which is not what this channel, nor our server is for.
I don't see why not
hi i made a game with pygame and turned it into an exe using pyinstaller, the code had the sql database's information (host, password, user) so is it safe?
If that's a public facing database.. then definitely not
how can i secure it?
Why do you need the database credentials in the game client in the first place?
.__. to store the highscores and shit?

You should instead make server/service the client can use to store that stuff.
o
Thinking of a little project - and whilst I like Python more than TS, last game things have been in Pixi.js. So, little out of the game, Python Gamedev wise. Question is - is Pygame still the 'gold standard' in game dev libraries in Python? I presume nothing is being transpiled to asm.js and supports a HTML5 canvas yet?
You can run pygame applications on the web now.
Made entirely possible by @vagrant saddle
Seriously...
😮
OK - guess I'm investigating Pygame as an option again!
music isn't played in the same no of loops as mentioned in the code
i used mixer of pygame module
what might be the problem ?
plz help
here's my code: ( if i change play(0) to play(1), the music will still be played only one time)
import datetime
from pygame import mixer
tme = datetime.datetime.now()
x = int(tme.strftime("%H"))
if x <24:
mixer.init()
mixer.music.load("Drink.mp3")
mixer.music.set_volume(0.7)
mixer.music.play(0)
v = input("Enter 'DONE' when you finish drinking water:\n")
if v == "DONE":
mixer.music.stop()
else:
print("Invalid input.")
plzz help
lmao wtf is this
a game about drinking water
and then u will sell it for 1 dollar in google play store
haha....very funny...... it's obvious that i am not trying to build a game here. small alarm sys . i thought u guys would be able to help, as u guys are in game dev and noone helped me in help channel
i think the code is alright but i don't know why it's not working? a problem in editor or what?
@potent ice there's 4 parameters that have to be typed but MS Paint only gives 2
😭😭😔😔
In "pygame.draw.line(screen, blue, [ , ],[ , ], )
Just wanted to pop in and let folks who might be interested know - my Python ECS library is now in release:
Do note that PyPI is taking some time to update its version to the latest, so specify '1.0.4' if installing from pip!
Do you watch someone's python course on YouTube? Ig
So i've been wondering, how should I manage a game state?
Like say I want to have a cutscene play, then return to the main loop, or the player opens an inventory or gui screen, then returning to the gameplay itself...
How do I keep track of the fact that the person would have passed the cutscene etc, or completed an action that would then cause the rest of the game to continue like normal
This is one thing that has had me stuck for the longest while now.
Would I just have to like, make a bunch of variables for all the different options etc, then have them
if then?
Or maybe an external file which will keep track of the state of the game?
I'm not sure
For example, say I'm using Arcade, and making use of their Views, when I switch back to the gameplay View, then the class would get reinitialized... so I'm really stuck here 😅
And If it is better to use an external file or something, what exactly should it contain and how should I read from it?
Thank you in advance!
Hey @lyric pawn!
It looks like you tried to attach file type(s) that we do not allow (.avi). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.
Feel free to ask in #community-meta if you think this is a mistake.
Videos showing 2 mechanisms I have implemented recently in my Minecraft prototype, they still need some improvements though 😉
yes why?
Cause i also watch a youtube he gave a project similar to you one one which you asking
healthy programmer, is it?
yes
I was just asking
did you finish it?
No i not made
I just watching series for learning
Me making discord.py bot so me learning from him
oo ok , i am still stuck in this project .
I'll try to help
but i will finish it today
sure. will ask u when i need help
I not finished series yet
Me on ep:68 of playlist
https://github.com/disketflu/minecraft_prototype I have juste made my minecraft prototype public if anyone wants to test it / modify it
I'll keep working on it for sure, will add different blocks to be placed, will probably be adding a GUI made using harfang engine as well 🙂
Be careful with minecraft clone.. it's very addictive and the rabbit hole is very deep 😄
import pygame
pygame.init()
#window
size =(700, 500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("1999")
clock = pygame.time.Clock()
#colors
red = ((153,0,0))
black = ((0,0,0))
white = ((255,255,255))
rect_x = 50
rect_x += 1
rect_y = 50
rect_y += 1
pygame.draw.rect(screen, white, [rect_x,rect_y,50,50])
#font of the text
font = pygame.font.Font("C:/Windows/Fonts/CHILLER.TTF", 100)
font = pygame.font.Font("C:/Windows/Fonts/CHILLER.TTF", 55)
font = pygame.font.Font("C:/Windows/Fonts/CHILLER.TTF", 55)
#text
text = font.render("1999", True, red)
text_2 = font.render("The Cursed Game: ", True, red)
text_3 = font.render("Enter if you Dare! ",True, red)
screen.blit(text,[300,100])
screen.blit(text_2,[220,150])
screen.blit(text_3, [230, 200])
exit_window = False
while not exit_window:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit_window = True
#background color
screen.fill(black)
pygame.display.update()
clock.tick(20)
pygame.quit()
We have this one for a reason 😄 https://paste.pythondiscord.com/
new biomes and materials 🙂
will be adding a gui this afternoon, and you can currently choose the material you build with as well (water, snow, rock, grass and sand)
I simple improvement could be to do chunk generation with multiprocessing. Just request chunks on a queue and get raw data back you can use to build the chunk. (non blocking writes and reads to queue)
Thanks for the feedback 🙂 I do have a queue for chunks generation, I do not really know how to do it and if it is possible on python to do real multiprocessing, I have only tried threading and so far it's just slowing down the whole thing, especially framerate.
I heard it was pretty much impossible to achieve real multiprocessing on python, but I'd like to be wrong 😄
Yeah you have to use multiprocessing to use all cores. Threading in python will slow down main process 🙂
Yeah that's exactly what I want to achieve but I haven't looked deep at it for now
Multiprocessing works fine even for realtime things in my experience.
You just need to make sure you read and write to the queue non-blocking
I'm learning about threading library in Python. I don't understand, how to run two threads in parallel?
Here are my python programs:
Program without threading (fibsimple.py)
def fib(n):
if ...
Yeah I was reading this and It seems like threading in python is a bit different than multiprocessing
Will try with multiprocessing for sure this week or even today, thanks a lot !
Threading is great if you are doing IO or light work. Anything more than that will crush the main thread
Yeah I see if you need a bot that calls multiple urls or so it's okay but does not really accelerate anything in the end
Just make sure the data you send in the queue is simple/generic. It's pickled and transferred between the processes. Not all objects can be pickled. You might have to quickly build the vertex data in the main thread, but this still means the subprocess will do the expensive work. I found it worked well to only read and create one chunk per frame to throttle things a bit.
Can also go fancy with "shared memory" later, but I don't think that is necessary for chunks
Thanks for the advice 😉 I was thinking of that too, I don't think I call call any engine function from another process, will do some tests this afternoon
It should work pretty well I think. If things get tights in the main thread you can use a generator function with timeout or fixed amount of work so you can continue in the next frame. It's worth adding to keep smoothness.
Wow! That solved my problem. Thank you!
I'll send u back to the dark ages
This channel is about game development. Random images from games are kind of off topic unless it's in the right context 🙂
I will be pushing the code in few minutes to github, I have done multiprocessing on most of the tasks related to chunk loading and I have done many more optimization regarding wether the player is moving or not
It is now way more enjoyable to move and look at the terrain being generated, everything seems smooth, still need to fix a bug where my chunks don't seem to get sorted by distance (doesn't happen often) even if i force it to be
Nice 👍
iAM ON windows 7. ii am using pygame to animate this sprite when it moves it leaves a trace. HELP
also i have to click then take of my finger then re click to move i cant do a prolonged click
Which engine ??? and lang..
You might want to share some minimal code https://paste.pythondiscord.com/
Are you clearing the display/screen? How are you handing the inputs?
Hi!
yea thats because theres no surface behind it
you need to put somethig like a pictue or something behind it
and behind it means behind it in the code
started adding a gui to my minecraft prototype today, also made using Harfang
I am using Harfang 3D as an engine and it's Python package so the language is Python 🙂
just updated the repository with the gui and the most recent version
you can build 5 materials as of now, and I have also added 2 levels to the terrain generation (stone and snow)
Hello, I have a question. Why does this happen? When I click the SETTINGS text, instead of disappearing, the text comes back. I figured it out that is because the python haves the hold Mouse function and not click. How can I change it to a click function? In advance, thank you very much for your help.
Here is the code:
import pygame as pg
import pygame
import self
import self as self
import mouse
from pygame import surface
pygame.init()
screen = pygame.display.set_mode((400, 400))
X = 50
Y = 200
running = False
silver = [190,194,203]
black = [0,0,0]
self.clicked = False
left, middle, right = pygame.mouse.get_pressed()
click = pygame.mouse.get_pressed()
pygame.MOUSEBUTTONUP = True
def Title():
pygame.display.flip()
screen.fill(silver)
pygame.display.set_caption('AVATAR PVP')
pygame.display.update
def AVATARPVP():
font_obj = pygame.font.Font(None,25)
text_obj = font_obj.render('Avatar PVP', False, black)
screen.blit(text_obj, (50, 100))
def START():
# START
font_obj0 = pygame.font.Font(None,16)
text_obj0 = font_obj0.render('START', False, black)
screen.blit(text_obj0, (50, 210))
def SETTINGS():
font_obj1 = pygame.font.Font(None,16)
text_obj1 = font_obj1.render('SETTINGS', False, black)
screen.blit(text_obj1, (50, 260))
def EXIT():
font_obj2 = pygame.font.Font(None,16)
text_obj2 = font_obj2.render('EXIT', False, black)
screen.blit(text_obj2, (50, 310))
# 50 i 90 310 i 325
def MOUSECLICK():
if event.type == pygame.MOUSEBUTTONDOWN:
posx, posy = pygame.mouse.get_pos()
print(posx, posy)
if((posx >= 50 and posx <= 90) and (posy >= 310 and posy <= 325)):
exit()
if((posx >= 50 and posx <= 130) and (posy >= 260 and posy <= 270)) or event.type == pygame.MOUSEBUTTONUP:
screen.fill(silver)
while not running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = True
Title()
AVATARPVP()
START()
SETTINGS()
EXIT()
MOUSECLICK()
nice
yeah i added a background and it worked thanks
u can also make a update function and call are your functions in there. and only call the update in the main loop. looks cleaner
Hey @hearty quartz!
It looks like you tried to attach file type(s) that we do not allow (.zip). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.
Feel free to ask in #community-meta if you think this is a mistake.
https://github.com/nate-4000/TSPUDTTY
I made this game, any code cleanup or efficiency comments?
A first step would be to put the contents of the zip into the repository instead of the zip file itself
a good idea would be to not add files via upload, but making a local repo looking like you want, then git pushing it to github
git push doesnt work, just tells me that the git file does not exist
did you create a repo in the folder with git init?
yes
i even git remote'd it
oop wait...
i just ryed agian
i'm a dumb***
i forgot to make the github repo
done
hello?
you guys dissapeared
seems to me like you're usually not handling the case if the input is wrong
yeah, i dont know how to do it without a try: ... except: ... block
you could make a helper function
def inp_num(prompt:str, max:int) -> int:
while True:
try:
res = int(input(prompt))
except ValueError:
print("Please enter an integer")
if not (1<=res<=max):
print(f"Please enter an integer from 1 to {max}")
else:
return res
e.g. that.
Put __pycache__ in a .gitignore file
kay, so i just do something like
stdin = inp_num("> ", 3)
# instead of
stdin = int(input("> "))
how
- Delete
__pycache__, commit and push - make a file called
.gitignorewith the following contents
__pycache__
add, commit and push.
__pycache__ contains compiled bytecode. It's not necessary to have in the repo just making a lot of noise in the change history
When you make a repository you can chose from several templates. The "Python" template will include a common sense .gitignore
It will just make sure you don't include unnecessary local files to the repo
hello
I need some help
I have programmed a video game in python
and I want to know if there is someway I can download the code as a file so that I can send the file to my friends, and they can try out the game
is that possible?
Not the best, but my first game created by python ( I just started learning python )
num = random.randint(1,100)
guess = []
guess_count = 0
guess_limit = 10
out_of_guesses = False
print("Welcome!")
print("This is a guessing game where you will have to guess a random number between 1 and 100")
print("You will be given a hint after each guess, and you will have 1 tries to guess the number")
print("GOOD LUCK!!!\n")
while guess != num and not(out_of_guesses):
if guess_count < guess_limit:
guess = int(input("Enter your guess: "))
guess_count += 1
if guess > num:
print("Hint: The number is less then your current guess!\n")
if guess < num:
print("Hint: The number is greater then your current guess!\n")
else:
out_of_guesses = True
if out_of_guesses:
print("Sorry, your are out of guesses, try again next time!")
else:
print("Congratulations, You WON!!!")```
perfect number 69

Video showing GUI animations and placing blocks
https://goodio.itch.io/black
Hey everyone, im trying out Godot. im working on a platformer game, can you guys give some ideas about what should i add to this to make it better
btw im using gd script for scripting much similar to python
nice, but why not using pygame and python ?
Work in progress on a 2D / 3D / VR GUI made in Python. Tell me what you think about it 🙂
great game, I think you forgot to add a '0' on line 10. You've also programmed it quite nicely
oh yeah, I added that in my program but I may accidently have removed it here, Thanks!
👍
wtf ure making game on python
its cool
Thanks 😉 And yes if you want to check out the code or learn how I have done it I can give you the github link or you can dm me
Hey there. I am trying to make a type of Wordle game. This is my code:
import random
import time
f = open("words.txt", "r")
random_words = f.readlines()
word = random.choice(random_words)
forbiden = ["\n"]
positon = 0
for char in word:
if char not in forbiden:
letters = []
letters2 = []
letters.append(f"{char}")
letters2.append(f"{char}{positon}")
positon = positon + 1
print(letters)
while True:
inp=input("Your guess (5 letters): ")
pos2 = 0
for char in inp:
print(char)
char2 = f"{char}{pos2}"
pos2 = pos2 + 1
print(pos2)
if char2 in letters2:
print("Correct letter and position: " + char)
elif char in letters:
print("Correct letter in wrong position: " + char)
else:
print("Wrong letter: " + char)
time.sleep(2)
Output:
['m']
['o']
['g']
['u']
['l']
Your guess (5 letters): mogul
m
1
Wrong letter: m
o
2
Wrong letter: o
g
3
Wrong letter: g
u
4
Wrong letter: u
l
5
Correct letter and position: l
Why does it only say that the last letter is correct only?
in the first for loop you are recreating letters2 = [] each pass, it will only contain last letter
Shouldnt it do it for all of the characters?
you should create the empty list before the loops, not make it a new empty one every iteration
oh. Now i get it. Your right. Thanks for the help.
How do i get the model stuff up in python?
In Pygame the movement is very slow i have to tap very fast if i want to go right or left but i cant keep my finger on a key to move.The movement isnt fluid. Is there solutions
???
Am a professional programmer with many years of experience in the filed of Developing Game app for iOS and Android. Do you wanna develop game app? If yes am capable for your project, I will provide proof of my work before We start Working together.
Kindly inbox me. Note I render proof of my work before we start work....
Thanks
!source
i am thinking of coding a computer game in pygame is there anything you can send to help
There is an ocean of resources for pygame if you search around. What you need might depend on your experience level. There are free books (http://programarcadegames.com is one of them), the official pygame docs (https://www.pygame.org) and probably hundreds of youtube videos. There is also a pygame discord server.
you can also use pygame-zero to simplify the initial tasks, and that serie was nice https://github.com/TechnoVisual/Pygame-Zero ( it also work out of the box on web )
yeah. pygame zero can also work. It's not super fast, but it can still do a lot
Hey um i've been getting a bit bored while writing basic python programs without any real use other than being cool and being low effort, so I would like to start making a game to keep me busy for a while. Where should I start?
Oh nvm just saw this, thanks anyways for this
Hi
font = pygame.font.Font('arial', 12)
pygame.error: font not initialized
anyone know how to fix this???????
help????
!helpdm
state_bool
!helpdm <state_bool>
*Allows user to toggle "Helping" dms.
If this is set to on the user will receive a dm for the channel they are participating in.
If this is set to off the user will not receive a dm for channel that they are participating in.*
Hey @nocturne zinc!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
mmmm
lets try again... hi all, im making a few custom recipes for a modpack and they aren't working, could anyone proof this and get back to me please? im tearing my hair out... thank you!
You probably need to me a lot more specific. I don't even see a game mentioned. Also, how is this related to game development in python?
sorry, sorry, its for minecraft
its my first post, i dont really know the correct way to post for this stuff
and in relation to game development, i didnt know where else to post...
If this is just pure minecraft stuff there are probably better communities out there to ask these kinds of questions. #game-development here is more about python game development and graphical programming in general. See the channel description.
No worries. Don't mind people discussing it here, but you are very unlikely to get an answer from a topic/question that is off topic.
Then it's kind of on topic, but the root of the question is about the minecraft 🙂
hello guys, can someone help me in the development of the sokoban game?
That's a whole lot to ask for. It's much easier to get a response from smaller question. For example: A very specific problem you are struggling with related to your game.
ok
Hello! Do you guys have any advice on how I should store world data? I am currently storing the world using multiple txt files with an item id table, but I would want a more efficient one.
Depends. do you want it local or online? how big is it gonna get? how often do you access this data? do you write to it more often or read? do you need frequent access to it? etc a lot of the times, a text file might just work
Also depends what you mean by "a more efficient one". That's the problem with the current solution?
im making a hobo life game
i made a typewrite ```py
import time
import colorama
color = Fore.YELLOW
msg = """hello welcome to hobo life"""
def typewrite(msg, wait=0.20):
char_amount = 0
for char in msg:
char_amount += 1
print(color + char, end="", flush=True)
if char_amount == len(msg):
print("", end="\n")
time.sleep(wait)```
better one it was sending a weird symbol at the beginnig of type write so i have its end " " at beginning to get rid of that error ```py
import time
import sys
from colorama import *
import os
first_typewrite = False
def typewrite(msg, wait=0.2):
os.system("cls")
global first_typewrite
color = Fore.YELLOW
if not first_typewrite:
first_typewrite = True
typewrite(' ')
os.system("cls")
char_amount = 0
for char in msg:
char_amount += 1
print(color + char, end="", flush=True)
if char_amount == len(msg):
print("", end="\n")
time.sleep(wait)```
you can change color to whatever you want
this has something to do with game development bc ppl can use this for text based games and im using it in my game
Help with what?
im making a small game in pygame and need help with collisions detection, i wanted to know what the best option would be to make it work
my code has a player class, and idk how to make another object which he can jump on
sorry for the late reply, but I would like one which stores multiple layers of tiles, instead of having a text file for each layer. My friend is telling me that he is using tiled XML, but I am not sure if it would suit my needs
Tiled XML is not more efficient in any way. It's used because it's what the Tiled editor outputs. So it depends if you want to be able to use that editor or not.
Okay, but do you know of a better way of storing tiles? Like I said in my previous message, I would like one which can store multiple layers of tiles instead of one file per layer.
You can create whatever file format you want.
Also is storing a layer per file actually a problem?
Are you ok with it?
Not currently, but it might be a problem in the future. It's fine right now, though.
Solve it when it actually becomes a problem. Until then, write your code in a way such that that part can be swapped out without affecting anything else.
"abstracted away"
Okay, thanks for the help!
If by more efficient you meant the speed with which you can create maps. Then Tiled can certainly help with that, although I prefer the more simple "dumb" method of using an image for the map where each color means some tile.
Something that works nicely in 2D games.
(With this method you can create maps in photoshop or whatever)
I could try that, but creating a text file of the map is kind of similar.
Yeah, just do whatever you prefer.
Okay
(You can even support multiple types later if coded correct (text, images, XML))
(So you don't need to throw away work)
(Or write a converter tool)
Got that, but I have an unrelated question. How do I get all the colours used in an image? get_palette() doesn't seem to work. I am using pygame as the library of choice.
I am getting the error pygame.error: Surface has no palette to get, though I'm not sure how I can fix that.
Also, please ping me if you have the answer.
MY PROGRAM HATES ME!!
I'LL NEVER BE A PROGRAMMER!!!
I'LL ALWAYS BE A FAILED PROGRAMMER!! 😭😭
Hey @zenith orchid!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
Hey @zenith orchid!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
how do u make 2 classes interact with each other?
can you explain more in detail of what you mean
like i want to have a player class and a block class, i wanna use these 2 classes to be able to have them collide with each other
how would i approach this situation
One way to do this is keep track of what you’re waiting to do, and what time to do it, in a list or similar. Then keep a timer running and when it becomes time “return” to the task by calling a function
WIP : Socket Server - Client made in Python using Harfang library.
Game is 2d for now, will try to do a sort of "metaverse" in 3D and possibly add Web3 signatures (ECDSA) as a way to log-in to the server, possibilities are infinite 🙂
I plan to add a "browser feature" to my project but I got no clue of what library I will need.
Someone know the names of them?
(I want to figure out the rest,just the names)
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
You might just want to delete what question and move in. It's 100% clear it breaks the server rules.
But here is game development everyone moving me from place to place can someone just direct me like
you can use rect collisions, pygame has some methods for that (search up pygame AABB) so the rects can act like the different hitboxes
hey can someone help me?
im trying to change values in an object but when i call the function that changes something it doesnt change
#EX.
def register_Clone(self,spritelist):
self.clonecount = self.clonecount + 1
clone = Sprite(self.name,self.pos[0],self.pos[1],self.costumelist,self.spritefunc,(self.clonecount,self.clonecount,self.currentcostume))
spritelist.append(clone.get_object())
return spritelist
``` when it runs the first peice of code it changes but only inside the function
so when it gets to running the sprite's function it says that the clone count is 0 but when it runs the clone's version it says 1
i can also provide the full spritehook.py
New project I have been working on recently : Client / Server app with Web3 Authentication using the socket and Web3 libraries + Harfang Engine to handle 2D/3D
GitHub source is here : https://github.com/disketflu/poc-harfang-web3
Any positive/negative feedback will be greatly appreciated 🙂
You can't ask for help to memory hack GTA5 anywhere on this server. It's that simple.
Anyone know the performance difference between pygame, panda3d and ursina? Both 2d and 3d games. Which would be the best for 3d performance wise, and which would be the best for 2d performance wise?
I havnt stress tested ursina and panda3d, but with pygame i can render 3500 2d circles at once with only using basic for loops and lists while staying above 60fps. And my pc is a potato.
Not too familiar with ursina or panda3d, so cant stress test them fairly.
Generally, Panda3D will be the fastest. Potentially by a large margin depending on what you are doing.
Ursina, being a Python extension of Panda3D, can match Panda3D at best.
Pygame is not really meant for 3D.
Is panda3d faster than pygame with 2d aswell?
Yes. Especially if you are using C++ and not Python. In both cases your Python game logic may be the limiting factor. If Python is not the limiting factor then Panda3D will often be faster.
Ok thank you. Ill have to learn panda3d.
Newer versions of Pygame are totally fine for 2D unless you are really going wild with it.
if the position is the same as before you could have it not print it in that console
I will be going wild lol
Millions of objects?
I would just do the more effort route then and go with Panda3D.
Def. not as simple to learn though.
Learning hasnt stopped me with anything yet lol
Thank you for helping me out with this
Panda3D provides 3 different physics options, I recommend Bullet3D.
The simulation will be on an atomic scale, so particles will attract and repel each other
Ok, then you can do that yourself.
Ye
That is best done in either C++ (Panda3D provides both C++ and Python APIs that match) or with compute shaders (which Panda3D also provides an API for).
Or maybe you prefer OpenCL, which you can do from Python with Pyopencl.
Is pyopencl faster than pygame?
If you are unfamiliar with GPU computing then I would not worry about it yet.
Ok
If you only need a couple of particles Python is fine.
If you want a lot, then switch to C/C++ or Cython.
However, the largest initial gains will come from algorithm complexity improvements, which you can still test while in Python before switching.
Rendering is all handled by Panda3D so it's not like you need a manual draw loop.
Bruh im trying to learn making bare scripts look them up at github takes memory overwrite this is the most basic and i cant do it
The point is not hacking but as i know pymem is a library that is ok to use to overwrite memory
anybody familiar with obj files?
i have s imple geo question
if i have a triangle defined by three points
(-0.5373618100229374, -0.6229249731125697, -0.5685127641500909)
(-0.600387386524909, -0.5598575261304555, -0.5710468777052161)
(-0.5327866385006366, -0.5598329623136813, -0.6346065333277624)
how would i find the edges?
import tkinter
import random
colours = ['Red', 'Blue', 'Green', 'Pink', 'Black',
'Yellow', 'Orange', 'White', 'Purple', 'Brown']
score = 0.
timeleft = 30
def nextColour():
global score
global timeleft
if timeleft > 0:
e.focus_set()
if e.get().lower() == colours[1].lower():
score += 1
e.delete(0, tkinter.END)
random.shuffle(colours)
label.config(fg=str(colours[1]), text=str(colours[0]))
scoreLabel.config(text="Score: " + str(score))
def countdown():
global timeleft
if timeleft > 0:
timeleft -= 1
timeLabel.config(text="Time left: "
+ str(timeleft))
timeLabel.after(1000, countdown)
def startGame(event):
if timeleft == 30:
countdown()
nextColour()
root = tkinter.Tk()
root.title("COLORGAME")
root.geometry("375x200")
instructions = tkinter.Label(root, text="Type in the colour"
" of the words, and not the word text!",
font=('Helvetica', 12))
instructions.pack()
scoreLabel = tkinter.Label(root, text="Press enter to start",
font=('Helvetica', 12))
scoreLabel.pack()
timeLabel = tkinter.Label(root, text="Time left: " +
str(timeleft), font=('Helvetica', 12))
timeLabel.pack()
label = tkinter.Label(root, font=('Helvetica', 60))
label.pack()
e = tkinter.Entry(root)
root.bind('<Return>', startGame)
e.pack()
e.focus_set()
root.mainloop()```
It's not printed anymore in the current version 🙂
An edge is defined by two end points. So you already have three edges right there. For three edges you need 6 points, but each edge in a triangle shares its two end points with two other edges of the triangle, so having it listed as 6 points would have 3 duplicates. So three points is all you need.
If by find the edges you mean the edge lengths, you can apply the distance formula for 3D:
What did I just walk into
You walked into some basic math used in games? 😄
Hey @lament gyro!
It looks like you tried to attach file type(s) that we do not allow (.zip). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.
Feel free to ask in #community-meta if you think this is a mistake.
how does 3d work on the screen and can python be used for 3d games without using 3d engines
Hey i am trying to make a placing and breaking system for my game, i have already managed to make an efficient breaking system.https://www.mediafire.com/file/hawhfy2a86kzacy/game.zip/file
like making your own, ik it would be very difficult
You can definitely do 3D without any fancy engine, but that requires learning quite a bit. Most people use 3D engines unless they have special cases.
you can study the code of TinyGL (https://bellard.org/TinyGL/) or the very complete OSMesa those are two libraries you could use in python to do complex 3D without 3d hardware engine. but it will be very slow
3d for mobile is a bit different see https://github.com/lunixbochs/tinygles instead
curious
what does the "normal projection" of a point mean
i have a triangle defined by (x1,y1,z1), (x2,y2,z2) and (x3,y3,z3) and i have a point (xp, yp, zp)
if i have to find whether the normal projection of the point lies within the triangle
then i have to find the projection of the point (xp, yp, zp) in the plane of the triangle, and then use that point to check - right ?
Pyglet game : https://nuelito.itch.io/bouncy-square-recoded
@summer inlet it's text based unfortunately
i wish i could use pygame
why arent you able to?? 🤔
tricky
oh, fair enough, all syntax just takes some time
also neat pokemon game
eyy thats good
which part seems to trick you up the most?
all of it
lol
well if you can get through understanding the class functions and objects, pygame is basically just a fancy rendering system after all 🤔
wow thats nice
coming from someone still learning opengl
Would someone be willing to let me share a game idea with them and they tell me if it sounds exciting/like a good idea? I'll send a quick description of the game in a message.
It's a browser-based MMORPG so only volunteer if that's your type of game!
Is there an easier way to check collisions with cherry? xD
(snakeHeadPositionX + snakeHeadSize[0] >= cherryPositionX and not snakeHeadPositionX >= cherryPositionX + cherrySize[0]) and (snakeHeadPositionY + snakeHeadSize[1] >= cherryPositionY and not snakeHeadPositionY >= cherryPositionY + cherrySize[1])
hi i created a game and posted it to my github
but how do i put the python files and folders into an index.html so that I can run it in github pages
hi, if it's a pygame / canvas2D/3D or vt420 game use https://pypi.org/project/pygbag/ more info here https://pygame-web.github.io , if it's text only with input() then maybe pyscript
to automate publication use github actions copying that yaml file https://github.com/pmp-p/pygame-breakout-wasm/blob/main/.github/workflows/pygbag.yml in your project ( as .github/workflows/pygbag.yml ), then run CI action (wait 1 minute or 2 ) then select [gh-pages] in combo list for web root in [projects settings]/[pages]
Hello guys I have a very solid knowledge about python and I want to start making games with it I want some tutorials about it (all of them tbh) and I have a previous experience on making games with godot but this time I want to make a game with pygame ,I will be very glad if you sent me some good tutorials .
Thanx for your time .
I don't know many pygame tutorials, since I mostly used books and personal projects to learn, but I see the work of Al Sweigart being complimented a lot. Here's an useful link of his materials regarding pygame: https://inventwithpython.com/pygame/
If you want to take a look at more advanced stuff, DaFluffyPotato is probably one of the most advanced pygame users at the moment, here's his youtube channel https://www.youtube.com/c/DaFluffyPotato with a lot of video tutorials
I make games and tutorials with/for Python/Pygame! :D
Website here: http://dafluffypotato.com
Remember I never followed any of these tutorials, so take my advice with a grain of salt, although, the guys behind those seem to know what they're doing, and Sweigart is an acclaimed Python author.
If you're interested, I also published a multi-purpose node editor made with pygame, totally free of charge and dedicated to the public domain. Here's the github link: https://github.com/KennedyRichard/nodezator. You can install it with pip install nodezator
Here's a video presenting it https://www.youtube.com/watch?v=GlQJvuU7Z_8
I'm happy to announce the Nodezator app, a node editor for the Python programming language that turns Python functions into nodes. It is expected to be released in June 2022, the first app of the Indie Python project to be released. Visit its dedicated website: http://nodezator.com
http://indiepython.com
https://twitter.com/IndiePython
http://...
I readed all your replies and I respect your pov and your experience and I will check these tutorials I already started in dafluffypotato tutorials but maybe I will read some books and I already downloaded some open source projects .I am glad and Thanx for your time
is there something like gl.glReadPixels(returns the rgb of a pixel coordinate given) but for the whole screen and not just the window, not specifically looking in opengl only
Pillow can read from desktop if you need that
pyautogui.screenshot did the job for me, first i screenshotted the area I wanted then converted it to an np array
What 2d graphic libraries are there that I can look into? I used Turtle and Pygame in 3 years ago
*trying to make chess game ui with it
THX!!
minesweeper random tile bomb or not code ```py
import random
e = {}
x_range = 30
y_range = 50
x = 0
y = 0
for _ in range(x_range):
x += 1
for _ in range(y_range):
if y == y_range:
y = 0
y += 1
e[f'{x},{y}'] = bool(random.getrandbits(1))
print(e)```
x range and y range can be infinitly expanded but i think if you make mine sweeper i think the max should be 99x99
I made a random maze generator
That you have to escape
Somewhat underwhelming for how irritating it was to make
But its done
WIN.blit(asset, (rect.x, rect.y))
rect.x += 1
``` i do this in a loop but it leaves a trail? ( pygame ) do I just blit it once and rect.x+=1?
can someone look at the terminal and tell me what's wrong
ball is not defined:(
and this is the full code
import pygame
import sys
import random
def ball_animation():
global ball_speed_x , ball_speed_y
ball.x += ball_speed_x
ball.y += ball_speed_y
if ball.top <= 0 or ball.bottom >= screen_height:
ball_start()
if ball.left <= 0 or ball.right >= screen_width:
ball_start()
if ball.colliderect(player) or ball.colliderect(opponent):
ball_speed_x *= -1
def player_animation():
player.y += player_speed
if player.top <= 0:
player.top = 0
if player.bottom >= screen_height:
player.bottom = screen_height
def opponent_ai():
if opponent.top < ball.y:
opponent.top += opponent_speed
if opponent.bottom > ball.y:
opponent.bottom -= opponent_speed
if opponent.top <= 0:
opponent.top = 0
if opponent.bottom >= screen_height:
opponent.bottom = screen_height
def ball_start():
global ball_speed_x, ball_speed_y
ball.center = (screen_width/2, screen_height/2)
ball_speed_y *= random.choice((1, -1))
ball_speed_x *= random.choice((1, -1))
pygame.init()
clock = pygame.time.Clock()
screen_width = 900
screen_height = 700
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Pong")
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
player_speed -= 7
if event.key == pygame.K_DOWN:
player_speed += 7
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
player_speed += 7
if event.key == pygame.K_DOWN:
player_speed -= 7
ball_animation()
player_animation()
opponent_ai()
screen.fill(bg_color)
pygame.draw.rect(screen, light_grey, player)
pygame.draw.rect(screen, light_grey, opponent)
pygame.draw.ellipse(screen, light_grey, ball)
pygame.draw.aaline(screen, light_grey, (screen_width/2, 0), (screen_width/2, screen_height))
pygame.display.flip()
clock.tick(60)
It's asking you what "ball" is. You never say what it is
there's no variable named "ball" in your code
to make a variable called ball, you'd have to do ball = something right?
where do you do that?
in the code ?
Continued working on the project today. Here are the results 🙂
I am using linear interpolation and the client receives 5 player positions / second, I still need to optimize a lot of things but it's starting to look good
I definitely need client and server in Java 2d engine lol
hello
question how do you make sure that objects dont phase through the turtle border but they will be able to still move
Hmm... I wanna have an seperate file with "high_score", how do i easiy way import it to the main.py when the game loads? ^_^
You should use numpy matrix and then you can use a module called msgpack-numpy to encode and decode
also use UDP thanks
i now have an inventory that displays the names of items
when you hover the mouse over the item
(btw, the names are procedurally generated)
Pickle is by default in Python and meets my requirements for encoding/decoding 🙂 And thanks for the UDP advice ! Will switch soon
I would LOVE to see something like this on HARFANG ❤️
awesome 
🌟 👉 hi guys, if you are into generative AI/generative art, you must try this Python library https://github.com/jina-ai/discoart super easy to use as long as you know a little bit Python and smoothly run with free GPU on Google colab! for example, one can use it to generate pixel item like this
Since its release a few weeks ago Nodezator is dedicated to the public domain, which means it is everyone's now. Feel free to use the source as you see fit. I actually made Nodezator so that it could be integrated into the workflow of any software using Python, specially because the node layouts used on it can be exported as plain Python code. It can also turn any callable into a node automatically, which means you can turn any callable from any project on pypi (hundreds of thousands of projects). If you want to know more, check the manual on https://manual.nodezator.com and for any questions/concerns/constructive criticism/feature requests or simply to follow its development check the discussions page at https://github.com/KennedyRichard/nodezator/discussions
what's the best way to represent tetris shapes in python? a list should be good but would it just be a 4 by 4 where some cells are going to be 1 depending on the shape?
consider using numpy and msgpack-numpy it will speed up everything
Thanks 🙂 I will try it out tomorrow, and I have made a udp server / client today, started to add some linear interpolation and will add more features like lag compensation, prediction when it will be good enough for me
Prediction implemented on server-side for now:
Blue : The last position received by the client from the server
Green : Linearly interpolated client's position
Red : Prediction of the actuel client's position (not yet received by the server)
The main goal was to train myself to do interpolation with network data correctly and it was cool to have all the infos at the same time (so I can implement them in the client side next 🙂 )
import pygame, sys
pygame.init()
clock = pygame.time.Clock()
screen_width = 900
screen_height = 700
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Pong")
ball = pygame.Rect(screen_width/2 - 15, screen_height/2 -15, 30, 30)
player = pygame.Rect(screen_width - 20, screen_height/10, 140)
opponent = pygame.Rect(10, screen_height/2 - 70, 10, 140)
bg_color = pygame.Color("grey12")
light_grey = (200, 200, 200)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill(bg_color)
pygame.draw.rect(screen, light_grey, player)
pygame.draw.rect(screen, light_grey, opponent)
pygame.draw.ellipse(screen, light_grey, ball)
pygame.draw.aaline(screen, light_grey, (screen_width/ 2,0), (screen_width/2, screen_height))
yall python hates me<3
i dont understand this shitn anymore
ok nvm im just dumb i got smth wrong with the equatiom
is pygame used for any serious games or is it just a toy? please ping me when responding.
"serious game" means usually educationnal subgenre, but i guess you meant "nice playable games" and then the answer is yes. Though usually a prototype could be made with pygame and recoded later in a compiled form before distribution without anyone knowing
I ment nice playable games
meant*
have a look to some very nice games here https://dafluffypotato.itch.io , can even run them on web out the box : see one here https://pmp-p.github.io/pygame-wasm/pygame.html?com.dafluffypotato.aeroblaster
right now I am learning python. I want to make a multiplayer web game in the future. What language is best for a high performance web game?
anything that compiles to webassembly
though above web demo is running cpython wasm + pygame so it is still interpreted by python
and it sill runs very well
sometimes cython is all you need to get more performance
what is cython
and how hard is it if you have a python game to turn it into a cython game?
what if you have to be checking collisions between 50 sprites?
i'd use pymunk for that
this is my game so far
now I am going to try to get the player to move based on their width and time
https://quantum-hg.itch.io/alien-dimension
Made this Game in under one week using Pygame and Python!!!
Consider giving feedback once you play!!!
uh hello im young and ive been planning a game for around a year now. I want to actually make it a real game but ive had trouble trying to learn and make. i wouyld rlly love some help. dm me or join the vc if u can help thank you.
actually just dm me pls
Made a game along with 2 wonderful teammates for the PyGame community game jam as well
GitHub - https://github.com/blankRiot96/Daves-Anniversary/
Itch - https://sss-says-snek.itch.io/daves-anniversary
help
what would you guys call a game thats based around spinning?
Twist
Spirograph? hah no not really
import pygame
from pygame.locals import *
import asyncio
from sys import exit
from random import randint
class Game:
def __init__(self):
pygame.init()
self.screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption('My Game')
self.clock = pygame.time.Clock()
@staticmethod
async def loop(event_queue):
while True:
await event_queue.get()
event_queue.put(pygame.event.wait())
event_queue.task_done()
@staticmethod
async def update():
pygame.display.update()
await asyncio.sleep(0.01)
async def events(self, event_queue):
while True:
self.clock.tick(60)
event = await event_queue.get()
if event.type == QUIT:
pygame.exit()
exit()
self.screen.fill((0, 0, 0))
await self.update()
async def main():
game = Game()
event_queue = asyncio.Queue()
task = asyncio.create_task(game.loop(event_queue))
await event_queue.join()
task.cancel()
await asyncio.gather(task, return_exceptions=True)
await game.events(event_queue)
if __name__ == "__main__":
asyncio.run(main())
can someone help me with connecting the events from pygame to the event_queue
why would you want to handle pygame events asynchronously ? the one and only await should be after the pygame.display.update()
anyway if you want to async discard some jobs because you are too late you'd need a priority queue and component event handler / drawing separated ( like in an ECS )
probably there are some capable libraries for that
and no need to asyncio to do that it just adds overhead
a typical asyncio pygame loop should look like that https://pygame-web.github.io/wiki/python-wasm/
no need to pollute all code with async
where was game state defined
game_state is a function pointer
in simple games it should point to current menu or game event handling + drawing
in complex games it should point to a scheduler handling a list of prioritized jobs
is a match statement
good for events
pygame events are numerical so something like a computed goto / dispatch table (with a dict ) is maybe faster than patma
im trying to
use a
api
in the game
it works, but its slow
Hey @rustic valve!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
you are blocking with I/O at 59
await self.get_word() should be a task, and should send a pygame event
so make it a pygame event, on the event, create_task
how do i make an event again
🗿
custom_event = pygame.event.Event( event_number)
here's a example of a green thread (coroutine ) sending events https://github.com/pygame-web/python-wasm-plus/blob/main/support/__EMSCRIPTEN__.overlay/pygame/wasm_patches.py