Re: [Tutor] Moveable and Animated Sprites

2011-08-15 Thread Alan Gauld

On 15/08/11 03:09, Jordan wrote:

Is there a more Pythonic way to create the class
"MoveableAnimatedSheetSprite" I am using multiple inheritance but I see
that I am really loading the image twice when I call __init__ for
"AnimatedSheetSprite" and "MoveableSprite". Should I just make a
moveable class and have moveable items inherit it with out inheriting
from "Sprite"?


This is really more a pyGame question than a Python one so you will
probably get a better response posting on the PyGame forum.
However there are a few pyGamers here so you might get lucky...


class Sprite(pygame.sprite.Sprite):
 def __init__(self, imageName, startx=0, starty=0):
 pygame.sprite.Sprite.__init__(self)
 self.image=pygame.image.load(imageName)
 self.rect=self.image.get_rect()
 self.image.convert()
 self.x=startx
 self.y=starty
 self.position=vec2d(self.x,self.y)
 self.selected=False

 def update(self):
 pygame.sprite.Sprite.update(self)



If you are just calling the superclass you don't need this method.
But I assume you will be adding extra content later? If not, your
subclasses can still call Sprite.update() without this definition being
here.

Beyond that I can't add much...

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Moveable and Animated Sprites

2011-08-15 Thread Peter Otten
Jordan wrote:

> Is there a more Pythonic way to create the class
> "MoveableAnimatedSheetSprite" I am using multiple inheritance but I see
> that I am really loading the image twice when I call __init__ for
> "AnimatedSheetSprite" and "MoveableSprite". Should I just make a
> moveable class and have moveable items inherit it with out inheriting
> from "Sprite"?
> By the way the code does work as intended right now.
> Thank you in advance, if you need more code or what ever just let me know.

You can use super() to avoid duplicate method calls in a diamond-shaped 
inheritance tree. The vanilla example:


>>> class A(object):
... def __init__(self):
... print "A"
... super(A, self).__init__()
...
>>> class B(A):
... def __init__(self):
... print "B"
... super(B, self).__init__()
...
>>> class C(A):
... def __init__(self):
... print "C"
... super(C, self).__init__()
...
>>> class D(B, C):
... def __init__(self):
... print "D"
... super(D, self).__init__()
...
>>> D()
D
B
C
A
<__main__.D object at 0x7f5345de9d50>

In your code it's a bit harder because you need compatible method 
signatures. One way to achieve that is to rely on keyword arguments and then 
stick in **kw. To illustrate:

class Sprite(pygame.sprite.Sprite):
def __init__(self, imageName, startx=0, starty=0, **kw):
super(Sprite, self).__init__(self)
...

class MoveableSprite(Sprite):
def __init__(self, imageName, **kw):
super(MoveableSprite, self).__init__(imageName, **kw)
speed = kw["speed"]
...

m = MoveableSprite("rumpelstiltskin", speed=10, category="fairy tale")

I usually don't get it right the first time, but here's what I think your 
update() method would become:

class Sprite(pygame.sprite.Sprite):
pass # no need to implement update() here

class AnimatedSheetSprite(Sprite):
def update(self):
super(AnimatedSheetSprite, self).update()
self.animate()

class MoveableSprite(Sprite):
def update(self):
super(MoveableSprite, self).update()
self.move()
   
class MoveableAnimatedSheetSprite(MoveableSprite, AnimatedSheetSprite):
pass # no need to implement update() here



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] print to file probelm

2011-08-15 Thread John Collins

Hi,
I'm a baffled beginner. The script below is one of a suite of scripts 
written by Simon Tatham a decade ago;

http://www.chiark.greenend.org.uk/~sgtatham/polyhedra/
http://www.chiark.greenend.org.uk/~sgtatham/polyhedra/polyhedra.tar.gz

OS: WinXP
Py Ver: 2.7
Script: canvas.py

It reads from a file name in the command line and should print to a file 
name also specified in the command line. It inputs and runs fine but 
outputs to the command prompt *screen* while creating and *empty* output 
file of the name specified? I cannot figure out why?


[the dashed lines below are not in the script(s)]
---
#!/usr/bin/env python

# Read in a polyhedron description, and output a JavaScript list
# suitable for use in the "data" field of a canvas used by
# canvaspoly.js.

import sys
import os
import string
import random
from math import pi, asin, atan2, cos, sin, sqrt
from crosspoint import crosspoint

args = sys.argv[1:]

if len(args) > 0:
infile = open(args[0], "r")
args = args[1:]
else:
infile = sys.stdin

if len(args) > 0:
outfile = open(args[0], "w")
args = args[1:]
else:
outfile = sys.stdout

vertices = {}
faces = {}
normals = {}

