#game-development

1 messages · Page 4 of 1

neon tinsel
#

@fallow glade this is what I want to avoid

@dataclass
class Rank:
    name: str
    wage: int
    work_dialogue: list
    emoji: str
    price: int
    description: str
    perms: list

    def work(self):
        return random.choice(self.work_dialogue)

peasant = Rank("Peasant", 2500, ranks['peasant']['responses'], ":palms_up_together:", 0,
               ranks['peasant']['description'], ranks['peasant']['perks'])
farmer = Rank("Farmer", 10000, ranks['farmer']['responses'], ":basket:", 10, ranks['farmer']['description'],
              ranks['farmer']['perks'])
citizen = Rank("Citizen", 25000, ranks['citizen']['responses'], ":busts_in_silhouette:", 45,
               ranks['citizen']['description'], ranks['citizen']['perks'])
educated = Rank("Educated", 60000, ranks['educated']['responses'], ":book:", 100, ranks['educated']['description'],
                ranks['educated']['perks'])
cultured = Rank("Cultured", 130000, ranks['cultured']['responses'], ":money_with_wings:", 250,
                ranks['cultured']['description'], ranks['cultured']['perks'])
weathered = Rank("Weathered", 240000, ranks['weathered']['responses'], ":mountain:", 500,
                 ranks['weathered']['description'], ranks['weathered']['perks'])
wise = Rank("Wise", 375000, ranks['wise']['responses'], ":trident:", 1000, ranks['wise']['description'],
            ranks['wise']['perks'])
expert = Rank("Expert", 1000000, ranks['expert']['responses'], ":gem:", 10000, ranks['expert']['description'],
              ranks['expert']['perks'])
#

It just becomes a mess

#

Obviously this isn't the way to do it

woven canopy
#

In that example yes. I personally don't liek the variable name surface myself either

dawn quiver
#

that is why I had asked lol

fallow glade
#

Or any preferred format

#

Even a new one you want to create

neon tinsel
#

And then I would just loop through the document?

fallow glade
#

Precisely

neon tinsel
#

How do you access the items then without a variable reference?

fallow glade
#
class Level:
    attributes like enemies, treasure spawns, terrain data, decoration objects, soundtrack playlist etc

def load_level(level_number):
    with open... 
       ... 
    return Level(...) 

def play_level(...):
     ... ```
#

Do you need fo access the individual items?

neon tinsel
#

I'm not necessarily making levels

#

They're items for a discord bot

fallow glade
#

Well even a single level is fine

#

you can access it from the Level object

#

Which can contain lists or dicts

#

Server.memebers: dict[int,...]

normal silo
neon tinsel
#

Here was my old approach:

class Rank:
    ranks = []

    def __init__(self, name, wage) -> None:
        self.name = name
        self.wage = wage
        Rank.ranks.append(self)

    def __repr__(self) -> str:
        return f"Rank: {self.name}\n" \
               f"Wage: {self.wage}\n"
rank1 = Rank(...)
rank2 = Rank(...)
rank3 = Rank(...)

# If I want to access a certain rank I either loop through the ranks list or just call the rank from its variable
neon tinsel
normal silo
#
peasant = Rank("Peasant", 2500, ranks['peasant']['responses'], ":palms_up_together:", 0,
               ranks['peasant']['description'], ranks['peasant']['perks'])
#

By default the description is just ranks["name"]["description"], etc.

neon tinsel
#

Okay, that could be simplified I suppose

#

But I still don't know how that would solve the problem of creating multiple lines to make instances of the ranks

normal silo
#

When you have multiple of something -> list.

#

If for example you have N peasants, you have a list of them.

#

If they are not unique then you can just generate them in a loop.

#

If they each are unique then that is similar to loading a level or stage / setup.

#

For that you can either just have a bunch of Python lines for each, or load via some external file format, such as a toml file for this.

neon tinsel
#

So I have a dictionary of all the ranks

#

A json file actually

#
"peasant": {
    "wage": 2500,
    "emoji": ":palms_up_together:",
    "price": 0,
    "responses": ["You actually manage to scrape up some bits. How wonderful.",
      "Someone donated a little more than normal. How kind.",
      "You are a peasant. Feel bad."],
    "description": "Born into the lower class, destined for the upper class.",
    "perks": ["-beg"]
  },
#

Structured like that

#

So I can fix the default stuff

#

So when I want to generate these and use them in my code

normal silo
#

Is every peasant the same and you have multiples instances of them, or multiples instances and each has an entry like that?

neon tinsel
#

One instance of peasant

#

Its there to hold data so I can match the users discord role with the roles here

normal silo
#

Wait so what is the issue?

neon tinsel
#
rank1 = Rank(...)
rank2 = Rank(...)
rank3 = Rank(...)
#

I end up doing this

#

Lets say I have 12 ranks

normal silo
#

But how many of those will you ever have? Only 12?

neon tinsel
#

Yeah just 12 for the ranks

#

But lets say for an Items class

normal silo
#

Then it's whatever, just 12~ lines.

neon tinsel
#

Lets say I have 100 items

#

I would run into 100 lines of declarations

normal silo
#

Are the ranks and items loaded from the file descriptions in the json?

neon tinsel
#

Sure, why not

#

Except I do wonder about how I would give items functionality

#

Like how would I store a function in a json file

#

Probably very nooby questions

normal silo
#

You don't you store flags / attributes.

#

For example, "has_health: true".

#

And now the health system can operate with such an item.

#

Your logic checks if the item it's currently processing has health, and if it does, applies the health logic to it.

neon tinsel
#

Yeah

#

Yeah that makes sense

#

But lets say items that do different things

#

For example one item adds 100 extra health above cap and another item instantly gives you +1000 coins or something

fallow glade
#

It's best to hardcode functions

#

In a different module

neon tinsel
#

That would end up being a lot of different functions, right?

fallow glade
#

Yes, depending on function effects

neon tinsel
#

I'm curious to see how games with many items store all the different functions

fallow glade
#

They usually call external scripts

#

They have events such as OnLoad OnHit

normal silo
fallow glade
#

And pass these events to all loaded object functions

dawn quiver
normal silo
#

Or you can have special scripts for items.

#

But breaking it up into systems as much as you can with flags allows for reuse / making new items without adding any new code.

#

Some may still require special scripts just for them.

neon tinsel
#

Yeah

#

I'm thinking for most items I could probably come up with values/flags to tell what kind of item they are

#

but some really unique ones I would just have to add in a function for

normal silo
#

If you are using an entity-component-system model then everything is broken up into reusable systems. Depends on what you prefer. Some just like a script per item.

#

The toml file could for example link to the python file to load and run.

neon tinsel
#

but a general use_item(item) function could sort of go through and check its flags and then apply the values relating to those flags to whatever attributes the player would have affected

fallow glade
#

That can also be an external script

normal silo
#

(For example, many card-game simulators just have a script per card (thousands of script files))

fallow glade
neon tinsel
normal silo
#

The entity-component-system method has more reuse, but requires some more boilerplate to set up.

#

And requires a different way of thinking to an extent / different style.

normal silo
neon tinsel
#

What are the scripts called? Where are they stored usually? I'm just curious about conventional methods and how a well developed directory might be formed

#

Like would you have multiple card scripts per file?

normal silo
#

They are python file, called whatever.

#

Each item has a path to their own script(s).

neon tinsel
#

Dang

#

So an entirely new file per item

#

That's crazy, but it seems very very organized

normal silo
#

One folder with 100 files for the 100 items in your case, easy for multiple devs to add new items in parallel.

#

Everyone can just add an entry to the json and a new script file.

#

Scales well with dev count.

neon tinsel
#

Yeah, makes sense.

#

Would running those scripts involve importing them??

normal silo
#

Yeah in Python you can just import them.

neon tinsel
#

What would that look like for 100s of items though?

normal silo
#

Because it's already a dynamic scripting language.

normal silo
neon tinsel
#

I might be missing a step

#

What is the json file here?

normal silo
#

The one that contains the item descriptions like the ranks.

neon tinsel
#

This is seriously helpful btw

normal silo
#

Flags, scripts file path, image / assets paths, etc.

neon tinsel
#

Oh I see

#

script file paths

#

Okay so here is a rewritten Rank class

#
class Rank:
    list_of_ranks = []

    def __init__(self, name, wage, work_dialogue, emoji, token_price, rank_description, permissions) -> None:
        self.name = name.upper()
        self.wage = ranks[name]['wage']
        self.work_dialogue = ranks[name]['responses']
        self.emoji = ranks[name]['emoji']
        self.price = ranks[name]['price']
        self.rank_description = ranks[name]['description']
        self.permissions = ranks[name]['perks']
        Rank.list_of_ranks.append(self)
#
{
  "peasant": {
    "wage": 2500,
    "emoji": ":palms_up_together:",
    "price": 0,
    "responses": ["You actually manage to scrape up some bits. How wonderful.",
      "Someone donated a little more than normal. How kind.",
      "You are a peasant. Feel bad."],
    "description": "Born into the lower class, destined for the upper class.",
    "perks": ["-beg"]
  },
#

Pulls from a json file like that

normal silo
#

You don't actually need a class.

neon tinsel
#

That's what I'm starting to realize

normal silo
#

Just need the loaded json as a dict of dicts, etc.

neon tinsel
#

Just for the ranks here though. If they had actual functionality I would, correct?

#

Or I wouldn't! Because their functionality would be stored in the script paths! I would only need a class if I were directly changing the attributes of the Items/Ranks, yes?

normal silo
#

Nope.

#

Yeah.

#

If you want to make a new rank, it's just the name, like ["peasant", "peasant"].

#

Two peasants.

neon tinsel
#

and then all of its attributes would be pulled from the JSON

normal silo
#

If you need to know what they do, etc, you can look it up in the dict (loaded json) from the json.

#

And if you want to save on memory, make a list so you can map integer -> name.

#

So you can have a list of integers.

neon tinsel
#

So lets say I've got my User class (this one actually has functionality) and I needed to grab the User's rank's wage

normal silo
#

[0, 0] is two peasants.

normal silo
#

You can do a lookup.

neon tinsel
#

Normally, I would have User.rank be assigned to peasant which is an instance of Rank

normal silo
#

If the wage changes per user, that is each user can be unique, then that is different.

neon tinsel
#

Nope

#

Wage stays same based on rank

normal silo
#

Then User has a rank string set once.

#

In init.

#

Can change the rank to another string too.

neon tinsel
#

and then to access the wage, I just use dictionary indexing

normal silo
#

Yeah.

neon tinsel
#

Instead of dot operators

normal silo
#

(dot operators are dict lookups)

neon tinsel
#

wym?

normal silo
#

You can think of objects as dicts, just with fancy dot syntax.

neon tinsel
#

User.rank.wage == ranks[User.rank]['wage']

fallow glade
#

User.__dict__[User.rank]["wage"]

#

Some number passed in place of User.rank above ^

neon tinsel
#

ranks is the dict

normal silo
#

Since multiple users can all share the same rank, you just keep that info in the loaded dict.

#

They just reference it then.

neon tinsel
#

Yeah, so instead of calling User.rank.wage to access their wage

normal silo
#

Then users can change rank by just changing reference.

neon tinsel
#

I would just call ranks[User.rank]['wage']

fallow glade
#

Yes, and you can do the same for other large objects

#

Like images (not applicable here(

#

sound files

neon tinsel
#

I feel like dictionary indexing could get long though, right?

#

Also, touching back on the Items storing functionality in different scripts, how would I actually call a function from a script path that's stored in a JSON file?

normal silo
#

It's not stored in the JSON file, the JSON file only has a path to the script file.

neon tinsel
#

Yeah

#

Unless I worded it wrong in my question

normal silo
neon tinsel
#

I think I'll take what I've learned so far and try to improve some of my code for now. Thanks for your help guys lemon_holding_back_tears

faint bane
#

game dev in python = weird

tranquil girder
#

no, it's good

faint bane
#

ik

#

but it is

#

weird

tranquil girder
#

how so?

faint bane
#

idk

dawn quiver
#

How would I make a Rectangle move? Should i be using spirtes or should i just use pygame to draw the rectangle?

eternal vessel
#
my_image = pygame.image.load("...")
my_rect = my_image.get_rect() # This will allow you to use (x, y) and other attributes```
dawn quiver
untold sentinel
#

