FreezeBlink 0 Light Poster

Is there any easy, very fast way to edit image files with Python? Any extension that Windows uses is fine.

FreezeBlink 0 Light Poster

I'm currently working on an application to which sound integration is important. Currently I'm using winsound for all the sound-related aspects of the program, but it is sub-optimal. I've been unable to make it completely work, and .wav files are bulky. Are there any equally usable alternatives to winsound?

FreezeBlink 0 Light Poster

Sorry, was I unclear? In essence, what I'm asking is how to construct a pointer in Python.

Suppose, for instance, you have a simple game, with an item creation mechanic that combines items into a new item. To add some mystery to it, you want the *option* of either showing what item will be produced or hiding it behind a "???" or something.

So, ideally, you would create an 'item' class, and give it two properties:
'name', and 'creationName' or something of the sort, where 'name' is the item's name, and 'creationName' is what the player is shown when creating it.

Now, then, you could simply set both of them to what you want whenever you made an item instance, but it would be much more convenient if 'creationName' automatically took on whatever value 'name' had, unless you set it to a different value. Here's more or less how it would look, ideally:

>>> class item:
	name = "An item"
	creationName = something

	
>>> itemInstance = item()
>>> itemInstance.name
'An item'
>>> itemInstance.creationName
'An item'
>>> itemInstance.name = "Different name."
>>> itemInstance.name
'Different name.'
>>> itemInstance.creationName
'Different name.'

Can this be done?

FreezeBlink 0 Light Poster

What you're looking for is collision checking. Off the top of my head, I don't have any examples of it, but a search on 'Python Square Collision Checking' or something like that might turn up an answer.

Will the square rotate, or will it always be aligned with the x/y axes? Because if it doesn't rotate, it would be much simpler to simulate.

FreezeBlink 0 Light Poster

I know, this is a stupid question, but is it possible for a class to have two variables, one of which has a value, and the other of which will always hold the same value, unless the user changes it?

In essence, making the second variable a duplicate of the first unless changed. Is this possible? And if so, how?

FreezeBlink 0 Light Poster

Sounds like that should work. Thanks!

FreezeBlink 0 Light Poster

Sorry to have to post two consecutive questions for other people to help me with, but I'm having a problem with winsound that I simply can't figure out. I've checked all the documentation I could, but there's no answer.

The problem is with SND_PURGE.

SND_PURGE
Stop playing all instances of the specified sound.

This is used in conjunction with PlaySound, which has the following entry:

PlaySound( sound, flags)

Call the underlying PlaySound() function from the Platform API. The sound parameter may be a filename, audio data as a string, or None. Its interpretation depends on the value of flags, which can be a bit-wise ORed combination of the constants described below. If the system indicates an error, RuntimeError is raised.

Also, SND_FILENAME is needed, I believe, since I'm playing from a file.

SND_FILENAME
The sound parameter is the name of a WAV file. Do not use with SND_ALIAS.

--------------------

Alright, so here's a problem. Put simply, SND_PURGE appears to do nothing.

Yes, absolutely nothing, no matter how I present it.

Take the following code. It shouldn't do anything, right?

from winsound import *

PlaySound("testSound.wav",SND_FILENAME) # Play testSound.wav
PlaySound("testSound.wav",SND_FILENAME|SND_PURGE) # Stop playing testSound.wav

Well, that doesn't work. Take out the SND_FILENAME from the fourth line? Still doesn't work. Am I using this wrong? And if so, can someone propose an alternative? Thanks in advance.

FreezeBlink 0 Light Poster

Really, the title says it all. Is there any way to compile all the instances of a class into a list, or other such data structure?

FreezeBlink 0 Light Poster

It's always bugged me how it seems that the only way to find out where you are inside a for loop is to use a counter. For instance, suppose you want to iterate through a list, and print every entry on a second line, but for the second-to-last entry you also want to print "Fish sticks" after the entry. This is the best way I know of to do this:

counter = 0
for entry in fishSticksList:
   print entry,
   if counter == len(fishSticksList) - 2:
      print "Fish sticks"
   else:
      print ""
   counter += 1

Now, that's not all that bad, but it irks me that it requires a counter variable. I doubt it, but is there any way to do this without creating a counter?

FreezeBlink 0 Light Poster

Are there any ways to do something of that sort which are not Unix-only?

FreezeBlink 0 Light Poster

