Your SlideShare is downloading. ×
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

# Python & Perl: PyGame Basics By Example: 2D Movement, Diagonal Sprite Movement with Bounce, 2D Vectors, 2D Movement Direction Change with Unit Vectors, Keyboard Control of 2D Movement

2,141
views

Published on

Published in: Technology

0 Comments
0 Likes
Statistics
Notes
• Full Name
Comment goes here.

Are you sure you want to Yes No
Your message goes here
• Be the first to comment

• Be the first to like this

No Downloads
Views
Total Views
2,141
On Slideshare
0
From Embeds
0
Number of Embeds
42
Actions
Shares
0
Downloads
0
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

### Transcript

• 1. Python & PerlPyGame Basics By Example2D Movement, Diagonal Sprite Movement with Bounce, 2DVectors, 2D Movement Direction Change with Unit Vectors,Keyboard Control of 2D MovementVladimir Kulyukinwww.youtube.com/vkedcowww.youtube.com/vkedco www.vkedco.blogspot.comwww.vkedco.blogspot.com
• 2. Outline● Review: 2D Sprite Movement● Diagonal 2D Sprite Movement with Bounce● 2D Vectors● 2D Movement Direction Change with Unit Vectors● Keyboard Control of 2D Movementwww.youtube.com/vkedcowww.youtube.com/vkedco www.vkedco.blogspot.comwww.vkedco.blogspot.com
• 3. ReviewBasics of 2D Sprite Movementwww.youtube.com/vkedcowww.youtube.com/vkedco www.vkedco.blogspot.comwww.vkedco.blogspot.com
• 4. Horizontal Movement● To move a sprite horizontally:– Initialize the sprites x coordinate– Initialize x_delta (number pixels thesprite moves per unit of time)– Move the sprite x_delta pixelsright/left every unit of timewww.youtube.com/vkedcowww.youtube.com/vkedco www.vkedco.blogspot.comwww.vkedco.blogspot.com
• 5. Vertical Movement● To move a sprite vertically:– Initialize the sprites y coordinate– Initialize y_delta (number pixels thesprite moves per unit of time)– Move the sprite y_delta pixelsup/down every unit of timewww.youtube.com/vkedcowww.youtube.com/vkedco www.vkedco.blogspot.comwww.vkedco.blogspot.com
• 6. Diagonal Movement● To move a sprite diagonally:– Initialize the sprites x and ycoordinates– Define x_delta and y_delta– Move the sprite x_delta and y_deltapixels simultaneouslywww.youtube.com/vkedcowww.youtube.com/vkedco www.vkedco.blogspot.comwww.vkedco.blogspot.com
• 7. Timed Movementwww.youtube.com/vkedcowww.youtube.com/vkedco www.vkedco.blogspot.comwww.vkedco.blogspot.comx = 0x_delta = 10 ## move sprite_img x_delta every sleep_time secondssleep_time = 0.5my_event = pygame.event.Event(KEYDOWN, key=K_SPACE, mod=0, unicode=u )while True:pygame.event.post(my_event)## checking for the QUICK event is omittedscreen.blit(background_img, (0, 0))screen.blit(sprite_img, (x, 80))x += x_deltaif x > 200.0: x -= 210.0pygame.display.update()time.sleep(sleep_time)source code is here
• 8. Clocked 2D Movementwww.youtube.com/vkedcowww.youtube.com/vkedco www.vkedco.blogspot.comwww.vkedco.blogspot.comclock = pygame.time.Clock()x = 0speed = 15 ## pix/secmy_event = pygame.event.Event(KEYDOWN, key=K_SPACE, mod=0, unicode=u )while True:pygame.event.post(my_event)for event in pygame.event.get():if event.type == QUIT: ## quit the gamescreen.blit(background_img, (0, 0))screen.blit(sprite_img, (x, 100))time_passed = clock.tick() / 1000.0distance_delta = speed * time_passedx += distance_deltaif x > 225.0: x -= 225.0pygame.display.update()source code is here
• 9. Diagonal Clocked 2D Sprite Movementwith Bouncewww.youtube.com/vkedcowww.youtube.com/vkedco www.vkedco.blogspot.comwww.vkedco.blogspot.com
• 10. ProblemWrite a PyGame program that does aclocked diagonal 2D sprite movement insuch a way that the sprite bounces in theopposite direction when touching thehorizontal & vertical boundaries of thewindow.www.youtube.com/vkedcowww.youtube.com/vkedco www.vkedco.blogspot.comwww.vkedco.blogspot.comsource code is here
• 11. Initializationwww.youtube.com/vkedcowww.youtube.com/vkedco www.vkedco.blogspot.comwww.vkedco.blogspot.com## 1. Load background and sprite imagesbackground_img = pygame.image.load(background_image_fp).convert()sprite_img = pygame.image.load(sprite_image_fp)## 2. Initialize a clock objectclock = pygame.time.Clock()## 3. Get the screens and sprites parametersscreen_w, screen_h = screen.get_width(), screen.get_height()sprite_w, sprite_h = sprite_img.get_width(), sprite_img.get_height()## 4. Initialize the x, y coordinates of the spritesprite_x, sprite_y = 0, 0## 5. Initialize the speeds along the x and y axesspeed_x = 100 ## pix/secspeed_y = 100 ## pix/sec
• 12. Blit & Add Distanceswww.youtube.com/vkedcowww.youtube.com/vkedco www.vkedco.blogspot.comwww.vkedco.blogspot.com## Blit background and spritescreen.blit(background_img, (0, 0))screen.blit(sprite_img, (int(sprite_x), int(sprite_y)))## Compute time passed in secondstime_passed = clock.tick(30) / 1000.0## recompute sprites x & y coordinatessprite_x += speed_x * time_passedsprite_y += speed_y * time_passed
• 13. Handling Vertical Boundary Contactwww.youtube.com/vkedcowww.youtube.com/vkedco www.vkedco.blogspot.comwww.vkedco.blogspot.com## Compute right vertical boundary contact & reverse## horizontal speed if necessaryif sprite_x > screen_w - sprite_w:sprite_x = screen_w - sprite_wspeed_x = -speed_x## Compute left vertical boundary contact & reverse## horizontal speed if necessaryelif sprite_x < 0:sprite_x = 0speed_x = -speed_x
• 14. Handling Horizontal Boundary Contactwww.youtube.com/vkedcowww.youtube.com/vkedco www.vkedco.blogspot.comwww.vkedco.blogspot.com## Compute lower horizontal boundary contact## & reverse vertical speed if necessaryif sprite_y > screen_h - sprite_h:sprite_y = screen_h - sprite_hspeed_y = -speed_y## Compute upper horizontal boundary contact## & reverse horizontal speed if necessaryelif sprite_y < 0:sprite_y = 0speed_y = -speed_y
• 15. 2D Vectorswww.youtube.com/vkedcowww.youtube.com/vkedco www.vkedco.blogspot.comwww.vkedco.blogspot.com
• 16. 2D Vectors● A point (x, y) is a static position in 2DA vector (x, y) is another point obtained from thecurrent position (x,y) by adding x to x and y to y● Given a point P1(x1, y1) and another P2(x2, y2),vector P1P2 is computed as (x2-x1, y2-y1)● Example: if P1(10, 4), P2(30, 35), then vector P1P2is (30-10=20, 35-4=31)● Rule of Thumb: Every game developer writes a dozen2D and 3D vector classeswww.youtube.com/vkedcowww.youtube.com/vkedco www.vkedco.blogspot.comwww.vkedco.blogspot.com
• 17. 2D Vector Classwww.youtube.com/vkedcowww.youtube.com/vkedco www.vkedco.blogspot.comwww.vkedco.blogspot.comclass Vector2D(object):def __init__(self, x=0.0, y=0.0):self.x = xself.y = y## called when print is called on Vector2D objectsdef __str__(self):return "(%s, %s)"%(self.x, self.y)source code is here
• 18. 2D Vector Class: Class Methodswww.youtube.com/vkedcowww.youtube.com/vkedco www.vkedco.blogspot.comwww.vkedco.blogspot.comclass Vector2D(object):@classmethoddef vector_from_points(cls, p1, p2):return cls(p2[0] - p1[0], p2[1] - p1[1])@classmethoddef vector_from_vectors(cls, v1, v2):return cls(v2.x - v1.x, v2.y - v2.y)Class methods do not require object instances to becalledA = (10.0, 20.0)B = (30.0, 35.0)AB = Vector2D.vector_from_points(A, B)print AB ## prints out (20.0, 15)
• 19. 2D Vector: Magnitude & Distancewww.youtube.com/vkedcowww.youtube.com/vkedco www.vkedco.blogspot.comwww.vkedco.blogspot.comdef get_magnitude(self):return math.sqrt(self.x ** 2 + self.y ** 2)def get_distance_to(self, point):if type(point) == tuple:px, py = pointelif type(point) == Vector2D:px, py = point.x, point.yelse:raise Exception(unknown type of point)return math.sqrt((self.y - py)**2 + (self.x - px)**2)
• 20. Vector Addition & Subtraction● If an agent needs to move from point A to point B andfrom B to C, adding AB to BC, produces the vector AC,which has the combined effect of moving from A to Band from B to C● Vector addition can be used to estimate moving costs● Subtraction is movement in the opposite direction: ifthere is a point in space an object wants to move awayfrom, the object calculates a vector to the point andthen subtracts it from its current position● Addition & Subtraction can be implemented with magicmethodswww.youtube.com/vkedcowww.youtube.com/vkedco www.vkedco.blogspot.comwww.vkedco.blogspot.com
• 21. 2D Vector Class: Magic Methodswww.youtube.com/vkedcowww.youtube.com/vkedco www.vkedco.blogspot.comwww.vkedco.blogspot.comclass Vector2D(object):## called when A and B are Vector2D objects## and A + B is evaluateddef __add__(self, rhs):return Vector2D(self.x + rhs.x, self.y + rhs.y)## called on A – B if A and B are Vector2D objectsdef __sub__(self, rhs):return Vector2D(self.x - rhs.x, self.y - rhs.y)
• 22. 2D Vector Class: Other Magic Methodswww.youtube.com/vkedcowww.youtube.com/vkedco www.vkedco.blogspot.comwww.vkedco.blogspot.comclass Vector2D(object):## negate a vector object, e.g., NEG_A = -Adef __neg__(self):return Vector2D(-self.x, -self.y)## scale a vector by a scalar, e.g., V * 2.5def __mul__(self, scalar):return Vector2D(self.x*scalar, self.y*scalar)
• 23. Unit Vectors● Vectors specify not only magnitude but alsodirection● If we want to remove the magnitude informationfrom the vector, we need to divide the vector byits magnitude● This division, known as normalization, producesa special kind of vector called unit vector● Unit vectors are used to represent heading andalways have the length of 1www.youtube.com/vkedcowww.youtube.com/vkedco www.vkedco.blogspot.comwww.vkedco.blogspot.com
• 24. 2D Vector Class: Normalizationwww.youtube.com/vkedcowww.youtube.com/vkedco www.vkedco.blogspot.comwww.vkedco.blogspot.comclass Vector2D(object):def get_magnitude(self):return math.sqrt(self.x ** 2 + self.y ** 2)def normalize(self):magn = self.get_magnitude()if magn > 0:self.x /= magnself.y /= magn
• 25. 2D Vector Class: Testwww.youtube.com/vkedcowww.youtube.com/vkedco www.vkedco.blogspot.comwww.vkedco.blogspot.comdef test_01():A = (10.0, 20.0)B = (30.0, 35.0)C = (15.0, 45.0)AB = Vector2D.vector_from_points(A, B)print AB=, ABBC = Vector2D.vector_from_points(B, C)print BC=, BCAC = Vector2D.vector_from_points(A, C)print AC=, ACprint ACAC_02 = AB + BCprint AC_02
• 26. 2D Movement Direction ChangewithUnit Vectorswww.youtube.com/vkedcowww.youtube.com/vkedco www.vkedco.blogspot.comwww.vkedco.blogspot.com
• 27. ProblemWrite a PyGame program that enables a sprite object tofollow mouse clicks, i.e., on a mouse click the spritestarts moving to the (x, y) point of the click.www.youtube.com/vkedcowww.youtube.com/vkedco www.vkedco.blogspot.comwww.vkedco.blogspot.com
• 28. Initializationwww.youtube.com/vkedcowww.youtube.com/vkedco www.vkedco.blogspot.comwww.vkedco.blogspot.com## initialize clock and constantsclock = pygame.time.Clock()screen_w = screen.get_width()screen_h = screen.get_height()sprite_half_w = int(sprite_img.get_width()/2.0sprite_half_h = int(sprite_img.get_height()/2.0)## initialize position and destination points & vectorsposition_vec = Vector2D(100, 100)position_point = position_vec.to_point()destination_point = Nonespeed = 100heading_unit_vec = Vector2D()source code is here
• 29. Moving to Mouse Clickwww.youtube.com/vkedcowww.youtube.com/vkedco www.vkedco.blogspot.comwww.vkedco.blogspot.com## capture MOUSEBUTTONDOWNif event.type == MOUSEBUTTONDOWN:## compute the destination point x and y from the mouse clickdestination_x = event.pos[0] - sprite_half_wdestination_y = event.pos[1] - sprite_half_hdestination_point = destination_x, destination_yposition_point = position_vec.to_int_point()## compute the heading unit vectorheading_unit_vec = Vector2D.vector_from_points(position_point, destination_point)heading_unit_vec.normalize()print heading_unit_vec.x, heading_unit_vec.y
• 30. Blit & Recompute Sprites Positionwww.youtube.com/vkedcowww.youtube.com/vkedco www.vkedco.blogspot.comwww.vkedco.blogspot.comscreen.blit(background_img, (0, 0))screen.blit(sprite_img, position_point)time_passed = clock.tick() / 1000.0distance_moved = time_passed * speedmove_vec = heading_unit_vec * distance_movedposition_vec += move_vecposition_point = position_vec.to_int_point()
• 31. ProblemWrite a PyGame program that uses left, right, and uparrow keys to control a sprite that moves downward sothat:– → moves the sprite left;– ← moves the sprite right;– up arrow moves the sprite up.www.youtube.com/vkedcowww.youtube.com/vkedco www.vkedco.blogspot.comwww.vkedco.blogspot.com
• 32. Initializationwww.youtube.com/vkedcowww.youtube.com/vkedco www.vkedco.blogspot.comwww.vkedco.blogspot.comclock = pygame.time.Clock()screen_w = screen.get_width()screen_h = screen.get_height()sprite_half_w = int(sprite_img.get_width()/2.0)sprite_half_h = int(sprite_img.get_height()/2.0)position_vec = Vector2D(100, 0)position_point = position_vec.to_point()destination_point = Nonespeed = 30source code is here
• 33. Get Key Type & Set Directionwww.youtube.com/vkedcowww.youtube.com/vkedco www.vkedco.blogspot.comwww.vkedco.blogspot.com## get pressed keyspressed_keys = pygame.key.get_pressed()direction_vec = Vector2D(0, 1)## set directions x or yif pressed_keys[K_LEFT]:direction_vec.x = -1elif pressed_keys[K_RIGHT]:direction_vec.x = +1if pressed_keys[K_UP]:direction_vec.y = -1elif pressed_keys[K_DOWN]:direction_vec.y = +1## normalize directiondirection_vec.normalize()
• 34. Blit & Recompute Sprites Postionwww.youtube.com/vkedcowww.youtube.com/vkedco www.vkedco.blogspot.comwww.vkedco.blogspot.comscreen.blit(background_img, (0, 0))screen.blit(sprite_img, position_point)time_passed = clock.tick() / 1000.0distance_moved = time_passed * speedposition_vec += direction_vec * distance_movedposition_point = position_vec.to_int_point()
• 35. Reading & References● www.python.org● http://en.wikipedia.org/wiki/Duck_typing● http://www.pythonware.comwww.youtube.com/vkedcowww.youtube.com/vkedco www.vkedco.blogspot.comwww.vkedco.blogspot.com