Holy moly XD Its the color and brightness of a glass furnace

dawn quiver
#

I accidentally changed it to that and forgot how, figured it out like 5 minutes after I sent that

#

Also it's not even that bright

quaint fog
#

yo is there a way to tell if a sprite hits the edge of the screen

#

like a built in hitbox function or something

#

in arcade

#
def on_update(self, delta_time):
        self.player_sprite.update()
        if self.player_sprite.center_x > SCREEN_WIDTH or self.player_sprite.center_x < 0:
            self.player_sprite.change_x = 0
        if self.player_sprite.center_y > SCREEN_HEIGHT  or self.player_sprite.center_y < 0:
            self.player_sprite.change_y = 0
#

this is how i did it

#

it works but the sprite goes a bit through the screen but comes back out

#

it doesent take into account the sprites radius

olive geode
quaint fog
#

There wasn’t an attribute for arcade.Sprite.radius but there was a height attribute

#

But I was wondering if there was a built in method to check if the sprite collides with the wall

#

With the edge of screen

quaint fog
#

because i did it like so and it works to some extent, it takes into acount the height using arcade.Sprite.height:

def on_update(self, delta_time):
        self.player_sprite.update()
        
        if self.player_sprite.center_x < self.player_sprite.height:
            self.player_sprite.center_x = self.player_sprite.height

        if self.player_sprite.center_x > SCREEN_WIDTH - self.player_sprite.height:
            self.player_sprite.center_x = SCREEN_WIDTH - self.player_sprite.height

        if self.player_sprite.center_y < self.player_sprite.height:
            self.player_sprite.center_y = self.player_sprite.height

        if self.player_sprite.center_y > SCREEN_HEIGHT - self.player_sprite.height:
            self.player_sprite.center_y = SCREEN_HEIGHT - self.player_sprite.height
#

it works pretty well

#

just that it stops a bit before touching the edge of the screen

#

maybe there is another way?

tiny widget
#

I was shocked by reading that.

#

then realized

eternal vessel
#

Unfamiliar with arcade, so not sure if there is something for the border. But on pygame you have to make it on your own, so I'm assuming you're just going to have to calculate it

torn jackal
#

hello guys i wanted to share you a game I entierly made with PyGame, and which is available on Steam

dawn quiver
#

like fr

torn jackal
torn jackal
dawn quiver
#

i mean, i remember playing those type back when i was young 😔 now i'm 18 year old man

torn jackal
#

Thank you very much

dawn quiver
#

LMAO

#

yessirr

torn jackal
#

If you want to try it ... 😁

dawn quiver
torn jackal
dawn quiver
#

TheCube is a 2D arcade game created by 2 people. As it is the first season, the game is only in English and is going to have a lot of changes (in the gameplay, in the graphics ...) . That's a simple speedrun game where you have to finish small labyritnhs in a short time. For this 1st season, it exists 100 levels. On the 40 first, you have to esc...

Price

$0.99

▶ Play video
#

dang

torn jackal
#

Haha actually know it

#

Yes thats this 😃

dawn quiver
#

🥶 i will see how to use steam on linux

#

i switched to linux just previous month

#

😂

torn jackal
#

Oh bad news my gale doesnt work on Linux 😬

#

Game*

dawn quiver
#

🥶 😂

#

damn

torn jackal
dawn quiver
#

and felt comfortable

#

but sometimes i've to look up on internet for some stuff

torn jackal
#

I am really familiar with rpi and debian so if u want help

dawn quiver
#

dang man

#

gg

#

which os you've used? 🥶

torn jackal
#

Haha ty 😂

#

I used rpi during all my childhood

#

(10y to 14)

dawn quiver
#

wow

#

🥶

torn jackal
#

Yes thats not like windows 😂

dawn quiver
#

haha

#

i've been using windows for past 7 years

#

recently switched to linux & trust me this feels more like tech kekw

torn jackal
#

Broooo thats horrible 😂

#

Do u like the pain ? 😂

#

Linux + Windows 7 🤯

dawn quiver
#

nah nah

#

i mean

#

i used windows os for 7 years

#

and now i'm using linux

#

no dual boot shit

torn jackal
#

Yes both are not very fast

#

Where do u from ?

dawn quiver
torn jackal
#

Yes

dawn quiver
#

I'm from India

#

👀

#

wbu?

torn jackal
#

Oh okay

#

I am french

#

I just wanted to be sure that we werent speaking english whereas we speak the same language 😂

dawn quiver
#

ahh yea yea that's fine

#

kekw

torn jackal
#

I followed u on Twitter 👍

dawn quiver
#

🥶

olive geode
quaint fog
#

So worth = height

#

But yes ur right

olive geode
floral sparrow
#

Does anyone here develop games with Ursina?

cyan viper
#

Have anyone used pygame with grpc for multi user streaming game?

potent ice
loud dirge
#

hello

potent ice
quaint fog
#

Ah ok I’ll join it

potent ice
#

You can ask questions here as well of course

quaint fog
#

Yes thanks

jolly forge
#

from turtle import*
color('red')
begin_fill()
pensize()
left(50)
forward(133)
circle(50,200)
right(140)
circle(50,200)
forward(133)
end_fill()

#

I just started making rpg games using python does anyone have any pointers or like a map of what I should be learning .... please and thank you 🙂

eternal vessel
#

Well it'd be better to use Pygame, Arcade, or Ursina over Turtle, as it's just used for drawing pretty much

shell girder
#

how do i restart my game everytime player wins

#

instead of pressing run again

#

like a loop

#

how can i add a line through the winning combination too?
then make it disappears wen new match starts

#

in my connect 4 game code

dawn quiver
weary jolt
#

me want to learn python

#

where I go?

rigid moth
#

whoops

#

didnt copy the link right

#

thats a dif thing

rigid moth
# weary jolt where I go?

This course will give you a full introduction into all of the core concepts in python. Follow along with the videos and you'll be a python programmer in no time!
Want more from Mike? He's starting a coding RPG/Bootcamp - https://simulator.dev/

⭐️ Contents ⭐
⌨️ (0:00) Introduction
⌨️ (1:45) Installing Python & PyCharm
⌨️ (6:40) Setup & Hello Wor...

▶ Play video
#

anyways I wanted to ask why when rotating an image in pygame with a degree thats not a multiple of 90 that it moves and how I could fix it?

untold sentinel
#

I got a big pack of elemental-spell effects for a game

#

I'm wondering if anyone knows of any "metal" themed effects which might be compatible with these

glossy elm
#

Cocos 2D for Python has been deprecated, right?
Wrote in Pygame years ago, and couldn't be bothered with my Typescript/Pixi.js thing for an experiment I want to try, and was trying to figure out which graphics library I'm going to bounce in on

#