I've been trying to program a "press any key to continue" function, simply because raw_input feels noobish, but so far I haven't been having much luck.

I did a search and the opinions are nearly unanimous that getch() is the way to go, but...things haven't gone that well. Here's an example of what happens:

from msvcrt import getch
while 1:
   keyPressed = getch()
   print keyPressed
   if keyPressed == "x":
      break

The output of running this seemingly harmless program? An infinite loop, even after pressing "x". What's more, getch() seems to pick up the "enter" keystroke to execute this, long after I've lifted the key.

What this looks like to me --and I could be wrong-- is that keystrokes are stored in a stack or list of some sort, and the "Enter" keystroke is on the top of that. It seems that getch() reads the top entry, but *does not remove it*, causing that keystroke to be read for eternity.

I checked both the Python docs and the module docs for info on msvcrt to try to find a way to clear the "enter" keystroke and move on to the next one, but I found utterly nothing. At all.

Anyone know how it's done?

FreezeBlink 0 Light Poster

Because if you create a new list and assign it to the old one, you're creating an un-needed variable.

FreezeBlink 0 Light Poster

Iterating over a list, possibly deleting elements. It's the bane of my existence. Suppose, for instance, we have a list of numbers, and want to iterate over it and delete each and every odd one. Sounds simple, right?

Sorta. It's trivial, but the code you end up with is pretty gruesome.

>>> nums = [1.0,2.0,3.0,4.0,5.0]
>>> for n in range(len(nums)-1,-1,-1):
	# Same as saying "if nums[n] is odd"
	if nums[n] % 2 != 0:
		del nums[n]

		
>>> print nums
[2.0, 4.0]

Surely there's a cleaner way to do that loop? Anyone?

FreezeBlink 0 Light Poster

Just noticed an odd little problem. Instead of explaining it, take a look at this IDLE run:

>>> ================================ RESTART ================================
>>> class test:
	eggs = True

	
>>> var1 = test()
>>> var2 = "text"
>>> type(var2)
<type 'str'>
>>> type(var2) == str
True
>>> type(var1)
<type 'instance'>
>>> type(var1) == instance

Traceback (most recent call last):
  File "<pyshell#49>", line 1, in <module>
    type(var1) == instance
NameError: name 'instance' is not defined

What's with that?

FreezeBlink 0 Light Poster

At various points in my text-based programs, I've had to write a function for use in multiple-choice menus. It needs to have the following qualities:

  • Ignores non-number input, repeating the request if it is given a string.
  • Can be given upper and lower limits on the acceptable numbers, repeating the request if the number the user enters is outside these limits.
  • Either or both limits must support being given the value False, in which case that limit will not be applied.

I already have a bit of code for this, but I hate its sheer ugliness and clumsiness. Here it is:

def getChoice(bottom,cap):
    testOne = False
    testTwo = False 
    while testOne == False or testTwo == False:
        
        choice = raw_input()
        
        try:
            choice = int(choice)
            testOne = True
        except:
            print "Please give a valid answer."
            testOne = False

        if (testOne == True):
            if ((choice < bottom) and (bottom != False)) or ((choice > cap) and (cap != False)) or (choice != round(choice)):
                print "Please give a valid answer."
                testTwo = False
            else:
                testTwo = True

    return choice

I'm not even sure if it's bug-free. Anyone able to suggest improvements or better implementations?

FreezeBlink 0 Light Poster

Sorry--I just realized that wasn't worded very clearly. What I mean is this:

Is it possible for Python to store the output of calling os.system([command])? For instance, is it possible to store, in a list, all the results of os.system("dir")?

FreezeBlink 0 Light Poster

That helps very much, thanks! One last thing, is it possible for Python to read the output of the commands it executes? For instance, storing the contents of a directory in a list?

FreezeBlink 0 Light Poster

This is probably totally absurd, but...is it possible to, through Python, access the command line and use it? For instance, write a program that outputted all of the files in a given directory, much like

cd [directory]
dir

would?

FreezeBlink 0 Light Poster

For instance, if you have the following (random example):

w = input("Enter width")
h = input("Enter height")

for x in range(0,w):
    for y in range(0,h):
        print x,y
        if (raw_input("Stop? y/n") == "y"):
            break

That would only break out of the y loop. You could introduce another variable, and change the loop to more or less this form:

