Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (779889), страница 21
Текст из файла (страница 21)
If the user clicks theSelect key, the laser beam is activated by setting the global variableshoot = True.The game code ends with the event loop. The pad is advanced theamount determined by the constant PAD SPEED, however keeping itwithin the screen limits. After this, status of the UFOs is updated. Then110SOUND, INTERACTIVE GRAPHICS AND CAMERAthe screen is re-drawn and the frame is paused on screen for a sleepfraction of a second.
The e32.ao sleep() function lets any new userevents, such as key presses, be processed during the pause. Finally, thetime counter, timer, is incremented by one and the event loop startsagain from the beginning.This example, besides being a highly addictive game, introduced several useful concepts that can be re-used in many game-like applications.As a further exercise, you might want to add background music and soundeffects to make the game even more engaging.
Creating a high-score listmight not be a bad idea, especially after you have read Chapter 6, whichexplains how to load and save data.5.6 SummaryIn this chapter we first showed how to program applications to play andrecord sounds in various formats. Then, we described three approachesto programming keyboard keys and we outlined how to draw graphicsprimitives to the screen, with other useful features of the graphicsmodule.
We introduced the basic functionalities of the phone’s internalcamera and showed the basic principles of making simple games.We hope you are inspired by the plethora of features that PyS60offers regarding sound, camera and interactive graphics. In this chapter,we introduced each of these features separately, using rather simplistic,but hopefully illustrative examples.
However, in reality, we think thesefeatures are best served as an unprecedented, rich and smooth mixture,preferably combined with other ingredients that are described in thefollowing chapters.6Data HandlingWhen building applications, sooner or later you will come to the pointwhere you want to store some user settings, log data, videos, music,or image files to the phone. This chapter gives you an introduction tohandling data like this. As you will see, PyS60 is quite flexible and easyto use in this regard.Nowadays, data persistence is often handled on the server side.
Thinkof Google GMail, Flickr or the contact list in Skype – all these servicesensure that your information moves with you even though you may accessthe services from various physical devices. Backups, scalability and dataaggregation are easier to handle on the server side than on a single smalldevice. These viewpoints should encourage you to think about storing datain unorthodox ways when programming mobile applications with PyS60.In many cases, sending data to a server is easier than saving it locally.In some cases, saving data locally is the only sensible option.
Youshould be able to save photos, sounds or log events without a networkconnection. You may need a local configuration file to specify how tosetup a network connection in the first place. And since mobile networksmay be unreliable and often have low bandwidth, caching informationlocally can be vital.This is where the lessons of this chapter prove useful.
First, inSection 6.1, we explain where files can be loaded and saved on theS60 platform. We introduce the File object that handles reading andwriting of files. In Section 6.2, we present a slightly different approach thatis based on the phone’s built-in database engine. Then, in Section 6.3,we present a brief overview of current positioning techniques and how touse them in PyS60.To show how to apply these techniques in practice, this chapterincludes two useful applications: in Section 6.3, we build an applicationthat tracks your location based on GSM cell IDs, which demonstratesfile access and a positioning technique. Finally, in Section 6.5, we show112DATA HANDLINGhow you can combine the camera, a sound recorder and some text inputdialogs to create your own vocabulary-learning tool for your next holidayin a foreign country.This chapter also includes two important Python language lessons:one about exception handling and the other about a data structure calleddictionary.6.1 File BasicsFiles on your Symbian device are organized in a hierarchical manner asdrives and directories, similarly to a typical Windows system.
The driveletters refer to the following resources:•C: internal memory of your device•D: operating memory space or RAM (read-only)•E: memory card•Z: fixed memory space or ROM (read-only).You don’t need to worry about drives D: and Z: since they are used bythe operating system only. Starting with Symbian OS v9.0 (3rd Edition ofS60), the directory hierarchy within the drives is strictly defined and onlypartly accessible to your program – see Appendix A for details.Many examples in this book save their files to the memory card, thatis, to the E: drive. If you do not have a memory card, you should changethe drive letter to C:.If your application must save anything to a file, such as private data,photos or sounds, it is polite to place the file in a logical place and try toavoid cluttering arbitrary directories unnecessarily.If a file, typically a photo or a sound, should be visible to thestandard Gallery or to other applications, including the Nokia PC Suitefile manager, the standard C:\Images or C:\Sounds directories, or thecorresponding locations on the E: drive, are appropriate choices.If a file is private to your application and does not have to be visibleto the user or any other application, you should make a private directoryeither under C:\Data or E:\Data.The standard directories E:\Images and E:\Sounds are created bythe built-in camera application and sound recorder, when you save aphoto or a sound to the memory card for the first time.
Thus, thesedirectories are often already available for your application.In contrast, any specific directory for your application has to be createdbefore any files can be saved. The module os provides the functionos.makedirs() that is used to create directories (see Example 40).FILE BASICS113Example 40: Creating a directory for application dataimport os, os.pathPATH = u"C:\\Data\\MyApp"if not os.path.exists(PATH):os.makedirs(PATH)We need to check that the directory does not exist before calling os.makedirs(), as it would throw an exception if the directoryexisted.6.1.1 Handling Error ConditionsEspecially when handling files, Bluetooth and network connections inthe following chapters, exceptions are common.
Often, you can designyour program so that, say, a missing file or an already existing one do notcause a fatal error. Instead, your program could detect the situation andact accordingly.It is not always possible or practical to detect the situation beforehand,as we did with the os.path.exists() function above. However,the program could react to the situation after an exception has occurred.Python provides a mechanism to detect and handle exceptional situationslike this, which is introduced in the language lesson.Python Language Lesson: catching exceptionsIn Python, error conditions are objects, too. Whenever somethingunexpected happens, for example, you try to use a return value of adialog even though it is None, an Exception object is created.
Youcan create exceptions of your own in the following way:raise Exception("I am exceptional")If the exception is not handled by the program, it is shown on theconsole and execution of the program may terminate.However, some exceptions are not really exceptional. For example,we know that trying to play a sound that does not exist will fail. Itmakes sense to prepare for exceptions like this. Exceptions are handledby enclosing suspicious actions between try and except statements,as in the following:114DATA HANDLINGimport appuifwtry:d = appuifw.query(u"Type a word", "text")appuifw.note(u"The word was: "+ word)except:appuifw.note(u"Invalid word", "error")If you type a word in the first dialog, everything works fine. However, if you click ‘Cancel’, an exception is raised since you cannotconcatenate None to a string.
This exception is handled inside theexcept block – in this case, an error dialog is shown.To summarize, if you know that some operations are likely tocause exceptions and you know how to recover from them, place thesuspicious operations between try and except statements and placealternative code in the except block.However, use these statements sparingly, since they may also catchand hide exceptions that are caused by real errors in your program. Thebest approach would be to capture only specific types of exception,instead of all exceptions as we did above. See Python documentationfor more information about this possibility.Note that, because of space constraints, examples in this book do notalways contain the try–except block around critical operations, eventhough using one might make sense. Feel free to make the examples morerobust by adding more exception handlers that take care of possible errorconditions properly.6.1.2File ObjectIn Python, files are read and written through the File object.