Re: [Tutor] Fwd: circular movement in pygame
for what ever it's worth I'd like to share the code below with you. I got the code to do what I wanted. Object falls onto a rotating platform and stays there without falling off. video is here -> https://www.youtube.com/watch?v=I6c5cKhLuo4 import sys, os, pygame from pygame.locals import * from standard_object_creator import * from math import sin, cos, pi, radians SCREENW = 800 SCREENH = 700 pygame.init() FPSCLOCK = pygame.time.Clock() FONT1= "data\Cookie-Regular.ttf" if sys.platform == 'win32' or sys.platform == 'win64': #os.environ['SDL_VIDEO_CENTERED'] = '2'# center of screen os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (10,30)#top left corner SCREEN = pygame.display.set_mode((SCREENW, SCREENH)) pygame.display.set_caption('rotating object') BLUE = (0, 50, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) PURPLE = (145, 0, 100) yellow = (220,220, 0) FPS = 160 # frames per second platforms = pygame.sprite.Group() boxes = pygame.sprite.Group() ## this is the center of rotation. objects will be placed on the radius according to the step cx = SCREENW / 2 # x pos in relation to screen width cy = SCREENH / 2 # y pos in relation to screen height ## self, posx, posy, imagelist, speedx = 0, speedy = 0, value = 0 plat = pygame.image.load("platform.png").convert_alpha() box = pygame.image.load("box.png").convert_alpha() box = object_factory ([box], cx, cy - 300, 0, 2) boxes.add(box) RADIUS = 100 # distance from the center angle = radians(0) # angular distance between objects omega = 1 for x in xrange(1): xpos = (cos(angle * x) * RADIUS) + cx ypos = (sin(angle * x) * RADIUS) + cy obj = object_factory([plat], xpos, ypos) obj.cx = cx obj.cy = cy obj.difx = 0 obj.dify = 0 obj.angle = radians(60 * x) # position each object around (cx,cy) obj.radius = RADIUS # distance from the center obj.omega = radians(omega) obj.offsetx = cos(obj.angle) * obj.radius obj.offsety = -sin(obj.angle) * obj.radius platforms.add(obj) mouseposlist = [] okkoma = [platforms, boxes] x = 0 l = [] while True: SCREEN.fill(BLACK) x += 1 ##-- pygame.event.pump() keys = pygame.key.get_pressed() for event in pygame.event.get(): if event.type == MOUSEBUTTONDOWN: if event.button == 1: pos = pygame.mouse.get_pos() val = [pos[0], pos[1], 0, 0] print val mouseposlist.append(val) elif event.button == 3 and mouseposlist != []: mouseposlist.pop(-1) if event.type == KEYDOWN and event.key == K_ESCAPE: print mouseposlist pygame.quit() sys.exit() for hp in boxes: hp.move() hp.collide(platforms) ## MOVE THE SPRITE IN A CIRCLE center of rotation = cx,cy. Each object is placed by varying the step) pygame.draw.circle(SCREEN, BLUE, (cx, cy), RADIUS, 2) for obj in platforms: obj.angle += obj.omega # larger value increases speed ( angle gets larger) #obj.radius += .1 # this will make the object move in an expanding spiral obj.offsetx = cos(obj.angle) * obj.radius obj.offsety = -sin(obj.angle) * obj.radius obj.difx = obj.offsetx - obj.rect.x obj.dify = obj.offsety - obj.rect.y obj.speedx = round(obj.cx + obj.difx, 2) obj.speedy = round(obj.cy + obj.dify, 2) l.append([obj.speedx, obj.speedy]) obj.move() for ekak in okkoma: ekak.update() ekak.draw(SCREEN) ## pygame.draw.line(SCREEN, BLUE, (0, SCREENH / 2), (SCREENW, SCREENH / 2), 2) pygame.draw.line(SCREEN, BLUE, (SCREENW / 2, 0), (SCREENW / 2, SCREENH), 2) pygame.display.update() FPSCLOCK.tick(FPS) pygame.time.wait(10) print l On Thu, Apr 30, 2015 at 12:27 PM, diliup gabadamudalige wrote: > Thanks all for the very informative responses especially to Alan for being > descriptive. > > I am now going to make my movement linear and move away from my current > circular one. > > I hope a little bit of fun and "Thank you" emails fall into the order of > the day.. > > :) > > On Thu, Apr 30, 2015 at 9:13 AM, Dave Angel wrote: > >> On 04/29/2015 02:37 PM, diliup gabadamudalige wrote: >> >>> I do not understand how Alan does not get the code that is in this >>> thread. >>> >> >> There are at least 3 ways of posting to "this thread": >>A) email >>B) newsgroup >>C) googlegroups >> >> and at least 5 ways of looking at "this thread" >>A) email >>B) email digest >>C) newsgroup >>
Re: [Tutor] Fwd: circular movement in pygame
Thanks all for the very informative responses especially to Alan for being descriptive. I am now going to make my movement linear and move away from my current circular one. I hope a little bit of fun and "Thank you" emails fall into the order of the day.. :) On Thu, Apr 30, 2015 at 9:13 AM, Dave Angel wrote: > On 04/29/2015 02:37 PM, diliup gabadamudalige wrote: > >> I do not understand how Alan does not get the code that is in this thread. >> > > There are at least 3 ways of posting to "this thread": >A) email >B) newsgroup >C) googlegroups > > and at least 5 ways of looking at "this thread" >A) email >B) email digest >C) newsgroup >D) googlegroups >E) various archives > > To get messages from one region to another involves going through a > gateway, and most of them damage some of the messages going through. To > minimize the likelihood that what looks good on your screen will be missing > or different on mine or on Alan's, follow a few rules: > >1) avoid html >2) avoid attachments > > There are others, but those seem to be the biggies. > > Many other guidelines will help readability and consistency, like not > top-posting, using proper quoting and attribution, giving enough > information but not too much, specifying the whole environment in the FIRST > message of a thread, etc. > > -- > DaveA > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Diliup Gabadamudalige http://www.diliupg.com http://soft.diliupg.com/ ** This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions. ** ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fwd: circular movement in pygame
Thanks Alan. It is partly due to curiosity but I also wanted to have a common update method. And as I almost always use the x+= some code, y+=some code for animation stuff I wanted to know how it could be done using this method rather than finding each position separately and assigning with x= some code, y = some code (new position). But here is STILL something curious in this whole matter. If I update the rect positions with obj.rect.x+ = some code obj.rect.y+ = some code then the rotation are NOT circular. BUT if I use obj.x += some code obj.y += some code and then do obj.rect.x, obj.rect.y = obj.x, obj.y then the rotation works correct!! This is really weird and I have no explanation as to why this happens!!! Can you or anyone else explain this strange behaviour? After all a position is a position.(at least that;s how I understand as long as you stick with the same coordinate through out.) The code is below. import sys, os, pygame, itertools from math import sin,cos,pi from pygame.locals import * SCREENW = 800 SCREENH = 700 class object_factory(pygame.sprite.Sprite): def __init__(self, image, xpos = 0, ypos = 0): """Constructor""" pygame.sprite.Sprite.__init__(self) self.image = image self.mask = pygame.mask.from_surface(self.image) # pixelmask self.rect = self.image.get_rect() self.rect.x = xpos self.rect.y = ypos self.x=xpos self.y=ypos pygame.init() clock = pygame.time.Clock() os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (50,50) #Set window position SCREEN = pygame.display.set_mode((SCREENW, SCREENH)) clock = pygame.time.Clock() pygame.display.set_caption('rotating object') ball = pygame.image.load("ball.jpg") pin=pygame.image.load("center.jpg"); platforms = pygame.sprite.Group() center_x = SCREENW/2 center_y = SCREENH/2 radius = 200 angle = pi/4 # starting angle 45 degrees omega = 0.1 #Angular velocity for _ in itertools.repeat(None, 6): xpos = center_x + radius * cos(angle) #Starting position x ypos = center_y - radius * sin(angle) #Startinh position y obj = object_factory(ball, xpos, ypos) obj.angle = angle obj.omega = omega #angula velocity obj.radius = radius platforms.add(obj) angle += pi/.5 #-- while True: clock.tick(24) pygame.event.pump() keys = pygame.key.get_pressed() for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): pygame.quit() sys.exit() SCREEN.fill((0, 0, 0)) SCREEN.blit(pin,(center_x - pin.get_width() / 2, center_y - pin.get_height() / 2)) pygame.draw.circle(SCREEN, (0, 0, 255), (center_x, center_y), radius, 2) for b in platforms: b.angle+=b.omega #Rect Base Rotation #b.rect.x += b.radius * b.omega * cos(b.angle + pi / 2) #b.rect.y -= b.radius * b.omega * sin(b.angle + pi / 2) #SCREEN.blit(ball,(b.rect.x,b.rect.y)) #Normal Rotation b.x+= b.radius * b.omega * cos(b.angle + pi / 2) b.y-= b.radius * b.omega * sin(b.angle + pi / 2) b.rect.x, b.rect.y = b.x - b.rect.width / 2, b.y - b.rect.height / 2 #SCREEN.blit(ball,(b.x,b.y)) # this and the line below gives the same result #SCREEN.blit(ball, (b.rect.x, b.rect.y)) platforms.update() platforms.draw(SCREEN) pygame.time.wait(100) pygame.display.update() On Thu, Apr 30, 2015 at 12:25 AM, Alan Gauld wrote: > On 29/04/15 19:37, diliup gabadamudalige wrote: > >> I do not understand how Alan does not get the code >> > > > Replying off list. > > I don't get it because text based email systems often strip out attachments > since they are a security risk. As the name says they are *text* based. > > However, now that I've seen it and I see your solution I can better > understand > what you were trying to ask, which was the solution to a very specific > scenario. > > I'm still not sure why you wanted to use augmented assignment, other > than curiosity perhaps, but at least I now see what you were trying to do. > Thanks for posting the solution. > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > -- Diliup Gabadamudalige http://www.diliupg.com http://soft.diliupg.com/ ** This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by re
Re: [Tutor] Fwd: circular movement in pygame
I do not understand how Alan does not get the code that is in this thread. Anyway I can conclude by saying that a friend of mine who is not in this thread solved the problem and I would like to share it with you. He has changed only a very smal portion in the original code that i posted in this thread. and it works perfectly. Apparently the problem is in the way the rect assignment is done in the Python/Pygame rect class. So as conclusion the code below works perfectly. No drifting. Class implemented. I hope everyone gets updated. Thanks for your time. import sys, os, pygame, itertools from math import sin,cos,pi from pygame.locals import * SCREENW = 800 SCREENH = 700 class object_factory(pygame.sprite.Sprite): def __init__(self, image, xpos = 0, ypos = 0): """Constructor""" pygame.sprite.Sprite.__init__(self) self.image = image self.mask = pygame.mask.from_surface(self.image) # pixelmask self.rect = self.image.get_rect() self.rect.x = xpos self.rect.y = ypos self.x=xpos self.y=ypos pygame.init() clock = pygame.time.Clock() os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (50,50) #Set window position SCREEN = pygame.display.set_mode((SCREENW, SCREENH)) clock = pygame.time.Clock() pygame.display.set_caption('rotating object') ball = pygame.image.load("ball.jpg") pin=pygame.image.load("center.jpg"); platforms = pygame.sprite.Group() center_x = SCREENW/2 center_y = SCREENH/2 radius = 200 angle = pi/4 # starting angle 45 degrees omega = 0.1 #Angular velocity #--- for _ in itertools.repeat(None, 6): xpos = center_x + radius * cos(angle) #Starting position x ypos = center_y - radius * sin(angle) #Startinh position y obj = object_factory(ball, xpos, ypos) obj.angle = angle obj.omega = omega #angula velocity obj.radius = radius platforms.add(obj) angle += pi/3 #-- while True: clock.tick(24) pygame.event.pump() keys = pygame.key.get_pressed() for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): pygame.quit() sys.exit() SCREEN.fill((255,255,255)) SCREEN.blit(pin,(center_x, center_y)) #Class implementation-- for b in platforms: b.angle+=b.omega #Rect Base Rotation #b.rect.x += b.radius * b.omega * cos(b.angle + pi / 2) #b.rect.y -= b.radius * b.omega * sin(b.angle + pi / 2) #SCREEN.blit(ball,(b.rect.x,b.rect.y)) # Normal Rotation- b.x+=b.radius * b.omega * cos(b.angle + pi / 2) b.y-= b.radius * b.omega * sin(b.angle + pi / 2) SCREEN.blit(ball,(b.x,b.y)) pygame.display.update() On Wed, Apr 29, 2015 at 10:00 PM, Alan Gauld wrote: > On 29/04/15 10:15, diliup gabadamudalige wrote: > >> x=42 good >> x += 42 -x ? >> >> That does not go by a mile of what I asked. >> > > You've asked three different things: > > 1) Why the += form gives different results from the assignment form, > 2) Why some code you apparently wriotre worked outside a class >but not in a class > 3) A specific question about some code for moving an object >in PyGame around in a circle > > Number 1 is the only one I can comment on as I can't see your attachments. > That is what I (and several others) have answered. > They are fundamentally different. There is no general way > to make an augmented assignment such that > > x = f(y) and > x += f(y) (or even g(y)) > > produce the same result except by the trivial > > x += g(y) - x > > Alan, are you telling me that there is no way that one can arrive at X2 >> which is the NEXT place that X1 will be after "some increment"? >> old x position = X1 >> > > No, that is a completely separate question and has nothing > to do with using augmented assignment. But it does depend > on the specifics of the situation and is mainly a mathematical > problem rather than a Python one.. > > new x position= X1 + some increment value >> which can be written as :new X = oldX + some increment value >> >> which can be simplified to X += some increment value? >> > > That may or may not be possible, it depends on what the > original equation in the pure assignment model is. > > my orginal question was >> >> *Why does the object NOT move in a circle when implemented as a clas
Re: [Tutor] Fwd: circular movement in pygame
x=42 good x += 42 -x ? That does not go by a mile of what I asked. Alan, are you telling me that there is no way that one can arrive at X2 which is the NEXT place that X1 will be after "some increment"? old x position = X1 new x position= X1 + some increment value which can be written as :new X = oldX + some increment value which can be simplified to X += some increment value? my orginal question was *Why does the object NOT move in a circle when implemented as a class?* All the code was provided. The above is what I asked. (I hope this is clear enough) On Wed, Apr 29, 2015 at 1:56 PM, Alan Gauld wrote: > On 29/04/15 09:03, diliup gabadamudalige wrote: > >> Thank you Alan. Understood. I already knew that. My question is >> >> How to to do it the second way. >> some code = what? >> >> The point is you cannot do it. > The second approach always uses the current value of x. > The first approach may or may not use the current value > of x. If it does not use x then the += style cannot be > made to work (unless you tag a -x on at the end! > > x = 42 > > x += 42-x > > Which is just stupid. > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > -- Diliup Gabadamudalige http://www.diliupg.com http://soft.diliupg.com/ ** This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions. ** ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fwd: circular movement in pygame
question to Lucas. Not sure if this is what you're looking for, but I would also use cos for the x coordinate as suggested. If: self.rect.x = self.radius * math.cos(self.angle) + self.center_x self.rect.y = self.radius * math.sin(self.angle) + self.center_y Take a derivative (assume: angle += angular_vel * dt for every increment in time dt), so that: self.rect.x += -self.radius * math.sin(self.angle) * self.angular_vel * dt self.rect.y += self.radius * math.cos(self.angle) * self.angular_vel * dt what is dt? On Wed, Apr 29, 2015 at 12:45 PM, diliup gabadamudalige wrote: > Thanks all for the responses. > Charles Cossé - yes I can write a simple pygame program that makes a > sprite move in a circle but it may not be the style and order that many may > approve or accept. I consider myself a student. :) > No one has pointed out why the object moves in a circle properly in the > bit of code where it is addressed directly and why it does not when the > same code is applied thru a class. > I know that an object can be made to move around the circumference of a > circle by constantly calculating the point and giving the x and y values > > 1. x = some code > > That is what I used and it worked. I was trying to find how we can do the > same thing by updating the current position by doing > > 2. x += some code > Above 1 works. 2 does not. Why is that? > > Both the same code. The same variable is used with different names cause > some others were confused when they were the same. > > I hope this time I have answered correctly. No more attachments. (e mail > or otherwise. :) ) > -- Diliup Gabadamudalige http://www.diliupg.com http://soft.diliupg.com/ ** This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions. ** ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fwd: circular movement in pygame
Thank you Alan. Understood. I already knew that. My question is How to to do it the second way. some code = what? My question is, how does one arrive at the code to put in place of "some code"? The code I used does not work correctly. The code is in this chain of email. I hope I am clear in what I am trying to do. On Wed, Apr 29, 2015 at 1:18 PM, Alan Gauld wrote: > On 29/04/15 08:15, diliup gabadamudalige wrote: > > 1. x = some code >> >> That is what I used and it worked. I was trying to find how we can do the >> same thing by updating the current position by doing >> >> 2. x += some code >> Above 1 works. 2 does not. Why is that? >> > > > Because they do completely different things! > > 1 is simply > > x = some code > > 2 is > > x = x + some code > > In 2 you are adding x to some code. > > Of course they don't work the same. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Diliup Gabadamudalige http://www.diliupg.com http://soft.diliupg.com/ ** This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions. ** ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fwd: circular movement in pygame
Thanks all for the responses. Charles Cossé - yes I can write a simple pygame program that makes a sprite move in a circle but it may not be the style and order that many may approve or accept. I consider myself a student. :) No one has pointed out why the object moves in a circle properly in the bit of code where it is addressed directly and why it does not when the same code is applied thru a class. I know that an object can be made to move around the circumference of a circle by constantly calculating the point and giving the x and y values 1. x = some code That is what I used and it worked. I was trying to find how we can do the same thing by updating the current position by doing 2. x += some code Above 1 works. 2 does not. Why is that? Both the same code. The same variable is used with different names cause some others were confused when they were the same. I hope this time I have answered correctly. No more attachments. (e mail or otherwise. :) ) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fwd: circular movement in pygame
I thank all those who responded to my question Here is the code that I had written. When updating is applied to a surface object the rotation works but when it is applied through a class to an object it goes wrong in about 3 rotations. As far as I can see the code is the same. What is wrong? If you can correct some code and show me would help. On Tue, Apr 28, 2015 at 11:58 PM, Oscar Benjamin wrote: > On 28 April 2015 at 16:38, diliup gabadamudalige > wrote: > > > > Looking at the code on this page lines 47 & 48 > > > > > http://programarcadegames.com/python_examples/show_file.php?file=sprite_circle_movement.py > > > > is there a way to do > > self.rect.x +*= some value* > > self.rect.y += some value > > > > rather than > > > > self.rect.x = self.radius * math.sin(self.angle) + self.center_x > > self.rect.y = self.radius * math.cos(self.angle) + self.center_y > > There's no way to do that. The second version ignores the previous > value of self.rect.x/y. > > I'm going to guess that the angle has only changed by a small amount > delta_angle between iterations in which case there would be a way to > do it approximately. > > The real question is just why though? The second version is correct > and will be correct for ever. The first version would only be > approximately correct and over time you'd probably find that the > position would drift so that the ball was effectively at a different > radius. > > In any case if > x = r * sin(theta) > then > dx/dt = r * cos(theta) * dtheta/dt. > Since > y = r * cos(theta) that's > dy/dt = x * dtheta/dt. > So you could update y approximately with: > y += x * dtheta/dt * deltat > where deltat is your timestep. In your code that would be: > self.rect.x += self.rect.y * self.speed > self.rect.y -= self.rect.x * self.speed > > Really what you have now is better though. > _______ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Diliup Gabadamudalige http://www.diliupg.com http://soft.diliupg.com/ ** This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions. ** import sys, os, pygame, itertools from math import sin,cos,pi, radians from pygame.locals import * os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (50,50) #Set window position pygame.init() clock = pygame.time.Clock() FPS = 1000 SCREENW = 800 #screen width SCREENH = 740 #screen height BLACK = (0, 0, 0) BLUE = (0, 0, 255) ORANGE = (128, 100, 30) FONT1= "Cookie-Regular.ttf" SCREEN = pygame.display.set_mode((SCREENW, SCREENH), 0, 32) #display screen clock = pygame.time.Clock() #--- def maketext(msg,fontsize, colour = ORANGE, font = FONT1): mafont = pygame.font.Font(font, fontsize) matext = mafont.render(msg, True, colour) matext = matext.convert_alpha() return matext #--- def print_info(): """""" textcos = maketext(str(round(obj.rect.x, 2)) + " " + str(round(obj.rect.y, 2)), 30) SCREEN.blit(textcos, (obj.rect.x, obj.rect.y + 30)) #--- class object_factory(pygame.sprite.Sprite): def __init__(self, imagelist, xpos, ypos, speedx = 0, speedy = 0, value = 0): """Constructor""" pygame.sprite.Sprite.__init__(self) self.name = "" self.frame = 0 self.imagelist = imagelist self.image = imagelist[self.frame] self.mask = pygame.mask.from_surface(self.image) # pixelmask self.rect = self.image.get_rect() self.rect.x = xpos self.rect.y = ypos #self.speedx = speedx #self.speedy = speedy self.timer = 0 self.timerlimit = 10 #-- #def mov
[Tutor] Fwd: circular movement in pygame
-- Forwarded message -- From: diliup gabadamudalige Date: Tue, Apr 28, 2015 at 6:22 PM Subject: circular movement in pygame To: pygame-us...@seul.org Looking at the code on this page lines 47 & 48 http://programarcadegames.com/python_examples/show_file.php?file=sprite_circle_movement.py is there a way to do self.rect.x +*= some value* self.rect.y += some value rather than self.rect.x = self.radius * math.sin(self.angle) + self.center_x self.rect.y = self.radius * math.cos(self.angle) + self.center_y ? I tired it in the code attached and strangely it works ok but only OUTSIDE THE class. When I implement the exact code in a class it does something weird. I can't find where I have gone wrong. Please help. Many thanks in advance. Diliup Gabadamudalige ** This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions. ** -- Diliup Gabadamudalige http://www.diliupg.com http://soft.diliupg.com/ ** This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions. ** import sys, os, pygame, itertools from math import sin,cos,pi, radians from pygame.locals import * os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (50,50) #Set window position pygame.init() clock = pygame.time.Clock() FPS = 1000 SCREENW = 800 #screen width SCREENH = 740 #screen height BLACK = (0, 0, 0) BLUE = (0, 0, 255) ORANGE = (128, 100, 30) FONT1= "Cookie-Regular.ttf" SCREEN = pygame.display.set_mode((SCREENW, SCREENH), 0, 32) #display screen clock = pygame.time.Clock() #--- def maketext(msg,fontsize, colour = ORANGE, font = FONT1): mafont = pygame.font.Font(font, fontsize) matext = mafont.render(msg, True, colour) matext = matext.convert_alpha() return matext #--- def print_info(): """""" textcos = maketext(str(round(obj.rect.x, 2)) + " " + str(round(obj.rect.y, 2)), 30) SCREEN.blit(textcos, (obj.rect.x, obj.rect.y + 30)) #--- class object_factory(pygame.sprite.Sprite): def __init__(self, imagelist, xpos = 0, ypos = 0, speedx = 0, speedy = 0, value = 0): """Constructor""" pygame.sprite.Sprite.__init__(self) self.name = "" self.frame = 0 self.imagelist = imagelist self.image = imagelist[self.frame] self.mask = pygame.mask.from_surface(self.image) # pixelmask self.rect = self.image.get_rect() self.rect.x = xpos self.rect.y = ypos self.speedx = speedx self.speedy = speedy self.timer = 0 self.timerlimit = 10 #-- def move(self): # wallsprites, Herosprite, looptime self.rect.x += self.speedx self.rect.y += self.speedy #-- def update(self): """""" self.image = self.imagelist[self.frame] if self.timer >= self.timerlimit: self.frame += 1 if self.frame >= len(self.imagelist): self.frame = 0 self.timer = 0 self.timer += 1 plat = pygame.image.load("plt0.png").convert_alpha() star = pygame.image.load("gemp0.png").convert_alpha() box = pygame.image.load("crateB.png").convert_alpha() platforms = pygame.sprite.Group()
Re: [Tutor] Error 22
:) On Thu, Jan 8, 2015 at 3:02 AM, Danny Yoo wrote: > >>> How I fix this error? when I open my python project (.py) it closes > >>> immediately. > >> > >> Since the op sent from Windows, I'm guessing he isn't opening up a cmd > >> window then running his program. But I'm not a windows guy lately. > >> Perhaps someone can tell him how to invoke the program? > > I think we simply need more information. "Error 22" on Windows is, > according to web searches, associated with some kind of device driver > failure. (What?!) > > So I am very confused. Without knowing anything else about the > program, I'm at a loss and my first instinct is to think that this has > nothing to do with Python. I think we don't have enough information, > so let's hear back from the original questioner. > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Diliup Gabadamudalige http://www.diliupg.com http://soft.diliupg.com/ ** This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions. ** ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] getting input for stdin
Dear alll, my code is given below if __name__ == '__main__': p = os.getcwd() filename = "\get scale of choice.txt" filepath = p + filename sys.stdout = open(filepath, "w") os.startfile(filepath) for i in data.info: # print all the scale info to window print i run = True while run: scaletemplate = ["C", "D", "E", "F", "G", "A", "B"] getscale = sys.stdin.raw_input(filepath) #getscale = raw_input("Which scale do you require?:") if len(getscale) > 1: getscale = getscale[0].upper() + getscale[1:] else: getscale = getscale.upper() if getscale in data.scalenames: scale = main(getscale) print scale elif getscale == "Q" or getscale == "X" or getscale == "": run = False print"exiting..." else: print "No such scale" I need to get the stdin input from the text I type into the same text file that I have stdout at. How do I do that. None of the answers at stackoverflow got me going. Any help on a code snippet would be appreciated. Thanks in advance -- Diliup Gabadamudalige http://www.diliupg.com http://soft.diliupg.com/ ** This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions. ** ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help
http://cscircles.cemc.uwaterloo.ca/run-at-home/ On Fri, Sep 19, 2014 at 11:04 AM, Danny Yoo wrote: > On Wed, Sep 17, 2014 at 4:36 PM, Art Pelletier wrote: > > > > I am a beginner with pythons programming I would like to see if their > is a site that has samples programs that I can practice on. > > Hi Art, > > > Yes, there are some good resources you can check out. Here's a link > to some of them: > > https://wiki.python.org/moin/BeginnersGuide/NonProgrammers > > Personally, I like How to Think Like a Computer Scientist: > > http://openbookproject.net/thinkcs/python/english2e/ > > but any of the tutorials in the beginner's guide should be helpful. > > > > Feel free to ask questions here on this mailing list too. > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Diliup Gabadamudalige http://www.diliupg.com http://soft.diliupg.com/ ** This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions. ** ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] extracting a cPickle/pickle file from inside a zip file
http://stackoverflow.com/questions/3006727/load-a-pickle-file-from-a-zipfile zf = czipfile.ZipFile(r"cpickletest.zip") pyfromzip = zf.read ("cPickletest.py", pwd="python") print pyfromzip, type(pyfromzip) this prints the following to the console (dp1 S'kola.jpg' p2 S'CSVTQq#w.@lm' p3 sS'p2.jpg' p4 S'CSVT$S.@lm' p5 sS'p1.jpg' p6 S'CSVT3S.@lm' p7 s. most probably this is the dictionary file written to disk as the keys and values are all there. now if i do this outfile = cStringIO.StringIO() outfile.write(pyfromzip) z=cPickle.load(outfile) it returns -> EOFError: I tried various experiments and the code below worked. filenames # this is a dictionary with open(p + "\\coded\\" + name_py,"wb") as outfile: cPickle.dump(str(filenames), outfile) # pickled dumped the dictionary as a string now the file is locked up in a pwd prtected zipfile using winrar zf = czipfile.ZipFile(r"cpickletest.zip") pyfromzip = zf.read ("cPickletest.py", pwd="password") c = pyfromzip.partition('"')[-1].rpartition('"')[0] c = eval(c) print c, type(c) # this gave back the original dictionary can someone think of a better way? On Fri, Aug 29, 2014 at 6:25 PM, diliup gabadamudalige wrote: > Alan, thanks for the reply. > nope. I tried both ways. Btw I am using Python 2.7.8. > This seem to be a problem with python itself. > > > http://stackoverflow.com/questions/3006727/load-a-pickle-file-from-a-zipfile > > zf = czipfile.ZipFile(r"cpickletest.zip") > pyfromzip = zf.read ("cPickletest.py", pwd="python") > print pyfromzip, type(pyfromzip) > > this prints the following to the console > > (dp1 > S'kola.jpg' > p2 > S'CSVTQq#w.@lm' > p3 > sS'p2.jpg' > p4 > S'CSVT$S.@lm' > p5 > sS'p1.jpg' > p6 > S'CSVT3S.@lm' > p7 > s. > > most probably this is the dictionary file written to disk as the keys and > values are all there. > > now if i do this > > outfile = cStringIO.StringIO() > outfile.write(pyfromzip) > z=cPickle.load(outfile) > it returns -> EOFError: > > > > On Fri, Aug 29, 2014 at 5:01 PM, Alan Gauld > wrote: > >> On 29/08/14 10:00, diliup gabadamudalige wrote: >> >> pload = cPickle.load(zf.open("my.py",pwd=password)) >>> this gives an EOF >>> >>> . Does any body know why? >>> >> >> I've never used zipfile so I don't know, but could it be >> related to the fact that your pickle file is binary? >> Do you need any flags to tell zipfile that you're >> extracting a binary file? >> >> Just a thought, >> >> -- >> Alan G >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> http://www.flickr.com/photos/alangauldphotos >> >> ___ >> Tutor maillist - Tutor@python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> > > > > -- > Diliup Gabadamudalige > > http://www.diliupg.com > http://soft.diliupg.com/ > > > ** > This e-mail is confidential. It may also be legally privileged. If you are > not the intended recipient or have received it in error, please delete it > and all copies from your system and notify the sender immediately by return > e-mail. Any unauthorized reading, reproducing, printing or further > dissemination of this e-mail or its contents is strictly prohibited and may > be unlawful. Internet communications cannot be guaranteed to be timely, > secure, error or virus-free. The sender does not accept liability for any > errors or omissions. > > ** > > -- Diliup Gabadamudalige http://www.diliupg.com http://soft.diliupg.com/ ** This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions. ** ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] extracting a cPickle/pickle file from inside a zip file
HI! To all, with open(from_dir + "\\" + name_py,"wb") as outfile: cPickle.dump(str1,outfile) after doing above I zip the file with some other files into a password secured zip file using win rar. I can extract all other files except the py file. pload = cPickle.load(zf.open("my.py",pwd=password)) this gives an EOF . Does any body know why? Can anyone show how to extract a pickle file from a zipfile? Thanks in advance Diliup Gabadamudalige http://www.diliupg.com http://soft.diliupg.com/ ** This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions. ** ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] time vs. timeit
Hi all, 1. why do some say that the time module is more accurate than the timeit module? s = time.time() or s = timeit.timeit() 2. Why is it that both modules never return the same answer on each run? Thank you for your response. -- Diliup Gabadamudalige http://www.diliupg.com http://soft.diliupg.com/ ** This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions. ** ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Fwd: Embedding resources
Hi Danny! The routine works fine and so does this one. http://www.pygame.org/pcr/zipshow/index.php The only problem with all these are that that the time taken to read these files and to either make a list or send to screen is WAY TOO LONG. The only one that works without much delay is in the file I have attached. It is a bit of code that I wrote with verbose print statements to follow the program in action while testing. As this uses base64 only there is no secure encryption. Please have a look at it and try to improve it. Am I doing this correctly? Are these messages getting to the community? On Wed, Aug 20, 2014 at 1:18 PM, diliup gabadamudalige wrote: > Hi Danny! > > You are always there to lend a helping hand I've noticed! Thanks for the > quick response! Let me try the code and get back to you. > > > > On Wed, Aug 20, 2014 at 1:02 PM, Danny Yoo wrote: > >> >> On Aug 19, 2014 11:53 PM, "diliup gabadamudalige" >> wrote: >> > >> > Hi all! >> > >> > Is there any way I can bundle all my graphics only using Python and >> Pygame so that the user may not be able to read them out of the program? >> >> (Changing subject line to more descriptive title) >> >> Would something like http://www.pygame.org/pcr/image2py/index.php apply >> to your problem? >> > > > > -- > Diliup Gabadamudalige > > http://www.diliupg.com > http://soft.diliupg.com/ > > > ** > This e-mail is confidential. It may also be legally privileged. If you are > not the intended recipient or have received it in error, please delete it > and all copies from your system and notify the sender immediately by return > e-mail. Any unauthorized reading, reproducing, printing or further > dissemination of this e-mail or its contents is strictly prohibited and may > be unlawful. Internet communications cannot be guaranteed to be timely, > secure, error or virus-free. The sender does not accept liability for any > errors or omissions. > > ** > > -- Diliup Gabadamudalige http://www.diliupg.com http://soft.diliupg.com/ ** This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions. ** """ Author: Diliup Gabadamudalige. dili...@gmail.com> Copyright: If you wish to use this code please keep this multiline comment, along with function source. Thank you. read the files in the current directory and get all files except ones in the exempt list or directories.. Get the file extension. and convert them by using maketrans without file extensions. When converting from original files with file extensions, remove the file extension(with the .), reverse it and add it to the begining of the filename. encode the file. add new file ext "@lm". eg: file name -> picture.tiff -> ffit.picture ->AFKDiO$1#&mL@lm. encoded files added to a directory "coded" which is created if not exist. decoded files added to a directory "decoded" which is created if not exist. path = your path where the files are run = True -> encode run = False -> decode """ import os import string import base64 from master_vars import alpha, coder def main(path, code = None, ex = [".wpr", ".wpu", ".py", ".pyc", ".@lm"]): getfiles = [] path = path code = code # exclude = ex items = os.listdir(path) if code: # if code = True then encode mode = "encode" if not os.path.exists("coded"): os.makedirs("coded") else: # else decode mode = "decode" ## if decode mode and coded folder does not exist exit program if not os.path.exists("coded"): print "nothing to decode." elif not os.path.exists("decoded") and os.path.exists("coded"): os.makedirs("decoded") elif os.path.exists("decoded"): items =
[Tutor] (no subject)
Hi all! Is there any way I can bundle all my graphics only using Python and Pygame so that the user may not be able to read them out of the program? Let us assume that the user does NOT know Python and will not go looking for people who knows Python to crack the files. In other words an average user. 1. I have tried the Zip file method by making a Zip file with Win Rar or Winzip and password lock the file. But the unpacking is WAY TOO SLOW! with ZipFile('stuff.zip') as zf: zf.extract("image.jpg", pwd="123456") 2. I have used the repr command and written the code to a py file but again the unpacking is WAY TOO SLOW. with open(name4pypath,"wb") as outfile: outfile.write(name4pyfile + "=" + repr(str1)) 3. The best out of the lot has been the one using base64 str1 = base64.b64encode(from_disk.read()) with open(code_to_dir, "ab+") as to_disk: to_disk.write(str1) Can anyone show me a better way? Thanks in advance -- Diliup Gabadamudalige http://www.diliupg.com http://soft.diliupg.com/ ** This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions. ** ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] global variables/constants versus volatile variables/constants
Thank you very much Allan! 100% clear. I thank each and every one of you who contributed to all my question on the above subject. A lot of things became very clear. May you all be well. On Sun, Jun 15, 2014 at 3:15 AM, Alan Gauld wrote: > On 14/06/14 13:53, diliup gabadamudalige wrote: > > Say if I have a lot of Lists, strings and variables used to carry data >> to and from various functions why can't I have a class with all these in >> it? >> > > You can but it should also have the functions that operate on the data > too. Thats the point of classes they link function and data together > so you don't need to pass lots of parameters around. If you have a class > that jusat holds lots of disparate data items you might as well just use a > list/tuple or dictionary. The value of classes is when you add behaviour or > methods to the mix. > > > > I thought on the lines of blood carrying various things to different >> organs in the body. >> > > But even there the blood has a distinct set of related items, it doesn't > carry the food to your stomach or the video signals from > your eye to your brain. And blood has operations - it can flow, > coagulate, increase/decrease red-cell count etc. It has > behaviour as well as data. > > > class Containers(): >> def __init__(self): >> self.last_selected_scale= "" >> self.scale_notes = "" >> self.arpeggionotes = "" >> self.handplayed_notes = [] >> self.MIDIscale = [] # the MIDI scale to be played is here >> self.play_MIDIscale = False >> self.play_MIDIarpeggio = False >> self.play_MIDI_scale_note = False >> self.play_MIDI_arpeggio_note = False >> self.MIDInote_inscale = 0 >> > > Now that could be a Tune... And it might have record/play/pause operations > > > > now say if I play the MIDI keyboard, I collect the notes played which >> will be appended to the list v.hanplayednotes. This will be done from a >> function which will scan the keyboard and append played notes to that >> list. >> > > But that could be a method of the Tune sub-class, MidiTune, which knows > how to record from a MidiSequencer object. > > > This is how I have used these variables, lists and strings in this >> program. So far it has run error free. >> > > The issue is not how to make it run - you can do that in assembler. > The issue is how easy is it to read and how easy os it to modify and fix > later. 80% of the cost of commercial software is in "maintenance" > The goal of professional software engineers is to reduce maintenance > costs even if that increases the initial 20% development budget. > > > Is this not correct or bad design. I know it is not the normal way of >> using class but is it wrong? >> > > Almost certainly, because it adds a layer of complexity for little or no > gain. > > Whereas adding the methods to the class improves the maintainability and > readability (and sometimes the performance, although that's a secondary > benefit). > > HTH > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Diliup Gabadamudalige http://www.diliupg.com http://soft.diliupg.com/ ** This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions. ** ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] global variables/constants versus volatile variables/constants
Thank you all for those great clarifications. I learnt a lot from these. My roots in programming are from the early 80s and with a gap of nearly 30 years till I restarted again last year in March with Python. :) So some of the new concepts like classes are a bit alien to me but I am catching on. I made a mistake by using the word variables on variables and constants both. My design structure would most probably be quite unconventional to most like Allen Gauld says. I am still learning and I like to jump into the deep end and learn to swim there and so far have managed to stay alive! :) I have gained immensely from these few emails and hope I can gain more knowledge to write better code. Say if I have a lot of Lists, strings and variables used to carry data to and from various functions why can't I have a class with all these in it? I thought on the lines of blood carrying various things to different organs in the body. One common container class. Containers for data exchange between all classes and functions. so I declare class Containers(): def __init__(self): self.last_selected_scale= "" self.scale_notes = "" self.arpeggionotes = "" self.handplayed_notes = [] self.MIDIscale = [] # the MIDI scale to be played is here self.play_MIDIscale = False self.play_MIDIarpeggio = False self.play_MIDI_scale_note = False self.play_MIDI_arpeggio_note = False self.MIDInote_inscale = 0 now i initiate the class with v=Containers() now say if I play the MIDI keyboard, I collect the notes played which will be appended to the list v.hanplayednotes. This will be done from a function which will scan the keyboard and append played notes to that list. This is how I have used these variables, lists and strings in this program. So far it has run error free. Is this not correct or bad design. I know it is not the normal way of using class but is it wrong? Thank you all in advance. -- Diliup Gabadamudalige http://www.diliupg.com http://soft.diliupg.com/ ** This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions. ** ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] global variables/constants versus volatile variables/constants
Thank you all for these elaborate explanations. so would it be wrong to assume that, 1. the list or dict if 'large' and not mutated is better declared once in a Class and used throughout the program? or 2. Lists that are read only are better off being tuples? or 3.the list or dict if 'large' and not mutated is better declared once as a global variable and used throughout the program? The variables, lists carrying variables, and dict. carrying variables are declared as a class. So why not include all above in the same class? Varables and constans which are used throughout the program in one class declared beofr the program enters the main executing loop? wouldn't this be fast and the memory usage static up to a point (for all declared items in the variables class)? On Fri, Jun 13, 2014 at 6:38 PM, Steven D'Aprano wrote: > On Fri, Jun 13, 2014 at 05:10:28AM -0700, Albert-Jan Roskam wrote: > > > The other day I used collections.namedtuple and I re-initialized > > Record (see below) with every function*) call. Bad idea! It looks > > nicer because I did not need a global (and globals are baaad, mkay?), > > but it was *much* slower. I processed a log of a few million lines, I > > think. > > > > # bad --> time-consuming > > import collections > > > > def do_something_with(raw_record): > >Record = collections.namedtuple("_", " ".join("v%%03d" % i for i in > range(100))) > >return Record(*raw_record.split()) > > Look at how much work you do here. First, you create a long string of > the form: > > "v000 v001 v002 v003 ... v099" > > representing 1000 v-digits names. Then you create a brand new Record > class that takes those 100 v-digits names as arguments. Creating that > class requires building a string, parsing it as Python code, and then > running it. (You're not expected to know that, but if you read the > source code for namedtuple you will see that's how it works.) So > creating that class is slow. Every time you call the function, it builds > a new "v000 ... v099" string, from scratch, then builds a new class, > also from scratch, and finally populates an instance of that class with > 100 values from the raw_record. > > Only that last step needs to be done inside the function. > > > > # better --> even though it uses a global variable > > import collections > > > > Record = collections.namedtuple("_", " ".join("v%%03d" % i for i in > range(100))) > > [Aside: you may find it easier to debug problems with this if you give > the namedtuple class a sensible name, like "Record", rather than "_".] > > How is that a global *variable*? It's a global name, "Record", but it is > no more a "variable" than it would be if you did: > > class Record(tuple): > def __new__(cls, v000, v001, v002, ... , v099): > # code goes here > > @property > def v000(self): > return self[0] > > # likewise for v001, v002, ... v099 > # plus additional methods > > > namedtuple is a factory function which creates a class. Buried deep > within it is a class statement, just as if you had written the class > yourself. Normally, when you create a class, you don't treat it as a > variable, you treat it as a constant, like functions. That is no > different from classes you create with the class keyword. So "global > variables are bad" doesn't apply because it's not a variable. > > Even if it were a variable, what really matters is not that it gets > stored in the global scope, but whether or not it gets explicitly passed > to functions as arguments, or implicitly modified secretly behind the > scenes. For example: > > # Not bad > data = ["put", "stuff", "here"] > process(data) > do_things_with(data) > > > # Bad, for various reasons > data = ["put", "stuff", "here"] > process() # process what? > do_things_with() # What are we doing things with? > > > > In the first case, "data" may be stored in the global scope, but inside > each function it is treated as a regular local variable. Let's contrast > how one might operate on a second set of data in each case: > > # Too easy > process(some_other_data) > > > # Ouch, this is painful > save_data = data > data = some_other_data > process() > data = save_data # restore the previous value > > > Global variables aren't bad because Moses came down from
Re: [Tutor] global variables/constants versus volatile variables/constants
Thank you all for these elaborate explanations. so would it be wrong to assume that, 1. the list or dict if 'large' and not mutated is better declared once in a Class and used throughout the program? or 2. Lists that are read only are better off being tuples? or 3.the list or dict if 'large' and not mutated is better declared once as a global variable and used throughout the program? The variables, lists carrying variables, and dict. carrying variables are declared as a class. So why not include all above in the same class? Variables and constants which are used throughout the program in one class declared before the program enters the main executing loop? wouldn't this be fast and the memory usage static up to a point (for all declared items in the variables class)? On Fri, Jun 13, 2014 at 9:42 PM, diliup gabadamudalige wrote: > Thank you all for these elaborate explanations. > so would it be wrong to assume that, > 1. the list or dict if 'large' and not mutated is better declared once in > a Class and used throughout the program? > or > 2. Lists that are read only are better off being tuples? > or > 3.the list or dict if 'large' and not mutated is better declared once as a > global variable and used throughout the program? > > The variables, lists carrying variables, and dict. carrying variables are > declared as a class. So why not include all above in the same class? > Varables and constans which are used throughout the program in one class > declared beofr the program enters the main executing loop? > wouldn't this be fast and the memory usage static up to a point (for all > declared items in the variables class)? > > > On Fri, Jun 13, 2014 at 6:38 PM, Steven D'Aprano > wrote: > >> On Fri, Jun 13, 2014 at 05:10:28AM -0700, Albert-Jan Roskam wrote: >> >> > The other day I used collections.namedtuple and I re-initialized >> > Record (see below) with every function*) call. Bad idea! It looks >> > nicer because I did not need a global (and globals are baaad, mkay?), >> > but it was *much* slower. I processed a log of a few million lines, I >> > think. >> > >> > # bad --> time-consuming >> > import collections >> > >> > def do_something_with(raw_record): >> >Record = collections.namedtuple("_", " ".join("v%%03d" % i for i in >> range(100))) >> >return Record(*raw_record.split()) >> >> Look at how much work you do here. First, you create a long string of >> the form: >> >> "v000 v001 v002 v003 ... v099" >> >> representing 1000 v-digits names. Then you create a brand new Record >> class that takes those 100 v-digits names as arguments. Creating that >> class requires building a string, parsing it as Python code, and then >> running it. (You're not expected to know that, but if you read the >> source code for namedtuple you will see that's how it works.) So >> creating that class is slow. Every time you call the function, it builds >> a new "v000 ... v099" string, from scratch, then builds a new class, >> also from scratch, and finally populates an instance of that class with >> 100 values from the raw_record. >> >> Only that last step needs to be done inside the function. >> >> >> > # better --> even though it uses a global variable >> > import collections >> > >> > Record = collections.namedtuple("_", " ".join("v%%03d" % i for i in >> range(100))) >> >> [Aside: you may find it easier to debug problems with this if you give >> the namedtuple class a sensible name, like "Record", rather than "_".] >> >> How is that a global *variable*? It's a global name, "Record", but it is >> no more a "variable" than it would be if you did: >> >> class Record(tuple): >> def __new__(cls, v000, v001, v002, ... , v099): >> # code goes here >> >> @property >> def v000(self): >> return self[0] >> >> # likewise for v001, v002, ... v099 >> # plus additional methods >> >> >> namedtuple is a factory function which creates a class. Buried deep >> within it is a class statement, just as if you had written the class >> yourself. Normally, when you create a class, you don't treat it as a >> variable, you treat it as a constant, like functions. That is no >> different from classes you create with the class keyword. So "global >> variables are bad" doesn't apply because it's not
[Tutor] global variables/constants versus volatile variables/constants
Hi All! Hope everyone is well. In my code there are many dictionaries and lists which are used in various functions. Is it better/pythonic/efficient to have these inside the function itself or declared at the beginning of the program in which case they will be global? They are all read only. I understand that global constants and variable have memory allocated to them but when declared inside a function are created on the fly, used and discarded. Please enlighten me further on this and correct me if i'm wrong. Thank you for your time and may you be well. -- Diliup Gabadamudalige http://www.diliupg.com http://soft.diliupg.com/ ** This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions. ** ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] which is faster
Hi All, This is a Pygame related question and if not answered it's ok and I apologise for asking. But if someone can answer it is much appreciated. In Pygame Which is faster? 1. filling the screen with a colour or 2. blitting an image to screen Thank you for the time. May you be well. -- Diliup Gabadamudalige http://www.diliupg.com http://soft.diliupg.com/ ** This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions. ** ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Pygame related question
I need to random pick a pygame sprite from a sprite class. The random module does not allow this to be used on a group. Is the shortest way to raed in the attributes thatr I need into a list and then random pick that or is there a shorter way? Sample code is given below. scalelist=[] for scale in all_scales: scalelist.append( [scale.name, scale.scaletype] ) scale = random.choice(scalelist) where all_scales is a sprite class with 45 objects. I append the 2 attributes of each sprite to a scalelist with the above function and then random pick an item from the scalelist. Is this the shortest way? Thank you to all in advance. -- Diliup Gabadamudalige http://www.diliupg.com http://soft.diliupg.com/ ** This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions. ** ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor