1 / 44

IST380: April edition

IST380: April edition. 4/14 ~ projects++. Hw # 8 due 4/9. More-d! Connect Four. 4/21 ~ C S ++. Final milestone due 4/30. Hw # 9 due 4/16. hw9pr1. 4/28 + 5/5 ~ project work. Final project due 5/7. 3d! the 20's defining technology. hw9pr2. The Board class.

kamal
Télécharger la présentation

IST380: April edition

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. IST380: April edition 4/14 ~ projects++ Hw#8due 4/9 More-d! Connect Four 4/21 ~ CS++ Final milestone due 4/30 Hw#9due 4/16 hw9pr1 4/28 + 5/5 ~ project work Final project due 5/7 3d! the 20's defining technology hw9pr2 The Boardclass Using the VPython3d graphics API there's no "bored" in this class! Notice that the value of (dimension + eyes) is conserved!

  2. IST380 right now! Hw#8 due 4/9 Classes/objects Dictionaries + text…! hw8pr1 hw8pr2 file and dictionaryclasses The Dateclass files dictionaries I might have to look up how to use dictionaries again!

  3. Classes: DIY data design-it-yourself! Class: a user-defined datatype Object: data or a variable whose type is a class constructor d = Date( 4, 7, 2017 ) d.tomorrow() print d object method dwould be named selfinside the Dateclass... uses repr Method: a function defined in a class called by an object self: in a class, the name of the object calling a method Constructor: the __init__ function for creating a new object repr: the __repr__ function returning a string to print data member: the data in self: self.day, self.month, self.year

  4. Whyclasses? Python has no Connect-four datatype… | | | | | | | | | | | | | | | | | | | | | | | | | | | |X| | | | | |X| |X|O| | | |X|O|O|O|X| |O| --------------- 0 1 2 3 4 5 6 Care for a game? … but now we can fix that!

  5. Data design… Not limited to 7x6! (Data Members) What data do we need? (Methods) What are capabilities do we want? What is the key ingredient that makes C4 different from most board games?

  6. Our Boardobject,b ? str str str str str str str str str str str str rows data Board b str str str str str str 5 6 str str str str str str ? height width str str str str str str columns b. How could we set ?and ?to 'X'

  7. constructor class Board: """ a datatype representing a C4 board with an arbitrary number of rows and cols """ def__init__( self, width, height ): """ the constructor for objects of type Board """ self.width = width self.height = height W = self.width H = self.height self.data = [ [' ']*W for row in range(H) ] This list comprehension lets us create H independent rows with W independent columns each.

  8. __repr__ def__repr__(self): """ this method returns a string representation for an object of type Board """ H = self.height W = self.width s = '' for r in range( H ): s += '|' for c inrange( W ): s += self.data[r][c] + '|' s += '\n' s += (2*W+1)*'-' # what will you need to add right here? return s | | | | | | | | | | | | | | | | | | | | | | | | | | | |X| | | | | |X| |X|O| | | |X|O|O|O|X| |O| --------------- 0 1 2 3 4 5 6

  9. a C4 board Try it! class Board: defaddMove(self, col, ox): """ buggy version! """ H = self.height D = self.data for row inrange(0,H): ifD[row][col] != ' ': D[row-1][col] = ox D[H][col] = ox col # 'X' or 'O' Buggy version! (1) Run b.addMove(3,'O') D 0 1 2 3 4 5 6 0 (2) Bugs!Can you find/fix them?! | | | | | | | | | | | | | | | | | | | | | | | | | | | |X| | | | | |X| |X|O| | | |X|O|O|O|X| |O| --------------- 0 1 2 3 4 5 6 1 2 3 4 5

  10. Try it, p.2 a C4 board class Board: defallowsMove(self, col): """ True if col is in-bounds and open False otherwise """ H = self.height W = self.width D = self.data if col # Finish this allowsMove method … If col is out-of-bounds or full, return False. If it's in-bounds and not full, return True.

  11. hw9pr1: Boardclass __init__( self, width, height ) the “constructor” allowsMove( self, col ) checks if allowed addMove( self, col, ox ) places a checker delMove( self, col ) removes a checker to write... __repr__( self ) outputs a string isFull( self ) checks if any space is left to write... winsFor( self, ox ) checks if a player has won to write... hostGame( self ) the game... to write... Which are similar to others? Which requires the most thought?

  12. winsFor( self, ox ) b defwinsFor(self, ox): """ does ox win? """ H = self.height W = self.width D = self.data 'X' 'O' D b.winsFor('X') or 'O' Watch out for corner cases!

  13. Whyobjects and classes? Elegance: Objects hide complexity! ifb.winsFor( 'X' ) == True: ifd.isBefore( d2 ) == True: Simple – and INVITING -- building blocks!

  14. This week's classes More-d! Connect Four hw9pr1 3d! the 20's defining technology hw9pr2 The Boardclass Using the VPython3d graphics API there's no "bored" in this class! Notice that the value of (dimension + eyes) is conserved!

  15. Twitter's power? a public API Object-oriented philosophy…

  16. Python objects used in VPython… Tuplesare similar to lists, but they're parenthesized: T = (4,2) V = (1,0,0) example of a two-element tuple named T and a three-element tuple named V

  17. Tuples! Lists that use parentheses are called tuples: >>> T = ( 4, 2 ) >>> T (4, 2) >>> T[0] 4 >>> T[0] = 42 Error! >>> T = ('a',2,'z') >>> Tuples are immutable lists: you can't change their elements... ...but you can always redefine the whole variable, if you want! + Tuples are more memory + time efficient + Tuples can be dictionary keys; lists can't - But you can't change tuples' elements...

  18. Creating 1-tuples would seem like a problem! Tuple problems… A possible bug from the bottom line of the Boardclass: W = 4 s = " ", for col inrange(W): s += str(col), " " yields a surprising result for s:

  19. Creating 1-tuples would seem like a problem! Tuple problems… A possible bug from the bottom line of the Boardclass: W = 4 s = " ", for col inrange(W): s += str(col), " " yields a surprising result for s: (' ', '0', ' ', '1', ' ', '2', ' ', '3', ' ')

  20. Python details used in VPython… Functions can have default input values and can take named inputs deff(x=9, y=33): return x + y example of default input values for x and y

  21. Python details used in VPython… Functions can have default input values and can take named inputs deff(x=9, y=33): return x + y example of default input values for x and y f() f(1) f(y=1) example of a named input

  22. Named inputs deff(x=2, y=0): return x*(1+4*y) Input your name(s) = ___________________________ What will these function calls to f return? f(3,2) f(3) f() f(y=3,x=1) second- What is a call to f that returns 42? What is the shortest call to f returning 42? Extra!

  23. VPython stonehenge.py www.vpython.org built by and for physicists to simplify 3d simulations bounce.py lots of available classes, objects and methods in its API Easily installable for windows… and mostly easy on Macs.

  24. Installing VPython Windows: www.vpython.org/contents/download_windows.html Mac: http://www.vpython.org/contents/download_mac.html I've tried both of these and they worked so far… Tutorials and documentation…

  25. API ... stands for Application Programming Interface a description of how to use a software library A demo of VPython's API: What's cylinder? What's visual? What's c? from visual import * c = cylinder() at least it's not Visual C… VPython example API calls: must be from a file

  26. VPython from visual import * c = cylinder() print"c.posis", c.pos print"c.color is", c.color # set the color to color.blue or a tuple # set the pos… hard to tell what's happening… scene.autoscale = False b = box(pos=(4,0,0)) a = sphere(pos=(0,0,4)) Set up the world with 3d objects more example API calls whileTrue: rate(100) # limits the loop rate in hz dt = 0.01 # the loop time a.pos += dt*vector(-5,0,0) Then, run a simulation using those objects…

  27. VPython! (0) How many tuples appear in this code? ________ (1) How many classes are used here? ________ (2) How many objects are used here? ________ (3) How do collisions work? (4) How does physics/gravity work? Look over this VPython program to determine with the Higgs boson! from visual import * floor = box( length=4,width=4,height=0.5,color=color.blue ) ball = sphere( pos=(0,8,0),radius=1,color=color.red ) vel = vector(0,-1,0) dt = 0.01 whileTrue: rate(100) ball.pos += vel*dt ifball.pos.y < ball.radius: vel.y *= -1.0 else: vel.y += -9.8*dt What physics is this if/elsedoing?

  28. vectors act like vectors! vel = vector(0,-1,0) named components vel.z vel.y vel.x vel += 0.01*vector(0,-9.8,0) multiplication by a scalar – finally! pos = pos + 0.01*vel component-by-component addition

  29. Orbiting "force arrow" in example code… from visual import * e = sphere(pos=(0,0,10),color=color.blue) #earth s = sphere(color=color.yellow,radius=2) #sun e.vel = vector(5,0,0) # initial velocity RATE = 50 dt = 1.0/RATE k = 70.0 # G! while True: rate(RATE) diff = s.pos - e.pos # vector difference force = k*diff/(mag(diff)**2) # mag e.vel += dt*force # acceleration d.e. e.pos += dt*e.vel # velocity d.e. with vectors!

  30. frames creating new data members for an object – on the fly! Note that the frame is being moved here ~ this moves all of the parts!

  31. Moving! by velocity or kbd while True: alien.pos += alien.vel*dt# this is physics! ifscene.kb.keys: # is there a keyevent? s = scene.kb.getkey() # get keypress if s == "p": printalien.pos # things the alien(s) can do! if s == 'J': # JOUST! alien.vel= vector(3,0,4) # stop the alien! # move the beam around if s == "i": friend.pos+= vector(0,0,1) if s == "k": friend.pos+= vector(0,0,-1) if s == "j": friend.pos+= vector(-1,0,0) if s == "l": friend.pos+= vector(1,0,0) Note that the frame is being moved here ~ this moves all of the parts!

  32. Your challenge: sometimes can be tricky… (1) Get VPython running! not so bad: event-loop thinking (2) Get used to VPython's style… this is they key – interactions! (3) Bounce an alien off one wall! stay in the x-z plane for now… (4) You're home free! … though you do need at least 2 aliens and 5 walls! and a small amount of gameplay (some interaction) VPython project ideas ~ next week!

  33. Good luck with VPython! … and Connect Four! no limits as to where you might go…

  34. Our Boardobject,b ? str str str str str str str str str str str str rows data Board b str str str str str str 5 6 str str str str str str ? height width str str str str str str columns b. How could we set ?and ?to 'X'

  35. Named inputs deff(x=2, y=0): return x*(1+4*y) Input your name(s) = ___________________________ What will these function calls to f return? f(3,2) f(3) f() f(y=3,x=1) second- What is a call to f that returns 42? What is the shortest call to f returning 42? Extra!

  36. VPython! (0) How many tuples appear in this code? ________ (1) How many classes are used here? ________ (2) How many objects are used here? ________ (3) How do collisions work? (4) How does physics/gravity work? Look over this VPython program to determine with the Higgs boson! from visual import * floor = box( length=4,width=4,height=0.5,color=color.blue ) ball = sphere( pos=(0,8,0),radius=1,color=color.red ) vel = vector(0,-1,0) dt = 0.01 whileTrue: rate(100) ball.pos += vel*dt ifball.pos.y < ball.radius: vel.y *= -1.0 else: vel.y += -9.8*dt What physics is this if/elsedoing?

  37. Everything in python is an object Demo! x = 20 y = 22 x.__add__(y) # either way! # even this! (19).__add__(23) id(x) id(y) Hey! No other aliens allowed! You mean superego? My ego approves!

  38. A complex object: It seems clear enough to me! >>> z = complex(3,4) >>> z (3+4j) >>> dir(z) all of the data members and methods of the complex class (and thus the object z !) >>> z.imag 4.0 >>> z.conjugate() 3-4j a data member of all objects of class complex its value for this object, z a method (function) within all objects of class complex its return value for this object, z

  39. A complex class: will have more methods (functions), too... defines the type of our complex-number objects

  40. Objects ~ DOTs ! Constructor! s = str('harvey mudd college') dir(s) s.spit() s.__len__() # I should underscore this point! s.title() # an entitlement? 20*'spam'.title() # how many capital S's? ('spam'*20).title() What, the L ?

  41. Everything in python is an object Demo! x = 20 y = 22 x.__add__(y) # either way! # even this! (19).__add__(23) id(x) id(y) Hey! No other aliens allowed! You mean superego? My ego approves!

  42. dir and help ! provide all of the methods and data members available to an object dir('any string') help(''.count) dir(42) dir( [] ) No memorizing! Just use dir & help… try sort!

  43. Examples… Graphics libraries Python's class libraries… Do reference libraries have library references? http://docs.python.org/lib/

More Related