for x in range(0,w):
    for y in range(0,h):
        print x,y
        stop = raw_input("Stop? y/n")
        if stop == "y":
            break
    if stop == "y":
        break

But that's pretty ugly, and there are a few cases where it could get very complicated, and you'd need to introduce a flag. Instead, is there any way to tell the break to break out of two levels instead of just one?

FreezeBlink 0 Light Poster

cell.health -= fighters[0].compDmg(fighters[0],cell)
TypeError: compDmg() takes exactly 2 arguments (3 given)

Both fighters[0] and cell are object instances. How on earth does it see 3 arguments in this? I don't think wider context is needed, but just ask if it is.

FreezeBlink 0 Light Poster

A classic of early text-based interfaces... Any way to do it in Python? I tried getch(), but it doesn't really work (for instance, if you hit Enter to confirm a menu selection, and then it goes to a "press any key" thing with getch(), getch() will pick up the Enter keypress.)

Any ways around this?

FreezeBlink 0 Light Poster

And, um, while we're at it...what does Lambda do, anyway?

FreezeBlink 0 Light Poster

There's a function that repeatedly shows up in languages, usually with more or less the following form (Python syntax):

var1 = raw_input("Input a number between one and three.")

choose var1:
   case "1":
      print "You inputted one."
   case "2":
      print "You inputted two."
   case "3":
      print "You inputted three."

Or something like that. I've also seen it called "switch." Does Python have anything like this?

FreezeBlink 0 Light Poster

Python's system of deciding for you what type to give all your variables is nice and all, but is there a way to force it to give a variable a certain data type? For instance, if you give it the following:

n = 2
m = 3
print n/m

It'll print out 0, because all the variables are ints, and it truncates the fraction off. Any way to get around this?

FreezeBlink 0 Light Poster

Recently I downloaded Ubuntu v8.04 (Hardy Heron), and was delighted to find Python pre-installed. However, that pleasant surprise was soon dampened by the fact that IDLE would not run, and so I am left without a decent program for coding in Python. gedit works, but lacks pretty much everything except color-coding. Anyone have a suggestion?

FreezeBlink 0 Light Poster

Hey. I'm working on a simple project that requires a way to find all the empty grid cells accessible along a path that's <= n cells long (an analogy would be TBS movement), and I've got an almost-working piece of code for it. Here's the function I wrote:

def findArea(distance,origin,gridUsed,emptyChar):
    if emptyChar == "x":
        seenChar = "X"
    else:
        seenChar = "x"
    grid = gridUsed
    grid[origin[0]][origin[1]] = seenChar
    returnList = [[origin[0],origin[1]]]
    if distance > 0:
        # x,y-1
        if (origin[1]-1) >= 0:
            if (grid[origin[0]][origin[1]-1] == emptyChar):
                returnList += findArea(distance-1,[origin[0],origin[1]-1],grid,emptyChar)

        # x,y+1
        if (origin[1]+1) < len(grid[0]):
            if (grid[origin[0]][origin[1]+1] == emptyChar):
                returnList += findArea(distance-1,[origin[0],origin[1]+1],grid,emptyChar)

        # x-1,y
        if (origin[0]-1) >= 0:
            if (grid[origin[0]-1][origin[1]] == emptyChar):
                returnList += findArea(distance-1,[origin[0]-1,origin[1]],grid,emptyChar)

        # x+1,y
        if (origin[0]+1) < len(grid):
            if (grid[origin[0]+1][origin[1]] == emptyChar):
                returnList += findArea(distance-1,[origin[0]+1,origin[1]],grid,emptyChar)
    returnList.sort()
    print "gridUsed:"
    print gridUsed
    print "grid:"
    print grid
    return returnList

gridW = 4
gridH = 4
emptyChar = " "

gameGrid = []
for xVar in range(0,gridW):
    gameGrid.append([])
    for yVar in range(0,gridH):
        gameGrid[xVar].append(emptyChar)

print "Before anything:"
print gameGrid
findArea(1,[2,2],gameGrid,emptyChar)
print "After everything:"
print gameGrid

You'll notice a lot of print-ing going on that's not really needed. The reason for that is I'm trying to debug it, and I'm having serious trouble. gameGrid, which exists on the main level, is somehow being altered within findArea. Which makes no sense. As far as I know, findArea has its own level of scope, it shouldn't be able to make changes outside that. Not to mention that I don't actually use gameGrid within findArea. The problem …