lineno = 0
while 1:
s = infile.readline()
if s == "": break
sl = string.split(s)
lineno = lineno + 1
if sl[0] == "point" and len(sl) == 5:
vertices[sl[1]] = \
(string.atof(sl[2]), string.atof(sl[3]), string.atof(sl[4]))
elif sl[0] == "face" and len(sl) == 3:
if not vertices.has_key(sl[2]):
sys.stderr.write("line %d: vertex %s not defined\n" % \
(lineno, sl[2]))
else:
if not faces.has_key(sl[1]):
faces[sl[1]] = []
faces[sl[1]].append(sl[2])
elif sl[0] == "normal" and len(sl) == 5:
if not faces.has_key(sl[1]):
sys.stderr.write("line %d: face %s not defined\n" % \
(lineno, sl[1]))
else:
normals[sl[1]] = \
(string.atof(sl[2]), string.atof(sl[3]), string.atof(sl[4]))
else:
sys.stderr.write("line %d: unrecognised line format\n" % lineno)
continue
infile.close()

# Normalise the radius of our polyhedron so that it just fits
# inside the unit sphere.
maxlen = 0
for v in vertices.values():
vlen = sqrt(v[0]**2 + v[1]**2 + v[2]**2)
if maxlen < vlen: maxlen = vlen
for v in vertices.keys():
vv = vertices[v]
vertices[v] = (vv[0]/maxlen, vv[1]/maxlen, vv[2]/maxlen)

# Assign integer indices to vertices and faces.
vindex = {}
findex = {}
vlist = []
flist = []
for v in vertices.keys():
vindex[v] = len(vlist)
vlist.append(v)
for f in faces.keys():
findex[f] = len(flist)
flist.append(f)

s = "[%d" % len(vertices)
for i in range(len(vertices)):
v = vertices[vlist[i]]
s = s + ",%.17g,%.17g,%.17g" % (v[0], v[1], v[2])
s = s + ",%d" % len(faces)
for i in range(len(faces)):
f = faces[flist[i]]
n = normals[flist[i]]
s = s + ",%d" % len(f)
for v in f:
s = s + ",%d" % vindex[v]
s = s + ",%.17g,%.17g,%.17g" % (n[0], n[1], n[2])
s = s + "]"
print s
--

The other scripts run and output just fine. They do have some extra 
script of varying parameters that seem to be about reassigning the print 
command, possible with formatting of output in mind? Here are a those 
sections from two of the other scripts:


From mkpoints.py

def realprint(a):
for i in range(len(a)):
outfile.write(str(a[i]))
if i < len(a)-1:
outfile.write(" ")
else:
outfile.write("\n")

def pprint(*a):
realprint(a)
--
the final output lines are
--
# Output the points.
for x, y, z in points:
pprint(x, y, z)
--

From drawpoly.py
--
def realprint(a):
for i in range(len(a)):
outfile.write(str(a[i]))
if i < len(a)-1:
outfile.write(" ")
else:
outfile.write("\n")

def psprint(*a):
realprint(a)
--
the last two output lines are
--
psprint("showpage grestore")
psprint("%%EOF")
--

For the problem script, canvas.py, the output is a long single line 
beginning with a "[", containing a mixture of integers and signed real 
numbers separated only by a commas, and ending in a "]".


Any help to begin my understanding of print (re)assignments, and, fixing 
this script would be MOST welcome, thanks to you all!


Best Regards,
John. [Total newbie, time since first Python DL, <24hrs! Still use
   GWBasic!!! ... Really need to learn Python!]
_

Re: [Tutor] print to file probelm

2011-08-15 Thread Peter Otten
John Collins wrote:

> Hi,
> I'm a baffled beginner. The script below is one of a suite of scripts
> written by Simon Tatham a decade ago;
> http://www.chiark.greenend.org.uk/~sgtatham/polyhedra/
> http://www.chiark.greenend.org.uk/~sgtatham/polyhedra/polyhedra.tar.gz
> 
> OS: WinXP
> Py Ver: 2.7
> Script: canvas.py
> 
> It reads from a file name in the command line and should print to a file
> name also specified in the command line. It inputs and runs fine but
> outputs to the command prompt *screen* while creating and *empty* output
> file of the name specified? I cannot figure out why?

> args = sys.argv[1:]
> 
> if len(args) > 0:
>  infile = open(args[0], "r")
>  args = args[1:]
> else:
>  infile = sys.stdin
> 
> if len(args) > 0:
>  outfile = open(args[0], "w")
>  args = args[1:]
> else:
>  outfile = sys.stdout

If you pass two args this will open two files, infile for reading, and 
outfile for writing. While infile is actually used...

> while 1:
>  s = infile.readline()
>  if s == "": break
   ...
> infile.close()

... outfile is not. The print statement

> print s

will always write to stdout. You can modify the print statement to

print >> outfile, s

or use

outfile.write(s + "\n")

instead. It is good style to close the file explicitly when you're done with

