Главная » Просмотр файлов » Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007

Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (779889), страница 15

Файл №779889 Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (Symbian Books) 15 страницаWiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (779889) страница 152018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 15)

The state of the game ismaintained in three variables:•the string current word, which contains the word to be guessed•the list guessed, which contains the already guessed characters intheir correct positions•the integer num guesses, which contains the current number ofguesses in total.It is convenient to handle guessed as a list instead of a string, sincewe cannot modify individual characters of a string without making a newcopy of it.

In contrast, list items can be modified without any restrictions.Notice how the guessed list is created in function new game():you can use the multiplication operator to make a string of a repeatingcharacter or substring. Once we have created a string containing as manydashes as there are characters in current word, we can convert it toa list of characters with function list(). For printing, the list is laterconverted back to a string with the join() function.The three game state variables are shared among all functions in thegame source code.

In contrast, some variables, such as word in thefunction new game(), are used locally in one function. Python makes adistinction between global and local variables: each variable assignmentis assumed to be local to a function unless it is explicitly declared asglobal. This distinction is explained in the language lesson.Python Language Lesson: local and global variablesBy default, variables that are introduced in functions have only alimited lifetime and visibility. They are visible only in the function inwhich they were created and they disappear when execution returnsfrom the function (see Figure 4.5).SMS GAME SERVER73Figure 4.5 Scope diagramIn Figure 4.5, the variable y is local to the function firstfunction().

You cannot use it outside this function. In contrast,keyword global declares that the variable x belongs to the globalscope, which covers all functions within a module. For this reason, youcan use x also in the function second function(). If a variableis defined outside any function, it belongs automatically to the globalscope, such as the variable z.A good rule of thumb is that if the same variable must be used inmore than one function, it must be declared as global or it must bepassed as a parameter to the functions.Note that you have to assign a value to a variable before it canbe used.

It is meaningless to refer to a variable which does nothave any content. Thus, in the example above you must call thefunction first function() before calling second function()or Python will complain NameError: global variable "x"isnot defined. This error means that no value has been assigned tothe variable yet or it was not declared as global.Example 20: Hangman server (2/3)def find_number(sender):cdb = contacts.open()matches = cdb.find(sender)if matches:num = matches[0].find("mobile_number")if num:return num[0].valueelse:74APPLICATION BUILDING AND SMS INBOXreturn Nonereturn senderdef message_received(msg_id):global guessed, num_guessesbox = inbox.Inbox()msg = box.content(msg_id).lower()sender = box.address(msg_id)box.delete(msg_id)print "Message from %s: %s" % (sender, msg)if current_word == None:returnelif msg.startswith("guess") and len(msg) >= 7:guess = msg[6]for i in range(len(current_word)):if current_word[i] == guess:guessed[i] = guessnum_guesses += 1elif msg.startswith("word"):if msg[5:] == current_word:appuifw.note(u"%s guessed the word!" % sender)guessed = list(current_word)num = find_number(sender)if num:messaging.sms_send(num, u"Status after %d guesses: %s" %\(num_guesses, "".join(guessed)))The second section of the code contains the game logic embedded inthe callback function message received(), which handles incomingSMS messages.

In this function, we first fetch the message contents to thestring msg and convert it to lower case. If the message arrives before anew game has been initialized, the variable current word is still in itsinitial value None and the function returns immediately.We recognize two types of message: the first follows format ‘GUESS x’where ‘x’ is any single character. The second format is ‘WORD someword’where ‘someword’ is the player’s guess for the full word. The functionstartswith() is used to distinguish the two cases.In the first case, we make sure that the message actually containssome character after the word ‘GUESS’: this is true only if the messagelength is at least seven characters. We reveal the guessed characters inthe list guessed by checking in which positions the guessed characterguess occurs in the original word current word.

We use a simplefor loop to go through the individual characters. Nothing is changed ifthe character does not occur in the word at all.In the second case, the player tries to guess the full word, so wecheck whether the word in the message msg[5:] (we omit the substring"WORD") matches the original word current word. Note that here weSMS GAME SERVER75do not need additional checks for the message length, since expressionmsg[5:] returns an empty string if the length is fewer than six characters.At the end of the function message received(), we send a replymessage to inform the guesser about the current status of the game.However, there is a small catch: the Inbox object’s function address(),which should return information about the sender of the message, doesnot always return the sender’s phone number.

If the sender exists in theaddress book of your phone, the name is returned instead of the phonenumber.This might be convenient for an application that shows the senderinformation to the user but, in this case, it makes replying impossibleif the sender’s number exists in the address book.

Luckily, there is aworkaround: we use the contacts module of PyS60 to access thephone’s address book, from which the sender’s actual phone number canbe found. This operation is performed in the function find number. Wedo not explain it in detail here, as the contacts module is introducedin Chapter 7.Example 21: Hangman server (3/3)box = inbox.Inbox()box.bind(message_received)appuifw.app.exit_key_handler = quitappuifw.app.title = u"Hangman Server"appuifw.app.menu = [(u"New Game", new_game),(u"Game Status", game_status)]print "HANGMAN SERVER STARTED"print "Select 'Options -> New Game' to initialize a new game"app_lock = e32.Ao_lock()app_lock.wait()The final section of the game source code is simple: it just constructsthe application user interface using the techniques introduced earlier inthis chapter. Here we also bind the message received() function tothe Inbox, so the incoming messages are captured correctly.Now, let us assume that you initialize a new game and choose ‘code’as the hidden word.

