Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Kivy - Interactive Applications and Games in Python

You're reading from  Kivy - Interactive Applications and Games in Python

Product type Book
Published in Jun 2015
Publisher
ISBN-13 9781785286926
Pages 206 pages
Edition 1st Edition
Languages
Author (1):
Roberto Ulloa Roberto Ulloa
Profile icon Roberto Ulloa

Table of Contents (13) Chapters

Kivy – Interactive Applications and Games in Python Second Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
1. GUI Basics – Building an Interface 2. Graphics – the Canvas 3. Widget Events – Binding Actions 4. Improving the User Experience 5. Invaders Revenge – an Interactive Multi-touch Game 6. Kivy Player – a TED Video Streamer Index

Chapter 5. Invaders Revenge – an Interactive Multi-touch Game

This chapter introduces a collection of components and strategies to make animated and dynamic applications. Most of them are particularly useful for game development. This chapter is full of examples of how to combine different Kivy elements and teaches strategies to control multiple events happening at the same time. The examples are all integrated in a completely new project, a version of the classic Space Invaders game (Copyright ©1978 Taito Corporation, http://en.wikipedia.org/wiki/Space_Invaders). The following is a list of the main components that we will work on in this chapter:

  • Atlas: A Kivy package that allows us to load images efficiently

  • Sound: Classes that allow sound management

  • Animations: Transitions, time control, events, and operations that can be applied to animate widgets

  • Clock: A class that allows us to schedule events

  • Multi-touch: A strategy that allows us to control different actions according to touches

  • ...

Invaders Revenge – an animated multi-touch game


Invaders Revenge is the name of our Kivy version of Space Invaders©. The following screenshot shows you the game we will build in this chapter:

There are several tags in yellow and cyan in the screenshot (or gray dashed lines in the printed version). They help identify the structure of our game; the game will consist of one shooter (the player), who shoots (shots) at 32 (8x4) invaders who are trying to destroy the shooter with their missiles. The invaders are organized in a fleet (which moves horizontally) and sometimes an individual invader can break out of the grid formation and fly around the screen before going back to its corresponding position (dock) in the fleet.

The cyan (gray in the printed version) line across the screen indicates an internal division of the screen into the enemy area and shooter area. This division is used to distinguish between actions that should occur according to touches that happen in different sections of the...

Atlas – An efficient management of images


When it comes to applications that use many images, it is important to reduce their loading time, especially when they are requested from a remote server.

Note

One strategy to reduce the loading time is to use an Atlas (also known as sprite). An Atlas groups all the application images into one big image, so it reduces the number of necessary requests to the operating system, or online requests.

Here is the image of the Atlas we use for invaders revenge:

Instead of requesting five images for the invaders revenge, we will just request the Atlas image. We will also need an associated json file that tells us the exact coordinates of each unit in the image. The good news is that we don't need to do this manually. Kivy provides a simple command to create both the Atlas image and the json file. Assuming that all the images are in a directory called img, we just need to open a terminal, go to the img directory (that contains the individual images), and run the...

Boom – simple sound effects


Adding sound effects in Kivy is very simple. A Boom instance will produce a sound when it is created, and this will happen every time a shot or missile is fired. Here is the code for boom.py:

52. # File name: boom.py
53. from kivy.uix.image import Image
54. from kivy.core.audio import SoundLoader
55. 
56. class Boom(Image):
57.   sound = SoundLoader.load('boom.wav')
58.   def boom(self, **kwargs):
59.     self.__class__.sound.play()
60.     super(Boom, self).__init__(**kwargs)

Reproducing a sound involves the use of two classes, Sound and SoundLoader (line 54). SoundLoader loads an audio file (.wav) and returns a Sound instance (line 57) that we keep in the sound reference (a static attribute of the Boom class). We play a sound every time a new Boom instance is created.

Ammo – simple animation


This section explains how to animate shots and missiles, which show very similar behavior. They move from their original position to a destination, constantly checking whether a target has been hit. The following is the code for the ammo.py class:

61. # File name: ammo.py
62. from kivy.animation import Animation
63. from kivy.uix.image import Image
64. from boom import Boom
65. 
66. class Ammo(Image):
67.   def shoot(self, tx, ty, target):
68.     self.target = target
69.     self.animation = Animation(x=tx, top=ty)
70.     self.animation.bind(on_start = self.on_start)
71.     self.animation.bind(on_progress = self.on_progress)
72.     self.animation.bind(on_complete = self.on_stop)
73.     self.animation.start(self)
74. 
75.   def on_start(self, instance, value):
76.     self.boom = Boom()
77.     self.boom.center=self.center
78.     self.parent.add_widget(self.boom)
79. 
80.   def on_progress(self, instance, value, progression):
81.     if progression >= .1:
82...

Invader – transitions for animations


The previous section uses the default Animation transition. This is a Linear transition, which means that the Widget instance moves from one point to another in a straight line. Invaders trajectories can be more interesting. For example, there could be accelerations, or changes of direction, as shown by the line in the following screenshot:

The following is the code of invader.py:

93. # File name: invader.py
94. from kivy.core.window import Window
95. from kivy.uix.image import Image
96. from kivy.animation import Animation
97. from random import choice, randint
98. from ammo import Missile
99. 
100. class Invader(Image):
101.   pre_fix = ['in_','out_','in_out_']
102.   functions = ['back','bounce','circ','cubic',
103.     'elastic','expo','quad','quart','quint','sine']
104.   formation = True
105. 
106.   def solo_attack(self):
107.     if self.formation:
108.       self.parent.unbind_invader()
109.       animation = self.trajectory()
110.       animation...

Dock – automatic binding in the Kivy language


You might realize from previous chapters that the Kivy language does more than simply transform its rules to Python instructions. For instance, you might see that when it creates properties, it also binds them.

Note

When we do something common such as pos: self.parent.pos inside a layout, then the property of the parent is bound to its child. The child always moves to the parent position when the parent moves.

This is usually desirable but not all the time. Think about solo_attack of the invader. We need it to break formation and follow a free trajectory on the screen. While this happens, the whole formation of invaders continues moving from right to left and vice versa. This means that the invader will receive two orders at the same time; one from the moving parent and another from the trajectory's Animation.

This means that we need a placeholder (the dock) for each invader. This will secure the space for the invader when it comes back from executing...

Fleet – infinite concatenation of animations


In this section, we will animate the fleet so that it has perpetual movement from right to left and vice versa, as shown by the arrows in the following screenshot:

In order to do this, we will learn how to concatenate one animation just after another one is completed. Indeed, we will create an infinite loop of animations so that the fleet is in perpetual movement.

Tip

We can concatenate two animations with the on_complete event.

The following code, fragment 1 (of 2), of fleet.py shows how to concatenate these events:

155. # File name: fleet.py (Fragment 1)
156. from kivy.uix.gridlayout import GridLayout
157. from kivy.properties import ListProperty
158. from kivy.animation import Animation
159. from kivy.clock import Clock
160. from kivy.core.window import Window
161. from random import randint, random
162. from dock import Dock
163. 
164. class Fleet(GridLayout):
165.   survivors = ListProperty(())
166. 
167.   def __init__(self,  **kwargs):
168....

Scheduling events with the clock


We saw that Animation has a duration parameter that establishes the time in which an animation should take place. A different time-related topic is the scheduling of a particular task at a certain time or during intervals of n seconds. In these cases, we use the Clock class. Let's analyze the following code, fragment 2 (of 2), of fleet.py:

189. # File name: fleet.py (Fragment 2)
190.   def schedule_events(self):
191.     Clock.schedule_interval(self.solo_attack, 2)
192.     Clock.schedule_once(self.shoot,random())
193. 
194.   def solo_attack(self, dt):
195.     if len(self.survivors):
196.       rint = randint(0, len(self.survivors) - 1)
197.       child = self.survivors[rint]
198.       child.invader.solo_attack()
199. 
200.   def shoot(self, dt):
201.     if len(self.survivors):
202.       rint = randint(0,len(self.survivors) - 1)
203.       child = self.survivors[rint]
204.       child.invader.drop_missile()
205.       Clock.schedule_once(self.shoot,random...

Shooter – multi-touch control


Kivy supports multi-touch interactions. This feature is always present but we haven't paid too much attention to it except when we used the Scatter widget in Chapter 4, Improving the User Experience. Additionally, we didn't clarify that the entire screen and GUI components are already capable of multi-touch, and that Kivy handles the events accordingly.

Note

Kivy handles multi-touch actions internally. This means that all the Kivy widgets and components support multi-touch interaction; we don't have to worry about it. Kivy solves all the possible conflicts of ambiguous situations that are common in multi-touch control, for example, touching two buttons at the same time.

That said, it is up to us to control particular implementations. Multi-touch programming introduces logic problems that we need to solve as developers. Nevertheless, Kivy provides the data related to each particular touch so we can work on the logic. The main problem is that we need to constantly...

Invasion – moving the shooter with the keyboard


This section offers a second possibility of how to move the shooter. If you don't have a multi-touch device, you will need to use something else to control the position of the shooter easily while you use the mouse to shoot. The following is the code, fragment 1, (of 2) of main.py:

280. # File name: main.py (Fragment 1)
281. from kivy.app import App
282. from kivy.lang import Builder
283. from kivy.core.window import Window
284. from kivy.uix.floatlayout import FloatLayout
285. from kivy.uix.label import Label
286. from kivy.animation import Animation
287. from kivy.clock import Clock
288. from fleet import Fleet
289. from shooter import Shooter
290. 
291. Builder.load_file('images.kv')
292. 
293. class Invasion(FloatLayout):
294. 
295.   def __init__(self, **kwargs):
296.     super(Invasion, self).__init__(**kwargs)
297.     self._keyboard = Window.request_keyboard(self.close,          self)
298.     self._keyboard.bind(on_key_down=self.press...

Combining animations with '+' and '&'


You already learned that you can add several properties to the same animation so that they are modified together (line 69 of ammo.py).

Note

We can combine animations by using the + and & operators. The + operator is used to create sequenced animations (one after another). The & operator lets us execute two animations at the same time.

The following code is fragment 2 of main.py, and illustrates the use of these two operators:

319. # File name: main.py (Fragment 2)
320.   def end_game(self, message):
321.     label = Label(markup=True, size_hint = (.2, .1), 
322.       pos=(0,self.parent.height/2), text = message)
323.     self.add_widget(label)
324.     self.composed_animation().start(label)
325. 
326.   def composed_animation(self):
327.     animation = Animation (center=self.parent.center)
328.     animation &= Animation (font_size = 72, d=3)
329.     animation += Animation(font_size = 24,y=0,d=2)
330.     return animation
331. 
332. class...

Summary


This chapter covered the whole construction process of an interactive and animated application. You learned how to integrate various Kivy components and you should now be able to comfortably build a 2D animated game.

Let's review all the new classes and components we used in this chapter:

  • Atlas

  • Image: The source property

  • SoundLoader and Sound: The load and play methods, respectively

  • Window: The height and width properties, and the request_keyboard, remove_widget, and add_widget methods

  • Animation: The properties as parameters; d and t parameters; start, stop, and bind methods; on_start, on_progress, and on_complete events; and '+' and '&' operators

  • Touch: ud attribute

  • Clock: schedule_interval and schedule_once methods

  • Keyboard: bind and unbind methods, on_key_down event

The information contained in this chapter presents tools and strategies you can use to develop highly interactive applications. By combining the previous chapters information with this chapter's insights into the...

lock icon The rest of the chapter is locked
You have been reading a chapter from
Kivy - Interactive Applications and Games in Python
Published in: Jun 2015 Publisher: ISBN-13: 9781785286926
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}