Главная » Просмотр файлов » Programming Java 2 Micro Edition for Symbian OS 2004

Programming Java 2 Micro Edition for Symbian OS 2004 (779882), страница 59

Файл №779882 Programming Java 2 Micro Edition for Symbian OS 2004 (Symbian Books) 59 страницаProgramming Java 2 Micro Edition for Symbian OS 2004 (779882) страница 592018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

‘‘BoyRacer forSony Ericsson P800/P900’’ or ‘‘BoyRacer for Nokia 6600 or Series 60’’).However, in every HTTP transaction, devices identify themselves in theUser Agent field (e.g. ”Sony Ericsson P900” or ”Nokia 6600”), and thiscan be used by the provisioning server to deliver the correctly packagedapplication. The Composite Capability/Preference Profiles (CC/PP, seewww.w3.org/Mobile/CCPP) UAProf standard for device identification isslowly becoming established and will enable the provisioning server toidentify a phone’s characteristics in more detail.The HTTP transaction includes a URI that points to details of thephone, but can also include a set of differences that identify how theindividual’s phone may have been modified from the factory standard.This potentially enables the provisioning server to dynamically create aJAR file tailored for a specific phone.In general, check out any style guides for target devices and try toconform to the guides.

Even though developers may implement whateverGUI they wish in the low-level APIs, it is easier for the user to use afamiliar interface. So, in deference to the host device, try to emulate thenomenclature of menus and commands as far as possible. Some devicesimpose certain styles to provide the user with a consistent UI. On Nokiaphones, for example, the right soft key is generally used for ‘‘negative’’commands, such as Exit, Back and Cancel, and the left soft key for‘‘positive’’ commands, such as OK, Select and Connect.6.3.1 Low-Level Graphical ContentThe graphical content in gaming applications forms the basis of theuser experience.PORTABILITY ISSUES327Although in a gaming environment the central character sprites canusually remain the same size, this may not be true for the backgroundimages.

The background forms the backdrop to the game ‘‘world’’ andhas to vary in size with the size of the screen. For example, the Nokia6600 display is 176 × 208 pixels, while the Sony Ericsson P900 displayis 208 × 253, reduced to 208 × 173 when the soft keypad is visible.When the UI is initiated, it needs to query the width and heightof the device’s screen using Canvas.getHeight() and Canvas.getWidth(). This gives it enough information to create the backgroundimage. Using TiledLayer we can do one of two things:• we can change the size of the tiles to reflect the screen sizeThis minimizes the impact on the MIDlet, though it puts a burden onthe graphic designer. More importantly, the tiles may now be out ofproportion to the rest of the game world.• we can make the TiledLayer intelligent enough to query the devicefor its screen dimensions on initialization and make the appropriatechanges to the background.The new dimensions of the tiled background depend on the individualtile and screen dimensions.

This is a better approach that allows us toadjust the viewport to reflect the differing screen dimensions, givingthe MIDlet user on a bigger device a larger view of the game world.For example, a maze game would show more of the maze. TheLifeTime MIDlet in Section 7.14 takes this approach, showing moreof the playing field on devices with a larger screen.The images used to construct the game usually have to be tailored tothe screen characteristics of the target phones, and possibly also to thememory and performance characteristics of the phone. They may evenhave to be adapted to cope with operator restrictions on download JARsize. So we need small black and white images on some phones, but can(and should) use larger color images for more capable phones with colorscreens.

It is generally necessary to create a JAR package for each targetdevice, or family of devices.One of the more useful additions to MIDP 2.0 is the Game API. Itallows a Sprite to be created with one graphics file containing all theframes for that character or screen object. In the Demo Racer MIDletin Chapter 5, we supplied a four-frame strip which encapsulated all theframes required for animation.The Sprite subclass is initiated with the PNG file and creates theframes for itself by knowing its own dimensions.

