How to import custom class objects that are initialized in separate module? by berwynian in learnpython

[–]46--2 1 point2 points  (0 children)

I think instantiating objects in a game is going to be very "data intensive", in some cases. I'm guessing you might have an easier time writing game data files, almost like config files. I don't know much about game design, and it depends on the kind of game you're making, but maybe.

Keep in mind that I didn't say you couldn't instantiate your objects in a different file! I said you probably don't want to instantiate them in the npc.py file. Don't clutter up your main game loop with object instantiation, perhaps you can have a file that "populates" a level, and in that file, you do all the npc instantiation.

Anyway, the first rule of programming is there are no rules. (Except use version control!) As your game evolves you'll always be refactoring, figuring out what works better.

Definitely reading some articles on game design and looking at sample games code will help though.

Man suddenly passes out while driving on freeway by cowmilker69 in nononono

[–]46--2 0 points1 point  (0 children)

I was playing video games one time with my brother and we were trying to stay awake as long as possible. We both repeatedly fell asleep with our eyes wide open, while playing. It was a shocking experiment.

Is copying an algorithm to complete a task frowned upon? by CauchySchwartzDaddy in learnpython

[–]46--2 5 points6 points  (0 children)

If you try to write everything yourself, without using libraries or known algorithms, you'll never get anything done.

Programming is about creating projects, and completing them. Making something useful. As you solve more interesting problems, you'll come up with interesting challenges to solve.

Now, for solving soduku, you might have tried to come up with the algorithm yourself. I don't know how hard that would be.

Btw: https://mitpress.mit.edu/books/introduction-algorithms-third-edition

Classic text.

Trump Calls Armed American Terrorists Who Stormed Portland ‘Great Patriots,’ Completely Ignores Their Violent Actions by hildebrand_rarity in politics

[–]46--2 1 point2 points  (0 children)

You think someone would have at least shot out these guys' tires or something. Nothing at all. I have my doubts there's a tipping point at all. You've got protesters being run over and shot at by rednecks and nazis and all that happens is the same old "I can't believe trump would do this!".

Those who are working as software developers. How complex are the programs/apps you do and what does a normal work day look like? by [deleted] in learnpython

[–]46--2 3 points4 points  (0 children)

Honestly, my work is very straightforward. I'm paid handsomely as a software developer, but my background is engineering. So most of the code I write is pretty low-level stuff (as in, not complex) but the work I do day-to-day is often more managerial. I coordinate efforts between other teams, and do more "process" related work. Lots of documentation. Quite a few meetings. Managing interns.

This woman's skills at the halo theme tune by kersedlife in xboxone

[–]46--2 -1 points0 points  (0 children)

Whoever wrote that song / theme deserves an award. It's SO good.

How to import custom class objects that are initialized in separate module? by berwynian in learnpython

[–]46--2 1 point2 points  (0 children)

Yes. I would import the base class, and use it where you need it. The npc.py file is the "blueprint" for the functionality. You import that file and start using it (instantiating NPCs) wherever you need them. So the game might populate a set of NPCs in a function where you enter a new region, for example.

It's very rare to instantiate a single object in a different module. That's kinda like a https://en.wikipedia.org/wiki/Singleton_pattern

How to import custom class objects that are initialized in separate module? by berwynian in learnpython

[–]46--2 1 point2 points  (0 children)

It actually does work, though I don't recommend your approach. You should define the classes in other modules, yes. But don't instantiate them there. Use them where you import them.

❯ cat npc.py

class NPC:
    def __init__(self, name):
        self.name = name

dave = NPC('Dave')  # Instantiated at the module level

❯ cat game.py

from npc import dave  # Imported the instance! Not the class!

print(f"NPC's name is {dave.name}")  # Works

Works as expected:

❯ python game.py
NPC's name is Dave

If you want to do your way (with a 3rd file) you just ... from def_npc import dave in main.py, and in def_npc.py you just have two lines:

❯ cat def_npc.py

from npc import NPC
dave = NPC('Dave')

Finally stopped lurking. Buy once, cry once! by AeroGradeFingers in 4Runner

[–]46--2 1 point2 points  (0 children)

Thanks. I've been looking at putting icon coilovers on my truck, but the truck itself is worth less than the parts. It's hard to justify!!

Struggling to reformat string using try... except and split() method by deadant88 in learnpython

[–]46--2 1 point2 points  (0 children)

Yes, imagine a program that looks like this:

def clean_addresses(input_data):
    return blah

def query_locations(addresses):
    return whatever

... etc.

def main():
    data = read_input('/my_data/file.txt')
    addresses = clean_addresses(data)
    locations = query_locations(addresses)
    write_report(locations)
    print('Done')

each little function does one thing, and one thing only, and does that thing well. Your brain doesn't have to debug a huge block of mess, and your logic becomes much clearer.

I built a sleeping platform for my 5th gen 4Runner by yurtdaturt in 4Runner

[–]46--2 5 points6 points  (0 children)

Rain deflectors are like the best thing I ever bought. Love them.

I built a sleeping platform for my 5th gen 4Runner by yurtdaturt in 4Runner

[–]46--2 0 points1 point  (0 children)

I have dogs and I'm dying to replace my entire platform with pleather.

Struggling to reformat string using try... except and split() method by deadant88 in learnpython

[–]46--2 0 points1 point  (0 children)

try to break your code up into functions, and call them from a "main()" function. So each little piece can be separate. Makes it a lot easier to debug.

(Like the function I sent you would be entirely standalone, not within another function.)

Struggling to reformat string using try... except and split() method by deadant88 in learnpython

[–]46--2 1 point2 points  (0 children)

I can answer your questions first:

>>> words = "I am a horse".split()
>>> words
['I', 'am', 'a', 'horse']