The game proceeds as follows – here the G linesdenote replies by the game server and P the player’s messages.P:G:P:G:P:G:P:GUESS iStatus after 1 guesses: _ _ _ _GUESS oStatus after 2 guesses: _ o _ _GUESS rStatus after 3 guesses: _ o _ _GUESS e76G:P:G:P:G:APPLICATION BUILDING AND SMS INBOXStatus after 4 guesses: _ o _ eGUESS cStatus after 5 guesses: c o _ eWORD codeStatus after 6 guesses: c o d eThe correct guess in the end triggers a dialog that shows the winningplayer’s phone number.

After this, you can either start a new game or closethe application. Now start spreading the word about your revolutionarynew SMS game!4.6 SummaryIn this chapter we showed how to build real S60 applications that includetitles, menus and dialogs. Without this skeleton, building highly functionalapplications would be cumbersome. The application framework camein useful immediately when we started to search and sort your SMSinbox.With the techniques in this chapter, especially in the concludingexample, you can start building various kinds of SMS services.

If youwant some further exercises, see the Wikipedia article about wordgames and use the Hangman example as a basis for implementingother games.In this chapter, you also learned a great deal about the Python language,including functions, callback functions, objects, tuples and the scope ofvariables – in other words, almost everything needed in this book. InChapter 6, two more lessons are presented. If you feel exhausted by theselessons, we can promise that Chapter 5 will not increase your burden.5Sound, Interactive Graphicsand CameraIn this chapter you learn how to program your phone to record and playsounds and to use its built-in text-to-speech engine.

You’ll see how touse the camera to take photos, either manually or fully automatically.The photos can be manipulated in various ways, for example by scaling,rotating or imprinting text on them with the image-processing features ofPyS60.We spice up the chapter with some interactivity: we show how toaccess the keyboard keys in three different ways. To enable you tobuild visually appealing applications, we show how to draw text andbasic graphics, such as squares and circles, to the screen, and use them asbuilding blocks for more complex graphics. We also make some referenceto 3D graphics and, at the end of the chapter, we build an action-packedmobile game.This is useful knowledge for creating your own music players, cameraapplications, games and software that can visualize data in real-time.

Buteven more, you may get some idea of how you could turn your mobilephone into an artistic tool.We hope that this chapter will unleash your creativity!5.1 Sound5.1.1 Text to SpeechLet’s start with a smooth introduction to sound. Most of the latest S60phones have text-to-speech functionality built-in, meaning that the phonecan speak aloud any given string.

Hopefully you can come up with someuseful and amusing application for this feature.78SOUND, INTERACTIVE GRAPHICS AND CAMERAThe module named audio provides access to the text-to-speechengine. The function audio.say() takes a string as its parameter andspeaks it aloud (see Example 22).Example 22: Text to speechimport appuifw, audiotext = appuifw.query(u"Type a word:", "text")audio.say(text)The word you type in the input dialog is spoken aloud by the phone.5.1.2Playing MP3 FilesThe S60 platform supports a wide range of sound formats, such as MP3,WAV, AMR, AAC, MIDI and Real Audio. Example 23 shows how to playa MP3 file.Example 23: MP3 playerimport audiosound = audio.Sound.open("E:\\Sounds\\mysound.mp3")def playMP3():sound.play()print "PlayMP3 returns.."playMP3()You must have an MP3 file named mysound.mp3 on your phone, onthe memory card in this example.

If the file is missing, the example raisesan exception. In Chapter 6, we explain the directory hierarchy in detail,so you know where to load and save files – here we just use a standardlocation for sounds.The call to the function audio.Sound.open() opens the specifiedfile, in this case E:\Sounds\mysound.mp3 and creates an audio.Sound object (which we have called sound). When we call the functionsound.play(), the MP3 file starts playing and plays from start to finish.In Section 5.1.5, we see how to stop the sound at any time when it isbeing played.Example 23 prints out "PlayMP3 returns.." when the sound startsplaying, as the play() function does not wait until the sound has reachedthe end.

This is desirable if you want to leave the sound playing in thebackground and continue doing other things.In some cases, however, you would like the play() function to blockthe program until the sound is played till the end. For example, thisSOUND79behavior might be useful in a game where short sound effects are beingplayed. Example 24 shows how to do that.Example 24: Blocking MP3 playerimport audio, e32snd_lock = e32.Ao_lock()def sound_callback(prev_state, current_state, err):if current_state == audio.EOpen:snd_lock.signal()def playMP3():sound = audio.Sound.open("E:\\Sounds\\mysound.mp3")sound.play(callback = sound_callback)snd_lock.wait()sound.close()print "PlayMP3 returns.."playMP3()Here we use the e32.Ao lock() object to wait for an event tooccur, in a similar way to the applications in Chapter 4.

Характеристики

Тип файла
PDF-файл
Размер
3,61 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Как Вы думаете, сколько людей до Вас делали точно такое же задание? 99% студентов выполняют точно такие же задания, как и их предшественники год назад. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6451
Авторов
на СтудИзбе
305
Средний доход
с одного платного файла
Обучение Подробнее