[Tutor] Making a character jump with pygame
Hi, I've edited the aliens.py example to make my character just move back and forth. However I can't make him jump! Here's my code (attached). I'm trying to make a platformer Mario style game. Thanks, Joe # Side Scroller v 0.1 a very simple Super # # Mario type game engine # # # # Created by Joseph Quigley# # Released under the GNU GPL (any version) # import os, sys import pygame from pygame.locals import * #import random import time if not pygame.font: print 'Warning, fonts disabled' if not pygame.mixer: print 'Warning, sound disabled' #see if we can load more than standard BMP if not pygame.image.get_extended(): raise SystemExit, "Sorry, extended image module required" SCREENRECT = Rect(0, 0, 640, 480) def load_image(file): "loads an image, prepares it for play" file = os.path.join('data', file) try: surface = pygame.image.load(file) except pygame.error: raise SystemExit, 'Could not load image "%s" %s'%(file, pygame.get_error()) return surface.convert() def load_images(*files): imgs = [] for file in files: imgs.append(load_image(file)) return imgs class dummysound: def play(self): pass def load_sound(file): if not pygame.mixer: return dummysound() file = os.path.join('data', file) try: sound = pygame.mixer.Sound(file) return sound except pygame.error: print 'Warning, unable to load,', file return dummysound() # each type of game object gets an init and an # update function. the update function is called # once per frame, and it is when each object should # change it's current position and state. the Player # object actually gets a "move" function instead of # update, since it is passed extra information about # the keyboard class Player(pygame.sprite.Sprite): speed = 10 bounce = 1 images = [] def __init__(self): pygame.sprite.Sprite.__init__(self, self.containers) self.image = self.images[0] self.rect = self.image.get_rect(midbottom=SCREENRECT.midbottom) self.reloading = 0 self.origtop = self.rect.top self.facing = -1 def move(self, direction): if direction: self.facing = direction self.rect.move_ip(direction*self.speed, 0) self.rect = self.rect.clamp(SCREENRECT) if direction < 0: self.image = self.images[0] elif direction > 0: self.image = self.images[1] self.rect.top = self.origtop - (self.rect.left/self.bounce%2) def main(winstyle = 0): # Initialize pygame pygame.init() if pygame.mixer and not pygame.mixer.get_init(): print 'Warning, no sound' pygame.mixer = None # Set the display mode winstyle = 0 # |FULLSCREEN bestdepth = pygame.display.mode_ok(SCREENRECT.size, winstyle, 32) screen = pygame.display.set_mode(SCREENRECT.size, winstyle, bestdepth) #Load images, assign to sprite classes #(do this before the classes are used, after screen setup) img = load_image('images/shared/largetux-walk-left-1.png') Player.images = [img, pygame.transform.flip(img, 1, 0)] #decorate the game window #icon = pygame.transform.scale(Alien.images[0], (32, 32)) #pygame.display.set_icon(icon) pygame.display.set_caption('CCN 2 Month Game') pygame.mouse.set_visible(1) #create the background, tile the bgd image bgdtile = load_image('background.gif') background = pygame.Surface(SCREENRECT.size) for x in range(0, SCREENRECT.width, bgdtile.get_width()): background.blit(bgdtile, (x, 0)) screen.blit(background, (0,0)) pygame.display.flip() #load the sound effects if pygame.mixer: music = os.path.join('data', 'house_lo.wav') pygame.mixer.music.load(music) pygame.mixer.music.play(-1) # Initialize Game Groups shots = pygame.sprite.Group() all = pygame.sprite.RenderUpdates() #assign default groups to each sprite class Player.containers = all #Shot.containers = shots, all #Create Some Starting Values clock = pygame.time.Clock() #initialize our starting sprites player = Player() while player.alive(): #get input for event in pygame.event.get(): if event.type == QUIT or \ (event.type == KEYDOWN and event.key == K_ESCAPE): return keystate = pygame.key.get_pressed() # clear/erase the last drawn sprites all.clear(screen, background) #update all the sprites all.update() direction = '' #handle player input direction = keystate[K_RIGHT] - keystate[K_LEFT] player.move(direction) #time.sleep(.05) #draw the scene dirty = all.draw(screen) py
[Tutor] Beautiful soup
I tried to use this script which I found on the web :- import urllib2, pprint from BeautifulSoup import BeautifulSoup def cellToWord(cell): """Given a table cell, return the word in that cell.""" # Some words are in bold. if cell('b'): return cell.first('b').string.strip() # Return the bold piece. else: return cell.string.split('.')[1].strip() # Remove the number. def parse(url): """Parse the given URL and return a dictionary mapping US words to foreign words.""" # Read the URL and pass it to BeautifulSoup. html = urllib2.urlopen(url).read() soup = BeautifulSoup() soup.feed(html) # Read the main table, extracting the words from the table cells. USToForeign = {} mainTable = soup.first('table') rows = mainTable('tr') for row in rows[1:]:# Exclude the first (headings) row. cells = row('td') if len(cells) == 3: # Some rows have a single colspan="3" cell. US = cellToWord(cells[0]) foreign = cellToWord(cells[1]) USToForeign[US] = foreign return USToForeign if __name__ == '__main__': url = 'http://msdn.microsoft.com/library/en-us/dnwue/html/FRE_word_list.htm' USToForeign = parse(url) pairs = USToForeign.items() pairs.sort(lambda a, b: cmp(a[0].lower(), b[0].lower())) # Web page order pprint.pprint(pairs) and it works well. However I change it to get it to look at a file on my PC, then I get this message :- Traceback (most recent call last): File "C:\Python24\beaexp2", line 43, in -toplevel- USToForeign = parse(url) File "C:\Python24\beaexp2", line 20, in parse html = urllib2.urlopen(url).read() File "C:\Python24\lib\urllib2.py", line 130, in urlopen return _opener.open(url, data) File "C:\Python24\lib\urllib2.py", line 358, in open response = self._open(req, data) File "C:\Python24\lib\urllib2.py", line 376, in _open '_open', req) File "C:\Python24\lib\urllib2.py", line 337, in _call_chain result = func(*args) File "C:\Python24\lib\urllib2.py", line 1119, in file_open return self.open_local_file(req) File "C:\Python24\lib\urllib2.py", line 1135, in open_local_file stats = os.stat(localfile) OSError: [Errno 2] No such file or directory: '\\C:\\Python24\\FRE_word_list.htm Any idea how to solve it ? The file is on my PC. I am using Python 2.4 on Win XP. Thanks in advance. David ___ How much free photo storage do you get? Store your holiday snaps for FREE with Yahoo! Photos http://uk.photos.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Beautiful soup
How did you change it to look at the file on your PC? You appear to have told urllib2 to use "FRE_word_list.htm", it cannot find that online so tried to look for it on your local disk at '\\C:\\Python24\\FRE_word_list.htm I would suggest that you either put your local html on a web server and send in that local URL or replace html = urllib2.urlopen(url).read() with html = open(r'c:\myfolder\myfile.html').read() and see where that takes you. cheers On 10/4/05, David Holland <[EMAIL PROTECTED]> wrote: > I tried to use this script which I found on the web :- > import urllib2, pprint > from BeautifulSoup import BeautifulSoup > > > def cellToWord(cell): > """Given a table cell, return the word in that > cell.""" > # Some words are in bold. > if cell('b'): > return cell.first('b').string.strip() # > Return the bold piece. > else: > return cell.string.split('.')[1].strip() # > Remove the number. > > > def parse(url): > """Parse the given URL and return a dictionary > mapping US words to > foreign words.""" > > > # Read the URL and pass it to BeautifulSoup. > html = urllib2.urlopen(url).read() > soup = BeautifulSoup() > soup.feed(html) > > > # Read the main table, extracting the words from > the table cells. > USToForeign = {} > mainTable = soup.first('table') > rows = mainTable('tr') > for row in rows[1:]:# Exclude the first > (headings) row. > cells = row('td') > if len(cells) == 3: # Some rows have a > single colspan="3" cell. > US = cellToWord(cells[0]) > foreign = cellToWord(cells[1]) > USToForeign[US] = foreign > > > return USToForeign > > > if __name__ == '__main__': > url = > 'http://msdn.microsoft.com/library/en-us/dnwue/html/FRE_word_list.htm' > > USToForeign = parse(url) > pairs = USToForeign.items() > pairs.sort(lambda a, b: cmp(a[0].lower(), > b[0].lower())) # Web page order > pprint.pprint(pairs) > > and it works well. However I change it to get it to > look at a file on my PC, then I get this message :- > Traceback (most recent call last): > File "C:\Python24\beaexp2", line 43, in -toplevel- >USToForeign = parse(url) > File "C:\Python24\beaexp2", line 20, in parse >html = urllib2.urlopen(url).read() > File "C:\Python24\lib\urllib2.py", line 130, in > urlopen >return _opener.open(url, data) > File "C:\Python24\lib\urllib2.py", line 358, in open >response = self._open(req, data) > File "C:\Python24\lib\urllib2.py", line 376, in > _open >'_open', req) > File "C:\Python24\lib\urllib2.py", line 337, in > _call_chain >result = func(*args) > File "C:\Python24\lib\urllib2.py", line 1119, in > file_open >return self.open_local_file(req) > File "C:\Python24\lib\urllib2.py", line 1135, in > open_local_file >stats = os.stat(localfile) > OSError: [Errno 2] No such file or directory: > '\\C:\\Python24\\FRE_word_list.htm > Any idea how to solve it ? The file is on my PC. > > I am using Python 2.4 on Win XP. > > Thanks in advance. > > David > > > > ___ > How much free photo storage do you get? Store your holiday > snaps for FREE with Yahoo! Photos http://uk.photos.yahoo.com > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- -- Paul Brian m. 07875 074 534 t. 0208 352 1741 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Beautiful soup
With error messages like that, the interesting bits are usually at the end: OSError: [Errno 2] No such file or directory: '\\C:\\Python24\\FRE_word_list.htm That should read "C:\\Python24\\FRE_word_list.htm". I use UNIX-style paths, which work fine for me under Windows, so it would just be "/Python24/FRE_word_list.htm" which is a bit cleaner. I am not sure if that is dependable behavior, however. Andrew On 10/4/05, David Holland <[EMAIL PROTECTED]> wrote: I tried to use this script which I found on the web :-import urllib2, pprintfrom BeautifulSoup import BeautifulSoupdef cellToWord(cell): """Given a table cell, return the word in that cell.""" # Some words are in bold. if cell('b'): return cell.first('b').string.strip() #Return the bold piece. else: return cell.string.split('.')[1].strip() # Remove the number.def parse(url): """Parse the given URL and return a dictionarymapping US words to foreign words.""" # Read the URL and pass it to BeautifulSoup. html = urllib2.urlopen(url).read() soup = BeautifulSoup() soup.feed(html) # Read the main table, extracting the words fromthe table cells. USToForeign = {} mainTable = soup.first ('table') rows = mainTable('tr') for row in rows[1:]:# Exclude the first(headings) row. cells = row('td') if len(cells) == 3: # Some rows have asingle colspan="3" cell. US = cellToWord(cells[0]) foreign = cellToWord(cells[1]) USToForeign[US] = foreign return USToForeignif __name__ == '__main__': url ="">' http://msdn.microsoft.com/library/en-us/dnwue/html/FRE_word_list.htm' USToForeign = parse(url) pairs = USToForeign.items() pairs.sort(lambda a, b: cmp(a[0].lower(),b[0].lower())) # Web page order pprint.pprint(pairs)and it works well. However I change it to get it tolook at a file on my PC, then I get this message :-Traceback (most recent call last): File "C:\Python24\beaexp2", line 43, in -toplevel- USToForeign = parse(url) File "C:\Python24\beaexp2", line 20, in parsehtml = urllib2.urlopen(url).read() File "C:\Python24\lib\urllib2.py", line 130, inurlopenreturn _opener.open(url, data) File "C:\Python24\lib\urllib2.py", line 358, in openresponse = self._open(req, data) File "C:\Python24\lib\urllib2.py", line 376, in_open'_open', req) File "C:\Python24\lib\urllib2.py", line 337, in _call_chainresult = func(*args) File "C:\Python24\lib\urllib2.py", line 1119, infile_openreturn self.open_local_file(req) File "C:\Python24\lib\urllib2.py", line 1135, in open_local_filestats = os.stat(localfile)OSError: [Errno 2] No such file or directory:'\\C:\\Python24\\FRE_word_list.htmAny idea how to solve it ? The file is on my PC.I am using Python 2.4 on Win XP.Thanks in advance.David___How much free photo storage do you get? Store your holidaysnaps for FREE with Yahoo! Photos http://uk.photos.yahoo.com___Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Beautiful soup
Oops, Paul is probably right. I thought urllib2 opened local files in the absence of an identifier like "http://". Bad assumption on my part. I remembered that behavior from somewhere else, maybe urllib. That path beginning with "\\C:\\" could still bite you, however. Good luck, Andrew ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Consistant Overhead Byte Stuffing (COBS) algorithm help
A little more info is below: With miniterm modified to output hex to the screen, here is the data coming in unformatted. (note zero bytes delimit end of packet): c:\Python23>python miniterm1.1a.py --- Miniterm --- type ESC to quit 0002860104DB203F0102860504CB1A740102860504CB1B740102860504CB1B740100 0002860504CB1B740102860504CB1B740102860504CB1B740102860504CB1B740100 0002860504CB1B740102860504CB1B740102860504CB1B740100 Here I have formatted it(one line equals a packet, currently about every 30 seconds): c:\Python23>python miniterm1.1a.py --- Miniterm --- type ESC to quit 00-02-86-05-04-CB-1B-74-01-00 00-02-86-05-04-CB-1B-74-01-00 00-02-86-01-04-DB-20-3E-01-00 00-02-86-05-04-CB-1B-74-01-00 00-02-86-05-04-CB-1B-74-01-00 00-02-86-05-04-CB-1B-74-01-00 00-02-86-05-04-CB-1B-74-01-00 00-02-86-05-04-CB-1B-74-01-00 00-02-86-05-04-CB-1B-74-01-00 00-02-86-05-04-CB-1B-74-01-00 00-02-86-05-04-CB-1B-74-01-00 00-02-86-05-04-CB-1B-74-01-00 here is what the data will look like after COBS decoding (the zero bytes are real data): 86-00-04-CB-1B-74-00 86-00-04-CB-1B-74-00 86-00-04-CB-1B-74-00 86-00-04-CB-1B-74-00 86-00-04-CB-1B-74-00 86-00-04-CB-1B-74-00 86-00-04-CB-1B-74-00 For those who are curious as to what I am doing, here is what telemetry is in the packet: packe type= 0x86 Device ID = 0x0004 Payload: Batt Volt.= 0xCB Pot Volt. = 0x1B Temp Volt.= 0x74 sw 1 = 0 sw 2 = 0 sw 3 = 0 sw 4 = 0 Btn 1 = 0 Btn 2 = 0 Yel LED = 0 Red LED = 0 Thanks, mike __ Yahoo! for Good Donate to the Hurricane Katrina relief effort. http://store.yahoo.com/redcross-donate3/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Trying to prevent ftplib from locking my script
Hi list, I'm trying to write a python script that uses ftplib to send items to a local server I have. I want to be able to give ftplib a file to send, and then just have it sort of go into the background and do its thing while the script does other "stuff" My attempts at it so far have caused the whole script to wait until the ftp transfer finishes (essentially pausing the rest of the script). Any ideas on how I can just make it go away, allowing me to do other stuff like output various info? Can threads be used? If so, does anyone have good resources to point me to for python threading? Thanks in advance! Tim ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Consistant Overhead Byte Stuffing (COBS) algorithm help
I'm not sure what the question is here. It looks like you need to write a COBS encoder / decoder in Python, maybe using your .NET code as a model. Then you can integrate that with comms code taken from miniterm. What help do you need? Kent Michael Cotherman wrote: > Hello, I am really new to python and really have not > programmed much since college, I played with it a > little now, and it seems to be a tool I feel > comfortable implementing a personal project in. > > I wish to communicate via a serial port to a device > that is using COBS. I wish to configure it and then > receive data at an interval and store it in a rrd. > The device itself receives telemetry information from > other devices, and this telemetry info is going to get > graphed and made available via a web page. > > The serial port will be com or tty, for which I > prepped by playing with pygarmin and miniterm. The > device is working and communicable? via a program > written in .NET by a friend of the friend who gave it > to me. The program has so many things I wish to change > that it would be easiest to start from scratch. I have > some of the source for bits and pieces that may be > needed. > > The data coming in/going out will be COBS encoded, > which changes/escapes all 0x00 bytes, then uses a 0x00 > byte for the framing. > > > COBS theory is explained here: > http://www.stuartcheshire.org/papers/COBSforToN.pdf > > and it looks like a version written in c is at: > http://gtk-gnutella.sourceforge.net/doxygen/cobs_8c.htm > > > I would initially be happy creating a cobs.py and then > modding the initial 1.1 release of miniterm and seeing > if I could listen to the device... The device will be > sending packets of 2-12 bytes at regular intervals > (99% will be 7 byte packets every minute or so), and I > can just move the serial cable over from the com port > with the working application to the cobs-miniterm one > to see if I am getting the right. > > Thanks in advance! > > -mike > clearwater, fl > > > > __ > Yahoo! Mail - PC Magazine Editors' Choice 2005 > http://mail.yahoo.com > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Trying to prevent ftplib from locking my script
Tim Rupp wrote: > Hi list, > > I'm trying to write a python script that uses ftplib to send items to a > local server I have. I want to be able to give ftplib a file to send, > and then just have it sort of go into the background and do its thing > while the script does other "stuff" > > My attempts at it so far have caused the whole script to wait until the > ftp transfer finishes (essentially pausing the rest of the script). > > Any ideas on how I can just make it go away, allowing me to do other > stuff like output various info? Can threads be used? If so, does anyone > have good resources to point me to for python threading? Yes, threads are one solution to this problem. Twisted and Kamaelia are two other solutions. See this msg for links to some helpful discussions: http://mail.python.org/pipermail/tutor/2005-October/041866.html Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Beautiful soup
On 10/4/05, Andrew P <[EMAIL PROTECTED]> wrote: Oops, Paul is probably right. I thought urllib2 opened local files in the absence of an identifier like "http://". Bad assumption on my part. I remembered that behavior from somewhere else, maybe urllib. The following function could be useful here - I got it from Dive Into Python - http://diveintopython.org/scripts_and_streams/index.html#kgp.openanything It tries to open a file with urllib, and if that fails it uses open(): def openAnything(source): # try to open with urllib (if source is http, ftp, or file URL)import urllib try: return urllib.urlopen(source) except (IOError, OSError):pass # try to open with native open function (if source is pathname)try : return open(source)except (IOError, OSError): pass # treat source as stringimport StringIO return StringIO.StringIO(str(source)) Olly ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Trying to prevent ftplib from locking my script
Normally I wouldn't pipe up here because threads really can be very tricky. But check out: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/435883 I use this recipe, originally from "Python in a Nutshell", all the time, to solve exactly your problem. Slow network stuff that I don't have to/want to babysit. The recipe is well-commented, with an easy-to-follow usage example. Basically though, Python's Queue module really takes away a lot of the trickiness here, acting as a thread-safe place to put jobs, and put results, without worrying about locks or sephamores or whatever it is people worry about. And the callback functions you can pass in with the job may be all you really need to report success/failure of the jobs. All in all, it's probably easier to just read the code. Good luck. On 10/4/05, Tim Rupp <[EMAIL PROTECTED]> wrote: Hi list,I'm trying to write a python script that uses ftplib to send items to alocal server I have. I want to be able to give ftplib a file to send,and then just have it sort of go into the background and do its thing while the script does other "stuff"My attempts at it so far have caused the whole script to wait until theftp transfer finishes (essentially pausing the rest of the script).Any ideas on how I can just make it go away, allowing me to do other stuff like output various info? Can threads be used? If so, does anyonehave good resources to point me to for python threading?Thanks in advance!Tim___ Tutor maillist - Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python equiv to PHP "include" ?
On Thu, Sep 29, 2005 at 05:16:57PM -0400, Jay Loden wrote: > Does anyone know of any soup-to-nuts CGI programming examples online for > Python that might make this clearer so I can bug the list less and just read > some example code? You might also want to take a look at cgi_app, a simple python web framework that works in either a plain old CGI environment, or can easily be adapted to mod_python. This page includes a basic usage example: http://thraxil.org/code/cgi_app/ -- Larry Holish <[EMAIL PROTECTED]> ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Mod_python greedy url matching
I'm having trouble with Apache and Mod_python - mod_python is set to use /var/www/html and pass all *.htm files on to the handler I wrote. Unfortunately, mod_python does a greedy match, so /var/www/html/subdirectory/file.htm still gets passed to the handler! Is there some way to limit the handler to the directory and NOT include subdirectories? -Jay ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor