shadwickman 159 Posting Pro in Training

Hello,

I was wondering how to go about having a redirect of stdout with Python take effect in a C extension. My python script redirects sys.stdout into a file handle created with open(...), but within the function in my compiled C-extension, any output (printf, puts, etc) is still given to the screen, and not the file object that the Python script invoking the extension is using.

Is there any good way to do this? The first thought in my head was to define a Python function that is passed a string and writes it to the file, and then pass that function into the C-extension as an argument. Then any output in C would be done via the passed-in function. Are there any proper ways of doing this?

Thanks!

shadwickman 159 Posting Pro in Training
shadwickman 159 Posting Pro in Training

I used to use FF all the time but honestly, it's becoming worse and worse in my opinion.

I've currently switched over to Iron (by SRWare), which is Chrome's source code minus any information mining crap by Google. I love how fast Chrome loads, and that there is pretty much no clutter with the UI, as the actual page takes up most of the space.

FF is seems to be getting bloated, and besides code testing + Firebug I don't use it anymore. I've been interested in looking at Opera too though...

shadwickman 159 Posting Pro in Training

How to Squander the Presidency in One Year

While I do not live in the US nor have been paying too much attention to their affairs for the past while, I have still really seen no difference in policies or anything else since Obama took office after Bush.

In my opinion, he was portrayed as liberal (as far as the US is concerned) during the election/presidential race, but once secured in office has turned much more conservative; not many changes to conservative policies put in place by predecessors.

Then again I don't know what the current situation is in congress and the senate so I'm not so sure how hard it would be for him to overhaul things (like it seemed he said he would do during the election campaign).

I guess we'll see what people really think once the next election rolls along; whether he gets reelected or booted.

shadwickman 159 Posting Pro in Training

I knew it was the memory manager of the OS, but I just wasn't sure if the compiler generated code to call it for all the indices or not. I'll take it then that the second snippet with the other for loop is the correct way. Thanks for confirming it for me!

shadwickman 159 Posting Pro in Training

Hello! I have a question in regards to malloc/calloc and free in C. What I'm unsure about is the "depth" (for lack of a better word) that free operates to. I know that sounds strange so let this example hopefully explain what I mean:

#include <stdlib.h>

int main ()
{
    int length = 10;
    char **list = (char **) malloc(sizeof(char *) * length);

    char *temp;
    int i;
    for (i = 0; i < length; i++)
    {
        temp = (char *) malloc(13);
        temp = "Hello world!\0";
        list[i] = temp;
    }

    free(list);  // free the char** AND all of its indices' malloc'd memory?
}

So I was wondering if the last call of free would not only free up the char ** memory of "list", but also all the malloc'd memory of each of its indices? Or does it not, and should in fact be called via:

for(i = 0; i < length; i++)
    free(list[i]);
free(list);

... which would explicitly free each index before the pointer to char pointers.

So would some compilers know that only freeing the list should free all its indices, or would I always get a memory leak with that? Either way, I want to know if there's an ANSI standard on this... which is probably the second method here if anything.

Thanks in advance for clearing up my confusion!

shadwickman 159 Posting Pro in Training

Hello, I know you probably get quite a few threads asking this, but the DaniWeb search didn't pull up what I was looking for. So here we go:

I have a page that I've made as "private" by including my access control script at the top. The access control script starts a session, then checks to see if a username and password were POSTed, and if not, if they are in $_SESSION. If all that fails, then it displays the log in page. If it gets results though, it validates them against my MySQL database of usernames + passwords. If that all goes to plan, then it allows the page which included it to finish loading.

I can try to go to this "private" page, and the login page gets displayed instead, so I enter my username and password, which is correct so it displays the "private" page. When I click a link that takes me to the other "private" page, it displays the login form first again, and THEN the other private page when I've rePOSTed my info.

So obviously the problem I'm having is that my session data is not persisting (even though I assigned keys in $_SESSION after logging in). My php.ini file has a correct path to a temp folder to store the sessions in, and I can actually see the session file in that directory when I'm on the private page, yet it has 0 bytes of info in it.

I'm …

shadwickman 159 Posting Pro in Training

Rumor has it she has a penis?? ...

