How to properly apply OOP in the bouncing ball code
I'm trying to apply OOP in this bouncing ball code in order to have multiple balls bouncing around the screen. The objective of this code is to create a method called settings, which controls all the settings for the screen and the bouncing behaviour of multiple balls, under the class Ball. However, I keep on getting errors related to attributes (e.g., speed). I'm new to OOP in Python so your help will be much appreciated. Thanks in advance. import pygame import random import sys pygame.init() class Ball: def __init__(self, X, Y): self.velocity = [1,1] self.ball_image = pygame.image.load ("ball.jpg") self.ball_boundary = self.ball_image.get_rect () self.black = [0,0,0] self.width = 800 self.height = 600 self.num = 8 self.X = random.randint(0, self.width) self.Y = random.randint(0, self.height) def settings(self): #X = random.randint(0, self.width) #Y = random.randint(0, self.height) clock = pygame.time.Clock() size = self.width, self.height screen = pygame.display.set_mode(size) ball_boundary = self.ball_image.get_rect() speed = self.velocity pic = self.ball_image pygame.display.set_caption("Balls") num_balls = self.num ball_list = [] for i in range(num_balls): ball_list.append( Ball(random.randint(10, self.width-10),random.randint(10, self.height-10)) ) while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit(0) screen.fill(self.black) for balls in ball_list: if balls.ball_boundary.left < 0 or balls.ball_boundary.right > self.width: balls.speed[0] = -balls.speed[0] if balls.ball_boundary.top < 0 or balls.ball_boundary.bottom > self.height: balls.speed[1] = -balls.speed[1] balls.ball_boundary = balls.ball_boundary.move (self.velocity) screen.blit (balls.ball_image, balls.ball_boundary) pygame.display.flip() play = Ball(random.randint(0, 800), random.randint(0, 600)) play.settings() Message File Name LinePosition Traceback C:\\Multiple_balls_TC.py63 settingsC:\\Multiple_balls_TC.py56 AttributeError: Ball instance has no attribute 'speed' -- https://mail.python.org/mailman/listinfo/python-list
Re: How to properly apply OOP in the bouncing ball code
Thanks for your help. I have updated the code as follows, there are no more errors but the images will not move at all, as all the images are staying at the upper left corner. Please advice, thanks. import sys, pygame pygame.init() size = width, height = 800, 600 black = [0,0,0] screen = pygame.display.set_mode(size) class BALL: def __init__(self,image): self.ball = pygame.image.load(image) self.ballrect = self.ball.get_rect() self.speed= [2, 2] def control(self): ballmove = self.ballrect.move(self.speed) if ballmove.left < 0 or ballmove.right > width: self.speed[0] = -self.speed[0] if ballmove.top < 0 or ballmove.bottom > height: self.speed[1] = -self.speed[1] def settings(self): clock = pygame.time.Clock() screen.fill(black) screen.blit(self.ball, self.ballrect) pygame.display.flip() clock.tick(60) while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() bob = BALL("spongebob.png") bob.control() bob.settings() patrick = BALL("patrick.jpg") patrick.speed[0] = 5 patrick.speed[1] = 8 patrick.control() patrick.settings() jaws = BALL("jaws.jpg") jaws.speed[0] = 1 jaws.speed[1] = 10 jaws.control() jaws.settings() On Friday, May 8, 2015 at 11:40:46 AM UTC-4, Tommy C wrote: > I'm trying to apply OOP in this bouncing ball code in order to have multiple > balls bouncing around the screen. The objective of this code is to create a > method called settings, which controls all the settings for the screen and > the bouncing behaviour of multiple balls, under the class Ball. However, I > keep on getting errors related to attributes (e.g., speed). I'm new to OOP in > Python so your help will be much appreciated. Thanks in advance. > > > import pygame > import random > import sys > > pygame.init() > > class Ball: > def __init__(self, X, Y): > self.velocity = [1,1] > self.ball_image = pygame.image.load ("ball.jpg") > self.ball_boundary = self.ball_image.get_rect () > self.black = [0,0,0] > self.width = 800 > self.height = 600 > self.num = 8 > self.X = random.randint(0, self.width) > self.Y = random.randint(0, self.height) > > def settings(self): > #X = random.randint(0, self.width) > #Y = random.randint(0, self.height) > clock = pygame.time.Clock() > size = self.width, self.height > screen = pygame.display.set_mode(size) > ball_boundary = self.ball_image.get_rect() > speed = self.velocity > pic = self.ball_image > pygame.display.set_caption("Balls") > num_balls = self.num > ball_list = [] > > for i in range(num_balls): >ball_list.append( Ball(random.randint(10, > self.width-10),random.randint(10, self.height-10)) ) > > while 1: > for event in pygame.event.get(): > if event.type == pygame.QUIT: > sys.exit(0) > > screen.fill(self.black) > for balls in ball_list: > if balls.ball_boundary.left < 0 or balls.ball_boundary.right > > self.width: > balls.speed[0] = -balls.speed[0] > if balls.ball_boundary.top < 0 or balls.ball_boundary.bottom > > self.height: > balls.speed[1] = -balls.speed[1] > balls.ball_boundary = balls.ball_boundary.move (self.velocity) > screen.blit (balls.ball_image, balls.ball_boundary) > pygame.display.flip() > > play = Ball(random.randint(0, 800), random.randint(0, 600)) > > play.settings() > > > > > Message File Name LinePosition > Traceback > C:\\Multiple_balls_TC.py63 > settings C:\\Multiple_balls_TC.py56 > AttributeError: Ball instance has no attribute 'speed' -- https://mail.python.org/mailman/listinfo/python-list
Questions on Pandas
Hi there, I have a number of questions related to the Pandas exercises found from the book, Python for Data Analysis by Wes McKinney. Particularly, these exercises are from Chapter 6 of the book. It'd be much appreciated if you could answer the following questions! 1. [code] Input: pd.read_csv('ch06/ex2.csv', header=None) Output: X.1 X.2 X.3 X.4 X.5 0 1 2 3 4 hello 1 5 6 7 8 world 2 9 10 11 12 foo [/code] Does the header appear as "X.#" by default when it is set to be None? 2. [code] Input: chunker = pd.read_csv('ch06/ex6.csv', chunksize=1000) Input: chunker Output: [/code] Please explain the idea of chunksize and the output meaning. 3. [code] The TextParser object returned by read_csv allows you to iterate over the parts of the file according to the chunksize. For example, we can iterate over ex6.csv, aggregating the value counts in the 'key' column like so: chunker = pd.read_csv('ch06/ex6.csv', chunksize=1000) tot = Series([]) for piece in chunker: tot = tot.add(piece['key'].value_counts(), fill_value=0) tot = tot.order(ascending=False) We have then: In [877]: tot[:10] Out[877]: E 368 X 364 L 346 O 343 Q 340 M 338 J 337 F 335 K 334 H 330 [/code] I couldn't run the Series function successfully... is there something missing in this code? 4. [code] Data can also be exported to delimited format. Let's consider one of the CSV files read above: In [878]: data = pd.read_csv('ch06/ex5.csv') In [879]: data Out[879]: something a b c d message 0 one 1 2 3 4 NaN 1 two 5 6 NaN 8 world 2 three 9 10 11 12 foo Missing values appear as empty strings in the output. You might want to denote them by some other sentinel value: In [883]: data.to_csv(sys.stdout, na_rep='NULL') ,something,a,b,c,d,message 0,one,1,2,3.0,4,NULL 1,two,5,6,NULL,8,world 2,three,9,10,11.0,12,foo [/code] Error occured as I tried to run this code with sys.stdout. 5. [code] class of csv.Dialect: class my_dialect(csv.Dialect): lineterminator = '\n' delimiter = ';' quotechar = '"' reader = csv.reader(f, dialect=my_dialect) [/code] An error occurred when I tried to run this code: "quotechar must be an 1-character integer... please explain. 6. [code] with open('mydata.csv', 'w') as f: writer = csv.writer(f, dialect=my_dialect) writer.writerow(('one', 'two', 'three')) writer.writerow(('1', '2', '3')) writer.writerow(('4', '5', '6')) writer.writerow(('7', '8', '9')) [/code] An error occurred when I ran this code. Please explain the cause of the error. 7. [code] But these are objects representing HTML elements; to get the URL and link text you have to use each element's get method (for the URL) and text_content method (for the display text): In [908]: lnk = links[28] In [909]: lnk Out[909]: In [910]: lnk.get('href') Out[910]: 'http://biz.yahoo.com/special.html' In [911]: lnk.text_content() Out[911]: 'Special Editions' Thus, getting a list of all URLs in the document is a matter of writing this list comprehension: In [912]: urls = [lnk.get('href') for lnk in doc.findall('.//a')] In [913]: urls[-10:] Out[913]: ['http://info.yahoo.com/privacy/us/yahoo/finance/details.html', 'http://info.yahoo.com/relevantads/', 'http://docs.yahoo.com/info/terms/', 'http://docs.yahoo.com/info/copyright/copyright.html', 'http://help.yahoo.com/l/us/yahoo/finance/forms_index.html', 'http://help.yahoo.com/l/us/yahoo/finance/quotes/fitadelay.html', 'http://help.yahoo.com/l/us/yahoo/finance/quotes/fitadelay.html', [/code] An error related to line 912 occurred as I tried to run the code. Please explain. 8. [code] Using lxml.objectify, we parse the file and get a reference to the root node of the XML file with getroot: from lxml import objectify path = 'Performance_MNR.xml' parsed = objectify.parse(open(path)) root = parsed.getroot() [/code] An error occured when I tried to run the code to access the XML file. Please explain. 9. [code] ML data can get much more complicated than this example. Each tag can have metadata, too. Consider an HTML link tag which is also valid XML: from StringIO import StringIO tag = 'http://www.google.com";>Google' root = objectify.parse(StringIO(tag)).getroot() You can now access any of the fields (like href) in the tag or the link text: In [930]: root Out[930]: In [931]: root.get('href') Out[931]: 'http://www.google.com' In [932]: root.text Out[932]: 'Google' [/code] The outputs for line 930 and 931 are the same as line 932 (i.e., Google). Please explain 10. [code] One of the easiest ways to store data efficiently in binary format is using Python's builtin pickle serialization. Conveniently, pandas objects all have a save method which writes the data to disk as a pickle: In [933]: frame = pd.read_csv('ch06/ex1.csv') In [934]: frame Out[934]: a b c d message 0 1 2 3 4 hello 1 5 6 7 8 world 2 9 10 11 12 foo In [935]: frame.save('ch06/frame_pickle') You read the data back into Python with pandas.load, another pickle convenience function: In [936]: pd.load('ch06/frame_pickle') Out[936]: a b c