Главная » Просмотр файлов » 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), страница 49

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

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

In total, 115 stories were written by theweb players. While illustrating these stories, the street players visited 197distinct GSM cells in midtown Manhattan.A major factor of the success was a smooth and fast-paced userexperience. The player had to think fast and act fast to find a suitabletarget in the urban environment which somehow represented a givennoun.

With one click, the user could accept a noun for illustration. Afterthis, a countdown timer was shown which gave the player 90 seconds toshoot a suitable photo just by clicking the Select key once. The photo wasthen automatically uploaded to the server and the game client returnedto show the list of available nouns. Thus, it was possible to play the gamejust by repeating this two-click, choose-and-shoot cycle.Both the mobile client and the game server were implemented inPython. Starting from a vague game concept and no code at all, it tookapproximately three months to implement the client, the server and ahighly dynamic website by one of the authors. The first prototype ofthe game client was finished in a weekend. The prototype was thenfield-tested and the second, improved prototype was implemented in two254COMBINING ART AND ENGINEERINGweeks based on experiences from the first version. After this, anotherfield-test was organized and the remaining rough edges were polished offto produce the final game client.Without rapid prototyping and field-tests, it would have been impossible to achieve such a smooth user experience.

Given only three months’development time, PyS60 was a perfect tool for the task. Being ableto use the same language on both the client and the server effectivelywas a major benefit as well. As discussed in Section 10.3.3, the gameclient included a mechanism for automatic updating which ensured thatlast-minute bugs could not spoil the experience.When implementing a system that orchestrates 200 mobile phoneclients, a public web application and a large public display in real time, itis crucial that the implementation language does not increase complexityby imposing arbitrary constraints or conventions. With Python, all thepieces came together on the first try – something that anyone with tightschedules can appreciate.An important success factor was that the client looked and felt likea game. Instead of using the standard user interface elements from theappuifw module, we implemented a custom-made set of UI elements,which were used to build the user interface for the game client (seeFigure 11.5).(a)(b)Figure 11.5(c)Manhattan Story Mashup user interfaceThere is nothing particularly difficult in making custom UI elementsin PyS60.

In our game client, the UI elements are drawn in the redrawfunction of the canvas, in a similar way to many examples in Chapter 5.The keyboard event handlers are used to modify some variables that affecthow the element is drawn on the screen, for instance, which line on thelist should be highlighted. This is similar to the UFO Zapper example inSection 5.5.MANHATTAN STORY MASHUP255In Example 113, we show how the list element in Figure 11.5(a), iscreated. Although Example 113 is just an excerpt of a larger program, itshould give you an idea of how to create custom UI elements.Example 113: Manhattan Story Mashup custom list elementdef list_redraw(self):self.img.rectangle(self.area, fill = WHITE)x = self.area[0] + 10y = self.area[1] + LIST_FONT[1]if len(self.list):sel_x = self.area[0]sel_y = self.area[1] + self.idx * (LIST_FONT[1] + 5)self.img.rectangle((sel_x, sel_y,\self.area[2], sel_y + LIST_FONT[1] + 4), fill = YELLOW)else:self.img.text((x, y), u"[empty list]", font = LIST_FONT,\fill = BLUE)for item in self.list[self.first_vis: self.first_vis +self.nof_visible]:txt = u"%s" % self.filter(item)self.img.text((x, y), txt, font = LIST_FONT, fill = BLUE)y += LIST_FONT[1] + 5if self.first_vis + self.nof_visible < len(self.list):x = self.area[2] - 30y = self.area[3] - 30self.img.polygon((x, y, x + 20, y, x + 10, y + 10), fill = BLUE)if self.first_vis > 0:x = self.area[2] - 30y = self.area[1] + 20self.img.polygon((x, y, x + 20, y, x + 10, y - 10), fill = BLUE)First, we clear the list area in white.