As much as I have a very strong dislike for Lady Gaga, I think if it were true we'd see the bulge is her underwear, as she just doesn't seem to own a single pair of pants.

EDIT:
And to stay on topic:
http://www.youtube.com/watch?v=LkjLSzb2yFo

Enjoy.

shadwickman 159 Posting Pro in Training

Python doesn't need to explicity declare variables in the same way languages like C/C++, Java, etc. do. By writing for comment in inComment: you are creating a new variable called 'comment' that is set to the value of the current index of 'inComment' as it iterates through the indices for it. The thing is, with lists and tuples in Python, they don't need to be declared as only having one datatype; a list in Python can contain a string on one index, then a number, then a class instance, another list, etc. The contents of a list or tuple are fully flexible in that they can be completely of mixed data types. That being said, that means that 'comment' for the for loop will be a copy of each index, including whatever datatype that index may happen to be. Sorry for the mildly confusing explanation!

Also, the %d is an example of string formatting, the same as they have in C/C++ (is it in Java too?). Regardless, Python does not cast types for you automatically, meaning that print "comment found at line " + i will not work because you are joining a string with an integer. You could use print "comment found at line " + str(i) which converts 'i' to a string, which you can append to the rest of that line because its also a string. The %d is just the way for formatting a number via string formatting similar to printf in C. Here's a …

shadwickman 159 Posting Pro in Training

Sneekula's correct. You're storing each item in the inComments like so: (lineNumber, lineText) . So you just need to access the correct index of the tuple, the same way you would access an item in a list (or Array in Java); just use the square brackets to get the value from the list's item.

# assume inComments was built using your above code...
item = inComments[0]
# item is now a tuple of (lineNumber, lineText)

text = item[1]
# text is now a string of the second index of item

lineNumber, text = item
# demonstrates tuple or list unpacking, where it will assign the
# first value of item to the lineNumber variable, the second index
# to the text variable, and so on; it's a magical unwrapper of lists.
shadwickman 159 Posting Pro in Training

I've been listening to rather a lot today...
Clutch (Blast Tyrant) on the drive to work, Tool all morning, a bit of Frederik Thorendals Special Defects (Sol Niger Within) and Naked City (Torture Garden) over lunch... Currently listening to some Meshuggah (Destroy Erase Improve)..but thinking of switching to some Front Line Assembly, Skinny Puppy, Foetus or Venetian Snares for this afternoons slog!

You sir, have good taste.

shadwickman 159 Posting Pro in Training

Yeah I'm not fond of thrash metal...Try Panic Attack by Dream Theater if you havent already heard it. That's about as metal as I get.:)

Dream Theatre has some good progressive metal, and includes other genres like jazz and such. I've never been a huge listener of them, as I prefer Tool's sound.

Check out Vicarious from 10,000 Days:
http://www.youtube.com/watch?v=hii17sjSwfA

As you might have guessed, the majority of my music is metal (and all its sub-genres), but I still like stuff like the Beatles. Oh, and some old-school electronic music, like Sector or Pulse Legion.

shadwickman 159 Posting Pro in Training

The Beatles are not a boy band. They are all very talented musicians and songwriters. The Backstreet Boys and N SYNC are boy bands.

They were a boy band of their time, at least initially. Then the LSD and drugs kicked in and things moved off in a different direction.

The Evile song must be a downloadable song because its not on the disc ... thankfully

Ahah, just because you don't like thrash metal... anyways. I never said the Beatles were bad. I like a lot of their stuff, but that doesn't negate the fact that they were a boy band, at least initially.

Also, currently I'm listening through Dopesmoker, by Sleep. Longest track in my music library, that's for sure...

shadwickman 159 Posting Pro in Training

I'm really getting into the Beatles because of the new Rock Band game ...

I've always wondered, as a boy band, how did they ever gain such popularity?
Regardless, I'm listening to to Thrasher from Evile's "Enter the Grave" album. And their new album comes out later this month!

And by the way Grn Xtrm, this song is also apparently on Rock Band too :P

shadwickman 159 Posting Pro in Training

Python is a good choice for easy-going desktop application development. Of course, you're going to want to get adjusted to and familiarized with classes, methods/functions, etc. before starting on GUI projects.