(after all, I write Python in a non-game setting every day, why not use the language I enjoy rather than the crap around the html5 build process, if I'm doing an experiment just for me?)

real flame
devout reef
#

HI, i have a school project where i have to make a code for the game Mastermind, and i am not able to make the part for checking if there are any colour which are correct but in the wrong place. Do anyone have some tips how to solve it?

glossy elm
paper zenith
#

Not constructive and not within the spirit of our code of conduct.

elder violet
frank fieldBOT
#

Hey @icy dawn!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

obtuse trench
#

Are their any good game engines that use python?

rigid moth
#

I'm working on a small topdown 1v1 shooter game using pygame I have everything I want working except for anything multiplayer so I'm making that now!

eternal vessel
#

noice

olive parcel
snow hill
olive parcel
#

In order from low-level to high-level: pyglet, Panda3D, Ursina (disclaimer: I'm a panda3d dev)

obtuse trench
olive parcel
#

Well, I haven't used it myself, but if you want something that's easy to start with, Ursina is an easier-to-use wrapper around panda3d, although it's a relatively new project with a smaller community, whereas Panda3D has a bit of a learning curve but is a very mature product and has quite a helpful community (https://discord.gg/UyepRMm). I recommend staying away from pyglet if you want something easy to work with.

final kernel
#

hey, I am creating a simple guess game with pyhton GUI

#

Could anyone help me with this error?

torn jackal
#

hey guys i have a big problem with Pygame

#

i would like to display this picture

#

but it displays it like this

#

we are seeing a huge difference

#

anyone has an idea to fix it ?

#

mention if u can help 🙏

twin maple
#

how do i implement a postgresql database in a pygame file 🙏

#

if i put it normally in the file anyone will be able to like see it after like decoding it?

potent ice
rigid moth
left star
#

Not easy. 😑

twin maple
native bear
#

hi guys i need one help actually i am a new comer on python so i decided to make a college map and using a star algorithm (the references are actually from tech with tim) how does a star algo work i am actually confused how to add a map to pygame i tried some of the sources but failed eventually ,could anyone help me with this problem!

old tundra
#

Hey, I'm making a wordle type of game and I'm wondering how could you input text in turtle without using like turtle.input(). Could you input the text in the same window

small jay
#

5-10 hours spent on following python tutorials, just trying to learn pygame, and finally I have the main screen for a tetris clone, minus the actual gameplay

#

I have the controls ready, though, so all I need to do now is program the logic for line clears and actually draw in the blocks

cunning saffron
hardy escarp
#
> a
  b.py
  c.py
  > d
    e.py
    f.py```
How does e.py get b.py?
vagrant saddle
#

otherwise it would be "from .. import b"

hardy escarp
hardy escarp
dawn quiver
#

anyone used libtcode, curses, or blessed

#

Just wanna know if i can work with someone on a terminal / command line like game

wooden pollen
#

Oml. Can someone help me with my game. My sprites are not overlaying the background and a sprite is duplicating itself when moving.

halcyon steeple
#

Heyy, just wanted to ask if it was possible to make bots with python to farm on rpg games

#

Technically, its... I guess..
Like, can i create one using OpenCV or something

mild forum
#

Anyone new to pygame here?
Asking because i want to learn pygame with someone

dusty rover
#

guncircle(x,y,xcircle, ycircle, left, right)
TypeError: guncircle() takes 4 positional arguments but 6 were give

what does this mean?

dawn nacelle
# dusty rover guncircle(x,y,xcircle, ycircle, left, right) TypeError: guncircle() takes 4 posi...

It means that you re trying to call a function named guncircle (that is probably in your code somewhere). If you look at that definition, you will find that it is defined to accept only four values, something like:

def guncircle(parameter1, parameter2, parameter3, parameter4):

But when you are calling it in the line you are showing, you are trying to pass in 6 values. The number of arguments passed in the call does not equal the number of arguments expected by the function.

dusty rover
dawn nacelle
#

def guncircle(parameter1, parameter2, parameter3, parameter4):

(But don't use those names, use meaningful names)

The real question is, what will your function do with those two extra values.

dusty rover
dawn nacelle
#

Glad to hear that you found it.

celest breach
potent ice
#

Definitely. It's also probably something you can ask about in other channels as well

dim ember
#

I've started making a game on Pycharm gonna take a while but who cares lol

small fable
#

Hey there I am trying to learn ai algorithms for future game projects by doing alpha-beta pruning but my implementation is stuck is someone familiar?

elder violet
#

can someone help me

#

i have a pygame project that i need help with

#

its on github at pythonatsea/tank-game

#

the collision isnt working quite right

frank fieldBOT
#

:incoming_envelope: :ok_hand: applied mute to @dawn quiver until <t:1668563572:f> (10 minutes) (reason: duplicates rule: sent 4 duplicated messages in 10s).

The <@&831776746206265384> have been alerted for review.

fickle glade
#

I've tried everything

#

I'm trying to add a logo on my main menu, but I keep getting this, could someone help me out

proper peak
#

the real issue is likely a line up from what you're looking at

fickle glade
#

oh nvm I just accidently added another screen

#

my bad

harsh kayak
#

Has anyone ever made a text rpg before?

lunar venture
#

It's plausible

harsh kayak
#

thats good to know

#

cuz im attempting to make one

lunar venture
#

Good luck

harsh kayak
#

👍

nimble ether
harsh kayak
#

cool!

#

im working on a selling mechanic rn and its not going super smooth

frank fieldBOT
dawn quiver
#

have no clue why it can't read it

raw shadow
#

cool little script

#
import random

import pygame

height, width = 1920, 1080
screen = pygame.display.set_mode((height, width))
clock = pygame.time.Clock()
running = True

gravity = 0.1


class Rain:
    def __init__(self, screen):
        self.vel = 2 * random.uniform(0, 3.665)
        self.screen = screen
        self.rain_instances = [
            pygame.Rect(
                float(random.randint(0, height)),
                random.uniform(-1000, 1000),
                random.uniform(1.2, 1.5),
                random.randint(3, 4),
            )
            for _ in range(width * 10)
        ]

    def draw(self):
        for rain in self.rain_instances:
            pygame.draw.rect(
                self.screen,
                random.choices(
                    (
                        (93, 63, 211),
                        (48, 25, 52),
                        (195, 177, 225),
                        (127, 0, 255),
                        (25, 25, 25),
                        (200, 200, 200),
                    )
                )[0],
                rain,
            )

    def update(self):
        for rain in self.rain_instances:
            rain.y += self.vel * random.uniform(1, 2)
            if rain.y > height:
                rain.y = 0


rain = Rain(screen)

while running:
    for event in pygame.event.get():
        if (
            event.type != pygame.QUIT
            and event.type == pygame.KEYDOWN
            and event.key == pygame.K_ESCAPE
            or event.type == pygame.QUIT
        ):
            running = False

    pygame.display.update()

    screen.fill((10, 10, 10))
    rain.draw()
    rain.update()

    pygame.display.flip()
    pygame.event.pump()
dawn quiver
#

anyone use libtcod, curses, blessed, or pygcurse modules?

dawn quiver
#

anyone want to make a rogue like with me using one of these modules?

harsh kayak
#

pycharm is being stupid

frank fieldBOT
#

:incoming_envelope: :ok_hand: applied mute to @storm lodge until <t:1668729945:f> (10 minutes) (reason: burst rule: sent 8 messages in 10s).

The <@&831776746206265384> have been alerted for review.

dawn quiver
#

so i am making a ascii art text based rpg and i am stumped because i wanna add a limit to how much of something u can buy in the shop

#

and i dont know how to do it

#
            if gold >= 25:
                ATK += 1
                gold -= 25
                print("You've bought a weapon upgrade!")
            else:
                print("Not enough gold!")
                input("> ")```
#

i wanna add a limit to how much of this the player can buy

glacial gull
#

could you not just

#
elif choice == "3":
            if gold >= 25 and hasup == False:
                ATK += 1
                gold -= 25
                hasup = True
                print("You've bought a weapon upgrade!")
            else:
                print("Not enough gold!")
                input("> ")
#

@dawn quiver

rain yoke
#

hey, im getting a memory leak when using this function python def rotate(self): mouse_x, mouse_y = pygame.mouse.get_pos() rel_x, rel_y = mouse_x - self.pos.x, mouse_y - self.pos.y angle = (180 / math.pi) * -math.atan2(rel_y, rel_x) self.image = pygame.transform.rotate(self.image, angle) ###DO NOT TURN ON### memory leak???

#

using pygame

vagrant saddle
# rain yoke using pygame

which pygame version ? and is self.image the only holder of the surface reference ( and what is self exactly : is is persistent or garbage collected ) ?

versed aurora
#

are we allowed to show screenshots of stuff we're making here?

grim abyss
versed aurora
#

aight

#

well here's minesweeper (mostly done)

#

all default python modules

#

im working on adding background colors rn

#

one problem i have is that i'm getting invalid characters sometimes, and if i encode it it doesn't work (i'm using ansi escape codes)

#

alternatively maybe i can replace them after encoding

#

yeah nope

#

it becomes this mess lol

versed aurora
#

here i'll post the code for now

frank fieldBOT
versed aurora
#

oop

dawn quiver
#

neat though different terminals may use different escape codes. Id use curses if you want to avoid this issue.

dawn quiver
#

only problem with curses is that it is linux only. There are ports of it but i haven't looked into it.

#

@versed aurora

versed aurora
#

its kinda windows dependent anyway since im using a windows module for controls, but ye

dawn quiver
#

@versed aurora Every heard of the game hive?

versed aurora
#

oh no i havent

dawn quiver
#

This is a recreation of hive the board game. It works in a linux terminal and might work in a windows command line once i port it

versed aurora
#

neat

grim abyss
dawn quiver
grim abyss
dawn quiver
#

well there are four triangles per hex. North East, North West, South East, South West. Each triangle has a foreground color and a background color. So hexagons that share an edge are drawn with a single triangle with a specific foreground and background color

#

#

these if you can see them

grim abyss
#

Yeah that shows up

dawn quiver
#

Next thing id like to do is record moves to playback a match

#

A help page that describes the game would be nice

#

But I am glad I got it working becuase I need a break.

grim abyss
#

Yeah it seems cool

grim folio
#

I made this turtle race game!
gonna work on snake game soon

#
import turtle
from turtle import Turtle
import random

turtle.setup(width=500, height=400)

x = -230
y = 120
n = 0

race = False
colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple']
turtles = []

for clr in colors:    
    turtles.append(Turtle(shape="turtle"))

for tur in turtles:
    if n != 6:
        tur.color(colors[n])
        n += 1

for tur in turtles:
    tur.penup()
    tur.goto(x, y)
    y -= 50

race_screen = turtle.Screen()
race_screen.title("Welcome to Turtle Race!")
user_bet = race_screen.textinput(title="Make your bet", prompt="Who will win the race? Enter a colour:")

if user_bet in colors:
    race = True

while race:
    for tur in turtles:
        speed = random.randint(0, 10)
        tur.forward(speed)
        if tur.xcor() > 220:
            race = False

            winner = tur.pencolor()
            
            if user_bet == winner:
                print(f"You've won! The {winner} turlte is the winner!")
            else:
                print(f"You've lost! The {winner} turlte is the winner!")

race_screen.exitonclick()

grim folio
dawn quiver
#

nice!

scenic dome
#

Anyone got a game idea but just need a boost coding to help see it to fruition?

prime pawn
#

HI
I hope someone can help me with a topic I created in Reddit.
Created a mini-version of Character rolls in Baldur's Gate game. The code works, but I'm trying to make the code better and faster, while still being easy to understand by someone seeing the code for the first time.

https://www.reddit.com/r/learnpython/comments/yz5d8f/baldurs_gate_character_creation_and_dice_roll_for/

scenic dome
brave escarp
#

I wanna learn

#

game development

versed aurora
#

I might write a simple module for terminal color, at least for windows, since idk how it works on linux

hoary inlet
#

how can u spawn an object every 3 seconds in pygame

versed aurora
versed aurora
hoary inlet
#

anyone know how to spawn an object across the screen every 3 seconds??

#

helllllooooooo

versed aurora
#

that just depends on how you do objects really

#

i usually have a list for my objects (though i mainly code things for terminal graphics, so your milage may vary)

eternal vessel
#

just create a variable and increment it every loop and whatever you have your FPS(clock) set to, have an if statement for when it's past your FPS X 3, spawn the object and reset variable back to 0

hoary inlet
#

ohhh ok thanks

eternal vessel
#

if you can't figure it out, I could try and be more descriptive or just help you code it

hoary inlet
#

yes please

#

sorry for the late reply btw i was eating dinner

eternal vessel
#

No probs

dawn quiver
# versed aurora

This is really cool. Have you ever thought about making a roguelike?

versed aurora
#

yeah actually

frank fieldBOT
#

Hey @crude ridge!

It looks like you tried to attach file type(s) that we do not allow (.ipynb). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.

Feel free to ask in #community-meta if you think this is a mistake.

untold sentinel
#

Hey Python people!

#

I'm building a topdown game as a school project

#

And its proving surprisingly difficult to find a decent tutorial on enemy AI. Most are for shooter games, and don't accommodate for enemys which can't rotate freely

#

Anyone have any resources on hand?

grim abyss
pallid mist
#

Hey guys, I am looking to make a 2d simulation in python. Which library is the best performance wise?

#

Is pyopengl the best solution?

vagrant saddle
#

you can do 2d sim with pymunk+pygame

pallid mist
#

Yes, for now I only need 2d, but I will eventually need 3d too. So using one library to learn would be good.
How about using c++ for performance and unreal engine?

pallid mist
vagrant saddle
#

maybe same as those complaining that the user's gpu is also too slow

#

also pygame allows to use shaders or convert your code to compiled code, so you can always go faster

grim abyss
#

There's also arcade

vagrant saddle
#

tbh the time you'll spend wondering if c++ is the way and maybe start learning it, you could maybe have a prototype in pygame and see what happens

small jay
#

how do I allow holding down a key to move

#

this is for a tetris game, i want to allow DAS and smoother soft drops

small jay
#

?

tranquil girder
#

are you using a framework?

small jay
#

using pygame

eternal vessel
# small jay using pygame

well if you want to be able to hold keys

keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
  print("do something")```
winter mist
#

Hi, im currently making a game with pygame and tried to make a ball that will move when you collide with it. It kinda works but theres one issue, and that is that when i hit the ball at one angle it moves the ball either a wrong path and then continues to move that path each time im pushing the ball at the left side that should make the ball move right.

https://paste.pythondiscord.com/zikevikema.py

#

is there any way i can fix this so the physics behind the ball object's movements are going the right path?

unreal parrot
#

not perfect but its a start 🥳🥳

dawn quiver
unreal parrot
#

how does one input music?

dawn quiver
unreal parrot
#

damn that’s sick

#

im guessing i need to download a music module or somet

#

for music

dawn quiver
unreal parrot
#

oh u see thank you i’ll check some turtorials

dawn quiver
small jay
dawn quiver
# small jay movement flags?

something like this, like if you want your character to move right whenever you are pressing the right arrow key

#

if event.type == pygame.keydown:
if event.key == pygame.k_right:
right = True
if event.type == pygame.keyup:
if event.key == pygame.k_right:
right = False

if right:
player_x += 1
@small jay

small jay
#

It’s not really a character tho, it’s a tetris piece

cosmic olive
#

:v

eternal vessel
#

:v

cosmic olive
#

Guys guys. Trick question.. how do I go about using logic to build an onscreen joystick lol

eternal vessel
#

I've got no clue, haven't bothered with controllers using pygame

cosmic olive
#

Just concepts is fine

#

I see

#

It's for mobile

#

So onscreen

#

:v

eternal vessel
#

You'd probably just have to look at the docs, but their pretty straightforward

cosmic olive
#

Or I'd have to use onscreen direction buttons

#

Which is ehh

#

Hmm

#

I'll start it first, see where I choke then check docs or come back here 😂

eternal vessel
#

yeah joysticks are nicer

#

then a d-pad

cosmic olive
#

What's a d pad

eternal vessel
#

for movement atleast

cosmic olive
#

Lh

#

Oh

eternal vessel
#

I tried

cosmic olive
#

:'v

eternal vessel
#

the arrows for up/down/left/right

cosmic olive
#

I see

#

Have you developed anything with pygame?

eternal vessel
#

This thing

cosmic olive
#

Yeah

eternal vessel
#

I code when I don't know what else to do

cosmic olive
#

I see

eternal vessel
#

unless I get random motivation

cosmic olive
#

I do it as hobby too

#

But I just started pygame

#

Watched a 2 hour tutorial and now I wanna see if I could do it on my own

eternal vessel
#

If you understand classes you could probably watch Clear Code's tutorials he has great ones

cosmic olive
#

I see

#

Yeah I understand classes

#

I wanna practice using them more tho which is perfect since I'm coding a game

#

And I heard there's sprite class

eternal vessel
#

Yeah I try and use classes for any project for practice

#

Yeah pygame has a sprite class you can inherit from

cosmic olive
#

Yup

#

Anyways I gtg for now

eternal vessel
#

Yep later

cosmic olive
#

Bruh I read your self-intro as "equal to or more than" and gave myself a seizure

dawn quiver
frank fieldBOT
#

Hey @scenic dome!

It looks like you tried to attach file type(s) that we do not allow (.zip). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.

Feel free to ask in #community-meta if you think this is a mistake.

eternal vessel
#

it's supposed to be just an arrow

#

There back to colons:

cosmic olive
#

#

You're welcome

#

#

▷▶︎▷

#

➯➱➩

#

・‥…━━━☞

eternal vessel
#

I'm good 👍 if I really wanted a fancy arrow I would've copied one when I changed it

prime pawn
scenic dome
prime pawn
scenic dome
prime pawn
scenic dome
prime pawn
scenic dome
#

Yes. Clean is what you do when the goal is just to make the code easier to read, shorter, and more flexible. Numpy is the high-performance version. In general you only make high performance code when you need to, and one of the ways to do so is with Numpy.

prime pawn
#

Regarding your comment for:
That part (based on max 18 in each attribute) is supposed to calculate what is possible to get 75 total attribute points with lowest possible rolls:
So for the first 3 attributes, it has to be greater than 21, or else you can't make it to 75 or higher.
On the 4th attribute, it's 39 or higher, etc...
(It will make the code "faster" as it's cutting what is not possible, instead of rolling all 6 attribute variants.)

If it's lower than that, it will **break **the loop, and restart the whole process again (will retry to generate a new 75 or higher total roll).

# What is this code for??? #TODO #if (total_all_attribute_sum < 21 and attrib_name >= 2) or (total_all_attribute_sum < 39 and # attrib_name >= 3) or (total_all_attribute_sum < 57 and attrib_name >= 4): # break

prime pawn
scenic dome
prime pawn
scenic dome
prime pawn
prime pawn
#

no, the tips was just normal, non-numpy

scenic dome
# prime pawn no, the tips was just normal, non-numpy

Fixed the 75 cutoff issue, it now takes about 0.07 s instead of 0.05 s (still very fast). Here is the snippet:
<code>
# Roll max_tries all in one line of code to take advantage of numpy native speed.
# It sounds like extra work to not stop early, but numpy is so fast that it can be faster.
sum_over_attr = np.zeros(max_number_tries, dtype=np.int64)
ixs = np.arange(max_number_tries)
while ixs.size>0:
sum_over_attri = np.zeros(ixs.size, dtype=np.int64)
for k in attrs:
jxs = np.arange(ixs.size) # Try, try, try again.
results = np.zeros(ixs.size, dtype=np.int64)
while jxs.size>0:
dice = np.random.randint(chargen.pip_range[0], chargen.pip_range[1]+1, size=[jxs.size, n_dice[k]])
total = np.sum(dice,axis=1)
results[jxs] = total
jxs = jxs[total<min_rolls[k]]
sum_over_attri = sum_over_attri+results
sum_over_attr[ixs] = sum_over_attri
ixs = ixs[sum_over_attri<chargen.lowest_roll_total]
</code>

eternal vessel
#

Yep

gusty umbra
#

I recommend using a dictionary

#

this dictionary will have dark and light mode as keys

marsh vapor
#

that's a very good idea! Thank you so much for your suggestion @gusty umbra!

gusty umbra
#

np

gusty umbra
#

Running into issues with circular definitions, I have a game scene classes and I want to have the ability to create a scene from the other scene

narrow ether
#

I am having to do a bit of physics simulation and I get values that are practically 0 but aren't, is there a way I can treat them as 0

eternal vessel
#

Could floor the number or round it, if that's what you mean

prime pawn
scenic dome
delicate raven
#

pygame or arcade

#

which is more beginner-friendly

icy valve
#

ive only used pygame what its the diference whit arcade?

delicate raven
#

idk, tbh

#

that's why i'm asking

neon herald
#

Hi

neon herald
#

They are both really easy

crystal mirage
#

can i develop games using python?

icy valve
#

yea you can

gusty umbra
vagrant saddle
#

and mobile/web friendly too

eternal vessel
delicate raven
#

oh yeah

#

i used classes alot so it just came kinda naturally to me

marsh vapor
#

hi there, is it possible to create an interactive dashboard with multiple data in pygame? or is it limited to pygame? if it is possible, what library I should consider to import with? and I am not sure how it is possible to store and get the data when the data is continuously added on. I guess that cannot use .cvs to do that, right?

gusty umbra
#

has anyone worked with nuitka?

#

are there alternatives?

gusty umbra
gusty umbra
vagrant saddle
icy valve
dawn quiver
#
  1. How can I make the sound of tires squealing and show smoke during sudden acceleration (currently the controller vibrates during sudden acceleration and braking)?
  2. How do I make the game visible as a Forza telemetry server?
  3. How do I add enemy cars to the game?
    https://github.com/sserver224/Car-Racing-3D
GitHub

Contribute to sserver224/Car-Racing-3D development by creating an account on GitHub.

torn sierra
#

Hello everyone, can anyone help me with installing Pygame?

#

Because it doesn't want to install and I don't know what to do.

snow hill
#

(all coded in Python, of course)

thin bear
#

or from import pygame *

eternal vessel
#

but you need to install it first

#

so that's likely not their problem

thin bear
#

cant u just use replit

#

and install from there

cosmic vale
#

When is the pygame competition coming up?

cosmic vale
cosmic vale
#

I'd like to check it up, if possible 🙂

eternal vessel
snow hill
cosmic vale
cosmic vale
#

@snow hill just found one vid of yours on dogfight/air to air combat hahah

#

I didn't even know such a thing like harfang3d even existed, that's pretty cool, I'll def take a deeper look into it

#

seems like you're one of the contributors to harfang

#

very nice man, good job

snow hill
#

But I contribute as project lead and tech artist

cosmic vale
snow hill
snow hill
#

or just pip install harfang

cosmic vale
#

'starred'

snow hill
snow hill
hollow mica
dawn quiver
sharp quiver
snow hill
sharp quiver
eternal vessel
dawn quiver
#

is turtle good for game making?

eternal vessel
#

that's for drawing pretty much

#

You can make games with turtle, but not very good ones

versed aurora
#

once again stretching the definition of 'game' but my parallax in terminal is going well

#

i can now load multiple layers and have them scroll at different rates

#

i gave up on using compressed data because it was stupid and more limiting and am now using raw data with a couple bytes header

#

the idea is i want to be able to render something like a scrolling cityscape with multiple layers

#

i basically can just draw the layers and put them in because all the hard part is done

versed aurora
olive timber
#

Hi

#

I am using ursina game engine

#

What is the syntax when a button is clicked

faint bane
#

how'd one go about drawing a sprite every time a key is pressed

#

for example if i'd pressed the arrow key to move the sprite left a new sprite would appear somewhere else etc etc

#

basically a function to automatically draw sprites

faint bane
#

elaborate?

tranquil girder
eternal vessel
#

Okay I didn't actually mean assign a variable to mixer.music.load

#

I meant the whole line of code

#

so

mixer.init()

my_sound = mixer.Sound("noise.wav") # assigns the sound to variable
my_sound.mixer.set_volume(0.7) # Setting the volume

my_sound.play() # Plays the variables sound```
dawn quiver
#

Like this?

from pygame import mixer

mixer.music.load 
mixer.init()
my_sound = mixer.Sound("DeathSoundEffect.mp3")
my_sound.set_volume(0.7) 
my_sound.play() 
#

@eternal vessel

eternal vessel
#

I believe that'd work but you gotta try it

dawn quiver
#

no work

eternal vessel
#

not sure if the set_volume will work since I haven't used the function

#

what's the error?

dawn quiver
#

just writes that

grizzled ocean
#

https://paste.pythondiscord.com/dicubecuxi.py

soo, i have this script, but when i run it WITH the while loop for time included the button doesnt work, if i remove the while loop tho, it does work, is there any way i can fix this??

i know i should use a time.time() or time.clock() but idk how to use those...

eternal vessel
dawn quiver
#

maybe idk

#

how long can the sound last

#

because the audio file is like 6s long

#

I dont think i have anyhting that stops it

eternal vessel
#

okay can you hear it when you don't use the set_volume

dawn quiver
#

nope

#

still cant hear

eternal vessel
#

not sure, it works for me

dawn quiver
#

Cursed

grizzled ocean
#

https://paste.pythondiscord.com/dicubecuxi.py

soo, i have this script, but when i run it WITH the while loop for time included the button doesnt work, if i remove the while loop tho, it does work, is there any way i can fix this??

i know i should use a time.time() or time.clock() but idk how to use those...

dawn quiver
#

right?

eternal vessel
#

Probably

#

You showed the terminal and an error didn't go through so it must be due to that

dawn quiver
#

I tried it with .wav and it still doesnt work

#

It gives me again

#

wth

eternal vessel
#

Is it in the correct directory?

dawn quiver
eternal vessel
#

Also changing the file to .wav if it's an mp3 can scuff the sound

dawn quiver
#

I tried the audio file

#

like listening to it

#

it works

#

But i heal like

#

hear**

#

a slight sound at the begining

#

like uhh

#

how do i explain

#

like for just a tenth of a second i hear a small scuffed sound

#

yk

eternal vessel
#

Maybe because it's 6 seconds long but it's going to restart every loop so you can't hear it

dawn quiver
#

When you unmute and mute your mic

eternal vessel
#

Are you trying to have it as background music?

dawn quiver
#
from pygame import mixer

mixer.music.load 
mixer.init()
my_sound = mixer.Sound("TypeWriterSoundEffect.wav")
my_sound.set_volume(0.7) 
my_sound.play()      
#

I want it when it prints text

eternal vessel
#

If not you're going to need some condition when playing it

dawn quiver
#

Im gonna make it like a typewriter effect

#

with

#

import sys

eternal vessel
#

Okay well you're going to need some condition or have it shorter so it doesn't spam play the sound

dawn quiver
#

and

#

stuff

dawn quiver
#

I can show you how i want to combine it

eternal vessel
#

Alright

dawn quiver
#

This,

import sys
import time 

def typewrite(string)
    for i in string:
        sys.stdout.write(i)
        sys.stdout.flush()
        time.sleep(0.05)

typewrite("Blah blah blah")```
#

And this

from pygame import mixer

mixer.music.load 
mixer.init()
my_sound = mixer.Sound("TypeWriterSoundEffect.wav")
my_sound.set_volume(0.7) 
my_sound.play()```
eternal vessel
#

Before the for loop you can try and play it

#

So it plays it but doesn't get iterated over and over again

dawn quiver
#
import sys
import time 

def typewrite(string):
    from pygame import mixer

    mixer.music.load 
    mixer.init()
    my_sound = mixer.Sound("TypeWriterSoundEffect.wav")
    my_sound.set_volume(0.7) 
    my_sound.play()    

    for i in string:
        sys.stdout.write(i)
        sys.stdout.flush()
        time.sleep(0.05)

typewrite("Blah blah blah")

#

like this?

eternal vessel
#

Not sure if the time.sleep(0.05) will scuff it

#

You can initialize the stuff outside of the function you just need the .play() before it

dawn quiver
#

nono it works

#

LETS GO

#

ÖLASKNJDOIASHD

eternal vessel
#

Because that's what plays the sound

#

Probably be better to initialize it outside of it though

dawn quiver
#

wdym

eternal vessel
#

Or at least put the import and init outside of the function

#

Also you can delete the mixer.music.load since it isn't being used I think

eternal vessel
dawn quiver
#

nono it doesnt work wihout it

eternal vessel
#

You could look at it in the Pygame docs, they're pretty straightforward

eternal vessel
dawn quiver
#

or wiat

#

Do you meant

#

mean

eternal vessel
#

I've been on my phone in the car lol

dawn quiver
#

my_sound = mixer.Sound("")

dawn quiver
eternal vessel
dawn quiver
#

okok

#

but another hting

#

how do i make it loop

#

if its a longer piece of text

#

while and break?

eternal vessel
#

Could try?

dawn quiver
#

Idk how it works

#

lol

eternal vessel
#

So pretty much you use the .play() when you want to play the sound

#

But if it triggers to quickly then it'll restart the sound

dawn quiver
#

can u show me

#

an example

#

while my_sound.play ==

eternal vessel
#

Crap I gotta go I've arrived to my airsoft place

dawn quiver
#

Alright gl man

#

ty for the help

grim abyss
#

You want sound to play on every character?

dawn quiver
#

I want sound to play whilst it is still printing

#

because it just stops when the audio is done

#

I want it to loop as long as typewrite("") is running

#

yk?

grim abyss
#

Call the mysound.play inside the for-loop after the call to sys.stdout.write

dawn quiver
#
import sys
import time 
from pygame import mixer
mixer.init()


def typewrite(string):

    mixer.music.load 
    my_sound = mixer.Sound("TypeWriterSoundEffect.wav")
    my_sound.set_volume(0.4) 

    for i in string:
        my_sound.play()
        sys.stdout.write(i)
        sys.stdout.flush()
        time.sleep(0.045)

        typewrite("Blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah Blah")```
eternal vessel
dawn quiver
#

This doesnt work

dawn quiver
#

lmao

#

alright

grim abyss
eternal vessel
#

Okay what I've thought of is using math based off the delay between loops and the length of the text you input. Could calculate when you'd need to play the noise

dawn quiver
#

YOu know the sound where you mute and unmute your mic

#

it plays that

#

for

#

1 tenth of a second

#

then stops

dawn quiver
eternal vessel
#

Idk what the equation would be

#

Wish I could be at my PC rn

dawn quiver
#

wait explain it to me again

#

math based

#

off the delay between loops

eternal vessel
#

I'm trying to think

dawn quiver
#

okok

grim abyss
#

Don't call typewrite () inside for loop

dawn quiver
#

Like this?

#

doesnt work

eternal vessel
#

That too, but I'm pretty sure audio will still repeat over and over because it's in for loop

dawn quiver
#

yeah

grim abyss
#

You want the sound effect to play on each character yes?

#

Sleep longer? Stop the sound? my sound.stop()?

eternal vessel
#

Nope

#

It's 6 seconds

grim abyss
eternal vessel
#

Yeah it's just typing noise that needs to play every 6 six seconds pretty much

dawn quiver
#

yes

#

exactly

eternal vessel
#

Could just try that logic and see if it works

grim abyss
#

Why every 6secs?

eternal vessel
#

Because that's the length of the file

#

So when it ends, it restarts

dawn quiver
#

its 3s but yes

grim abyss
#

A key press sfx should not be 6secs long...

dawn quiver
#

no but bruh

grim abyss
#

Get a single key press sfx

dawn quiver
#

that would also be smart

#

but then there's no variation in the sound

eternal vessel
#

I thought of solution I think

dawn quiver
#

not so livley

#

tell em

eternal vessel
#

Though you're probably gonna look at the docs because I don't got it memorized

#

Pygame has a background music type feature that you can loop

#

So when it ends it restarts automatically

dawn quiver
#

i see

#

lemme search it up

grim abyss
#

You could pause the sound lol

dawn quiver
#

It works

#
import sys
import time 

def typewrite(string):
    from pygame import mixer

    mixer.music.load 
    mixer.init()
    my_sound = mixer.Sound("TypeWriterSoundEffect.wav")
    my_sound.set_volume(0.7) 
    my_sound.play(loops =-1)    

    for i in string:
        sys.stdout.write(i)
        sys.stdout.flush()
        time.sleep(0.05)

typewrite("Blah blah blah Blah blah blah Blah blah blah Blah blah blah Blah blah blah Blah blah blah")

#

The thing is the sound like fades the last second

#

so can i somehow just cut out the part that fades

grim abyss
#

If you found a better sfx file that's shorter(like 0.350 secs) then you could do the effect like it should be done....

#

And just sleep for the length of the sfx on write...

dawn quiver
#

Alright ill try to find another shorter

#

Or i could just edit

#

and cut

#

right+

grim abyss
#

Yup

dawn quiver
#

okok hol up

#

How long should it be

grim abyss
#

Long enough to hear the "click" of the key being pressed

#

I would say it needs to be less than half a sec though

#

Or it will take forever on sentences

dawn quiver
#

ok

grim abyss
#

Ideally, something like 0.250 long? If possible

dawn quiver
#

alr alr

#
import sys
import time 
from pygame import mixer

def typewrite(string):
  
    mixer.music.load 
    mixer.init()
    my_sound = mixer.Sound("TypewriteSound.wav")
    my_sound.set_volume(0.3) 
    my_sound.play(loops =-1)  

    for i in string:
        sys.stdout.write(i)
        sys.stdout.flush()
        time.sleep(0.05)

typewrite("Blah blah blah Blah blah blah Blah blah blah Blah blah blah Blah blah blah Blah blah blah Blah blah blah Blah blah blah Blah blah blah Blah blah blah Blah blah blah Blah blah blah")
#

Ok now

#

It prints the same audio file over and over again

#

How do i make it more lively

#

its 0.25s long

#

@grim abyss

dawn quiver
grim abyss
#

Had to make a coffee

dawn quiver
#

np

grim abyss
dawn quiver
#

what is sfx

grim abyss
#

Length of file/sfx?

dawn quiver
#

aha

grim abyss
#

sfx = sound effect(s)

dawn quiver
#

0.25s

grim abyss
#

Ok so call play in the for-loop and sleep for that long. Init the mixer outside of the function

#

Call mixer.init() above the function...

dawn quiver
#

above typewrite

#

?

#

doesnt work

#

nvm

#
import sys
import time 
from pygame import mixer
    
mixer.init()  
mixer.music.load   

def typewrite(string):

    my_sound = mixer.Sound("TypewriteSound.wav")
    my_sound.set_volume(0.7) 
       
    for i in string:
        my_sound.play(loops =-1) 
        sys.stdout.write(i)
        sys.stdout.flush()
        time.sleep(0.25)

typewrite("Blah blah blah Blah blah blah Blah blah blah Blah blah blah Blah blah blah Blah blah blah")```
#

like this?

grim abyss
#

Yeah and also the my_sound = ....

#

No wait

dawn quiver
#

it doesnt wokr

#

it

#

gradually speeds up the audio

#

idk

#

nvm

#

it

#

just

#

earrape

grim abyss
#

Feedback...try stopping the sound at the end of the for-loop

#

my_sound.stop() after the sleep

dawn quiver
#

ok

grim abyss
#

Wait...

#

Try not passing the loop param to my_sound.play()

#

Maybe that's why it was blowing up

dawn quiver
#

it just cuts if i put it above for loop

grim abyss
#

You want the my_sound.play() inside the for-loop

#

Show current code

dawn quiver
#
import sys
import time 
from pygame import mixer
    
mixer.init()  
mixer.music.load   

def typewrite(string):

    my_sound = mixer.Sound("TypewriteSound.wav")
    my_sound.set_volume(0.7) 

    for i in string:
        my_sound.play(loops =-1) 
        sys.stdout.write(i)
        sys.stdout.flush()
        time.sleep(0.05)
        my_sound.stop()

typewrite("Blah blah blah Blah blah blah Blah blah blah Blah blah blah Blah blah blah Blah blah blah")
grim abyss
#

Remove the arg to play! We don't wanna loop.

Just my_sound.play()

#

Also time.sleep(0.05)?!?!

dawn quiver
#

whoops

grim abyss
#

You need to sleep the length of the sfx...

dawn quiver
#
import sys
import time 
from pygame import mixer
    
mixer.init()  
mixer.music.load   

def typewrite(string):

    my_sound = mixer.Sound("TypewriteSound.wav")
    my_sound.set_volume(0.7) 

    for i in string:
        my_sound.play() 
        sys.stdout.write(i)
        sys.stdout.flush()
        time.sleep(0.25)
        my_sound.stop()

typewrite("Blah blah blah Blah blah blah Blah blah blah Blah blah blah Blah blah blah Blah blah blah")
#

So

#

it still sounds

#

very

#

choppy

grim abyss
#

Are you hearing the complete sfx?

#

On each character?

dawn quiver
#

yeah

grim abyss
#

Is it "popping"?

#

Try sleeping after the call to stop

dawn quiver
#

yeah

grim abyss
#

Yeah, sleep after stop

dawn quiver
#

like this?

grim abyss
#

No, remove first sleep

dawn quiver
#

now I cant hear anything

#

And the text is supperr slow

#

it's just better if i take the audio file i started with

#

and just cut out the last part

#

and then loop again

#

This just sounds choppy

grim abyss
#

I guess it's stopping sfx before letting it play

#

Have patience!

dawn quiver
#

brb

grim abyss
#

Put the sleep before the stop like we had it. Increase sleep time to 0.35?

dawn quiver
#

it's even slower now

#

hol up

grim abyss
#

Of course it's slower but does it sound better?

#

I'm on mobile so I can't do much....

dawn quiver
#

I fixed it

#

ty

#

It works fine now

grim abyss
#

Great, show working code please

#

@dawn quiver working code?

dawn quiver
thorn mulch
#

There is my code and output. As you see the x of rectengle isn't changing. How can i change it. I'm trying to move it!

#

i changed it but it isn't moving

dawn quiver
#

Why doesn't my input work?

import sys
import time 
from pygame import mixer
import os

os.system("cls")

def typewrite(string):

    mixer.music.load 
    mixer.init()
    typeSound = mixer.Sound("TypeWriteSoundEffect.wav")
    typeSound.set_volume(0.2) 
    typeSound.play(loops =-1)    

    for i in string:
        sys.stdout.write(i)
        sys.stdout.flush()
        time.sleep(0.06)

username = input(typewrite(f'''

    ░▒▓▆▅▃▂▁𝐓𝐇𝐄 𝐔𝐍𝐂𝐀𝐍𝐍𝐘▁▂▃▅▆▓▒░   
 
    Welcome adventurer, what is your name? 
'''))

    #typewrite(f'''Alright {username}, welcome to THE UNCANNY, your mission is to save your ''')
    
    # You still have a long way ahead of you, this is your only chance to turn
    # back. Do you still want to continue?
dawn quiver
#

Results:

vast mortar
dawn quiver
#

you dont have pygame installed

#

pip install pygame

vast mortar
#

can you even do that in PyCharm

dawn quiver
#

idk

#

try

proper peak
vast mortar
#

ah I gotta download a package

#

now idea how to find that

#

no*

dawn quiver
#

go to visual studio code and run it

vast mortar
#

i just got the package hold on

dawn quiver
#

okok

vast mortar
#

bruh

dawn quiver
#

just choose any other soundfile

#

you have

vast mortar
#

i have no sound files lol

#

also automatic

#

your input does work

#

I just don't know why it puts none when you use typewriter

#
username = input(typewrite(f'''

    ░▒▓▆▅▃▂▁𝐓𝐇𝐄 𝐔𝐍𝐂𝐀𝐍𝐍𝐘▁▂▃▅▆▓▒░   

    Welcome adventurer, what is your name? 
'''))
print(typewrite("Alright hero " + username + " let the adventure begin!"))
dawn quiver
#

huhhh

vast mortar
#

huhhh what

#

the input works

dawn quiver
#

it doesnt work for me

vast mortar
#

what happens for you

dawn quiver
vast mortar
#

you can't type?

dawn quiver
#

Why does it write none

#

i wanna remove

vast mortar
#

it has smth to do with typewriter

dawn quiver
#

no i cant type

vast mortar
#

did you click it

pine plinth
vast mortar
#

uh u can still use their library no?

dawn quiver
vast mortar
#

and then try typing

dawn quiver
#

Aha

#

yes

#

but like

pine plinth
dawn quiver
#

It types none

#

how do i fix it

vast mortar
vast mortar
versed aurora
#

if your function has a print, just call it, no need to print the function itself

eternal vessel
#

!docs pygame

frank fieldBOT
dawn quiver
#

thats why you see none becuase you are printing the result of the typewriter function

heady ginkgo
#

How do I make save file readable from the menu file?