Then, we position the coordinatesx and y at the upper left corner of the list area. Depending on whichitem in the list is selected, a yellow rectangle is drawn to depict thehighlighted element. If there are no elements in the list, the text ‘[emptylist]’ is shown.After this, we loop through the visible list elements and draw them onthe screen using the Image.text() function. During each iteration, they coordinate is increased, so each item is drawn on a separate line.If the list contains more items than those which are visible, a smalltriangle is drawn to notify the user that she can go up or down the list.One such triangle is visible in Figure 11.5(c).As you can see, there is no magic in making custom UI elements.Although this approach requires much more work compared to using thestandard UI elements from the appuifw module, it allows you to tailorthe user interface to your particular application. If done well, this can256COMBINING ART AND ENGINEERINGincrease usability and lead to a smoother user experience.

In any case,you are guaranteed to get a distinctive look for your program!11.3MobileArtBlog – Image-Composition ToolThe image-composition tool described in this section allows the user tocompose and draw images, as seen in Figure 11.6. With the camera andnavigation keys, a photo can be placed multiple times on the canvasand its size can be changed. Alternatively the photo can leave colortraces by moving it on the canvas using the navigation keys. At anytime during the composition process, a new photo can be taken. TheFigure 11.6A collage of MobileArtBlog imagesMOBILEARTBLOG – IMAGE-COMPOSITION TOOL257composed image is stored in the gallery of the phone and is also uploadedto the Internet by pressing only one button. The application was createdby one of the authors for his MobileArtBlog concept.

He uses it duringhis travels when he is stimulated by things he sees and experiencesin different cities, places and situations, trying to capture the momentand turn it into a memorable ‘art piece’ (mobile art). Once the imageis composed, it is posted directly over the mobile data network to hisMobileArtBlog website with metadata such as the name of the place andits GPS coordinates. The GPS data are read by way of Bluetooth from anexternal GPS device. A large collection of created images can be seenat www.mobileartblog.org with their originating positions on a Googlemap view.Let’s look at the code to see how the application works. We list themobile-client code, as well as the server-side PHP scripts that demonstratehow Python can easily be used to upload an image file to a URL.Finally we show how PyS60 can be used to insert data into a MySQLdatabase.11.3.1 MobileArt Client CodeMost of the code is similar to the examples in Chapter 5 regarding drawinggraphics primitives and images and controlling graphic movements andthe use of the camera.

The MobileArtBlog is a combination of thoseapplications with some additional functionality.Example 114 presents the first part of the MobileArt client. It showsmainly the key-handling functions and some initialization logic. Example115 presents most of the image-composing logic.Example 114: MobileArtBlog (1/3)import camera, appuifw, e32, graphics, key_codeskeyboard_state={}downs={}def handle_event(event):global downs,keyboard_stateif event['type'] == appuifw.EEventKeyDown:code=event['scancode']if not key_is_down(code):downs[code]=downs.get(code,0)+1keyboard_state[code]=1elif event['type'] == appuifw.EEventKeyUp:keyboard_state[event['scancode']]=0def key_pressed(scancode):global downsif downs.get(scancode,0):downs[scancode]-=1258COMBINING ART AND ENGINEERINGreturn Truereturn Falsedef key_is_down(scancode):global keyboard_statereturn keyboard_state.get(scancode,0)def quit():if appuifw.query(u"Save image","query") == True:background.save('e:\\Images\\art_picture.jpg')appuifw.app.set_exit()def handle_redraw(rect):canvas.blit(background)appuifw.app.body=canvas=appuifw.Canvas(event_callback = handle_event,\redraw_callback = handle_redraw)appuifw.app.screen='full'appuifw.app.exit_key_handler=quitimage_size = canvas.sizebackground = graphics.Image.new(image_size)transfer_pic = graphics.Image.new(image_size)transfer_pic.clear(0xffffff)transfer_pic.save('e:\\transferpic.jpg')picture = graphics.Image.new((50,50))picture.clear(0x000000)x = 100y = 100picture_size = 50running = 1drawing = 0switch = 0e32.ao_yield()The basic concept of composing the art image is that a newly takenpicture is stored as an Image object named picture and is drawn onthe canvas at a certain position on top of the background image object,named transfer pic.