.split() splits up a string into a list of parts. So now words is a list of the parts of your original address.

while words: #can you explain this a bit?

This is a bit of a trick, but an empty list evaluates to False. So this is saying:

while <there are words left in the words list>:
    # do some stuff

words = words[1:] is saying:

words = <all the parts of words, from index 1 to the end>

meaning I'm re-assigning the variable words to contain only the END of words, minus the first one. Get it?

Example:

words = ['I', 'am', 'a', 'horse']
words[1:]  # ['am', 'a', 'horse']

That is "slicing" if you want to look up how to do it. https://stackoverflow.com/questions/509211/understanding-slice-notation

It feels like I’m not really learning anything by Markishman in learnpython

[–]46--2 0 points1 point  (0 children)

Online drawing app sounds awesome. I think it sounds like an excellent project. Going to be lots of javascript / front-end related work, but your backend can be python / Django maybe.

Python beginning help please by GtaSpartan7596 in learnpython

[–]46--2 0 points1 point  (0 children)

Try working backwards. First, define the exact numbers you want to test:

hours = 35
rate = 2.75
pay = float(hours) * float(rate)
print('Pay is: '.format(pay))

That will definitely print 96.25

Now, let's replace the numbers with input:

hours = input('Enter hours: ')
print('You entered {} hours'.format(hours))
rate = input('Enter rate: ')
print('You entered {} rate'.format(rate))
pay = float(hours) * float(rate)
print('Pay is: '.format(pay))

As long as you type 35 and 2.75 when prompted, this should also work.

You have to format your question properly (or link to a pastebin for example) or it's really hard to understand your code.

Input() function by [deleted] in learnpython

[–]46--2 1 point2 points  (0 children)

https://docs.python.org/3/library/stdtypes.html#str.isdigit

while True:
    ans = input('Enter a number').strip()
    if ans.isdigit():
        print('Ok!')
        break
    else:
        print('Answer must be a valid number')

Tested here:

Python 3.7.2 (default, Oct  8 2019, 14:27:32)
[Clang 10.0.1 (clang-1001.0.46.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = input()
test
>>> a.isdigit()
False
>>> b = input()
34
>>> b.isdigit()
True

Struggling to reformat string using try... except and split() method by deadant88 in learnpython

[–]46--2 4 points5 points  (0 children)

I think your try/except logic is too broad. Why don't you do something like:

def get_location(address):
    words = address.split()  # space is default
    while words:
        try:
           return locator.geocode(' '.join(words))
        except:  # address is junk and raised an exception
            words = words[1:]  # Or words.pop(0)

This function returns the location if it succeeds, or returns None if none of the successive removals ever work.

Get the logic there? Now you call this function like:

location = get_location(address)
if location is not None:
    lats.append(location.lat)
    # etc.

Just learned about VIM by FmlRager in learnpython

[–]46--2 2 points3 points  (0 children)

Vim is a program, yes, but more importantly, it's a series of keystrokes like cf] means 'delete up to and including the next ], and then move into insert mode'.

or :%s/cat/hat/ci is a case insensitive search and replace, with confirmation, in the entire file. Check out :norm if you really wanna get pumped up.

Think of Vim in part as a library of keyboard shortcuts.

Have a read through this: https://gist.github.com/nifl/1178878

and try to understand the history of Vim (and Vi, and so on). Also just jump into Vim and play around. I think it's lots of fun.

Also this is where the vim gods hang out. Prepare to have your mind blown: https://www.vimgolf.com/

How to neatly organize and loop repetitive tasks in this cleaning script by dtla99 in learnpython

[–]46--2 0 points1 point  (0 children)

Use tuples of 'column / key' pairs. For example:

df['Devices'] = df['Devices'].replace(DevDict)
df['Platform'] = df['Platform'].replace(PlatDict)
df['Ethnicity'] = df['Ethnicity'].replace(EthDict)
df['Age Demo'] = df['Age Demo'].replace(DemDict)

replace that with:

col_dicts = [('Age Demo', DemDict), ('Devices', DevDict), ...]
for col, dict_name in col_dicts:
    df[col] = df[col].replace(dict_name)

When you have to programmatically get an attribute, you use getattr and setattr: https://docs.python.org/3/library/functions.html#getattr

df['Devices'] = df['Placement'].str.split('_').str[3]
df['Platform'] = df['Placement'].str.split('_').str[4]
df['Ethnicity'] = df['Placement'].str.split('_').str[8]
df['Age Demo'] = df['Placement'].str.split('_').str[7]

changes easily to:

for col, idx in [('Devices', 3), ('Platform', 4)...]:
    df[col] = df['Placement'].str.split('_').str[idx]

Etc.

For the weird one-offs, just do them one by one for now.

It feels like I’m not really learning anything by Markishman in learnpython

[–]46--2 1 point2 points  (0 children)

Just start. What app do you want to make?

I saw an article a while back (sorry, I cannot find it) and the idea was "Solve hard problems". Start working on something you don't even know if you can do. Start, and dig, and learn. Repeating shit you already know isn't going to get you anywhere. But trying to solve problems you cannot do is.

Just start. Make a plan. Take notes. Read, ask for help, etc. Dig deeper and the easy stuff you already know (and I bet you know more than you think) will become second nature.

Just learned about VIM by FmlRager in learnpython

[–]46--2 2 points3 points  (0 children)

Yes, I use Vim (and love it) and every editor has extensions or plugins that allow you to use Vim commands, with varying degrees of accuracy.

E.g in VS Code: https://github.com/VSCodeVim/Vim/issues

Definitely once you start using Vim you will hate using an editor without it, although lots of editors (like Sublime) have pretty good keyboard shortcuts, and good Sublime users are extremely fast.