This means that if thesize of the screen changes and the number of frames remains the same,we can change the frame strip rather than making code changes and thesprite will remain in proportion.328MAKING JAVA CODE PORTABLEWe have talked about the need to adjust graphics to suit the device, butthe characteristics of the sprites may also need to be changed. If the Spriteclasses are intelligent enough to determine their own size then all well andgood. They may move differently, however, and this means changing themovement methods.

Collisions between sprites may change. For example,a smaller image may require a smaller collision area. In some cases usingthe whole image for collision detection is too expensive on the processor,so we define a smaller area using defineCollisionRectangle(). Achange in sprite size may mean a related change to this collision area.A change in screen size may also require fewer copies of certainsprites. There may be less room for enemy characters, or the frequencywith which they are to appear on the screen may drop. In the classicSpace Invaders game, for example, smaller screen dimensions may meanfewer invaders attacking the player character.

Do you allow them toshoot as many bullets as on a larger screen? Do you ask the MIDletto work out at initialization time how many can comfortably fit on thescreen without compromising the game difficulty? Should there be feweror smaller barriers to hide behind? Some of these values may have beenhard-coded in the Sprite class members. Is it wiser to create a resourcebundle to supply these values, or perhaps add them to the JAD file andthen ask the MIDlet to query those properties at startup?Use GameActions as far as possible.

These provide a mappingbetween commonly used gaming actions, such as Fire, Up, Down, Left,and Right, and easily selectable buttons on a keypad, such as 2, 8, 4 and6. A keypad with a different layout, such as that of the Siemens SX-1, aMIDP 1.0 phone, may map these actions to different keys.

Even thoughthe Sony Ericsson P900 is mainly a pointer-based device, the jog dialfacility can be used for Up and Down game actions. The game designmay have to be simplified, or it may be possible to make selections suchas game menus into scrollable choice lists.Some devices provide the ability to poll a key to determine its state,which can either be ‘‘depressed’’ or ‘‘released’’. Polling a key to checkwhether it is currently depressed means we can give the user ‘‘rapid fire’’functionality.

Not all devices have this capability, so it is something towatch for.6.3.2Variations in Input MethodsDevelopers need to be aware of the different input methods on differentdevices. At the very least, they need to code defensively to allow forvariations. It may be wise to test for the presence of a pointer device orkeypad entry. If a MIDlet is being ported to the Sony Ericsson P900, forinstance, buttons may need to be put onto the screen, or graphics mayneed to be expanded to make it easier for the user to select an item.

Onkeypad devices, such as the Nokia 6600, the user relies on the joystick tonavigate between items and the selection occurs automatically.PORTABILITY ISSUES329The Sony Ericsson P900 provides a soft keyboard to compensate forthe missing keys. How will this affect game play for the users? Will theystill enjoy the same experience as users on a keypad phone? Insteadof catering for both input methods in a single user interface, should adifferent user interface be developed? For example, instead of listeningfor the left and right keys, the MIDlet could detect the part of the screenon which the stylus has been pressed; if it is to the left or right of the hero,the character could be moved in that direction.

Pressing the stylus on thecharacter itself could invoke the fire mechanism. The jog dial could beused in tandem with the pointer. In other words, instead of emulating thekeypad, try to look for other ways of interpreting user input.Maybe the developers need to ask themselves whether pointer-baseddevices appeal to a different set of users altogether.

Should the gamedesigner be thinking about applications that utilize the features of thedevice, rather than trying to port an unsuitable game? The best businessdecision may be not to port at all, but to create a specially-developedconcept for that device.6.3.3 High-Level User Interface ComponentsUsing high-level UI components such as TextField, List and Form,rather than drawing directly to a Canvas, generally provides a portableUI. These components and their layout are abstracted, with the deviceimplementation handling the display of the components on the screen.The application is not concerned with the capture of user input or withindividual keys, does not define visual appearance, and is unaware ofsuch actions as navigation and scrolling.This works well for information-based applications, as the developer can be more concerned with organizing information into coherentscreens.

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

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

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

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