At any time, when the user presses the Selectkey, the background image object merges with the photo, so the photois ‘stuck’ to the background, and is saved. The new background imageobject is then drawn to the canvas and the photo (in form of the pictureimage object) can be freely moved to the next position on the canvasusing the navigation keys and so on. The size of the picture object canbe changed with the 4 and 7 keys.

The entire screen can be filled and thenew art image composed.Example 115: MobileArtBlog (2/3)while running:if drawing == 0:background.clear(0xffffff)background.blit(transfer_pic,scale=1)MOBILEARTBLOG – IMAGE-COMPOSITION TOOL259background.blit(picture,target=(x,y,x+picture_size,y+picture_size),scale=1)handle_redraw(())e32.ao_yield()if switch == 1:picture = camera.take_photo(size = (640,480))if key_is_down(key_codes.EScancodeLeftArrow): x -= 2.0elif key_is_down(key_codes.EScancodeRightArrow): x += 2.0elif key_is_down(key_codes.EScancodeDownArrow): y += 2.0elif key_is_down(key_codes.EScancodeUpArrow): y -= 2.0elif picture_size > 10:if key_is_down(key_codes.EScancode4): picture_size -= 2elif picture_size < 90:if key_is_down(key_codes.EScancode7): picture_size += 2elif key_pressed(key_codes.EScancodeLeftSoftkey): switch = 1elif key_pressed(key_codes.EScancode6): drawing = 1elif key_pressed(key_codes.EScancode9):background.save('e:\\transferpic.jpg')transfer_pic = graphics.Image.open('e:\\transferpic.jpg')drawing = 0elif key_pressed(key_codes.EScancodeSelect):background.save('e:\\transferpic.jpg')transfer_pic = graphics.Image.open('e:\\transferpic.jpg')switch = 0elif key_pressed(key_codes.EScancodeHash):background.save('e:\\transferpic.jpg')transfer_pic = graphics.Image.open('e:\\transferpic.jpg')upload()To implement the photo leaving traces on the canvas, the backgroundimage object, transfer pic, is prevented from being redrawn throughsetting the variable drawing to 0.

When the user presses the hash button,the art image is uploaded to the MobileArtBlog website by the upload()function (Example 116).Example 116 presents the third part of the MobileArt client, whichdeals mainly with the uploading of the art image to the MobileArtBlogwebsite and its MySQL database by two HTTP POST requests:conn1.request("POST", "/upload_to_url.php", chunk, headers)conn2.request("POST", "/insert_artblog.php", params, headers)In the first HTTP POST request, the art image – stored in the variablechunk – is handed over to the PHP script named upload to url.php(see Example 117), which saves the image to the server and returns itsdynamically created filename as a URL back to the PyS60 script to thevariable picture url.In the second HTTP POST request, some data such as location name,image URL and GPS data are first encoded and stored to the variablenamed params and are then pushed into a MySQL database by the PHPscript named insert artblog.php (see Example 118).260COMBINING ART AND ENGINEERINGExample 116: MobileArtBlog (3/3)upload():# text = u'name of location'# lat = GPS data from external device# lon = GPS data from external devicef = open(u'e:\\transferpic.jpg',"rb")chunk = f.read()f.close()headers = {"Content-type": "application/octet-stream","Accept": "text/plain"}conn1 = httplib.HTTPConnection("www.myserver.com")conn1.request("POST", "/upload_to_url.php", chunk, headers)response = conn.getresponse()picture_url = response.read()conn1.close()params = urllib.urlencode({'data': text , \'eggs': picture_url, \'bacon': lat, 'noodle': lon})headers = {"Content-type": \"application/x-www-form-urlencoded",\"Accept": "text/plain"}conn2 = httplib.HTTPConnection("www.myserver.com")conn2.request("POST", "/insert_artblog.php", params, headers)conn2.close()quit()11.3.2 Server-side PHP ScriptsThe server of the MobileArtBlog runs PHP and holds the PHP files inExamples 117 and 118.

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

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

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

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