And for GUIs, I'd still really suggest wxPython over Tkinter. I personally can't stand the non-native look of Tk's widgets, whereas wxPython's elements use the native operating system's look.

shadwickman 159 Posting Pro in Training

What I can recommend, though, is capturing the keypress key and appending that key's value to the text input.

Thanks, that would be nice if it were that simple :P I'd have to handle the proper action if the key was not a regular, printable character, such as if the user pressed left arrow, backspace, delete, etc.

On top of that, there goes support for different keyboards, because of the placement of different keys in different places on international keyboards. Because the keycode would be run through my script instead of the native handling on the client's browser/OS.

I think I'll just find some alternate solution for this...

shadwickman 159 Posting Pro in Training

Hello,

I am currently trying to figure out some event stuff with Javascript. I have the page capturing all onkeypress events by calling my function keyPress, and passing the event as an argument.

The key presses get passed to a text field that I have on the page (even if it's out of focus at the time of the key press) by using textfield.focus() within my keyPress function. This seems to pass the event along to the text field so that it registers the stroke and handles it as if the field was in focus at the time of the key press.

My problem lies in that I need to then grab the new value of the text field for use with another part of the script. It seems though that with the way I'm setting focus, it'll execute the rest of my keyPress function (with the outdated text field value) before the text field handles the event.

Is there a way to yield the event to this text field first?

Sorry, this was a long post, but I guess here's a short recap:
If I handle key presses via the body of the page, so that regardless of the text field's current state of focus it updates the text field accordingly, is there a way to have that happen first before the rest of my function that needs to use the new value of the text field?

Thanks in advance!

shadwickman 159 Posting Pro in Training

It would be nice if you explained the code above rather than just plopping it down on the page.

shadwickman 159 Posting Pro in Training

For some reason (this hasn't happened to me in the past), any wxPython scripts I package via py2exe crash on my other Windows computer (lacking a Python install). If I try running it on my other machine, I get an error message telling me to look at a log file that Windows has created. This is what it says (test.exe was my program):

Traceback (most recent call last):
  File "test.pyw", line 1, in <module>
  File "zipextimporter.pyc", line 82, in load_module
  File "wx\__init__.pyc", line 45, in <module>
  File "zipextimporter.pyc", line 82, in load_module
  File "wx\_core.pyc", line 4, in <module>
  File "zipextimporter.pyc", line 98, in load_module
ImportError: MemoryLoadLibrary failed loading wx\_core_.pyd

So it looks like there's a problem when trying to import something for the wxPython module. This happened on even the most basic of wxPython programs... this is the script I ran through py2exe:

import wx

app = wx.App()
frame = wx.Frame(None, -1, "Hello wxPython!", size=(300, 175))
frame.Centre()
frame.Show(True)
app.MainLoop()

And using this setup script for py2exe:

from distutils.core import setup
import py2exe

setup( name='test.exe', scripts=['test.pyw'] )

Does anyone have any clue as to what's messing up here? My guess is something with packaging wxPython as it says it's missing wx\_core_.py. I haven't had issues with this sort of thing in the past, but does anyone have any idea what I should try doing to fix it? Thanks in advance!

shadwickman 159 Posting Pro in Training

Thank you siddhant3s.

Wiki

and another link LOL

Yeah, I already Googled around but for some reason combining both the template part and the variadic part got me confused. Thanks though, I'm straightening it all out!

shadwickman 159 Posting Pro in Training

Yeah someone in the comments posted that English translation of the Hungarian part. Drone metal isn't really my thing, but I do have random times where I love to listen to it. One similar band that I prefer more though is Earth.

Earth - Engine of Ruin

shadwickman 159 Posting Pro in Training

you cant have an undefined amount of variables in function deceleration.

Seriously? There's no options that do this for regular functions, the same way it can be done for the main function when it's handed command-line arguments? I thought it was possible to do:

// something like
myFunction(12, 33, 5);

// ...rather than
int x[] = {12, 33, 5};
myFunction(x, 3);
// like you suggested

I know other languages have this functionality, like Python's *args and **kwargs options. I can always fall back to your approach, but I thought it would be much easier to use any sort of variable argument passing if C++ could offer it.

And thanks firstPerson for the help with getting the template stuff done correctly.

shadwickman 159 Posting Pro in Training
shadwickman 159 Posting Pro in Training

Hello, I've just recently tried to make a class template whose constructor should be able to accept a variable amount of arguments of the class passed to the template. I have something like this, with the prototype inside the class definition, and the actual implementation of the constructor defined outside:

template<class T>
class List
{
public:
    List(const T&, ...);
}


List::List(const T& first, ...) {
    // constructor here
}

This of course gives me errors, and I'm not entirely sure how to go about allowing the variable length of parameters, and combine that with the template idea. Thanks for any help!

shadwickman 159 Posting Pro in Training

edit your php.ini file

find this "short_open_tag = On" default is Off so turn it on.

Thank you so much, that was the problem!

shadwickman 159 Posting Pro in Training

Yes, I was just submitting the form data to the same page. But I'm just confused now because I'm wondering if the <?= ... ?> format works, because upon submission, I have another HTML segment to output some info, along with the statement:

<p>Your email is <?=$_POST['newemail']?>.</p>

Which should output the newemail variable stored from the POST action, but it outputs a blank. Within a PHP segment though, if I do echo $_POST['newemail']; , it displays the email stored as newemail.

Any suggestions?

shadwickman 159 Posting Pro in Training

Hello, I'm using easyPHP to locally test some scripts I'm building, but I came across a problem that I can't seem to resolve. Within one of my PHP scripts, there's a segment where I end the PHP ( ?> ) and output a form in HTML, then resume the PHP section ( <?php ). The problem is, in this HTML segment, I have the following in the action value for the form tag:

<form method='post' action="<?=$_SERVER['PHP_SELF']?>">
    <!-- etc... -->

When the form is submitted and the page reloaded with the POST values, I just get the following error:

Access forbidden!

You don't have permission to access the requested object. It is either read-protected or not readable by the server.

If you think this is a server error, please contact the webmaster.
Error 403

The URL bar has the address http://127.0.0.1/PHP Testing/<?=$_SERVER[PHP_SELF]?>.

I'm using Apache 2.2.13 with PHP 5.3.0 which all came with easyPHP 5.3.0. Can I assume that there are some values or permissions that I didn't set (possibly in php.ini)? And if so, how can I fix that? Any help would be appreciated, thanks!

shadwickman 159 Posting Pro in Training

... and I bet nobody is going to even notice it.

I noticed and I loved it haha. Nice to see some humour being put into this thread :D
And I thought that comic strip was actually really good.

shadwickman 159 Posting Pro in Training

Judging by your first post, when you said "link it to another ..." did you mean pass the values and variables from the first function to the second one?

If you specify what this "previous issue" is that you're trying to fix we can help you out better :P

shadwickman 159 Posting Pro in Training

Well if you install it manually, you need to put it into the C:\Python2X\Lib\site-packages directory in its own folder. Then in that site-packages folder, make a file called chilkat.pth, and in it, write only chilkat (which is the name of the folder for it in the site-packages directory). Hopefully after this, if you start up the interpreter and type import chilkat it should import like any other module.

I haven't ever used chilkat, but this is the generic way to install a regular package, if it doesn't come with its own setup.

shadwickman 159 Posting Pro in Training

Nope, there apparently are three causes of 9/11 and they're all 100% our fault.

I'd say America really does have to take a large part of the blame. The US has been trying to instill their politics in so many different countries over the years, it's no surprise that people will get eventually get angry. And again, the best example is the training of Bin Laden by the CIA, and the funding and support of the Taliban solely because it was an indirect way of confronting the USSR. Then in the mid 80s there was that scandal with Reagan (who's so well revered) where his government had subverted Congress in order to sell weapons to Nicaragua (via Iran) to fund the civil war going on there; another weaseling of themselves into politics that don't concern them.

That being said, I know that there are other factors that play into this, like as Vernon Dozier mentioned, brainwashing and indoctrination through religion. But at the same time, that needed a reason to start. The Afghans didn't wake up one morning and say "oh hey, let's hate America with a burning passion from now on". No, it stemmed from America's previous events and actions regarding Afghanistan, and possibly even other foreign affairs. And will that hatred stop once the democracy that the US wants has been crammed down the throats of the Afghans? I am still in doubt of that.

All in all though, it can be a very complicated matter …

shadwickman 159 Posting Pro in Training

If you don't mind as much about memory usage, you could use

if number in range(10, 24):  # careful!
# This gives a range of 10 - 23.
# The end index (24) isn't included in it.

if number in xrange(10, 24):
# The xrange doesn't load the range list into memory all at once,
# but iterates over it one value at a time.
# This can save you a lot of memory for intensive/large-scale things.
# Again, the end index isn't included in the range.
shadwickman 159 Posting Pro in Training

Have been trying to find a non-dodgy DL link for that one... can you post a source??

Um... firefox is available from the official site. Unless you thought he meant "firefox 4", in which case that's not even coming out this year.

shadwickman 159 Posting Pro in Training

Yes, nearly 100% of the citizens of Iraq voted and Saddam Hussein won 100% of those votes during the "election". But I would not have called that a democracy. Dictatorships are sometime disguised as democracies.

But kaninelupus said that in reference to Australia, not a country that whose government enforces single-party rule. The context of that quote makes all the difference...

But I see the point you're trying to make. I know that enforcing voting as mandatory restricts the rights of those who purposefully choose not to vote as an action of disfavour with the current politics. Yet, by not making voting mandatory, a new group is created - those people who don't vote only because they can't be bothered to. Sadly, in countries like America and Canada, this group makes up a large portion of the population, so that the voter turnout can be only ~60% on average. The problem raised by this is that only a slim majority of the country took action in choosing their "representative", and only a majority of those who turned out chose that particular representative over the opposition. This results in very skewed and disproportionate representation, and if the country uses a system like PR, rather than first-past-the-post, much more often the winner of the vote does not actually even hold a majority of the votes from those who voted - an even slimmer portion of the population deciding on the representative of the whole nation.

shadwickman 159 Posting Pro in Training

Now, if we could only find a way of controling the intrusive expansion of government in the our lives....

If I recall properly (because I may be wrong), but in theory extreme right (fascism) tends to allow less intellectual freedom, but it does allow economic freedom. Fascism has government control of personal rights and information and knowledge (sorry to be cliché, but think Orwell's 1984). Yet the far left (communism) allows intellectual freedom but not economic freedom, due to the government nationalizing all industry and such. Now, this was in theory. In practice, both extremes are much more similar (mostly because the extreme left is way too full of ideals that can't function in real life). So communism in practice ends up incorporating too many properties of fascism, thus leaving its citizens with neither intellectual nor economic freedom (usually).

Though it's funny how we always say that there are "communist governments" in some countries, but that in itself is an oxymoron. If they were practicing communism in accordance to the theory, there wouldn't actually be a government. Of course, that's not going to ever happen in real life.

I think one will always have government intrusion in one way or another.

shadwickman 159 Posting Pro in Training

I could give you a full example written for wxPython, but not for Tkinter, sorry :P

But regardless, you'll probably need to use threading for this, as your program will stall until the zip command is complete (I think?...) before continuing along with the rest of the script.
If that IS the case, then you can create a thread to run the zip command, and another to handle the message dialog and the updating of it. Otherwise, the subprocess module may be what you're looking for to run the zip command with.

Secondly, there should be some sort of dialog class in Tk like there is in wxPython. Something that holds the focus of the program so that the parent window can't be accessed until the pop-up is destroyed. I have never used Tk so I don't know if this code will be helpful to you, but this may be what you're looking for:
http://www.java2s.com/Code/Python/GUI-Tk/Customizeddialog.htm

I don't know if that will maintain the program's focus on the dialog though. wxPython dialogs have the ShowModal() method to do this... I assume Tk has an equivalent.

Sorry I can't be more specific!

shadwickman 159 Posting Pro in Training

No offense, but gross code you have there. You have an unbelievable amount that's just copy-pasted. I mean, all the questions are running pretty much the exact same code except for the Q it prints and the answer that's correct. This is what a function would be VERY useful for. Set it up so that you have a function that performs the question code, and just have it accept a string as the question, and a string of the correct letter. Roughly laid out as so:

# obviously this isn't valid Python code, just a template
def doQuestion(question, answer):
    print question
    get input
    if input is answer:
        do correct stuff
    else
        wrong stuff

# just make calls to that ONE segment of code with different arguments:
doQuestion('How old is the Internet?\nA. 5 years ...ETC', 'A')

Also, if I typed 'c' (lowercase) as an answer for a question whose answer is C, your program will tell me I'm wrong. It's comparing the user answer to only the uppcase letter. Just convert the user's answer to uppercase first by calling the upper() method on the string: if userAnswer.upper() == 'A' .

shadwickman 159 Posting Pro in Training

"Fear of the Dark" and "Number of the Beast" by Iron Maiden.

You sir, have good taste. I'm giving a run through the album "Sin After Sin" by Judas Priest :)

shadwickman 159 Posting Pro in Training

Like Hiroshe said, learning a programming language depends on what you're trying to use it for. Different ones are suited for different things. They also all have pros and cons so you'll most likely be using a variety of languages.
Although, there are general theory aspects that you can usually apply to a variety of languages.

Hiroshe >> Maybe assembly language
You actually have a good point there. Honestly, if one can master assembly then high-level languages would feel so utterly automated :P I second this suggestion hahah (Now to get brush up on my Assembly skills... or lack thereof.) Maybe also try looking into Fortran and/or Lisp while you're at it?

shadwickman 159 Posting Pro in Training

The armRight variable is declared and assigned to True before it is called for anything.

I'm quite sleepy, so excuse me if I'm way off here, but is armRight declared within the global scope of the script? If so, then you need to state global armRight within your function so that when you modify armRight within the function, it does in fact change the global armRight.

And when you get into passing within Python, I find it tends to get a lot more complicated than the straight-forward ways of passing in C++. It's kind of a hybrid I guess, but you do get used to the way if works and if you use Python long enough you structure your code work quite seamlessly with this part of the language.

This can sum it up fairly well though:
"If using objects' methods within a called function, a variable is considered “passed by reference” – it is modified out of the function’s scope. If using assignment on a mutable object, it is created a-new within the function, and the global value isn’t modified."

You can take a peek at a short but to-the-point snippet about Python's passing of arguments here.

shadwickman 159 Posting Pro in Training

Oh damn, I forgot, sorry. The list you pass to join should be strings, so it looks a bit messier but you could change that to this:

fh.write(','.join([str(i) for i in [gold, level, ship]]))

Which makes a list of gold, level, and ship converted to strings.

shadwickman 159 Posting Pro in Training

Well you've screwed up the try/except thing that I've tried to explain over and over.

You currently have the if statements inside the except block, meaning if there is an error it will print what you've written, and then try to load or save the game. Neither of those will become true anyways because the only reason the except block got fired was because 'choice' was not an integer.

For the last time, I'll fix your try/except part:

while True:
    try:
        choice = int(raw_input('Input a Number! \n'))
    except ValueError:
        print 'Invalid Input, Please type a Number!\n'
    else:
        break

if choice == 1:
    LoadGame()
elif choice == 2:
    SaveGame()

If you still don't understand the above code, you can find at least 5 posts in this thread where I've explained it.

Also, your LoadGame function won't do anything. You're using global variables for gold, level, etc. so you actually need to declare them as global inside that function in order to modify them:

def LoadGame():
    global gold, level, ship

    fh = open('saved_data', 'r')
    data = fh.read()
    fh.close()
    data = data.split(',')
    gold = int(data[0])
    level = int(data[1])
    ship = data[2]
shadwickman 159 Posting Pro in Training

Well like I was saying, you'd be using pickle for classes and stuff more (or dicts, lists, or tuples).

If you're only wanting to save something like gold, level, ship, then you should only need the basic file I/O like I showed above, not pickle.

And as for placement, you're going to want to put the saving code into a function (saveGame) and the loading code into its own as well (loadGame).

Obviously, you'd want to call the saveGame function when the user wants to quit, so you need to make a call to it, saveGame(), before allowing your script to end.

As for loading, at the start-up of your game, if a user wants to load a game instead of starting a new one, then you'd have to make a call to the loading function, via loadGame(). This function should modify the global variables that you're using in your script. (Or if you were passing values around instead of using global ones, it could return those variables.) Then your game could begin with those modified variables instead of setting them to a new game's default values.

shadwickman 159 Posting Pro in Training

Then you can just invent some simple format for a file to write that to. Say, the file has the values stored, separated by commas, in a specific order, like: gold,level,ship,name So you would just need to write those variables to a file like you would anything else. And then you'd need to re-assign them upon reading a file like that.

# SAVING:
fh = open('saved_data', 'w')
fh.write('%s,%s,%s,%s' % (gold, level, ship, name))
# or
# fh.write(','.join([gold, level, ship, name]))
fh.close()

# LOADING:
fh = open('saved_data', 'r')
data = fh.read()
fh.close()
data = data.split(',')
gold = int(data[0])
level = int(data[1])
ship = data[2]
name = data[3]

If you're making a game you'll soon realize how useful and simple it is to use pickle with the objects you want to save.

shadwickman 159 Posting Pro in Training

Beck dressed up

Nice one! Thank you for that image hahaha :)

shadwickman 159 Posting Pro in Training

What is it you want to save exactly? This is where classes could come in VERY handy. If you had a player class, and all the stuff you wanted to save were properties of that class (like player.gold, player.name) then you could just pickle the whole class instance to a file. Then when reloading the game, you just make the instance of the player in the game the unpickled instance from that same file.

Example usage:

import pickle

# SAVING:
# assuming that 'player' is the class instance you want to save
fh = open('saved_data', 'w')
pickle.dump(player, fh)
fh.close()

# LOADING:
# 'player' is now the same as the instance you saved
fh = open('saved_data', 'r')
player = pickle.load(fh)
fh.close()

You can read about the pickle module here. It's a very easy way of serializing data for saving and stuff.

shadwickman 159 Posting Pro in Training

Instead of using a global variable for p, you could just pass that to the function as an optional parameter for the recursion you're doing. And you may want to rename the function. I think that loop is not a great description of what it does; something like sumOfDigits is better.

Other than that, you can't actually modify p within the loop function until you define p as the global WITHIN the loop function, like:

p = 0
def loop():
    global p
    # now you can modify p in this function's scope

Also, your code will always print 0. You never actually make a call to the loop function at all! You just define it.

shadwickman 159 Posting Pro in Training

For collision detection, tomtetlaw had a similar question, so I'll give you the same answer I gave him. This is for simplistic levels:

Why not try making a black and white image for your level, where white is free space, and black is blocked space (or vice-versa)? Then you can load this image and read the colour values of it using the Python Imaging Library (PIL), and save this data into a list. Or even better, save it into a Numpy array which is faster as far as I know.

Then, when you call the function to move the player, take the coordinates that the player would be at if you allowed the move. Compare these coordinates to the corresponding spot in your black and white map list, and if it has white space, allow the player to move there. If it's black, then end the function without moving the player. You'd also need to take into account the width and/or height of the player, and check that whole area on your collision map, so that you ensure the whole player would be moving into free/available space.

Obviously this isn't good for loading huge levels at a time, but it's ok for simple platformers. If it's for a larger map, you'll want to come up with some sort of optimized loading system for keeping the memory usage down by only loading applicable map segments at a time.

It's also even better if your game can be …

shadwickman 159 Posting Pro in Training

Bumsfeld is putting you on the right track. I'll say not to convert the raw_input to an integer like you're doing now, so that you can cycle through each character in it as a string. Then just make sure to convert to integers at the right times (i.e. when adding them).

shadwickman 159 Posting Pro in Training

Flash can take command-line arguments. So you can do os.system("flash.exe myFileToOpen.fla") . That'll open Flash and have it open the document "myFileToOpen.fla".

If the FLA is in a different directory however, you'll need to give the path in front of the filename in the command line argument. It can be relative or absolute. And if it contains spaces, you'll need to wrap it in quotes.

# absolute path and with quotes because of spaces
os.system("flash.exe 'C:\the\directory\to my file\here.fla'")
# or for relative, using just the .. syntax
os.system("flash.exe ../doc.fla")