#game-development
1 messages · Page 29 of 1
and i still cant find the solution
as you can see i made a fuction on Bullets class to make it move but idk what i should do next
https://devdocs.io/pygame/ref/sprite#pygame.sprite.Group
pygame.sprite.Group.sprites() gives you a list of all sprites in the group
then you iterate over them, and call .Move() on each one
you need to know if your bullets should just fly straight or have different patterns
so i accidently broke the sprites fuction because i add that move() fuction
whatever it is that function looks unfinished
you mean that move() function
well I guess it works if they're just supposed to fly upwards
the function is not used anywhere of course
you need to link their movement to time somehow
Maybe try calling the move method
i try that
didnt work
anyway
its doesnt matter anymore
because i change the move() function to update() and it work now
so what should I do to fix it
any ideas how to set the background of a pygame.Wiindow transparent
ive searched the -ce docs cant find anything
its the .opacity attribute
ranges from 0 to 1
it should be easy to figure out. Give the variables you check for in that function the global treatment. There should be better ways than using a ton of globals, but it should work.
that sets the entire thing transparent
as in including stuff u blit on top
yes that's the only way
oh
otherwise you need to grab an image of what's behind your window
will that not be really slow to grab it pretty much every frame
yeah so thats not an option usually
actually i dont know many apps that do the kind of translucency you're talking about
ye I haven't really seen it before
I'll see if it's manageable or use threading or smthn
if not just accept the background staying there
maybe you could do something with set or convert alpha
Hey, y'all. I inherited a code base that uses PyGame to access gamepad input. I'd like a leaner solution, so I've been looking to pyglet, which seems to provide a similar API, but with fewer dependencies (and a smaller binary size). I don't want to directly access the USB driver, since I could not find any HID-ish cross-platform libraries. Any other library I should check out?
hello, I have the basics in python and I want to make a little 2D platform game and why not market it on steam (I mean maybe), where is the limit of python for video games?
I want to do something simple but addictive with retro graphics
something like that
very possible
definitely ur just constrained by the time and effort u put in
look at dafluffypotato's vids and games for really polished results
thank you guys, I'm going to see all that and above all start
though I would be lost if the game just doesn't work for some people
Did unity remove their run time fee ?
You're only limited by yourself. It's up to you 😉
can i load gif using pygame.image
they wont be animated
the closest u can get is extracting each frame and animating it urself
Hello:
New member here. Not sure if I should post here, but I am wondering if anyone's used the esper (
https://github.com/benmoran56/esper
)
or any pyESC libraries and if so, how good are they when it comes to actually handling the entities and such in an efficient manner? By ESC I also mean entity component systems.
I've only found a few and I'm trying to pick the most efficient one for a multiplayer project I'm doing. I did some shoddy benchmarking and so far I'm inclined towards esper, but curious if anyone's had any noteable experiences.
been making a 4x in python using pygame, if anyone is interested in helping with the overall project, lemme know 🙂
4x?
4X (abbreviation of Explore, Expand, Exploit, Exterminate) is a subgenre of strategy-based computer and board games, and includes both turn-based and real-time strategy titles. The gameplay generally involves building an empire. Emphasis is placed upon economic and technological development, as well as a range of military and non-military routes...
Can someone lend a hand with my attempt at context steering with pygame? The code nearly works, except the agent can get stuck when I start adding multiple obstacles, which is not desired or expected...
Here is the pastebin to my code: https://pastebin.com/0DYQnnAy
It creates an agent, and the left and right mouse buttons add obstacles and targets, respectively. There is a threshold distance for obstacles to affect the agent, but not targets.
Additionally, here is a link to a short paper on the steering method I'm trying to apply: http://www.gameaipro.com/GameAIPro2/GameAIPro2_Chapter18_Context_Steering_Behavior-Driven_Steering_at_the_Macro_Scale.pdf
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
That's a cool article, I'll have to give it good read. Have you checked out any of Craig Reynolds original steering behavior papers too? https://www.red3d.com/cwr/steer/gdc99/
I don't understand context steering though I have played with some of those steering behaviors
I haven’t, but thank you for the share.
I like that you're doing the elementwise vector stuff, just to mention pygame.Vector2 class has many vector math methods that can make some of that a little easier
And thank you for the share as well, gives me terms and more info for steering behaviors to build upon
Also, if you can parse the logic in Java or JS, The Coding Train on youtube has a nice playlist (and his whiteboard explanations) for much of Reynolds' paper
So you guys you Pygame?
I do.
i can make hangman dm if u need any help
Is there a demo yet?
my movement is kind of janky can anyone please tell me why? ```import pygame
pygame.init()
screen = pygame.display.set_mode([800,600])
class PLAYER():
def init(self):
self.surf = pygame.Surface((30,30))
self.rect = self.surf.get_rect()
self.surf.fill("red")
self.y = 300
self.x = 400
def update(self,keys_pressed):
if keys_pressed[pygame.K_w]:
self.y-=5
if keys_pressed[pygame.K_s]:
self.y+=5
if keys_pressed[pygame.K_a]:
self.x-=5
if keys_pressed[pygame.K_d]:
self.x+=5
player = PLAYER()
clock = pygame.time.Clock()
run = True
while run == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.K_DOWN:
if event.key == pygame.K_ESCAPE:
run = False
screen.fill("green")
keys_pressed = pygame.key.get_pressed()
player.update(keys_pressed)
screen.blit(player.surf,(player.x,player.y))
pygame.display.flip()
clock.tick(30)```
what do u mean by janky?
BTW if u have a rect there's no point in storing and x and y value
u can use screen.blit(player.surf, player.rect)
and modify it in ur update method with
self.rect.x += 5
self.rect.y -= 5
etc
perhaps increase the FPS since its at 30
generally 60 gives "smooth" gameplay, ive seen 45-50 work as well but its less convential
if u want like REALLY smooth movement you would need smthn like
when i press w for example the square will move stop for a second and carry on moving
thanks i didnt know this
vec = pygame.math.Vector2
FRICTION = 0.9
class PLAYER():
def __init__(self):
self.surf = pygame.Surface((30,30))
self.surf.fill("red")
self.rect = self.surf.get_rect()
self.vel = vec()
self.acc = vec()
def move(self, keys_pressed):
self.acc = vec()
if keys_pressed[pygame.K_w]:
self.acc.y = -5
if keys_pressed[pygame.K_s]:
self.y = 5
if keys_pressed[pygame.K_a]:
self.x = -5
if keys_pressed[pygame.K_d]:
self.x = 5
self.vel += self.acc
self.vel *= FRICTION
self.rect.topleft += self.vel
#the above three lines are a faster way of doing
# self.vel.x += self.acc.x
# self.vel.x *= FRICTION
# self.vel.y += self.acc.y
# self.vel.y *= FRICTION
#
# self.rect.x += self.vel.x
# self.rect.y += self.vel.y
def update(self,keys_pressed):
self.move(keys_pressed)
hm that shouldnt happen lemme run ur code
oh i see the problem
careful of ur identation
run = True
while run == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.K_DOWN:
if event.key == pygame.K_ESCAPE:
run = False
screen.fill("green")
keys_pressed = pygame.key.get_pressed()
player.update(keys_pressed)
screen.blit(player.surf,(player.x,player.y))
pygame.display.flip()
clock.tick(30)
is ur code
run = True
while run == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.K_DOWN:
if event.key == pygame.K_ESCAPE:
run = False
screen.fill("green")
keys_pressed = pygame.key.get_pressed()
player.update(keys_pressed)
screen.blit(player.surf,(player.x,player.y))
pygame.display.flip()
clock.tick(30)
ye
i was so confused
yeah
Would usually normalize player movement so it moves at a constant speed even at angles
oh good point
in the code I sent yesterday that would just be
self.vel += self.acc.normalize() * some_constant
I don't remember specifically but u might need to check if the magnitude of self.acc is greater than 0 aswell or it might give a zero division error
Is a terminal-based Virtual Table Top something anyone would want and/or use?
Like I'll have fun programming it regardless, it's just one of those things you have to ask
Hey all,
Thought I would drop by and remind them that UPBGE exists (fork of blender for game dev) and it has a robust py api.
New blender patches include multipass composition nodes system working (in game soon too!)
'Fast' Blue Noise (faster to converge on noisy renders)
Much Much more!
(soon Vulkan!)
UPBGE is free and open source
nice
guys i know this is kinda nooby but is there any possible reason that im getting this error?
TypeError: argument 1 must be pygame.surface.Surface, not str
happens whenever i update the screen or at least im attempting to do that
is making another variable that loads a surface illegal?
well for this code
r u sure u wanted to scale up Framer1
not Face
hold on lemme give that a try
oh god
ofcourse its a simple mistak
ye it happens
sorry im new to pygame so i couldnt see such a basic
ugh
ive been working on this for hours
no no dont worry about it u just tunnel visioned
thanks
no wonder it was complaining about a string , ill leave comments explaining this for future me in my code base
thanks for your help
You could assign those surfaces to variables and use those instead instead of loading the images every time you draw them
I made snake!
Its playable in its current state .
Does anyone here know renpy?
DDLC was later rewritten in Unity :p
(for letting people do file-editing tricks on platforms this is hard on, mainly)
o ok
smart but wouldnt be efficient for looping animations. lists of paths to images might be better
how?
surely it's less efficient to keep loading the same image over and o er again
rather than "caching" them once and reusing
It's always more efficient to load images outside of the game's main loop
Loading during draw is the worst time
i suppose if you were doing a game that would be the case
i am sorta doing a game
but not exactyl
its more of using pygame to load images and visuals and sounds since its much easier to do that then use a bunch of seperate libraries to achieve the same thi g
thing*
also i gotta ask
why does adding the .convert to the image load
screw up having 2 images at a time
this happens
INSTEAD
of this
eg the mouth is supposed to be animated ontop of the actual face
prolly need convert_alpha()
THANKS DAMN tho i gotta admit they really shouldve added that in the docuementation nexts to convert
its basic stuff like this
that gets me sooo
this guys basically a virtual pet
so thats what i mean by not technically a game
but still within the audio , visuals and interactivity
All methods pygame.Surface are shown here, including .convert() and .convert_alpha()
Can I get some feedback on a rudimentary game I made using John Zelle's graphics.py module? https://github.com/cosmicmatter98/boundary-dash
Calling it a game is a big stretch, still thought about sharing and getting some feedback and ideas for enhancements and improvements on this.
Main purpose was to get to use the different functions of the module. Even though I haven't used the Image class, but I am planning to use it for the background and the player thing.
i cant really install the module, but from the code alone
perhaps create some obstacles or walls
Updated Readme: the command to install the module would be pip install graphics.py instead of just graphics. It should work then.
kind of like... a maze?
i mean if u make it like that sure
just thought it might an interesting thing to think about how u would detect collisions with multiple objects
not just the boundary
I have a bug in my raycasting demo that I have no idea how to fix. I'll demonstrate in the video.
You can see that when I stand away from the walls and move closer to them, the walls move up and down in an oscillating wave. The wave is more and less obvious from different vectors of movement but its always there.
If I turn off drawing the textures and go back to drawing solid rectangles, you can't see it anymore. I dont know if this is because it still happening on the solid color and I just cant see it as clearly or what
I know this is a python server but this demo is in Typescript with no other libraries rendering on canvas. You can look at it yourself if you want to https://github.com/divSelector/raycast/
Even just an explanation for why this happens from someone who knows game dev very well would be potentially useful
i mean one slight difference i can see is ur flooring the y values in ur texture one
is that meant to be like that
yeah that is definitely what caused it, I felt really stupid when that was found.
yes, that's something I gotta think about. thanks for the idea.
That's really cool, makes me wanna design some Doom levels and enemies
can someone help me, ive been struggling to make this 2d game for hours lol, can someone fix the code for me
i js found this discord cuz i needed help
yeah Classic Doom is way more advanced than this but still the same idea behind faking 3D from 2D. Doom is next evolution of that idea.
John Carmack was always one of my heroes. He used to do a blog, not sure if he still does, he'd gotten into amateur rocketry too and his blogs were pretty good, sometimes really deep
Carmack, one of the founders of ID and creators of Doom
The other founder was Adrian Carmack, seems quite a coincidence the two are not related
I'm literally watching High Score episode 6 on Netflix right now (cool documentary series) which is all about that and its really amazing what they did at the time with the hardware 🤯. I remember playing doom and wolfenstein 3d when I was younger and being blown away and also scared out of my mind lol, but at the time didn't think about how involved it was to pull that off
Like someone would have done it eventually but ID were the pioneers, everything that followed was in at least some small way based on what they started
I still have, in fact, a bunch of Doom levels and shit burned on DVDs and collecting dust in a closet somewhere
Though I don't even have an optical reader these days
how do i detect when a key is currently pressed
Tkinter doesn't work cause it reports KeyPress and KeyRelease in the same frame when i first press the key
and trying to use keyboard.is_pressed('w') gives me and error
this is the error
https://paste.pythondiscord.com/AJIQ
Does anyone know how to decrypt source codes inside dlls from game mods?
I need one from a mod called Custom Shaders Patch for a game called Assetto Corsa so that I can take a portion of it related to KN5 decryption (compressed format used to store FBX model, textures folder and a ini materials file for the game)
I think language is C and not Python
y would u ask the python discord then 🙏
this gives me this 👆 (as shown in video) and it the blank screen stays their forever why??
I would check the values of things like game.start_game and game.died and make sure none of them are things that you dont expect. Find out where the execution is going with a debugger or using print() statements
here is my thing btw
i need to get a better screen recorder but yeah
with?
prolly ask #discord-bots
i would assume u dont have the uh
def setup(bot):
bot.add_cog(Music(bot))```
at the bottom of ur file
is that raycasting in pygame?
its raycasting in typescript on 2d canvas context
there was a pretty bad frame drop when i tried to add floor and ceiling raycast, because you cant do it in the same raycast. But I think I also might have been doing it wrong and I want to try it again before i give up.
I love python and its definitely my preferred language for backend or command line tools, but... i feel like its so much easier to share a simple game you can deploy to the web.
So id just rather do it that way
wow
uhh
do u have the package installed
do pip list
see if its there
i havent used discord_slash before so idk
how do i detect when a key is currently pressed
Tkinter doesn't work cause it reports KeyPress and KeyRelease in the same frame when i first press the key
and trying to use keyboard.is_pressed('w') gives me an error
this is the error
https://paste.pythondiscord.com/AJIQ
you should use something other than this keyboard module. The github says that its unmaintained and wanting you to give it admin priv is ridiculous.
Maybe try this instead https://pynput.readthedocs.io/en/latest/
enemy = Enemy(randint(0, width), 0) # random x position and at the top of the screen
enemies_grup.add(enemy)```
You might want that on a timer or something so it happens automatically when running the game, but that's the basic idea
Alr thanks
And it looks to me that your coordinates are backwards on your update() methods py def update(self): self.rect.y += 10 if self.rect.top < 0: self.kill() this is moving the rect down yet you're checking if it's above the screen?
You can print the len of your groups to see how many are in them, surely they never die like this
uhh
idk combo meter?
like if u get the right card multiple times there's some point multiplier
i will, thank you
funny i was thinking about this exact term earlier today
r u making that in ur jam
Slot machine is a fun idea, never thought about it before
what on earth does this mean
This process is not trusted! Input event monitoring will not be possible until it is added to accessibility clients.
wait no i found it
fuck
fixed it
dear lord that was today
time is slow
hello I am making a render engine for my VFX & 3D software project but the output of engine is total black.
this is the code : https://paste.pythondiscord.com/W6KQ
can some one help me ?
I'm making a slot style game:
https://paste.pythondiscord.com/XIDQ
If you dont understand anything ping me!
I want to run some ideas for it by anyone.
So i was thinking about changing the King queen Jack combo to the 4 suits.
Then with King i was thinking about adding a chess thing where the king gives you points if it has another chess piece near it and maybe more depending on what piece.
I can't run it rn but just looking from the code
should the red and green colours be [1, 0, 0] rather than [255, 0, 0]
oh u multiply it by 255
is it off screen qt all
maybe print the object locations
no there is no problem in locations and colors
Anyone i can bounce an idea off of?
sure
sorry cant figure it out maybe someone else can help
uh just a code thing, i would advise using .lower() and ig .strip() on ur inputs
for example it doesnt accept dice instead of Dice
Just incase they put something goofy?
What does .strip() strip
no its more the case of capitalisation or putting extra spaces at the end by default
removes whitespaces
like extra spaces or tabs
ye
Right so i was thimking of changing the king queen jack combo
To a 4 suite
So that i can add a chess combo
the "royalty combo" right
Yeah
right ye
So instead i was thinking of changing it to 4 suits( in playing cards) spades hearts clubs and diamonds
sounds fine ye
So i could add a new chess mechanic
Where the king loses you points unless its next to a chess piece
To “protect” it
Then it gives u more points depending on the piece value in chees
So queen gives more than a pawn
You following?
Im on that now
o ok
Which do u think would be better:
1)Rarity system where your less likely to get queen than pawn but are cards obtainable normally.
2)normal obtain system for pawn and when pawn is in top row of grid (like in chess) it will permanently transform(promote) into a better piece(using a weighted random towards the bishop/knight)
Or if u have ur own proposition idm
i mean the second one makes more sense
But does it sound good or crap?
Well ill add it today or tomorrow. I can show u the game after and see what u think then if u want
alr just send it here ill prolly see
is it python ? this one is https://finfetchannel.itch.io/time-of-the-machine
Typescript.
Maybe I should look at other hobby raycaster games for inspiration
!pastebin
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
https://paste.pythondiscord.com/IVHQ
Added changes
Works perfect i think
Gonna add more comments and improve users experience now ig
Should i break down the points calc function into separate ones for each?
This game is turning into such headache. It was fun when it was just a graphics rendering demo but now that its becoming a game its just like fuuuuu
maybe i just need a break from it
@pine smelt
ye it would feel more structured
try working on another side project that usually helps
yeah sometimes but in this case i feel like im either gonna do something with this project or i never will.
it's not that i dont want to work on it. Its that there is some pretty big problems to solve before I can get back to doing fun stuff.
Alr and then add it those small functions to the big one
hi
cn anyone answer the question i asked on the bottom lines of the code im js kinda curious
what acc is keys
i dont see it defined anywhere
or keyboard for that matter
i actually have no idea either but it somehow still works fine for me but i think its the keyboard i use i believe idrk
im using a code editor from my python class and without adding the variable of key nor keyboard i think that you mentioned it still runs fine
but i dont think it matters on which code editor you use
I'm guessing it's setup in such a way that it imports pgzero
https://pygame-zero.readthedocs.io/en/stable/builtins.html#the-keyboard
And keyboard and other stuff is already predefined for you
oh
so some code editors can predefine those variables and i dont need to add them myself?
can someone help me with this code I am making a render engine for my VFX and 3D program named HydrogenFX and need help for developing This is the code: https://paste.pythondiscord.com/BDHA
I don't think it's about the code editor specifically
If you put import pgzero or whatever the name of the library is at the top of the file, and you have the library installed, your python program will be able to use variables/functions/etc. from the library
Your class probably set it up in such a way that you don't have to worry about it
oh alright thanks
didnt answer my main question but still thanks i probably couldnt really explain my main question kind of well anyways
can someone help ?
could anyone help me? so ive been working on a project checkers with help of youtube but now i wanna make that game online so like i can play with a friend but i have no clue how sockets etc work
whats the problem tho
there might be some information in the pinned messages of #networks
this prolly
alright thanks man!
there is no problem I want help to develop this,
!pastebin
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
python discord needs to pull the updates from upsteam pinnwand so that it will get my update 🙂
How long lineswise are like proper games. Eg a 2d platformer???
Depends on what you consider a "proper game", but realistically a few thousand lines for a simple 2d platformer? This advanced-ish arcade example is 500 lines: https://github.com/pythonarcade/arcade/blob/development/arcade/examples/platform_tutorial/20_views.py
Nice. I got a question
Any tips for making neat cose
Cose
Code
Thats basically how mine looks rn
@proper peak
its generally just about using plenty of white spaces
and empty lines to section off parts of ur code
also consistent identation
i edited urs
u can prolly do more
- Either do-
from random import choice, randint
And use the methods choice and randint everywhere in your code
Or
import random
and use random.choice & random.randint in your code.
Instead of -
import random
from random import randint
And using random.choice and randint in your code. This makes your code more uniform. Although I would prefer the latter method as it explicitly mentions from where you're calling those methods from and increases readability.
-
I'd personally split up the code into multiple files like constants.py, funcs.py (having all the game functions) and main.py which runs the code all together. You can split it in however way you want / feel comfortable or not do it at all.
-
Use a specific casing style. Some of your functions are pascal + snake casing while others are in pascal..? Any casing is fine but stick to one casing throughout your code.
In python people usually follow snake casing for vars and function/methods and pascal casing for classes. -
Use a formatter like black to fix up inconsistent spaces and makes your code more readable
-
Unnecessary comments, almost 90% of them are unnecessary. And the places where you use comments to describe what a function does, replace that with docstrings instead.
-
NEVER use try except without explicitly mentioning the exception type. This can suppress important errors for you to debug leading to unexpected results and makes your code less readable.
-
Type hinting, this isn't nessescary I think? But it hugely helps with code readability.
I really try to do 4 but its so buggy on android
You use android for coding? 💀
For now i plan on getting a pc soon xd
Pydroid I think
That was back when I first started to code like 4 or 5 years ago
Ever since I started coding on pc I never went back
Yeah obviously i use pydroid as wl
Also you can lmk if you wanna know anything in detail
I kinda just gave an overview
Alr i havent wven looked at it yet xd. Been running through otherguys 1st
Ye icl i havw no clue half this xd
2) idk how to link files together and havent done anything like that
3) whats pascal casing?
4) dont know what a formatter is
5) whats a docstring
6) fair enough
7) also dont know
@slow copper 🤣
Sorry
You use spaces at the end of loops. In-between topic changes in the code etc?
I code at school on pc as well but i forgot how much harder pydroid makes it to read
Linking files is easy, fir example if you have-
funcs.py
def hi():
print("hi")
def bye():
print("bye")
And in main.py
from funcs import hi, bye
hi()
bye()
# or
import funcs
funcs.hi()
funcs.bye()
Is #line for bigger sections of code like variable declaring creating ui. And then actual gameplay
Is that like what 90% of ppl do or just a preference.
Pascal casing is capitalization of the first letter of each word in a variable or function name. Example: MyName, YourName
And snake casing is everything should be of lower case and we use underscore to split between words
my_name, your_name etc
Well it organizes your code by a lot and I can't really bring out any percentage here but as your code gets bigger, having everything in a single file gets really hard to manage so that's why we split code to different files
thats how i use it
i dont really see many other ppl use lines of hashtags
but it helps me seperate it so
realistically its a definite majority
Oh ye
especially with larger projects
Yeah
So you would already split my project into smaller chunks? Sort of where sh put the ###s
Pretty much yeah actually lmao
example from my current project
i use both the hashtag lines and the importing thing
and clearly seperating sections of code
And formatters are basically tools to organize your code by fixing uneven spaces, wrapping long lines into multiple shorter lines etc without actually changing the functionality of your code. One of the formatters I use is black you can pip install it and in your terminal do black "path of file" to format it
do u just do that at the end of a project
Do u have different files for this project or allcin 1
bro theres so many
imagine all of that code in every single file combined into 1
it would become a mess really quickly
hence y its advised to split ur code into multiple modules and importing them
😭this seems like the part where im gonna hate
I just do it when I'm bored or when I'm done doing a section of my code lol
If you wanna get better at python you'll have to learn, it may take time to get used to but it's definitely worth it
And I'm not sure if this will work on pydroid though
i finally made pygame can use IME now.....
with a bad way....
This is my biggest project so far so im learning quite a lot as theres lots of problems ive not come across
i use ctypes to call win api, and bound a text box to the pygame window....
Yeah just keep practicing and pick up new projects and you'll learn eventually
Woah
so it will have a right click menu.
Cool stuff
thank you.
Thats why i started a bigger project cos i can constantly add new bits
but i dont know how to use winapi to draw the image directly. so i have to use a slow way....
does anyone knows how to do so?
or better, knows how do make the text box without a background?
Does that ever break / ruin ur code a bit
Damn
I'm still learning pygame so can't help much
It doesn't break or change the functionality of your code
It just formats it
And it has been pretty helpful ngl
Especially when I have a long nested one liner stuff
Like generators / comprehension
I'm going to go sleep now
So bye
👴🏿👋🏿
Cya
i am making a game
Nice
Whats num 7 anyone?
Btw do you have 1 file that just nicks stuff from all other files and puts it together. Like just functions in there
its when u dictate what the variable's type is
but it doesnt do anything, its just a visual prompt and for ur interpretor to know syntax wise what it should tell u i THINK
example
Right
text: str = "obama"
number: int = 5123
fruits: list[str] = ["apple", "banana"]
Hold up so how do u end up like running your game? Is it mostly stuff nickdd from other files and then some èxtra stuff
yuh
Ohr i get ye
Ahh thats what id do
this the top of my main.py
tho most of its
acc thats a bad example
cuz i only really import those for caching, a game dev thing
bruh no one cares as long as its readable
its not some law u'll get arrested for if u break the syntax slightly
Btw whats that code in like what app cos mine looks different at school xd
😭feels like it
vs code
maybe u use repl?
honestly dont worry about it its more advice than strict rules
not saying u should write ur code in a complete mess but it helps for structure and clarity
Yep ill copy some across iab to different files
Idk. Its called "python idle 3" so no clue
Only good for 1 file im pretty sure
ohh
thats the interpretor that comes with python by standard
it wont have too many addons
u can still use multiple files tho
just create them in the same directory and import them in ur main file
I mean u cant have them in the same like tab if ygm
oh right ye
The one you gkt cost extra?
nah all of them are free
uhh
integrated access to github
syntax highlighting
code suggestions
error highlighting
all files in the same window
multiple languages
those r the ones i use anyway
As in not just python ?
ye
So its just QOL and makes life easier
yup
Right ill save vs code incase i use it
alr
Anyone looking to join ongoing projects? Been working on a Python based 4X strategy game for 2 months now. We have 5 active people on the team but would love some more help and minds! You can dm me if interested 🙂
Requirements
- know Python to an extent
- Have the ability to have fun and be creative.
- be 18+
Whats a 4X?
Btw incase you didnt gather im way too inexperienced xd
Have you played Civ or age of empires?
No is it like a troop battle game?
Like a city building empire building game
Ok thx
Do you have Python experience?
Very little. Best thing I’ve coded is like a battleships game
Did you use pygame or a similar library?
Nope it was fully terminal. I have 0 experience with pygame
Ah ok well if you fit the requirements and are interested let me know!
Ah im still at school xd
Still in school is ok, just gotta be 18+
Yeah im not though
Lemme know how the game goes
Gotcha for sure!
out of interest is there a reason it has to be 18+
is it to do with the game content
Maturity and tbh, too many bad experiences I mean if you are mature I can overlook that lol
oh okay fair enough
Just to add what sh said, you can even use it to hint whats the type of the parameters of a function/method, which is where its mostly used.
def add(a: int, b: int) -> int:
return a + b
Over here we have type hinted a and b as int type.
If you pass in a string or any type other than int your code editor will raise a warning that it isn't of int type. Even though the code will run with whatever parameters you supply, type hinting is just used for convince.
The -> int you see is the return type of the function, as return a + b returns an integer. If we don't return anything from a function we use None instead, for example-
def add(a: int, b: int) -> None:
print(a + b)
And type hints also allow you for code completion in editors
sadly, cpython cannot use that information to run faster.
it can only make it runs slower.....
Damn
That's sad
I assume it just takes time to annotate the object and completely ignore it
iirc, if you use list[int], it has to run to create a list[int] object when you run the progarm.
>>> class mylist:
... def __getitem__(s,i):
... print('runned')
... return i
...
...
>>> mylist=mylist()
>>> def f(x:mylist[int]):
... pass
...
runned
so when creating the funtion f, it runs list s __getitem__ or __class_getitem__ stuffs....
I see
Ahk
space game in progress
Nicee
I think the controls would be better if you could control the spaceship's rotation with the mouse and the movements with the keyboard
help me on pygame guys
honestly this isnt too pygame related but i cand find a more general text area but since i feel so dumb
im calling a function
it has an arguement
HOWEVER
for some damn reason
it doesnt work
it says im not parsing any data to it
def transition(Target_Emotion):
and calling it via the transition(Target_Emotion)
it feels so wierd but whener i ask it to return target_emotion it just gives me blanks
honestly if this is something scope dependant or something i might just
do what i did before and make it a file that stores data
Can you share more of your code? Also you can make a thread in https://discord.com/channels/267624335836053506/1035199133436354600 if it isn't gamedev related
oh thank you i couldnt see that channel amongst all the text
i might try that if i fail to get it working the file way
Hello, I'm currently working on a small 2d game with the Turtle library. I am attempting to update the window (a TurtleScreen object) from within a thread. I know that Turtle does not support threading, so I have used a global variable to attempt to cause an update. Here is the code for checking the update, which is within the main game loop of the program.
with lock:
if update == True and game_started == True:
money_counter(win_right=win_right, win_top=win_top,
money_count=money, money_cap=money_cap
)
Here is the code run by the threads.
def add_auto_money() -> None:
"""
Adds money per autoclicker.
"""
global money, update
if autoclicker_on_off == False:
ic()
while True:
for _ in range(autoclicker_counter):
time.sleep(15 - autoclicker_speed)
money += autoclicker_income
if money >= money_cap:
money = money_cap
if autoclicker_on_off == True:
ic()
while True:
if autoclicker_counter != 0:
update = False
time.sleep(15 - autoclicker_speed)
money += autoclicker_income
with lock:
if money >= money_cap:
money = money_cap
update = True
the variables money & update are the amount of currency the player has, and the global variable i have attempted to use to check for a screen update respectively
autoclicker_on_off variable is whether or not the player wants to have their currency update everytime the autoclicker adds to it (true for updating everytime currency is added to)
ic() is my debugger
autoclicker_income is how much to add to the money variable by
money_cap is the maximum money avaible to be stored
game_started variable is a boolean of whether i am running the "menu screen" or the "game screen"
money_counter function displays the money count to the screen
win_right and win_top variables are the right of the window and the top of the window respectively
lock is a threading.Lock object
so now that my schools out and im out of my computer science class where do i go now i didnt learn anything about game development i just know basics on how to use python i would still use pycharm yes?
pygame-ce
Is a python library for making games
ok thankyou 🙂
And yes you can still use pycharm
Yo what are classes ive seen so many ppl use them
!class
Classes are used to create objects that have specific behavior.
Every object in Python has a class, including lists, dictionaries and even numbers. Using a class to group code and data like this is the foundation of Object Oriented Programming. Classes allow you to expose a simple, consistent interface while hiding the more complicated details. This simplifies the rest of your program and makes it easier to separately maintain and debug each component.
Here is an example class:
class Foo:
def __init__(self, somedata):
self.my_attrib = somedata
def show(self):
print(self.my_attrib)
To use a class, you need to instantiate it. The following creates a new object named bar, with Foo as its class.
bar = Foo('data')
bar.show()
We can access any of Foo's methods via bar.my_method(), and access any of bars data via bar.my_attribute.
What does this help with on peoples games??
Organizing code into their own classes is a lot easier to maintain
Especially things like pygame sprites. Imagine needing a few enemies moving around the screen, maybe chasing the player. To do this without classes means a bunch of variables and lists and code to handle each of those enemies. If they're all objects that handle their own behaviors, you just add more objects and update/draw them
Ig i just dont really get how they work
yeah classes are a whole topic, it takes time to learn
Should i need to worry cos rn im only doing terminal?
what do you mean only doing terminal?
No.
Stay in the terminal for a while until you learn more Python, unless you are bored (and need visuals to get excited about coding / motivation).
Oh i wanted to make it 2 player but then was like nah ai will be easier. So im making a boss that has abilities and you have to kill it. Im gonna work on making it 2 player soon. If i do make it 2 player(on 1 device) will i need to change a lot to make it 2 player across 2 devices using networking?(which i havent even started learning)
K
Is this basically saying from the class Person run the function say_hi .
Dkes that mean it wouldnt work if you just put say_hi()
The function in that context is defined inside the class. Thus, python would throw an error as the function is a method (a function declared inside an object), not in the global scope.
Would this be a good place to use a class?
Line 68
I've been trying to learn classes and would it be good to create a class for the moves on line 68 with their cooldowns instead of just inputting and outputting a ton of variables
https://paste.pythondiscord.com/DETQ
anyone answer. I need to know if im right or completely wrong
are those the player's attacks or boss's attacks
i would organise it like
Boss
class Boss:
def __init__(self):
self.hp = 100
def attack1(self, player):
player.hp -= 5
def attack2(self, player):
player.hp -= 8
...
smthn like that
oh have the player in its own class too
Ima mess around in like an hour or 2 and test stuff out
👍
Hi! I am making a card game in pygame and I am struggling with the design of my game, I introduce restrictions and rules early on for no reason at all except to satisfy my autistic need of order in everything. I just need an advice with direction I am going (what to pay attention to, what rules to relax) with and the code design. So far I am just drawing surfaces and I implemented simple on click event for button type surfaces. I got 270 lines long script, if anyone's willing to look I'll share it. The main thing I am concerned with is --if I continue with my code design what kind of problems will I face, again, I introduced too many rules.
send the code we have no reference to the "rules" ur talking about
do the characters only become black if u comment tint_screen?
I pasted it here becuse discord does not allow it: https://pastebin.com/jmkSigkT
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Surfaces have to be encapsulated by classes with Element inteface.
Surfaces have to be drawn at least once, through draw method.
Rendering has to be done through render method that is being passed the env (state)
I haven't touched on other concepts on pygame yet, I am learning pygame as I go. Right now I struggle with with positioning surfaces but it has to be done in a way that the size of the window does not matter
And right now I am thinking of how to attach event handlers to Surfaces for pygame and custom events without burdening subclasess. It has to have some order but flexible enoug. and events have to be handld similar to render method in Shisen class
yes. the game loads the characters and player visible pixels to be black.
and apologise for double posting the question; it was locked in #1035199133436354600 so i followed the instructions and put it here.
anyway, very mysterious but I am hopefull someone can identify the problem. claude, chatgpt and myself are all stumped >.<!
are u able to record what u mean at all
i temporarily rewrote the transition_check and tint_screen methods to this, since i didnt know what "transition_sprites" were:
# transition system
def transition_check(self):
sprites = [sprite for sprite in self.transition_sprites if sprite.rect.colliderect(self.player.hitbox)]
if sprites or pygame.key.get_pressed()[pygame.K_SPACE]:
# self.player.block()
# self.transition_target = sprites[0].target
self.tint_mode = 'tint'
else:
self.tint_mode = 'no tint'
def tint_screen(self, dt):
if self.tint_mode == 'tint':
self.tint_progress += self.tint_speed * dt
elif self.tint_mode == "no tint":
self.tint_progress -= self.tint_speed * dt
self.tint_surf.set_alpha(self.tint_progress)
self.display_surface.blit(self.tint_surf, (0,0))
seemed fine to me player sprite wise, idk if its a problem with the player.block()
for the size thing, look into the "pygame.SCALED" display flag in the docs
If i wanna make my game 2 player can i just shove it all into a class and then each person can have their own score deck variable etc within the class and it saves copying out the code again. Or is there anyother way that might be better
https://paste.pythondiscord.com/DETQ
Think thats the game
Yeah that's one of the main purposes of classes
Allows you to reuse and structure various functionalities concisely
Now ive gotta find all the places where i usrd the variables and put self. In front of them 😭
Btw I made a small post about classes https://discord.com/channels/267624335836053506/1235883588206202942 it might help you
Can anyone recommend a game engine for python?
For 2D games I recommend pygame-ce
Though it's not really an engine, its a library
The only GUI engine I know for making games with python is using godot with the python plugin but its unmaintained afaik
There is a game engine for python (non gui based) called ursina
You can check that out
Thank you
Depends on which type of game you're looking for, but I'd recommend Ursina or Panda3D (or both at the same time) to make a 3d game even tho you can also make 2d games.
hi there.
my program works diffenently after using nuitka.....
left is the one after nuitka. and the right is the one before nuitka....
https://paste.pythondiscord.com/7TFQ
Whys the SlotGrid Variable the same for both player 1 and player2 when i print it. Im new to classes.
Is it something to do with the print grid function not inside the class?
I can guide you round my code if you need to find atuff
list.copy() is a shallow copy, that it, it is a new list, but the contents are references to the same objects, and since you have a list of mutable objects (other lists) - you can see the problem: changing those "inner lists" changes them for both players, because they're the same lists (literally, those are just different references to the same lists in memory).
if you want a new list, and for everything in it to also be copied - you want a "deep" copy which you can get with copy.deepcopy(list), or just.. write a function that makes the grid
!e
xs = [
[]
]
ys = xs.copy() # ys is a new list, but ys[0] is identical to xs[0]
ys[0].append(0)
print(xs)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
[[0]]
!e
from copy import deepcopy
xs = [
[]
]
ys = deepcopy(xs) # slow, but copies everything (recursively)
ys[0].append(0)
print(xs)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
[[]]
!e
def f(): return [[]] # simple & fast
xs = f()
ys = f()
ys[0].append(0)
print(xs)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
[[]]
Ohr thanks
An alternative would be to input the list in itself and not as a variable
Why doesnt it affect the deck list as well
because strings are immutable. it doesnt matter if its a shallow or deep copy in that case, you cant change the strings.
xs = ["x"]
ys = xs.copy() # new list, the string is the same one, but, we cant change it anyways, so no bamboozle like with appending in the above examples can happen
its not a good idea anyways - more like a band-aid fix. just make a function that returns a new grid each time
^did you import it?
Ohhhh
But yeah a function makes more sense
Could i not just input py [[],[] etc
well, you could copy-paste that expression each time you need it, but why not give it a name? and since you want to re-evaluate it each time, make that a function
My game is now 2 player(on the same device)
Can someone have a look and lmk what they think
@pine smelt
lookin good
one small thing is prolly just readability but its definitelly better than the last code i saw
like example
for this:
Player1 = Player([Ace],50,[
['□','□','□',],
['□','□','□',],
['□','□','□',] ], input("Player 1, what is your name?"))
i would write it as
Player1 = Player(
[Ace],
50,
[
['□','□','□',],
['□','□','□',],
['□','□','□',]
],
input("Player 1, what is your name?")
) ```
idk how others would do it but thats what seems the most clear to me
also for function names,
keep the same naming convention like pascal case and stuff the other guy talked about last time
not having different ones like CardChoice(self) and Print_Slots(self)
Oh ye i forgot to change print slots
Is it fine if for future projects i want to use snake case and pascals mixed if ygm
Yeah smart tbf
u mean, Pascal_Snake_Case?
Yes
entirely fine as long as u stick with it
theres tons
my favourite sounding name is prolly kebab case or screaming snake case
But most_common_is_snake?
ye
Whattttt😂
Show me
Hypens not supported?
well think about what a hyphen does in python
Ahh subtract
ye
Very sad
Im pretty sure this is ambitious but imma try get my game to be 2 player over 2 devices
Is it networking i need to learn?
i need help downloading python modules. I am trying to download pygame, and some data stuff like tensorflow and when i try to download them they never work. I tried homebrew, I downloaded python through the website and the terminal. whille trying to download pygame It said pip needs to update and gave me a command for it and when i copy and pasted the command it still wont update
you dont need the latest pip to download modules
any moderngl book recommendations?
hey so i try your tips and it didnt work
the vcs say "randint" is not defined
for loop i suppose
for i in range(number):
enemy = Enemy(randint(0, width), 0) # random x position and at the top of the screen
enemies_grup.add(enemy)```
print('Choose your class')
print('Assasin,Archer,Herbalist,Cleric,Wizard,')
character = input(" ")
if character != 'Assasin' + 'Archer' + 'Herbalist' + 'Cleric' + 'Wizard':
print('wrong')
if character == 'Assasin' + 'Archer' + 'Herbalist' + 'Cleric' + 'Wizard':
print('mmmm I see, you have chosen '+ character)
print('A fine choice,I hope...... that you do not come to regret this ')
import turtle
it keeps printin wrong after character selection
Using + means your strings get added together, so you end up with 'AssasinArcherHerbalist' etc.
Your input is never equal to that, so your if statement always evaluates to True and will always print 'wrong'
You probably want something like:
if character not in ['Assasin', 'Archer', 'Herbalist]:
print('wrong')
This is called a list, it allows you to store multiple values
And the in keyword checks if a value is somewhere in that list or not
tysm
Would discussion of a ttrpg character manager go here as well? Trying to put together a Cyber:RED one as an exercise/something to chew on to produce serotonin
tabletop roleplaying game, and cyberpunk: red
A little refactor for the fun of it, tic tac toe in terminal again https://paste.pythondiscord.com/UN7A
Fellow ttrpger spotted.
Good luck with the char sheet, there's some examples out there, mostly web apps.
Hello. I made a pygame. Who wants to play it? or is this the wrong channel?
if you want more people to play your game maybe put a pygame-web version on itch and drop the url here
i meant an url like those https://itch.io/c/2563651/pygame-wasm
not sure how you can start a game from reddit, i think you would have to host it somewhere before
its a pygame not a web game
these are pygame games
oh okay
how do you play pygames in a web browser?
you can use pygbag runtime (optimized for games) or maybe pyodide, you can also do pygame scripts eg https://pygame-web.github.io/showroom/pygame-scripts/org.pygame.touchpong.html ( look at html source page code )
I can use some help is it possible to add keys together like holding down shift and then moving a wsd my apologies
You can use that to see if modifier keys are being held, like shift, ctrl, alt, whatever else is there
What can I use to make sure that part of code doesn't break when I hold it down because I'm using the basics for right now my apologies
@limber veldt
You're asking how to not break code, I can't answer that
I'm sorry
@limber veldt would this work for a maze with a colider
#maze#
Import random
#===[generateion]===#
Maze_wall =Pygame.Rect(random.randint(0,79), random.randinit(0,79),random.randinit(0,50),random.randinit(0,50)
Draw.pygame( (255,0,255),maze_wall)
#===================#
My apologies
checkout blender geometry nodes for generating maps
the game engine upbge you can use py to access the evaluated blender object
depsgraph = context.evaluated_depsgraph_get()
ob = KX_object.blenderObject
eval_ob = ob.evaluated_get(depsgraph)
geometry nodes can encode attributes we can accelerate retrieval using bvhtree or kdtree
(kdtree for points / edge centers / face centers - bvhtree for raycasting)
https://docs.blender.org/api/current/mathutils.html is like a treasure trove
I used BGE quite a lot before the fork, like when it was still part of Blender
Bless. It's coming along relatively well. Only lost a handful of brain cells so far!
That looks good choom! Keep up the good work.
How do I resume the debugger?
idk but that button looks like it
Now it seems to not pause where the breakpoint is which means the code breaks before the breakpoint, thoughts on how to fix?
How do I get started?
get started with what?
is there no terminal or error logger
i dont really know how javascript works
I'm trying to code a platformer level and i need to put the player in space once theyre y value reaches 0 and it works but the space background is blitting over the player and i dont understand why https://github.com/Laughattack7339/all_things_gravity
@me if you can help
i mean taking a quick look at the code
wait no
nvm lemme see
ok one thing im noticing
when the player is "in space"
u teleport them to the bottom of the screen?
ye and whne u do that
when u call update_positions()
it just sets in_space to false again
cuz they're still on screen
Yeah if they jump from the top of the screen up on the next screen they should be at the bottom right
Not bottom right, bottom, right
dont reset in_space to false then
in update_positions
once they're in space ideally they should stay in space
If you fall down from space then it would make since to go back to the first background and level
but u put the player at the bottom of the screen
they immediately fall back down
maybe give them an upwards velocity when u enter space
So I know how to toggle fullscreen in pygame but the window bar at the top doesn't show
neither does the task bar
how would I accomplish this
info_object = pygame.display.Info()
display_surf = pygame.display.set_mode((infoObject.current_w, infoObject.current_h))
That's what I have right now
and it covers the whole screen
I'm making a settings menu and wanted to make a windowed mode
uhh
what about
width, height = pygame.display.get_desktop_sizes()[0]
display_surf = pygame.display.set_mode((width, height))
is your taskbar set to always show?
i thought pygame.FULLSCREEN would have achieved what you're looking for
Need some help with a making a collision system for walls to keep the player from going through the wall my apologies
uh assuming the walls are rects, and the player has its own rect
if player.rect.colliderect(wall.rect):
if player.rect.right > wall.rect.left:
player.rect.right = wall.rect.left
if player.rect.left < wall.rect.right:
player.rect.left = wall.rect.right
if player.rect.top > wall.rect.botom:
player.rect.top = wall.rect.bottom
if player.rect.bottom < wall.rect.top:
player.rect.bottom = wall.rect.top
this isnt perfect but its a start
Nah it doesn't work
neither does this
thank you
Hi. Trying to figure out how to make a "simple" draw program. If anyone knows which modules I can use to get started with would be much obliged
- Draw stroke, but store them so I can move them around (animation purposes) - I'd like to be able to be able to click in the middle of a line for example and move it so it forms a bend in the line (like a triangle) like moving vertexes around
- create different layers
- be able to combine all layers and export as PNG or GIF
optional - add color
if this is the wrong channel let me know and I will delete
Way too specific to be an entire package. You can make that yourself using any graphical interface lib. For your problems you can store the pixels under a dictionary for layers and drawing and you can probably find some library in pypi to do the export for you
Sorry, pretty new to programming. any recs for a GUI module to start with?
Not gonna lie you might be looking for something lower down the line of abstraction to help you with this, this is the kind of thing I'd make with pygame (not because pygame is the most ideal for guis, but because it can be used to more easily access lower level concepts like "brush strokes" by saving them an separate surfaces for example, and defining your own BrushStroke class etc.)
Might be achievable with pyside6 though, but whatever you choose will be complicated and ton of research to make everything you listed with no prior programming experience
appreciate it, will look into pygames. Yes I want to avoid low level where I have to build everything up. Doing this project as a learning to basic graphic programming
cool, but i feel obligated to advice you not to do this as your first project if you plan on seeking help with it - the instructions to be given on help will be complicated and frustrating for the helper if you cant keep up with the basic concepts
maybe build a small tic tac toe game at least with pygame then go ahead
I can try that. ty
@pine smelt sorry for the ping but why its now just stuck up there
can someone help me please
when exporting with pyinstaller it becomes necessary to install libraries in whichever device you will use it in, is there a way to make it so you dont have to install libs?
trashcan_grup = pygame.sprite.Group() bullet_grup = pygame.sprite.Group() enemies_grup = pygame.sprite.Group() trashcan = Trashcan(int(width / 2), height - 100, 3) trashcan_grup.add(trashcan)
You are also not using super().__init__(group) in group classes
And instead of the class being used for .update() method you are using the group ITSELF (Dont use the group itself, get in a for loop like for enemy in enemy_group: enemy.update() )
since its multiple sprites
and not a single
Forgot the bracket btw
Does this even work?
As enemies is inside another function which isnt a global var
not really sure how your code is in reality but try this
anyone can help me with a pygames issue?
I put buttons on a surface which itself is on the "main screen" When I go to click the button it doesn't work as intended (should print "Clicked" to the console)
Now I know the issue is that the button.rect is giving the value of it's position RELATIVE to the surface I placed it on (the surface is on the right side of the screen)
When I click in the spot that printing (button.rect) gives It triggers the button
my current code, any help would be appreciated
the collision attempt is in the draw function of the Button class
Seems you'd have to do the math to translate the position of the mouse when pressed, maybe subtract the button's self.screen.topleft.x from mouse.x and self.screen.topleft.y from mouse.y, not sure just reading the code
the mouse position when trying to click the button is like 650, 20
the button thinks it is located at 60, 20 since it's only 60 pixels from the side of the surface I put it on
I just tested and it does work if I put it only the main_screen at it's true location, was just hoping not to hard code it
Is there a framework or a library for simple text based games with some ASCII graphics? It also doesn't need to be anything more than turn based (the game is paused while the user is thinking of the input), so real time processing is unnecessary
I'm thinking pygame is just a huge overkill for something like this
why do you need a framework? if it's going to run in a console, can't you just make the world in a 2d array and use the basic python functions for making characters, dialog etc?
I guess so, I was just thinking maybe there's a library that will make it easier to handle ASCII art, I've never worked with it before
I'll just write it myself, should be a good challenge
If asking for clicks, you might look into using the event loop in your main file and checking for ```py
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
print(pygame.mouse.get_pos())``` This will give you single clicks instead get_pressed() which looks for held buttons
appreciated this. The overall issue though it that the button thinks it's in the wrong position because I put it on the surface instead of the display and was hoping to solve this
Yes, understood
And that should be just doing the math like I mentioned before
Using the mouse event like above, you could test the math, I haven't needed to click relative positions on surfaces enough to just know off the top of my head but if you add the above to your event loop, you should be able to wrok it out pretty easily
gotcha
If you subtract the topleft.x of options_list x surface from the mouse position, it should give you the relative position on that surface
Then do the same for y
Or any of the left virtual attributes, there are a few ways to get the x of a rect, topleft.x, left, bottomleft.x among them
thank you. Will be looking it up. couldn't find a way to get the surface top left coordinates in terms of the main screen space
I played with it a little, clicks are printed relative to the topleft of the blue surface https://paste.pythondiscord.com/YU7Q similar math can move those numbers relative to other objects as well
Like this finds the test_button ```py
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
pos = pygame.mouse.get_pos()
relative_pos = pos[0] - option_list_location[0], pos[1] - option_list_location[1]
if relative_pos[0] > test_button.rect.left and relative_pos[0] < test_button.rect.right:
if relative_pos[1] > test_button.rect.top and relative_pos[1] < test_button.rect.bottom:
print('clicked test_button')```
Long lines suck but it's ok for now
Your option_list surface doesn't have a rect, I realized after I talked about finding the topleft of it, but you already have that location in your option_list_location so really don't need the topleft of its non-existent rect, lol
oh wow, thank you so much !!
I couldn't figure out what to do and was going to do more googling tomorrow because when I was printing the rect I was getting 0,0 as the location of topleft. Forgot I calculate the location already 🤦♂️
Really appreciate you working out this for me
No problem, I changed your code a little but I think you got it pretty good, keep at it
appreciated 🙂
now I'm trying to get the layer_manager to work, all the new layers added keep the same list of points drawn on, but I'll try to figure it out tomorrow lol, it's too late to think anymore
when i go here: https://www.pygame.org/register and try to register, i get: "Spam check… Registration by invite only" - Can anyone help?
I don't know about registering there but I'm pretty sure it's unnecessary. If you want to install and use pygame, I suggest installing pygame-ce, the Community Edition (and updated, unlike old pygame that is no longer really even active)
i want to upload my game on the website and im pretty sure that takes a registration
Oh I'm not sure in that case, maybe someone here will know the right answer though
Do you want to upload your game to that specific website or to any website? Usually people upload their games to itch, as far as I know
Matiiss isn't active but they'd probably know
I'll try this when i got back home
And for your question
Idk
Idk what am i doing most of the time
Same, but I keep practicing anyway
Keep practicing
Do you know about pyinstaller?
when exporting with pyinstaller it becomes necessary to install required libraries in whichever device you will use it in, is there a way to make it so you dont have to install libs?
Sorry, but I haven't used it (nobody cares about my codes so I don't put a lot of effort into sharing them)
ah its okay but its not like that
won't u need those to run the game tho
wellimean whats the point if they have to install everything anyway
pyinstaller also compiles the third party libs your project uses if thats what you mean
but id reccomend using nuitka over pyinstaller tho
what's the advantage
less likely to be flagged as a virus and a bit faster than pyinstaller compiler
using pyinstaller enraged me
;-
i use Linux so I'm tryna use Wine to compile it to .exe format
and then when i launch it
but nuitka exes are much larger than pyinstaller tho
are you sure that's due to wine and not an issue with your pyinstaller setup? check that a normal linux build works, and also make sure to use a venv (in my experience pyinstaller has all sorts of weird problems when used without a venv)
isn't wine itself a veng
venv
not python one
but it is standing to the definition of virtual environment
not in that sense; I mean that for some reason pyinstaller works better in a venv compared to an empty global environment
oooh
I'm using global
but there's just 1 problem
I'm already far in the project even in GitHub, if i switch to venv will that change anything or ruin anything?
also you might need to be using an old enough python version, since wine emulates... well, it can be changed, but isn't it like Windows-7-equivalent by default?
nono
my wine is windows 10
it's box64 running in it
and the python is the latest 3.12.4
well, presumably you have been-
wait, your project is on github?
private repo
that makes things massively easier; you can stop messing with wine and instead use github actions to build on a windows system
wait howww
e.g. here's my workflow for that, triggered by pushing a tag: https://github.com/RundownRhino/aw-watcher-mpv-sender/blob/master/.github/workflows/build.yml
ActivityWatch watcher for mpv. Contribute to RundownRhino/aw-watcher-mpv-sender development by creating an account on GitHub.
my project code is in GitHub
not the executable or its build files
so does that count
everything necessary for the build needs to be on github, so that the action can use it
the results of the build will be posted as an artifact (see the end of the workflow i posted), where they can be downloaded from
I'm working on something specific and I don't want to use just pressed for key I'm still I have making another key my apologies
from time import sleep
Player_speed=1
#===[abilities]===#
Def Dash ():
Player_speed += 2
sleep(5)
Player_speed-=2
Print(player_speed)
#===============#
My apologies
@limber veldt
Hi
I'm sorry I'm my code okay my apologies I'm sorry
All good
Would that work?
Would what work, time.sleep? That has no place in a game but for very specific uses...maybe, but probably not
most game devs: "I can't use free assets because they never have everything i need and it doesnt match"
me
which engine
defold.
it's a pretty good engine if your main priority is ease of deployment to different platforms. But it doesnt have as many features as larger engines.
But if you dont need them, its kind of refreshing
oh another good thing about defold is they have almost no terms of the license
the only terms is that you cant commercialize the editor, which is source available. but you can do anything else
oh nice
This is So Funny for some reason
Nah it's lua. That engine uses a file type .go for a game object. It's pretty annoying because vs code always thinks it's go.
damn
I'm trying to use while pygame.mouse.get_pressed()[2]:
but it turns into an infinite loop, even when the right click is up. How to fix this?
Using another while loop that is to span more than one game loop can be tricky, a nested while blocks the outer one, so the event loop doesn't happen or whatever else needs to be constantly updating in the main loop
I'm trying to make a drag selection box, so I am trying to detect the highest and lowest corner the user drags their mouse over. if statements keep resetting though
Hmm, maybe get the mouse position at button down and get it again at button up?
that would work, but how to draw the box dynamically while mouse is moving?
I want user to be able to see wht they are over
oh maybe the MOUSEMOTION event - store initial click in variable, then capture current position and draw the box to that position?
Use some kind of flag when the button is pressed that your draw loop can use, when that flag is True, print your saved mousebuttondown location and your current mouse position and go from there?
When that flag is False, don't print the values
After you get something printing, draw a rect using those values instead of printing them
?
This can draw that rect https://paste.pythondiscord.com/GJ6A
I commented the ternaries and left the regular if/else statements, but the ternaries do the same thing
Thank you so much! I’ll test this code in my program when I get back home 😎
No problem, just a matter of breaking it into pieces that draw.rect() can use
And we actually don't need the location at button up, just to set the flag to False
I suppose if you wanted to do something with that rect, you might save it in the draw() function or method, just stuff it into a variable
def create_enemy():
for e in range(10):
enemies = Enemy(randint(10, width - 10),randint(-1000, height - 1500))
enemies_grup.add(enemies)
create_enemy()
how do you make so it wont spawn too close and overlap to each other
Maybe make a list of positions to spawn at and random.choices() from that list?
list?
This way they're not entirely random, they can only spawn at positions in the list
how do i make this list
my_list = [[200, 0], [400, 0], [600, 0], [800, 0]] If we choose from that list, they can only spawn at those locations for x an y, or similar. If you need to learn lists, I suggest a tutorial on them
Either way, randomly choosing will have some overlapping others. Setting up a list of positions to iterate and spawn one at a time isn't too difficult though you lose the randomness
Maybe make a few lists of positions and spawn waves in different shapes as the game progresses
Pre-determined waves instead of random waves
so i need to make a list of coordinate of spawn position and then apply it to the function
sound confusing to me
Totally up to you, just an idea
also how do you make the enemy spawn one at the time
Just iterate a list of positions and spawn one enemy for each position
Not a range of enemies like you are now
iterate?
Your create_enemy() creates 10 enemies by iterating a range(10), so it creates 10 enemies, that is iterating a list
so instead using range i have to call my list
so something like this?
def create_enemy():
for e in my_list:
enemies = Enemy(randint(10, width - 10),randint(-1000, height - 1500))
enemies_grup.add(enemies)
Do something like this py def create_enemy(): positions = [[200, 0], [300, 0], [400, 0], [500, 0], [600, 0]] for position in positions: enemy = Enemy(position[0], position[1]) enemies_grup.add(enemy) maybe not exactly that but similar
oh
So use the list instead of random
alr
I mean, it's something you could do, an idea, maybe right for your intentions, maybe not, but maybe worth a try for you
man coding is hard. like, i find out how to solve a problem but idk how to turn it into code
Keep practicing what you learn, try not to move on too much until you know each thing
try not to move on too much?
Right, like if you're just starting, learning something really complicated is even harder
And that function should actually be named create_enemies() since it creates more than one enemy
Always want your names to make sense
btw can i call a list with this randint thing
No, but you can get a random.choice(your_list) to get any one of them randomly
oh, thanks
def create_enemies():
positions = [[200, 0], [300, 0], [400, 0], [500, 0], [600, 0]]
for position in positions:
x, y = random.choice(positions)
enemy = Enemy(x, y)
enemies_grup.add(enemy)``` to be clear, I hope you get the idea, keep practicing
AttributeError: 'builtin_function_or_method' object has no attribute 'choice'
i did
Then maybe you have assigned something else to choice = something?
huh?
Would have to see your code to know why
oh ok
- imports are too vague, generally shouldn't use them
Cause now you have this call to choice() with no reference to it in the code, it just became available because of the * import
A pygame.rect wants a tuple of (x, y, width, height), so something isn't right with your values
tuple?
what am i doing wrong here
def create_enemies():
X_position = [[100, 0], [200, 0], [300, 0], [400, 0], [500, 0]]
Y_position = [[0, -100], [0, -200], [0, -300], [0, -400]]
for e in range(10):
x = random.choice(X_position)
y = random.choice(Y_position)
enemies = Enemy(x, y)
enemies_grup.add(enemies)
create_enemies()
It's like a list but not a list, just some values separated by commas in inside () instead of []
oh wait
You have lists inside your list, right? The [100, 0] is a list inside your x_positions list
fuck i forgot to change the range
So you are getting that list with random.choice() when you only want one value, the x_position
yes
So make your list more like x_positions = [200, 300, 400, 500, 600] or whatever single values, not lists
Since you only want one value from the list
And of course, do the same for the y_positions
Choose each one separately and send them to the enemy
like this?
def create_enemies():
X_position = [[100], [200], [300], [400], [500]]
Y_position = [[-100], [-200], [-300], [-400]]
for e in range(10):
x = random.choice(X_position)
y = random.choice(Y_position)
enemies = Enemy(x, y)
enemies_grup.add(enemies)
oh i forgot to erase that square thing
You don't need all the [100] [] in those
Just the values like I showed you
You're still making lists inside a list
so what should i do with that range()