outfile.close()


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] print to file probelm

2011-08-15 Thread Prasad, Ramit
Hi John,

Just as a note, I am looking at the included scripts (and not the linked 
scripts). I believe the problem you are having is with the lines below. 


for i in range(len(faces)):
 f = faces[flist[i]]
 n = normals[flist[i]]
 s = s + ",%d" % len(f)
 for v in f:
 s = s + ",%d" % vindex[v]
 s = s + ",%.17g,%.17g,%.17g" % (n[0], n[1], n[2])
s = s + "]"
print s

The problem is probably caused by the very last line above. This prints 's' to 
std out (the console) instead of a file. This should probably be something like 
 (not tested - just a guide)
outfile.write(s)
outfline.close()


I would also like to add that string concatenation is not recommended in 
Python. The better way to concatenate is to do something like:

S = []
s.append( 'test' )
s.append( ",{0}".format( vindex[v] ) )
s.append( ",%.17g,%.17g,%.17g" % (v[0], v[1], v[2]) )
# Join at the very end
" ".join(s)


Furthermore, the following can be easily written without the backslash (which 
can be prone to errors if something appends anything after it (like non-CRLR 
whitespace --or whatever Windows uses). Instead you can wrap things is 
parenthesis

normals[sl[1]] = \
 (string.atof(sl[2]), string.atof(sl[3]), string.atof(sl[4]))

Try this instead:
normals[sl[1]] = (string.atof(sl[2]), 
 string.atof(sl[3]), string.atof(sl[4]))


OR if you have a single long string. 
Var = ( self.really_long_variable_name + some_other_really_long_variable + 
what_another_really_long_variable ) # returns a single element

Be careful not to put a comma at the end of the parenthesis, because if you do 
the statement will return a tuple instead.

Var = ( self.really_long_variable_name + some_other_really_long_variable + 
what_another_really_long_variable, ) # returns a tuple with one 
element



Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] which version do i have and how do i change it

2011-08-15 Thread Connor Merritt
So i installed python 2.7.1 on my linux and i bought a book that requires
python 3 so installed python 3, and i used terminal and typed in python -V
and it said 2.7.1 how do i get it to be 3 (i tried deleting it but i
couldn't what should i do?)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] which version do i have and how do i change it

2011-08-15 Thread Walter Prins
On 16 August 2011 00:43, Connor Merritt  wrote:

> So i installed python 2.7.1 on my linux and i bought a book that requires
> python 3 so installed python 3, and i used terminal and typed in python -V
> and it said 2.7.1 how do i get it to be 3 (i tried deleting it but i
> couldn't what should i do?)
>

Try

python3 -V

The default is probably still Python2 but that does not mean you can't use
Python explicitly.

Walter
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] which version do i have and how do i change it

2011-08-15 Thread Walter Prins
On 16 August 2011 00:48, Walter Prins  wrote:

> The default is probably still Python2 but that does not mean you can't use
> Python explicitly.
>

Meant to say, "can't use Python3 explicitly".
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] directory within directory

2011-08-15 Thread questions anon
I would like to open up a bunch of files within a folder within a folder and
then process them and output them in another location but with the same
folder structure. I seem to having trouble with the folder within folder
section.
I have a separate folder for each year and then within a year I have a
separate folder for each month but when I try to make a directory in a new
location it does not place the month folders within the year folders,
instead they are all places in the outputpath together
any help will be greatly appreciated

import os

inputpath=r'E:/temp_samples2/'
outputpath=r'E:/figureoutputs/'

for (path, dirs, files) in os.walk(inputpath):
for dir in dirs:
print path, dir
newfolders=outputpath+dir
if not os.path.exists(newfolders):
   os.makedirs(newfolders)
   print newfolders
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] help in TKINTER

2011-08-15 Thread aditya
Hello tutors,

I wanted some help in using the Tkinter class for button creation, I am not
able to add on click events i.e. when I press the button certain action
should be performed for example if I press the button named 5, then it
should display 5 in the text field .

 Help will be appreciated.

-- 
Regards
Aditya
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] which version do i have and how do i change it

2011-08-15 Thread Lisi
On Tuesday 16 August 2011 00:48:08 Walter Prins wrote:
> On 16 August 2011 00:43, Connor Merritt  wrote:
> > So i installed python 2.7.1 on my linux and i bought a book that requires
> > python 3 so installed python 3, and i used terminal and typed in python
> > -V and it said 2.7.1 how do i get it to be 3 (i tried deleting it but i
> > couldn't what should i do?)
>
> Try
>
> python3 -V
>
> The default is probably still Python2 but that does not mean you can't use
> Python explicitly.

If you prefer to have Python 3 only, you could also uninstall Python 2.7.1.  
You do not say what version of what distro you are using, nor what method you 
used to install Python 2, so I can't be more explicit.

Lisi

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor