#game-development
1 messages ยท Page 60 of 1
hey how are you
Made this with arcade 2.4 using the new low level rendering api (moving points with gpu). About 35k points here. It can probably handle 500k+ easily. It can also be used with pyglet.
Some area around the mouse position. Passing that position to a transform
Buffer data is current pos and desired pos
Just make the points "afraid" of the mouse pointer ๐ ```glsl
// Move the point away from the mouse position
float dist = length(pos - mouse_pos);
if (dist < 125.0) {
pos += (pos - mouse_pos) * dt * 10;
}
Kind of a sloppy shader, but it works
ah i thought you were doing actual repulsive forces lol
500k points with O(n^2)?! haha
It's O(N)
yeah but repulsive forces between all particles and the mouse would be O(N^2)
i thought you were treating the particles like electrons or something
and the mouse was one big electron hah
ah. nah. Just fake it. That's what computer graphics is all about
i need to print that and hang it on my wall hehe
im still too used to trying to figure out how to do stuff "correctly"
when faking it would cut it 100%
What would be the best current library to show off 3D space trajectories and motion therin?
like visualize them?
is there a discord server for pygame?
is there a discord server for pygame?
@silk marsh yes, there is! you can find the link on this page: https://www.pygame.org/wiki/info
cheers
Is it possible to recreate Pokemons in pygame?
@dawn quiver you have to elaborate on your question. Pokemon franchise is copyrighted by Nintendo and Nintendo is very aggressive in defending its intangible assets
Iโm just wondering if it is possible.
I would create own pixelated characters etc. Just the game mechanics itself.
Sure
At least old pokemons, I don't know new pokemons, if there's 3D stuff, particles etc. Python may fail to provide good framerate
But that's not mechanics, that's graphics
you can do you every game game you want in 2D with pygame so yesss it's probably doable, the only limit is your imagination ;)
so i am working on random placement for my trees but now the while loop runs every time and the random value of the x coordinate keeps updating. how can i make it to run the random numbers onely once but still be able to update the location for the parallax effect?
Create them on startup. Then store them in a sprite list. The display the sprite list. Update the sprites in the list as needed for the parallax effect.
Okรฉ thx @frozen knoll
https://youtu.be/zN9wOvCGEA8
Update on the game
What's the command for the frame rate on pygame
@frail totem I looked at this yesterday and apparently you can force the framerate using clock.tick(60) for 60fps. The tick will in such a case block until the time required for 60fps have passed. Clock is available in pygame.time
...although that doesn't prevent your frame rate from dropping below 60 fps.
so i can't use it on nnormal python
I always just calculated it myself, I don't think that's something built-in.
ok
Not with pygame anyway.
ok
@frozen knoll if your framerate is below 60fps you got performance problems. No tick command can fix that.
Hi there, if anyone can help:
"I have a python script/game (using pygame and pygame.mixer) that plays some audio (linux). When the device is busy by some other app (let's say youtube in browser), my script will not play audio and vice versa, aka, when it plays, no other app can use the device. I guess this is probably related to ALSA dmix but not sure. Has anyone faced such an issue? And if so, how can I async use the same device across multiple apps or python scripts. Thanks"
BTW to calculate TPS in a tick function you can just do 1 / time_since_last_tick, some people might find that useful
Seems like pygame.mixer isn't the right solution then tbh
hi @fervent rose thanks for the reply, the problem is that this happens not only with pygame.mixer but every other thing, like pyaudio, etc
Hmm that's weird, I'd say that the issue is coming from your OS
@fervent rose I think so too, just tested in Windows and was able to async access sound device, I'm using Ubuntu 20.04
maybe some driver issues or something
I'll investigate more, thank you for the help!
Hi, I am new in this language and I wanted to know how to put an image in the head of the snake instead of only a colour
How do I import a custom font in arcade module?
turtle, the one that comes with python
@dawn quiver Copy the true-type font to same directory as your project. Then when you use draw_text set the file_name parameter equal to the font's filename.
draw_text has filename parameter?
for my character sprites, I used a website that makes it for you, but it downloades it all as one image
like this, but I need them all as seperate images
or maybe it could work like this, if someone could teach me how. Im using pygame, and the tutorial I watched the guy loaded each image individually
@trail escarp could you just use a screen capture tool such as snipping tool or gyazo to screenshot each one?
yeah i thought there would be an easier way lol
it's called a sprite sheet
you put all the frames in one image instead of many because it's faster that way
yeah how do I do that
Soo, uh. I just started learning not even a day ago. There's 2 road blocks I ran into and dunno how to go about it. I'm just creating a simple text based game. I can't get the code to do else: print("Good bye!") if the person say's they don't wanna play the game right after that. It says wrong syntax? I've tried even elsif and it didn't work? Along with that I can't get the game to spit out the multiple options I want for it in one take. Like have it display "Assassin", "Thief", and whatever other option to be had. Tried the stuff I know. Like I said I just learned some very basic stuff. Some advice would help if possible. ๐
I did that. Said wrong syntax? or the other thing it would say there was nothing on the line to relate it to. Which got me pretty confused. I'll try it again. Maybe I missed something?
Screenshot?
Lol did you even look at what I sent you
else:
print("Good Bye!")
Do it like that
Ohhhh
Sorry. I didn't notice that. I totally overlooked it. I thought you meant like return and def. Dunno what those two functions do yet. Thought you were referring to that. ๐
no worries
Like this? 
No put it all the way at the beggining of the line
So it's in line with the original if want_to_play:
The way you have it right now, it will only print good bye if the answer isn't thief
Is else just not supposed to work here like that? This is really troubling. I feel like I'm really doing something wrong here. Haha.
can you just copy paste that all of that so I can show you
Yeah I can.
print("Welcome to A Rogues Journey")
want_to_play = input("Do you want to play? ").lower()
if want_to_play == "yes":
ans = input("Are you a Male or Female? ").lower()
if ans == "male":
name = input("What is your characters name? ")
print("Alright", name, "please pick what type of rogue you want to be!")
ans = input("Assassin""Thief" ).lower()
if ans == "Assassin":
ans
print("Welcome to A Rogues Journey")
want_to_play = input("Do you want to play? ").lower()
if want_to_play == "yes":
ans = input("Are you a Male or Female? ").lower()
if ans == "male":
name = input("What is your characters name? ")
print("Alright", name, "please pick what type of rogue you want to be!")
ans = input("Assassin").lower()
if ans == "assassin":
ans = input("Thief").lower()
if ans == "thief":
pass
else:
print("Good Bye!")
it works now
just delete the pass though if you want to put anything after the last if
Mind if I ask what pass does? o.o
yeah, it just ignores it
Doing pass just ignores the error?
no
without the pass there would be an error because its saying if ans == 'thief' but you didnt tell it what to do after that
but pass tells it to do nothing and just move on
Ah, I see. I get it. So, it would be useful for lines of code that might not be finished but you need to test it out. So, it would just make it go along smoothly right?
yeah
like if you want to make an if statement but write in what for it to do later, you could just right pass
Alrighty. I really appreciate the help and the time you gave me. Thanks!
np
will these give back the same type of objects?
items = browser.execute_script("return document.getElementsByClassName('a-section a-spacing-medium')")
items = browser.find_elemenets_by_class_name("a-section a-spacing-medium")
How is using selenium related to game development?
i was told to ask that in here
Sorry, they were incorrect. You'll have better chances if you claim a help channel. #โ๏ฝhow-to-get-help
Hello every body... I need somebody's help... I want to make a game with pygame... who can help me???
Hello everyone, I created a web game in flask/python which I would love your thoughts on. It allows you to play the role of an Intelligence Officer operating in a hostile country under diplomatic cover. You will plan intelligence operations, build a network of local sources, analyst and classify intelligence. There are a few little tricks in there too. It is free to play in Alpha at https://secureup.link/
is there a way to make screen.listen() take multiple inputs? in my game when i press the second pads upward button the first pad stops
both pads are user controlled
I have random imported but this line chance = random.randit(1,4) throws an error. Any suggestions?
This is the error btw: module 'random' has no attribute 'randit'
Spelling error ๐คฆโโ๏ธ Thanks @proper peak
Also @dawn quiver https://www.youtube.com/watch?v=FfWpgLFMI7w
Learn how to use Pygame to code games with Python. In this full tutorial course, you will learn Pygame by building a space invaders game. The course will help you understand the main game development concepts like moving characters, shooting bullets, and more.
๐ป Code: https:/...
Freecodecamp is a pretty good resource, but it also depends on whether or not you have experience with another programming language.
Hello
I have a question about animation
In 2D how can I rotate an object about the vertical axis to give the impression of 3D rotation?
you can note that for a flat object, rotating it around an axis(parallel to y) laying in its plane transforms the coordinates in the following way:
(x,y) - coordinates of a point in the object's frame of reference, (x',y') - in the screen's
x' = x * cos(phi)
y' = y
so the object basically gets shrunk horizontally, by a coefficient of cos(phi) (and mirrored, when it's <0)
@proper peak : Thanks, so the matrix is
[ cos(phi) 0]
[ 0 1]
?
But how could that change the perspective?
@dawn quiver basically, it's like looking at a infinitely thin plane with your sprite on it
So my nephew is somewhat in a weird place the kind of 16 year old kid who is overweight/really into video games but I am trying to get him into a more productive place. I think he might be really interested in trying to make his own video-games. Unfortunately thats not what I do nor do I have any experience in that area. I was wondering if python might be a good introductory language for that and if yall have any resources you like for it?
Try looking at https://learn.arcade.academy
thank you!!
how do i make a setup file with my executable?
in vs19 its easy but there is an option go check out some yt videos
is pygame legit or is there somewhere bigger to work to in game dev with python
Module 'pygame' has no 'init' memberpylint(no-member)
pygame.init()
size = width, height = 800, 600
black = 0,0,0
screen = pygame.display.set_mode(size)
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
screen.fill(black)```
code
hey
Pygame is legit. There are other good libraries like Kivy, Pyglet, and Arcade. Kivy can make games for Android. Arcade makes better use of the GPU for faster and more advanced graphics. It's also a bit easier in my biased opinion. https://arcade.academy
@drifting fable This sometimes happens if you name your file pygame.py or have a file with that name.
Hi guys, I just published my first game on the playstore! And I was wondering if someone could give me feedback
https://play.google.com/store/apps/details?id=com.GeekSand.RingDefender
this is my game
I'm new to coding. I've only gotten to know python for the last couple days. I'm building a simple game to get me familiar with the coding. I was wondering if someone knows how to clear when the player hits enter, or after a certain amount of time. Instead of like a continuous line of previous stuff that looks bad. Like this:
Clock = pygame.time.Clock()
all_sprites = pygame.sprite.Group()
all_sprites.update()
dis.fill(black)
all_sprites.draw(dis)
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((50, 50))
self.image.fill(green)
self.rect = self.image.get_rect()
self.rect.center = (dis_width // 2, dis_height // 2)
all_sprites = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
def update(self):
self.rect.x +=5```
the sprite should go right
but when i run it i just get a blank screen
oh wait
also
i get this error
Does anybody know of a 3D space/environment library I could use similar to NetLogo3D in this picture? Something that allows for agents/vehicles to move within the space given commands
@sleek pawn You could use panda3D.
I've checked out Panda, it seems more for 3D models rather than navigable spaces?
What do you mean by navigable space ?
Something similar to the software NetLogo. Where agents can move around in a 3D world, detect their environment and make decisions based off those detections
I guess I'm missing the right terms
It's not only to show 3D models. There are collision detection or physics engine in it, also.
So I guess you could use it as a way to display what you want in a 3D space.
But you would have to compute the agents decision yourself, I guess.
In the most basic case, I'm just wanting a 3D space where a drone can be given a command e.g. forward(5) and it can return it's new position once completed
I assumed there'd be small open source systems to use like this but think I may be wrong
You can perfecly do that in panda3D.
You can display 3D models and move them around in the 3D space very easily.
If it's all you need, it should do the job. (and it's open source!)
I'll probably explain this badly but... Would Panda3D allow me to process "perspectives" from the vehicle? The main aim of the vehicle's is to scan its environment using sensors. Would it be possible for the vehicle to process the terrain around it in this way?
Ideally, being able to analyse its "scanned" terrain for gaps, amount completed etc.
You mean, beeing able to "see" what the vehicule see ? Like if there were a camera in the vehicule ?
Yep pretty much
Like the ability to take sections of the terrain geometry for further processing
Then you can put a camera object on your vehicule and take pictures. You should then be able to do whatever you want with those pictures.
@sleek pawn omg Jason derulo is here
Thanks for your help. Would the camera object just take pictures or does it let you process local geometry in this way?
@sleek pawn It would just take a picture. What do you mean by "process local geometry" ?
So say for example the drone's objective would be to scan a given area (e.g. a 10m square of land) within the game. It would do so using a sensor on the bottom of the drone pointing downwards at the terrain. Now if the terrain in the game is made up of a pointcloud file or similar. Would it be possible to record which points or polygons have been "scanned" by the sensor?
You could use collision detection for that :
you can have a box (or whatever shape you want) and use a collision ray to detect if you hit the box
It would be as if your drone had a laser pointing toward the floor. The laser would be able to detect when he hits a specific box, for instance.
Sweet. I tried to implement something similar (ray collision) in Unity but with it being less open of a software I didn't think it would allow interfacing to my external program. I'll have to have a look into Panda3D properly
Sorry another question, thank you for your advice so far! What I'm working on will be utilising a planner and domain/problem using the STRIPS/PDDL planning languages. Do you know if there's any examples of people interfacing to Panda3D with planners in this way?
I have no idea at all. You can maybe ask this on panda3D discord server or on https://discourse.panda3d.org/.
Okay thanks, I'll check it out
sooooooo I have a weird one
I am working on a MUD/MUSH server design. This is a text-based multiplayer RPG where player characters move between 'rooms' linked by exits. go north, west, south, up, down, east, etc. (although it isn't necessarily direction-based in all games, I want mine to be.)
Having seen a few MUDs that had an automapper (it shows an ASCII art minimap of your surroundings as a 2D grid), I am pondering how to put together such a thing myself
this has lead me to the topic of how the heck I would create a 'region' of room objects arranged on a 3D grid which I can then conveniently search.
Of course I can think of several ways of doing a '3d container' like a dict<x, dict<y, dict<z, room>>> but that doesn't sound like a great idea.
Wondering how this kind of issue is normally handled.
To store a 3d grid of something I'd usually use a 3d array for the sake of speed, but that depends on how you need to access it
If you want to map a room to a 3d vector a 3e vector to a room, an array should be the way to go
now when you say array in a Python context what do you mean exactly? we've got Lists, Dicts, Sets, etc... but for instance like let's say I have a given point on the grid and I want to generate a 5x5 ASCII map of the surrounding rooms (some points on this grid may not have rooms).
In python it would be 3 nested lists 
aha. I suppose I could just stick None objects in the unused ones
since it's being displayed over a telnet client... I can't see what good drawing more than one z-level would do
so
Well, you could use a color gradient for the depth, or go crazy and do a 3d render, and then translate it to ascii haha
The question is - 3 nested lists filled with lots of Nones over nested dictionaries?
Depends on the size of your room
And the amount of empty space
Remember that at low level for the same amount of data a dict is way way larger than a list
Helter-skelter. lots of empty space is expected for some maps. For others it might be very densely packed but unlikely to be more than a hundred rooms
Oh wow
That's a lot
A 3d list isn't the right choice then I think
If you only want to render a 5x5 grid, you could take each pixel and compute if it collides with any room
If you need to speed things up, you can break up your map in 5x5 squares and list every room that collides with it, and only check the collision with rooms inside this square
nah its's gotta move with the player... I'm kind of headscratchy because I know this is doable, but the program I saw it done on is running in C. And I dont know what it's doing or how. Yet.
Do you know how to read C?
Ah I see
I have a hunch though of how this automapper works now
I'm guessing it's not checking against a 'map index' at all. I'm actually wondering if maybe instead it's sending out 'feelers' and scanning your local pathing. Like... if I have an exit to the north of my character's location, its easy to retrieve that specific room and scan ITS exits... so, from a starting point, you crawl through every room and generate a map out to XY distance.
this would mean you don't actually have a true coordinate system in place - it's smoke and mirrors.
... I just randomly thought of this method.
No I want to display something like this:
D
C
CCXCC
C
F
you are at point X. you are on a city street going east/west.
To the south is a Forest tile
To the north is a Desert tile
and two methods of generating this display have occured to me
the first is to have an actual 3D grid of points containing references to the rooms.
Hmm, in that case, you should have the whole map stored in memory, and query it
The second is to 'crawl' the exits from your current location and go by whether it's a n/s/e/w exit to figure out where to put it on the generated map
and the third would be to generate the map head of time yes
and just replace the center with the X
You could generate the map as you go, but without caching that would be pretty resources heavy
yeah.
I'm investigating the coordinate system because I have been having various ideas of how to use it creatively and for more purposes than just 'automapper of rooms'
Guys if you want an even simpler way than python you should try Ursina Engine
https://www.ursinaengine.org/ Its built upon panda3d
thats not useful to me I'm afraid... I'm basically writing a multiplayer game server
zero graphics
...... I just had an apostrophe
Hi, I am new to pygame and I cannot figure out how to use colliderect
pygame.draw.rect(DISPLAY, WHITE, (1050, 320, 10, 80))
My two rectangles are defined like so
But I am unsure of how to turn them into an object to compare them
I am not using classes yet as I am just adjusting to the basics of pygame, although it may seem I have to start right away
Any python/Django devs that are also tabletop RPG fans?
I'm looking to partner up with another dev for something I'm already running online. It currently has a solid platform in place based on the RPG space. I'm looking to focus on the business side and have someone come on to help with continued development.
Message me if you'd like to know more.
im very new to pygame, check the question in #help-cookie
Can someone help me
Im using pygame to make a A* pathfinding program and I already have it finished now I want to add a that when I press the key R the program will reset/clear instead of need to reopen it
if event.key == pygame.K_c:
start = None
end = None
grid = make_grid(ROWS, width)
I wrote this but when I open the program it opens and closes quick
anyone know any good website to make a game?
or where they teach how to make a game
...
if anyone knows dm me
Hey @steady swift!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
โข If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
โข If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
@dawn quiver Which type of game do you wanna make??
Only then can I specify which website to follow
Platformer?
like subway surf
so which is the simple one
U can start by making 2d games like mario
U can use Pygame or Python Turtle graphics
For it
thx
Wc Keep coding!
i will ๐
To be honest, you shouldn't use Turtle to build a game, it isn't made for that
Yes
It is a very primitive and slow librAry built out of tkinter
U can use pygame
Well, to be really honest, I think pygame is a pretty bad library for what it is meant to do
I'd suggest you to use arcade instead
Why is pygame so popular?
Probably because it is simple at first glace, but once you start making a more complex game or switch to a fully featured game engine, you'll realize why you shouldn't have picked it in the first place
@dawn quiver take a look at https://arcade.academy Especially the tutorials.
hello mates i need a little help
i`m newbie in python
trying hard to develop my skills
i stuck in one easy task for some of you , but for me i cannot figure out
hi mates
what they want me to do
i need help
so its a game with grid
x and y is my grid
on row 1 i will have lets say 1 cell on row 2 i will have 2 cell but , it shoud look like this
o
oo
ooo
oooo
or
oooo
oooo
oooo
oooo
or
oooo
ooo
oo
o
Hello guys, I have a problem relationated with pygame, when I was doing a game with a character that he is flying and he has a ultimate, I don't know how to put the ultimate that is a class apart of the character together, for example, when I move the character, the ultimate too. Is there any way to do this?
cd D:\Python
File "<stdin>", line 1
cd D:\Python
^
SyntaxError: invalid syntax HELP ME PLS~!!!!!!
@plush wedge newbie to python here too, I'm trying to resolve the exercise :)
Hello guys, I have a problem relationated with pygame, when I was doing a game with a character that he is flying and he has a ultimate, I don't know how to put the ultimate that is a class apart of the character together, for example, when I move the character, the ultimate too. Is there any way to do this?
@bleak locust sorry but I don't use pygame and I'm not good with classes
Garv take a look at https://arcade.academy Especially the tutorials.
@frozen knoll ok i will
cd D:\Python
File "<stdin>", line 1
cd D:\Python
^
SyntaxError: invalid syntax HELP ME PLS~!!!!!!
@hollow socket what are you trying to do?
you seem to be using bash commands in python
Trying to get a shape to appear in my window in a turtle project but I can't for some reason: import turtle import time wn = turtle.Screen() wn.title("AI") #wn.bgpic("map1.gif") wn.bgcolor("white") wn.setup(width=800, height=600) wn.tracer(0) #Window Update while True: wn.update() #AI Graphic player = turtle.Turtle() player.speed(0) player.shape("square") player.color("black") player.shapesize(stretch_wid=50, stretch_len=10) player.penup() player.goto(0,0)
Any ideas? I'm not sure why the graphic wouldn't show up.
so i was using pygame to make a platform that moves when u press a button
pressing a button involves colliding with the button (players, buttons and platforms are all rect objects)
i wanted 2 toggle the button so u press it once and it goes all the way up and u press it again and it goes down
in the first frame where ur on the button, it activates it so the platform moves
u can only press the button again after u step off the button
but when u go back on it, nothing happens unless u jump off it
so it gets to a point where the only way to activate it is to step on the button then quickly jump off
i'll send the code later but im just sending all this now so i dont forget
thats the code^
pressed is a boolean value passed in from outside the function
basically if the players on the button (pressed = True), self.lever_pressed should change from False to True or True to False
from what i could tell, on the second button press, it goes from the if statement with "0000000" to "22222" in one cycle
ill explain later if any1 wants 2 help but doesnt get it
but for now, i have 2 go
is there a way in pygame to make the ingame camera 250 x 141 and the viewport 1280 x 720?
im making a pixelart game and i need it to be more zoomed in
is anyone on atm to help me with something?
Anyone wanna help mecreate fps game ive done graphics and menu
@strong obsidian link to source?
In the arcade library, does anyone know how to disable the fuzziness on textures when they're scaled?
I'm trying to go for a pixelated effect
hey, anyone working with ml and gamedev?
well, lets say, i have mnist data set trained in python, now what i want is to integrate that trained model in the unity to out that in application and add some custom ui and other stuff so that it works like AR
so my main issue is integrating the python trained file into the unity
if anyone can help, please lemme know
@everyone please give a look at above problem
@dawn quiver for spites there is a filter parameter for this
I think this should work ```python
from arcade import gl
sprite_list.draw(filter=gl.NEAREST)
The default is LINEAR causing the texture to smooth out
@potent ice thank you so much!
I was scared I was gonna have to scale all my images up
hey guys i just wanna know if i can use turtle model to make a game
can definitely make some simple games with it
Turtle is certainly great, but pygame offers more functionality. If your aim is to learn python, I suggest you start with pygame.
Or Arcade. https://arcade.academy and https://learn.arcade.academy
personal projects are in #303934982764625920 ๐
Hello I wnt to get started with 3d games I only know python๐
How can I start
Plz tag me when u answer
Panda3d will be good for me??
@storm bolt It might, depending on how you are familiar with the concept of classes, for instance.
I got Pygame installed but it still shows this error even after i restarted pygame
pycharm*
@storm bolt It might be a good idea to get familiar with the concept first.
You can try panda3d on your computer and see if you understand the introductory example of the manual :
https://docs.panda3d.org/1.10/python/introduction/index
Since the engine is very light, you can quickly install and uninstall it (unlike UE4, for instance).
There are also sample programms in addition with the one in the tutorial. You could look at those and run them too.
@storm bolt Did you already make 2D games before ?
Yes, it can. There is an exporter to convert blender files to some format that panda3D can read.
Ooo
Then I would suggest you to start with a basic game (or anything else) using classes, just to get a bit familiar with the concept.
That is the custom python version that comes with the panda SDK.
But you can just pip install panda3D, it's easier.
hi i wanted to install pygame but there is a error that pip doesnt exist can someone help me?
What is the error ?
the error said that the name pip dont exist
he suggest me to use .\pip but that didnt works tough
Try to install with python -m pip install pygame
D:\python.exe: No module named pip he said that should i first install pip
Try to get it with python get-pip.py
Funny thing. Im having an issue installing pygame also
first timer
am I suppose to use gitbash?
nvm i got it
im suppose to use CMD
im using pygame
when i click the mouse
how can i let the code trigger once and only once
like if i do
for event in pygame.event.get():
if pygame.mouse.get_pressed()[0]:
print(f"Clicked at {pygame.mouse.get_pos()}")
and the console will spam Clicked at (xxx, yyy) when i clicked once
i did something like that but the print() didnt even get triggered
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN and pygame.mouse.get_pressed()[0]:
mouse_pos = pygame.mouse.get_pos()
if event.type == pygame.MOUSEBUTTONUP:
print(f"[MOUSE] Clicked at {mouse_pos}")
Why are you using pygame.mouse.get_pressed()[0]? if you don't have a particular need for it, you can use the following code
to make sure it is left button
or how can i make something like
mousebuttondown -> wait until mousebuttonup -> run
An error in your code is the fact that, you are asking if the event is mousebuttonup within your mousebuttondown event
You cannot do this, since the event is mousebuttondown. So the mousebuttonup loop will never run
I found a solution which may not be the most efficient one, but here it goes:
if event.type==pygame.MOUSEBUTTONDOWN:
if pygame.mouse.get_pressed()[0]:
main_settings.mouse_button=True
if main_settings.mouse_button==True:
if event.type==pygame.MOUSEBUTTONUP:
mouse_position=pygame.mouse.get_pos()
print(mouse_position)
main_settings.mouse_button=False
the main_settings is a settings class where I defined all my variables.
uhh i had a solution
if event.type == DOWN: # lazy to type
for event in event.wait()+event.get(): #not sure i forgot lol
if event.type == UP:
code()
i made a simple game
here is the code
background_image_filename = 'black.png'
mouse_image_filename = 'red.png'
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
print("Do you want to open a file or start a new file ?")
save_open = input(">")
if save_open.upper() == "OPEN":
print('Input the file name.')
file_name = input('>')
background_image_filename = (f'{file_name}.png')
screen = pygame.display.set_mode((640, 480), 0, 32)
pygame.display.set_caption("iScribble")
background = pygame.image.load(background_image_filename).convert()
mouse_cursor = pygame.image.load(mouse_image_filename)
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_s:
file_name_input = input("what do you want to save it as?:- ")
pygame.image.save(screen, f"{file_name_input}.png")
screen.blit(background, (0,0))
if pygame.mouse.get_pressed() == (1, 0, 0):
x, y = pygame.mouse.get_pos()
x-= mouse_cursor.get_width() / 2
y-= mouse_cursor.get_height() / 2
screen.blit(mouse_cursor, (x, y))
pygame.display.update()```
those are the two files needed for it to work
so if youo run this
its like a mini version of ms paint
i want to open a file and run it
but its not working
can some one help?
anybody wanna help me ?
I think reading this will help you. It's surprisingly useful : https://pythondiscord.com/pages/asking-good-questions/
We're a large, friendly community focused around the Python programming language. Our community is open to those who wish to learn the language, as well as those looking to help others.
how panda3d works
Hey guys, I'm using pygame to make a lightweight (first) game project and found a small issue that there is no scenes mechanic. I used the scene logic from the following page: https://nerdparadise.com/programming/pygame/part7
I feel like an idiot, but can someone explain where the game loop is supposed to be? Example: I'm building the main menu. I made a "Buttons" class in an extra file with "add" method, etc. and that works quite well. But I want the button that I add in "Render()" to highlight when I hover over it with the cursor. But how? I can't add it as an event in "ProcessInput()", as the buttons are created later in the last "Render()" method, so of course the ProcessInput() it has no idea what I mean. "Update()" won't work either, as that method is called before rendering as well.
How am I supposed to make the game react to objects that are created after the reacting? :-/
Thanks in advance.
Hello everyone
Can anyone help me with a game I am making?
I will link the reddit post I made including all my details
anyone
Oh
Ok thanks, please look over it
On stack overflow my question got removed for some reason
I'm really desperate and thsi has been stressing me out for a long time
any help I would really appreciate
@chilly hazel
did you find anything?
No, I'll check after a while
what is the objective of this game?
Like what's it about?
How do I set border_radius to a shape????
What do you neab
lfh with pygame install (fedora32/python3.8)
doing a pip install returns the following:
ERROR: Command errored out with exit status 1:
command: /home/thoroc/Projects/scrap/.env/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-acmuxlez/pygame/setup.py'"'"'; __file__='"'"'/tmp/pip-install-acmuxlez/pygame/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-vhxaxdri
cwd: /tmp/pip-install-acmuxlez/pygame/
Complete output (18 lines):
WARNING, No "Setup" File Exists, Running "buildconfig/config.py"
Using UNIX configuration...
Hunting dependencies...
SDL : found 1.2.15
FONT : found
IMAGE : not found
MIXER : found
PNG : found
JPEG : not found
SCRAP : found
PORTMIDI: not found
PORTTIME: not found
FREETYPE: found 23.2.17
Missing dependencies
----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
using virutalenv
Hello, I need some help about pygame....
I want to make an image disappear after showing it.
How to do that?
Can you be more specific? There are multiple ways to do it. For instance you can draw a new screen on top of your old image to make it disappear, or if the image is a sprite contained in a group, you can use {groupname}.empty() to remove it completely. There are many ways to do it, but the choice depends on why you need to do it.
@tough kayak for general information on using Panda3D, please take a look at the Manual (https://docs.panda3d.org/1.10/python/index). In particular, I believe you will find the Introduction chapter/section useful.
Should you avoid threading using pygame?
It is my first time using their library so I thought you guys might be more experienced than me. I read a thread on stackoverflow; there was someone saying you probably should keep everything within the main event loop but he doesn't seem to be too sure himself. Any idea?
This is my code and in my situation it looks like I have to thread that function in order to continue updating the rest of the frames.
Is that because you should avoid threading using pygame?
I don't see the benefit of making your game loop multi-threaded. I think understand what you're trying to accomplish, but it really shouldn't be done. Game loops ideally should be on a single thread unless you're looking for some very specific performance gain. In fact, using threads this way might make the game slower by having to create, manage, and join threads for every bullet fired.
Oh, yeah that makes a lot of sense. Would it not be a lot more complex if I had to update the enemy frame while shooting (takes around 2 seconds for the bullet to disappear) though?
See how the enemy keeps moving?
Threading isn't what you need to fix this issue.
So you're saying I should not use a while loop? Because I would not be able to update the enemy whilst looping through the bullet changing.
That's not how you do it. Unfortunately pygame encourages poor programming habits.
See here for an example:
Wow ok, I was just going to ask for hints on Pygame, but it seems people aren't too keen on it haha
I'm trying to build a main menu. I want the click sound (hover over with mouse) to play once, but whatever I try, I can only get it to either repeat the sound as long as the cursor is hovering over it or play once and never again. I'm using the rect.collidepoint(cursor) method and I suppose it collides and doesn't at the same time, so it resets instantly...
any advice?
Well you need to only play it when it when it enters the box, not while its in the box
can you think of a way you might be able to do that
I did actually, I tried using a variable that flips when the cursor is in the box and flips back when it leaves the box. But the variable flips back while inside the box anyway. :-/
I also tried reading up on triggering after a variable changes (in general, not to a certain value), but it looks tto data sciency lol
not sure what that dudes problem is with it
@humble siren, I have no problem with the code; it works just fine. I just wanted to clarify that you should not use threading and keep everything within your event loop.
Oh that wasn't @ you
A) don't use semicolons
B) assuming this is in your loop, you are just flipping soundplayed back and forth continuously
Some people prefer semicolons, it is not forbidden. But if you would like to write Pythonic code, then yeah you should not use semicolons.
Well it is bad style, which matters a lot if you ever want to work with other people or share your code
Why have two different variables for whether or not the sound is played and whether or not its hovering
it seems like you only want to play the sound when hovered changes from False to True
I got despearte. I have the "play sound" in START's class, but the function I use to update the button's color (and sound) when interacted with is in the update loop to check when it's interacted with, which means the variable will continuously be called and reset anyway. :/
Just play the sound when you go from not hovering over the button to hovering over the button
You make it sound that easy, but I've been trying to get it into pygame speak for an hour now lol
how do I check if a variable changes from one value to another?
You don't need to, just do it at the same place you change the variable
set the variable telling you if its hovering already to true, and play the sound
the button's method
calling the method for the created button
leads to wild clicking while hovering over the button
hey guys I've got an interesting question that's kind of multi-topic but I think the biggest part of it touches on gamedev so
ok I think I'm too dumb for Pygame, much like Paul Craven said, I'm probably confused by the game loop and shouldn't be putting the method for the button in the update function lol.
I just don't quite understand how to react to player input, as the event listener has the same issue in that it's always running and will reset any variable I put in to stop it...
You might want to cruise through on-line tutorials.
Like: http://programarcadegames.com/ starts at the basics and goes up from there.
It can be hard to get started if you don't have someone right with you to keep you from sinking time into something that doesn't work. I suggest starting small.
Thank you for the kind words. I had made something last year using the online tutorial and understood it quite well at the time, but I'm trying to use a scene manager and everything looks a bit more different.
Or maybe I'm simply too old to reliably learn something this complex. :)
Ha, doubt that.
As a hint, if you use three back-ticks, you can make code samples.
print("hi")
Then it is easy to copy and reply back to you with edited code.
Like I'd help with your sound play, but I'm too lazy to retype.
So I'm working on something that can be thought of as a.... Not-so-massive multiplayer RPG. It's a MUD/MUSH - meaning, you connect to it via telnet and the server spits text at you and it reads text commands you send it.
I've chosen to split it into (at least) two different processes - the first is a sort of gateway/lobby. Said gateway runs on asyncio and handles all of the complicated networking, like the telnet, and hosting a small website that features a WebSockets method of accessing the game too.
The second process is supposed to be the game server. This will hook up to the gateway using a single WebSocket client connection - that's the extent of its networking responsibilities. 'keep in touch with the gateway and send/receive JSON messages. If you lose connection, pause the game loop and keep trying to reconnect or (something I dunno)'. All the game server really needs to do is run world simulation logic... but this isn't physics logic at all. It's more 'player has entered room X. run scripts on any NPCs in room X that trigger if a player enters the same room as this NPC.' Or 'combat is occuring between players A and B. keep track of auto-attack intervals' or 'Player C has died. teleport them to room Z'. It needs to have a fairly sizable amount of objects in play. Lots of timers ticking away. But it also needs to be pushing changes to a database fairly regularly. And databases and async seem to have an uneasy relationship overall.
(Note: the game server doesn't necessarily need to be implemented in Python. but the gateway is already running in it so...)
I'm fishing for some advice on what approach I might want to take for the game server and why.
@prisma heart You need to do different things in your onhover if hovered is true or false
@spiral shale don't use semicolons apparently lol
start here I think: http://programarcadegames.com/
Another alternative: https://learn.arcade.academy/
@barren torrent take a look at some existing MUD frameworks built in Python like https://github.com/evennia/evennia
Listen to them, I just got here haha
@prisma heart
if self.area.collidepoint(mousepos):
if not self.hovered:
# Play sound here
self.hovered = True
I think something like that might help.
Only play sound when you transition from NOT over, to over.
Volund, what you've described is a bunch of different things. for your "intervals", somewher down the line you need a player tick function, I'm not sure where in your architecture this sits, but somewhere near to whateve'rs handling server-side player state, you'd have a tick function that deals with anything tick-based like combat. this can be an asyncio periodic task. you can either DIY this and put an async sleep in a while True loop, or use whatever is part of your async framework (like Tornado's PeriodicCallback)
The last MMO backend I made was based on Tornado, what I had was a whole bunch of NPC nodes hooked up to redis, and using aioredis in tornado for async communications. each node would pick up a bunch of NPCs from the entity pool (a list in Redis), and begin processing NPC logic. Each instance had its own PerodicCallback running a tick function
everthing was pub-sub between NPCs and player nodes over redis, segregated by map chunk. In a MUD, it would probably be per-room (if you go with this pub-sub approach)
I like this because it's nice and scalable
but maybe you don't need so much infrastructure for a MUD...I'm not sure, haven't looked at the processing requirements
so I guess consider this two ends of the spectrum: one large asyncio loop with however many tick functions as you have NPCs that need to do anything (tick rate is probably very slow when NPCs are idle); other end of the scale is everything linked together by a message broker
@frozen knoll I tried something, still the same results. Obviously because while I'm hovering over the button, the sound will keep playing until I'm not
` def onhover(self, mousepos):
if self.area.collidepoint(mousepos):
self.hovered = True
else:
self.hovered = False
if self.hovered == True:
self.colour = (250, 150, 30)
hoverclick = pygame.mixer.Sound("assets/sounds/click3.ogg")
hoverclick.play()
else:
self.colour = (150,30,30)`
what you said about "player C has died, teleport them to room Z" is a different matter. this isn't just about infrastructure but also how your event system works. One option is to have player and NPC nodes broadcast events, and have some rules instance listen to events and perform those actions. The other option is to house those triggers/events within the player node. Up to you really
I still don't understand how to trigger on "transition"
def onhover(self, mousepos):
if self.area.collidepoint(mousepos) and not self.hovered:
self.colour = (250, 150, 30)
hoverclick = pygame.mixer.Sound("assets/sounds/click3.ogg")
hoverclick.play()
self.hovered = True
else:
self.hovered = False
self.colour = (150,30,30)
Use the boolean. If you are transitioning from not hovering, to hovering, then play the sound.
...actually, that code's got an issue.
def onhover(self, mousepos):
collide = self.area.collidepoint(mousepos)
if collide and not self.hovered:
self.colour = (250, 150, 30)
hoverclick = pygame.mixer.Sound("assets/sounds/click3.ogg")
hoverclick.play()
self.hovered = True
elif not collide and self.hovered:
self.hovered = False
self.colour = (150,30,30)
Maybe that.
Yay! Happy to help.
So I was on the right track using two conditions, I just needed to not be an idiot lol. Thank you very much. :)
The first version you had triggered 60 times per second. The second version here should only trigger when we transition. We use the boolean 'hovered' to track that.
I see, we move onto the button when "colliding" but "not hovering" and move off when "hovering", but "not colliding"
Jesus christ, I'm too old for this ๐
Nah, you got it.
Anyway, got to step away from discord for a while and get work done. Hope you have a great day.
You too, friend. Have a great day :)
I'm baaaack
meseta: yes I'm very aware of Evennia.
I know all about it. I've torn it apart several times and am now doing my own take on the subject. ๐
very nice
Hmmm. redis... I'm not really familiar with redis...
the takeaway I got from your answer though is 'async is not a bad idea.'
though I'm still trying to wrap my head around the idea that there can be a game server that doesn't have the entirety of its state all in memory at once. This idea of keeping things in something like redis kind of confuses me because now I have a ton of copies of the data all over the place.
Is there any way to get rid of this sound delay using mixer?
I know for sure that it isn't the audio itself that is delayed; I was the one to trim it.
@barren torrent you're right in that there's no single game state. but the point here is that you don't actually need a single game state
MUDs are highly asynchronous - there isn't a lot of determinism happening. it's not like a platform fighter where millisecond inputs need to happen all at once to keep things "fair". MUDs are pretty loose (MMOs are too), if your attack happens a few seconds sooner or later, it probably doesn't even matter
so you can get away with not having a single game state in one place. In fact, players (and NPCs) really only care about "observable game state" - MUDs can be vast. players and NPCs don't really care what's going on on the other side of the MUD world, they can't interact with it
I am also quite positive that it is not the if statement being reached too late as a normal print statement executes immediately. I also figured it could be me loading the sound each time so I tried loading it at the start of the program but that did not make a difference.
all they really care about is what's happening near them, probably in the same room as them
and so what you can do is distribute your processing and communications across different rooms. Everything in one room can communicate with each other and share state
the server is authoritative - in fact with MUDs, client has zero authority ever. Everything is server-side. So what the server determines is the case. you don't have to worry about desyncs, you don't have to worry about input validation. Player sends commands to server. Server performs the action and sends results
in practice what this means is that your player node - the thing that handles player state, whether that's an actualy separate process, or just an async loop inside a player class; that contains the player state, and it also observes the state broadcast from other entities
Okay, so I initilized pygame.mixer and that seem to have solved the delay issue. Thank you guys anyways.
you can pretty much leave it to your player/NPC nodes to handle rules and validation. I'll give you a simple example: Player and NPC are in a room together. their processing nodes are subbed to the same room pub/sub channel so are broadcasting state updates to each other
player initiates an attack on the NPC. for the purpose of this example, the attack processes immediately (no attack delays, or attack timers)
exactly how you implement this is up to you, but what could happen is player node issues attack action to NPC, this can be done via pubsub, or could go directly via addressed message via broker, however it does it, player node tells NPC node "I attack you with sharp blade, strength 10, base damage 5; in room A; this attack's ID was <unique ID>"
Huhhhhhhhhhhhh.
NPC receives the message, and checks a few things: is NPC still in room A? if NPC in that time moved away, it fails the attack and responds "attack <unique ID> missed"; otherwise run some calculation for damage done, adjust HP, broadcast "attack <unique ID> hit for x damage", adjust aggro state, etc. etc.
so there isn't a single game state, but each entity is in charge of their own state. The NPC is never able to die twice, because it is processing these incoming attacks serially, and if it's dead, it'll never accidentally process another attack that was queued up and die again, it'll just say "attack <unique ID> failed, reason: already dead" or something
I don't really know the formal language to describe this situation, but it's not that dissimilar to how lag compensation works in FPS games
Not sure if my system is so simple as that; I have some pretty weird ideas - but I get what you're saying
right yeah
with FPS games, there technically isn't a single game state across all clients either. lag compensation for those kinds of games typically means that the server is taking your lag into account, and validating your shots against the position of other players at where it thinks you saw them on your screen given your network latency. So in effect, the server is playing out the game with slightly different versions of the game state for every player
this results in what some players think is "unfair", since they might feel like they were shot after they dived into cover; but it's because on someone else's screen they were in the open, and that person pulled off a successful shot while they were in the open on their screen, and the server decided that this was valid
no, they can't send that because the server handles that logic
the player sends the server commands to "attack enemy" the server holds the player's state, and knows what weapons a player is holding
remember, this is a MUD, so there's no client-side logic happening. everything is on the server
the server doesn't accept any messages that look like "sharp blade, str 10000", it only accepts the command "attack npc"
at which point the server creates the correct attack event descriptor based on what weapons are wielded, and player stats, none of which come from the player client
even if this were a graphical MMO game, the situation would be similar - the player client send message to server node "player placing attack on npc with equipped weapon", and server node looks at what's equipped (server node is authoritative over player inventory and stuff) and figures out what the stats are
player client could be hacked and have a giant-ass sword spawn into inventory, and then issue the command "equip slot 9", the server will simply say "no item in slot 9, wot you on about?"
this is the benefit of server authority. with MUDs, there's no option for hacked clients anyway, because the client is basically a dumb text terminal (with colours, and cosmetic addons I guess these days)
placuszek: Yeah thankfully that's not how MUD/MUSH works at all
in MUD, the player types 'attack X with knife' and the server figures out what that means. the server is fully authoritative and all that players get to send to it are text commands
yep yep. ๐ MUDs are great like that
So you think I should proceed with an async engine design? Just need to figure out my database approach then...
I think it's an ok option; you'll want to do some performance monitoring to make sure you're not lagging when your async loop can't handle everything in time, but actually with MUDs even that's not such a big deal
Well
The glorious thing about the way I've split the project up.... the gateway process is a genius piece of work (as long as it DOEs in fact work - I think it will, but it's not 100% proven yet). The asyncio gateway process that handles telnet and etc... allows the game server to hook up as a websocket client, and then it multiplexes player activity over that connection by sending JSON back and forth.
This means that the game server only needs to support Websocket Client, ANSI text rendering, and JSON.
So I can, and probably will, write more than one.
(The gateway can even link up multiple game servers at once.)
sure, JSON works. the implementation I was using actually sends JSON-RPC between client and server; and then it's not quite JSON-RPC but a lot of the same fields over pubsub
JSON is great for this
The reference game server is probably going to be more of a social/freeform RP game for some tabletop hijinx like Exalted and World of Darkness and etc.. but there are a few long-lived MUDs that I actually would like to modernize/port. Those projects... it's hard to say if they're gonna use Python or not. C++, C#, Go, or Rust are also viable candidates to varying extends. (though I'm least enthused about Rust)
Async in Rust is a hellish headache too
It's very very powerful and efficient, no question there.
But oh dear god I wouldn't want to write something like a game server in it.
Particularly as you need to be able to make rapid changes.
I'm sorry what?
O_o
This may sound stupid but are you absolutely certain the version of your software and the documentation matches?
I have 1.9.6, so yes.
well it says 1.9.6 on it
you might want to go check the source code in that case
I have fixed the issue, I had to use one of the loaded sounds; thought it would change the general sound just like mixer.music but appearently not.
# Correct
loaded = pygame.mixer.Sound('sound.wav')
loaded.set_volume(0.5)
# Incorrect
pygame.mixer.Sound.set_volume(0.5)
..... ohhhhhhhhhhh
I must say it was not very clear in their docs though. https://www.pygame.org/docs/ref/mixer.html#pygame.mixer.Sound.set_volume
LOGIN IS WOOOOORKING. Yay!
Hi! Can one make a 2d game with a pygame, which is not to slow and doesn't suck :). Sorry for stupid question!
there are some very impressive examples with it
@proper peak can you please send some links with examples?
@naive abyss Here's one:
https://discordapp.com/channels/267624335836053506/660625198390837248/708861249286307900
Is there a reason to keep to PyGame1, or are the 2 builds okay to use?
Like, how buggy is it?
@proper peak yes i know this dude, i did watched some of his videos. But it seems that only he has a some what good game going one. Are there some other examples?
Hello, not sure if this is in the appropriate place, but I need some tips. In short I'm interested in creating some virtual environment similar to a chess board, where I will be having one "robot" which I can command to "move forward, turn left etc" and some other obhects with 1-2 attributes such as color, shape, etc
Now obviously I want this whole business to be viewable and update the screen as soon as something moves
But I've no Idea were to even begin
Would you say this sounds like something relatively simple or something that might take a large amount of time?
I'm working on an NLP application where you can tell or query a robot stuff and it was suggested by my supervisor I might be interested in creating something like this instead of messing with complicated virtual environments with physics engines etc
How much programming experience do you have? Are you just starting out or do you already know Python basics?
I'm doing a MSc in Data Science, but I've only done a "game" using Processing in my BSc
so I've done OOP some time ago, and I've been neck deep in python the last year ๐
I've been watching a tutorial on a pygame package, it sounds like it might suit my needs
Any other packages I might want to look into before I commit to this one? @frozen knoll
@last thunder you should also check out arcade https://arcade.academy
Pygame, Pygame Zero, Arcade, Kivy, Pyglet, are all legit options.
I like Pygame, and created Arcade trying to mimic the simplicity of Pygame. Even with Pygame being simple, when I taught programming with it there were still things that students kept running into problems with, that were Pygame issues. So Arcade eliminates a lot of that.
I get students to develop much more advanced games in one semester now than I did with Pygame.
So my biased opinion is it is a better choice. But clearly from the excellent work other people have created with the other libraries, they are also perfectly good choices.
Is there a reason to avoid Pygame2 nowadays, or are the builds stable enough already? One can't read a StackOverflow answer about Pygame without a comment about some Pygame2 feature that's better than the Pygame1 alternative in literally all the ways, so it seems to be quite good feature-wise ๐
Might as well start using pygame2. It's true that it's superior in many ways. It has been stable enough so far.
Are there any breaking changes?
2.0 are meant to be 100% backwards compatible as far as I know
It's mainly about moving from sdl to sdl2 + cleanup + optimizations
.. and bugfixes of course. There have been several bugs in pygame lingering for a few years
nice, probably going to update then
why is it still marked as a dev build at all, then?
(as in, not automatically distributed when you do pip install pygame, for example)
It's incomplete I guess. Might be some bugs. Still it's pretty far out in the development. I'm sure a dev11 will appear soon as well
add --pre option to pip for the last pre-release
You can always be a bit conservative about using new features so you can revert to 1.9.x
i havent really red docs or much of anything about pygame, but is that a 2d only engine?
also, would this channel be fine for openGL, which is what I'll be using.
Oh, you should use moderngl.
how come?
Paul, you should say arcade.gl now ๐
Or that. Pygame isn't really centered around opengl. You can do it, but that's not what the library uses much internally.
oh, i was just asking about pygame, unrelated
i want to do as much as i can from scratch tho
It is great if you are interested in old-school bitmapped stuff.
Ive been using Unity for 2D paltformers and such with pixel type graphics
Arcade isn't bad for OpenGL or 2D stuff.
but i want to move more to 3D
No Python library really has the GUI Unity type graphics.
sorry i confuesed you
Yeah, my goal is to move towards 3D, doing as much as I can from scratch, and If i feel that is too tedious, i will move towards something like moderngl+pygame or opengl+tkinker
but i think ill need open/moderngl either way even if working from scratch
If you want to stay low level using 3.3 core+ I think moderngl is a good start
Arcade's arcade.gl module is a subset of the moderngl api. Can also be an option, but we need more docs
I think ill start with moderngl, also just joined the moderngl discord ๐
do i need anything else, or can i just use moderngl?
An easy start is using moderngl-window
All the moderngl examples are using it. There are examples in the moderngl-window project as well
thanks. ill tell you how it goes!
+1 for moderngl. If you want something higher-level, you can check out Panda3D.
or pyglet if you just need batch drawing of simpler geometry with no need of shader customization
I was surprised to find a channel for game development in python
Games are awesome.
there's a really cool game engine in python
it's a simplified version of Panda 3D
i think you've already heard of it
Ursina Engine
but i want to know if there is any famous game that's actually made with python
just curious
does anyone use unity here?
Mhm. I use unity 2D.
Isn't godot atleast somewhat python based (as scripting language)
Is anyone familiar with the pygame-ai library?
Because I can't find a way to get a npc's position or to stop it from going off screen
@frozen knoll Arcade does indeed seem like a neat library. do you have some tutorial to suggest?
If you are new to Python: https://learn.arcade.academy/
Otherwise check out, in order, the tutorials on the Python page: https://arcade.academy/
!^%#&@)(:"?<>.,+_/-
I have a question
I'm trying to make a solitaire game with pygame
i have made a Class Card and every card is an instance of the class
every card has a colour (if it is red or black) and a number from 2-14
i have put all the card objects into a list and then shuffled
now what is the best way to continue the game?
I've got a solitaire tutorial here:
https://arcade.academy/tutorials/card_game/index.html
While it uses Arcade instead of Pygame, a lot of the concepts on data-handling with the cards is the same.
Might be worth a look-through for ideas.
It is like Pygame, a 2D graphics library.
How do i check the bottom cards together at the beginning to see if there is a valid move?
I'd break the problem down.
First, make sure you can print the two cards correctly.
I have created a Card class and every card is an instance of it. But then when i put all the cards(instances) inside a list in order to shuffle the cards, then I cannot access the card's variables from the list. Is there any idea?
If the object is in the list, you should be able to access the attributes.
You might be running into an issue where you aren't getting pop ups, like in pycharm or vs?
That would be because once it goes into a generic list, it doesn't know it is an instance of the card class when you pull it out.
You can still use the card attributes, you just don't get the pop-up code completion in your IDE.
self.deck = [hearts_2.card, hearts_3.card, hearts_4.card, hearts_5.card, hearts_6.card, hearts_7.card, hearts_8.card, hearts_9.card, hearts_10.card, hearts_J.card,
hearts_Q.card, hearts_K.card, hearts_K.card, clubs_2.card, clubs_3.card, clubs_4.card, clubs_5.card, clubs_6.card, clubs_7.card,clubs_8.card, clubs_9.card,
clubs_10.card, clubs_J.card, clubs_Q.card, clubs_K.card, clubs_A.card, diamonds_2.card, diamonds_3.card, diamonds_4.card, diamonds_5.card, diamonds_6.card, diamonds_7.card,
diamonds_8.card, diamonds_9.card, diamonds_10.card, diamonds_J.card, diamonds_Q.card, diamonds_K.card, diamonds_A.card, spades_2.card, spades_3.card, spades_4.card,
spades_5.card, spades_6.card, spades_7.card, spades_8.card, spades_9.card, spades_10.card, spades_J.card, spades_Q.card, spades_K.card, spades_A.card]
random.shuffle(self.deck)
Then I want to access the attributes of the first item in the deck list, but i can't
i want to access the instances of self.deck[0] for example
self.deck[0].my_attribute
Should work.
Or do you need to add the full card?
self.deck = [hearts_2, hearts_3]
[meta] You can use a service like pastebin that makes it easy to post your code. Nicely formatted, easy to copy. https://pastebin.com/
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.
you need to pass the deck to the check function
and then you can do deck.deck[0] to get the first card
By doing this: self.deck = [hearts_2.card
You are ONLY adding the image to the deck. Not the entire card.
You need to add the entire card.
self.deck = [hearts_2,
Then you can access the members in the card.
(Side note - Eventually, if you refactor to using lists, and split the card value from the suit, you could eliminate about 80% of the code. But don't do that until you've got a version that kind of works, and you save a backup.)
Well, I know that this is a simple question but
Im creating libraries with different users and random scores just for learning purposes
There are two keys inside these libraries: one for the nickname, and another for the score
and all the libraries are inside a list
but I don't know how to sort it by the score, putting the highest score in the first of the list
Can someone help me?
Here is the code
from operator import itemgetter
info = {}
players = []
for c in range(0, 4):
info["name"] = f"player {c + 1}"
info["score"] = randint(1, 100)
players.append(info.copy())
for p in players:
for k, v in p.items():
print(k, v)
print()
for d,p in enumerate(players):
ranking = sorted(p[d].items(), key=itemgetter(1), reverse=True)
```
You are doing this a very strange way
You are making a list of 2 item dictionaries
A much better way would be to make a dictionary where keys are names and values are scotes
Use this for sorting them, note the bit at the top is what's accurate for current versions of python
Since dicts are ordered by default now
This is how I did in my first try, but after I wanted to add more informations about the user, and got stuck on that
Do you plan on making functions that change/use information about the user?
If so then a class would be best
But otherwise yes a list of dicts would be a good approach
You can sort the list of dicts like this
WOH! that's what I was looking for!
You don't want to loop through players, but just sort is based .info["score"]. The easiest is to create a function for 'key' in sorted()
what do you mean by creating a function for key?
First time doing these things so Im rly confused
The built-in function sorted takes a keyword argumemt key that takes an item from the iterable, and returns the value to sort by
a lambda or a function or operator.itemgetter. all of them work
It's exactly what the solution I posted earlier did
Are there any good resources there for making sure your game is good even if it's text based?
I'm making a bitlife clone and when I asked about GUI the general channel went on a riot so I decided to go text based
Solitaire stuff so far
cards are duplicated because I'm just finding out where I should put everything
made the card sprites with help from a friend of mine
I'm trying to make Joker card sprites but I just don't know what to do
Hey @jade owl!
It looks like you tried to attach file type(s) that we do not allow (.zip). We currently allow the following file types: .3gp, .3g2, .avi, .bmp, .gif, .h264, .jpg, .jpeg, .m4v, .mkv, .mov, .mp4, .mpeg, .mpg, .png, .tiff, .wmv, .svg, .psd, .ai, .aep, .xcf, .mp3, .wav, .ogg.
Feel free to ask in #community-meta if you think this is a mistake.
ummm hi
i need help
with something
how do i make a function that will repeat itself every 1 second?
pygame?
@mental aspen
you can make a event by doing my_event = pygame.USEREVENT + 1 and then you can give it a timer by doing pygame.time.set_timer(my_event,1000) #1000 refers to the amount of milliseconds
end then, in the main event loop (pygame.event.get()), you check if event.type == my_event: and then your function
I really wish I knew about Arcade when I made my first game like a year ago, would've made the process a lot easier with the detailed tutorials and everything\
How can I do a linear interpolation for vec3s without scipy? What I want is : A = Vector((0,1,0)) B = Vector((0,0,1)) A.linear_interpolate(B, t) thats just some psuedo code from GODOT but obviously need it with python
Numpy's linspace accepts vector endpoints, I believe.
wait, that's not numpy vectors, nevermind.
though it may still end up the best idea if there isn't a native solution, so:
In [44]: np.linspace([0,1,0],[0,0,1],5)
Out[44]:
array([[0. , 1. , 0. ],
[0. , 0.75, 0.25],
[0. , 0.5 , 0.5 ],
[0. , 0.25, 0.75],
[0. , 0. , 1. ]])
Oh yeah no problem I can make them numpy vectors. Just can't use scipy. Great, I will give that a shot! Thank you ๐
Yay, glad it helped you ๐
you could check for a hit, then restart the level (or whatever you want to happen)
what do the enemies and the player look like?
squares,i just started pygame today
kk
what you could do is check if the points of the enemy rectangle are inside your rectangle
i know im a noob but how do i do that
one sec
with the rect "player" and the rect "enemy", you can do if player.colliderect(enemy): and then your code to react to the collision
@mental aspen
sure
do ii need to import anything?
nothing but pygame
i choose to not make a dodging game afterall,but i will test it out today in another project for sure!
im doing this game as a college project,even tho im not in college but those projects prepare me for the future
nice
first there was basic python,basic node.js and now pygame project
ah
literally a chapter is just an introduction to pygame and then saying "welp go make a game and search everything up cuz we did not teach u"
lmao
wow
lmao
final problems to solve:how many apples does bobby have?
anyway, goodnight :ยฌ)
good night too ^^
to be fair, knowing how to search everything up is the most important skill
hello
i just need help with actually getting pygames onto my computer
because it doesn't seem to work
What are you doing to install it @desert panther?
also note that you don't run pip inside Python itself; you run it from your system cmd console
(this is a common mistake, a lot of people trip over this one)
thank you
That work?
What error did you receive?
'python' is not recognized as an internal or external command,
What do you get if you type py -0p
It seemed to do something
try running python3 -m pip install --user pygame
It helps if you tell us what that something was :D
You might not have the command set as python but rather python3
ill try
py -m pip install --user pygame may also work
it says python3 is not recognised
YES
@round obsidian
it worked
thank you :)
ok, good
one ore thing:
py -0p will list the path to the Python interpreter
you'll need to use that path to launch Python so you can invoke scripts properly with it that use Pygame
e.g., if it's C:\Python3\python.exe, you need to run a Python script by invoking it with C:\Python3\python.exe script.py
It may also be possible to just use py script.py
but if that doesn't work, the other fallback should work
perfect
thank you
i'll work on a game tommorow
also
is trinket.io a good site to use to save my work?
@round obsidian @deft spindle
I haven't used it, couldn't say
Was there any reason you'd not want to save it locally?
You can just save files on your computer
Just like you'd save a text file or an image file
All of your work has to be in a .py file for it to run using the python interpreter
No you can just save it using a text editor
IDLE is the IDE/text editor pre-installed with python. Popular text editors would be Sublime Text, Visual Studio Code, and PyCharm
Oh okay
Think of them like a notepad that has syntax highlighting and other useful features
I see
thank you
ok
sorry to bother you
but one last time
how do i make something run in sublime text
@deft spindle
You have to install it first
Oh I see what you're saying, you want to run a program you typed up in Sublime
Sublime Text 3 has the option to select the build so you can display the terminal output. Go to Tools > Build > and select Python
y'all have any recommendations on pyglet/openGL guilds?
https://gafferongames.com/post/fix_your_timestep/ I was going over this, to anyone who used pygame I was wondering how I am supposed to save the state of my game for currentState and previousState. This is for framerate independency
Introduction Hi, Iโm Glenn Fiedler and welcome to Game Physics.
In the previous article we discussed how to integrate the equations of motion using a numerical integrator. Integration sounds complicated, but itโs just a way to advance the your physics simulation forward by som...
Hello, I'm using pygame to create a virtual world using object oriented programming
This is my world, each shape is an object, and the cyan one with the yellow radius is the one the user controls. Each object has some attributes such as speed (how much it moves with each button press), range of view (the size of the yellow circle) etc. Is there someway where I could create a menu or some on screen sliders to adjust these values while the game is running?
hmm that sounds like a neat native solution. I'll look into it if I have some more time
where do i port my gif files?
i think i made a mistake at the start because my files got deleted from my computer and i want re add it
do i drag the file inside the py file?
no
or just a folder
in the same folder
ah
as the .py
lemme try that
or you can get it from another folder if you give the full path
it works tysm
np :ยฌ)
do u wanna see it
sure
alright lemme inv u
hi
how do i make the beggining x position of an enemy be random?
like i want the enemies to drop out of the sky from random places
What library are you using? Arcade? Pygame? Kivy?
So, I'm trying to run a simple print program on sublime, and it says Python is not recognised as an internal or external command
Any ideas on how to fix this?
@desert panther , what os are you using?
sublime lol
@desert panther Run the python installer again, click modify, then go through and when you see the check box that says "Add python to enviromental variables" click that
^^
thank you
what you can also do is (for windows) type "env" in the search bar, and then click on "environment variables"
dw
thank you
perfect
you can add python to the env variables manually
if you don't do @lament lotus 's method
thanks :)
np, have you got it working?
:ยฌ)
:)
Hey!
I need someone who can create graphics for my game.
Its an arcarde runner and my screen resolution
Iยดm using PyGame and need:
- a character [~60x150px, walking animation - 2-4 images]
- a soft background [1366x768 yeah i know... wired]
- a foreground [1366x~310]
I wont pay something and if you do it (youre bored??) you can send me an pm with the pics.
Thanks! Here the old grphics (i know... bad): https://github.com/Flynni123/game_assets
Maybe add an open license to your project if you are reaching out for help.
i cant wait to be that good at phyton, I just started learning it lol
I'm writing a very simple text RPG for learning purposes, and trying to implement DoTs in. I'm tracking statuses under a property of the player or enemy (enemy.status_effects = {}) as a dictionary that contains dictionaries named after the spell. I've got it adding the effect, using it to do damage, and decrementing it's duration, but when I go to remove it, I'm receiving a "RuntimeError: dictonary changed size during iteration"
I've seen this is in python3, and a suggested solution is using dictionary comprehension to remove them instead, however couldn't find specifics for a few other points.
1: I'm already iterating through the list with for debuff in theEnemy.status_effects:I'm assuming I need to do a list comprehension after this to filter 'expired' debuffs, but just want to verify it can't be done inside.
2: the examples of list comprehension i've seen for removing elements does not have examples of filtering based on elements inside another dictionary. The current format I have is: character.status_effects = {'Rot': {'damage': 60, 'duration': 5}}
Appears (from general) {key: value for key, value in theEnemy.status_effects.items() if value['duration'] > 0} returns a list that filters out anything with 0 or less duration.
Please Help Me ASAP i WANT TO MAkE A 2D GAME USING PYTHON PLS DM ME THE CODE THANK YOU
from the scratch pls
python code for a basic 2d game
pygame.init()
WIDTH,HEIGHT = 500,500
screen = pygame.display.set_mode((WIDTH,HEIGHT))
BG_COLOUR = (255,230,230)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
break
screen.fill(BG_COLOUR)
pygame.display.update()
there's the basis for a pygame game
oh thank you so much buddy
Lot of examples here: https://arcade.academy/examples/index.html
^^
what should i use for graphics and all that stuff like main screen character choosing and all
Start simple.
Like open screen. Get something on the screen. Move it.
If you aren't familiar with programming, this kind of steps from the start: https://learn.arcade.academy/
okay okay ill get to work
i know how to create lists tuples dictionary loops conditional loops user defined functions file handling fraphs and all using python
Then just looking through the examples might be enough.
Take one, start modifying it.
Those links use the Arcade library. If you want to use Pygame there are links here: http://programarcadegames.com/index.php?chapter=example_code
Both are good libraries, but I think you'll get further, faster with Arcade.
yh
how do i download python? i really want to learn code but i really dont know how
is there any videos u would recomed for bennginers?
personally, I would recommend sentdex's tutorials
okay thanks
is there any videos u would recomed for bennginers?
@torn scroll I watch Mosh's Python course
Combo text and video: http://programarcadegames.com/
That uses pygame.
This uses arcade, but the videos arent for every chapter yet: http://learn.arcade.academy/
what can u do with code once youve wrote it?
Export
ya but can u make any \thing with it?
i mean you're in #game-development, so i'm guessing you could make games
^^
i mean i have no idea how to even code yet soo
pick a tutorial and stick to it
okay ima start watching em
hey what do i do if when i load up pycharm it does not let me choose the python interperter?
What is the best python module to make games with?
hey what do i do if when i load up pycharm it does not let me choose the python interperter?
@torn scrollCtrl+N, Tab over to theActionssection, typeInterpreterand go through those options until you're in that window that has a gear icon next to the Python drop down menu selection thing, which lets you create a new interpreter.
Hello all. I hope you have a great day. I feel confident with the basics of python and now I want to study game development with python. Any suggestions for a book/course?
@solid root https://arcade.academy/
thanks
apologies for spamming the channel, if this could be considered that, but I just posted this in the careers thread, but it's probably more suitable here:
"Hi All, I just joined the server, I have some professional experience in python from some years ago when I worked at a VFX studio, but the last 5 years or so have been in game dev and as such a lot of c++/c code as well as domain specific stuff such as shader languages and even gpu assembly (yes, it gets hairy at times). However I'm thinking of making a lateral move from graphics and engine programming to more gameplay centric topics, and as such scripting langs are common in job specs. I understand that these scripts are probably interpreted by a c++ engine rather than any tech being built in python itself. Does anyone here have any exp of gameplay programming at a studio? Or know someone who does and would be kind enough to introduce me? Thansk
Thanks, even"
Disclaimer : I'm not working in a game studio, but I know pretty much how they often organize, especially studios working with the unreal engine Scripts languages are often interpreted by a VM, which make them a ton slower than pure programming, using C++/C#, so they aren't used to be build the engine itself, neither for the core mechanics
Most of the users of those scripting languages are actually artists (most of the time level designers) that need a quick side mechanics for their scene and don't want to learn a fully featured programming language
@fervent rose Hey, thanks for the response, yeah anyone with any experience will know that python is absolutely not suitable for things with very tight time constraints like engines. As for Unreal there used to be "Unreal Script" for UE3 but UE4 uses this horrible visual scripting style thing called "Blueprints", which yes are usually put together by well meaning designers but my colleagues spend most of their engineering time debugging them
I personally like blueprints ยฏ\_(ใ)_/ยฏ
I remember a live training that taught you how to keep your blueprints manageable
i like them, as long as you know what you;re doing with them and me and two other people don't have to spend a whole day unpicking your mess
