Главная » Просмотр файлов » Wiley.Games.on.Symbian.OS.A.Handbook.for.Mobile.Development.Apr.2008

Wiley.Games.on.Symbian.OS.A.Handbook.for.Mobile.Development.Apr.2008 (779888), страница 68

Файл №779888 Wiley.Games.on.Symbian.OS.A.Handbook.for.Mobile.Development.Apr.2008 (Symbian Books) 68 страницаWiley.Games.on.Symbian.OS.A.Handbook.for.Mobile.Development.Apr.2008 (779888) страница 682018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

However, there is one major drawback to thetechnology – in order to keep the resulting JAR file below the 30 KB sizelimit, DoJa developers generally have to adopt sub-optimal programmingtechniques (actually they’re appalling, but I’m trying to be nice).To some people, this won’t matter, but I’m really not a fan of this.In general, the design patterns for DoJa applications, whether games orotherwise, tend to consist of a main class that starts the application andthen another class that actually contains it (yes, you read it correctly – allof it in one big class).

My reaction to this is a sound ‘‘Umm . . . no.’’Things are changing though – the latest versions of DoJa allow for moreflexibility, and many of the above restrictions either have been relaxedor do not apply. At the time of writing, the current version is 5.0, whichallows up to 1 MB of memory to be shared between the JAR file and theScratchpad. It also supports GPS, RFID reading (FeliCa3 ), a gesture reader,ToruCa (for transactions using dedicated read/write hardware), 3D sound,matrix maths libraries for 3D graphics, and support for a number of effectsuseful for game development, such as fog, lighting, transforms, textures,and collision detection (in 3D) based on OpenGL ES 1.0.There’s only one catch (there’s always one) – all this is designed for useexclusively in Japan, and it’s really hard to understand javadocs writtenin Japanese (although arguably, most javadocs I’ve seen to date in anylanguage may as well have been in Japanese).

As I mentioned above,2.5oe is the latest DoJa API available for work outside Japan, so we’regoing to have a look at this, and see what it does let you do.10.4DoJa 2.5 OverviewThe easiest way to get started in DoJa development is to download theDoJa 2.50e development kit from the NTT DoCoMo website at www.dojadeveloper.net/downloads.

Make sure that you grab the development kituser guide, release notes, and API docs while you’re there. The installationprocess is straightforward, and the only thing to note here is that you can(and should) install the plug-in for Eclipse (at least version 2.1.1) via thecustom installation option.

Figure 10.1 shows the installation in progress.When you run the emulator, you get a start-up screen where you canopen or create new DoJa projects. The emulator does not include a texteditor, but you can set up an external editor of your choice via the Editmenu. The default is Notepad. Of course, the better option here is to justuse Eclipse in the first place, but we’ll get to that in a bit.3www.nttdocomo.co.jp/english/service/imode/make/content/felica.DOJA 2.5 OVERVIEW303Figure 10.1 Installing the DoJa toolkitFigure 10.2 The javaappliTool interfaceThe javaappliTool (shown in Figure 10.2) allows you to load and runa project and includes an emulator supporting three device skins. Theylook a little strange, and probably the best one is shown in Figure 10.3.I’ve already mentioned that the DoJa profile runs on top of a CLDCJava VM. In i-mode handsets, this is the KVM which can run with only128 KB available memory.

Well good – but you’ll need a little morethan that if you’re going to build a useful GUI application, and the DoJaprofile (also referred to as the i-mode extension API) enables you to dojust that. The version 2.5oe profile consists of the packages shown inTable 10.1.Traditionally, when you’re learning a new technology, it’s aroundabout this point where the author walks you through the canonical HelloWorld! application. I find that approach rather irritating.

With that in304GAMES IN JAPANFigure 10.3 DoJa device skinTable 10.1 i-mode extension APIsPackageDescriptioncom.nttdocomo.langUnsupportedOperation andIllegalState exception classescom.nttdocomo.ioConnection classes and exceptions forOBEX and HTTPcom.nttdocomo.utilTimers, events, encoders, and a phoneutility class for making callscom.nttdocomo.netURL encoder and decodercom.nttdocomo.systemClasses for sending SMS messages andadding new entries to the phonebook(although reading from the phonebook isunsupported)com.nttdocomo.uiCore widget classes for GUI development,sprite classes, and another phone utilityclass exposing vibration and backlightfunctionalitycom.nttdocomo.deviceCamera class allowing pictures and videoto be taken using the onboard cameraDOJA 2.5 OVERVIEW305mind, and given that this is a book on game development, let’s fly in theface of tradition and build a quick little DoJa game called Irritant.Start the javaappliTool via Start->Programs->javaappli DevelopmentKit for DoJa-2.5->javaappliTool for DoJa-2.5, and click ‘New Project’ onthe toolbar.

When prompted, enter the project name and click ‘Create’(shown in Figure 10.4).Figure 10.4Creating a new DoJa projectOpen Windows Explorer and navigate to the project’s directory underyour DoJa installation. On my machine, this is located at c:\jDKDoJa2.5\apps. You should see a new directory named Irritant here, whichholds the project files as described in Table 10.2.Table 10.2 Project directory structureDirectoryDescriptionbinHolds the ADF file (.jam) and JAR executableresLocation for any image, video or audio resources to bedistributed with the applicationspLocation for the Scratchpad filesrcSource files locationNext, choose Project->Make New Source File, call it Irritant andclick ‘Create’.

This will create a basic source file in the src subdirectoryof the project and open it for editing. When you’ve done that, enter inthe code as shown below.import com.nttdocomo.ui.*;import com.nttdocomo.io.*;import java.util.*;public class Irritant extends IApplication implements SoftKeyListener{private final int BOUND_MIN= 1; // input bounds306GAMES IN JAPANprivate final int BOUND_MAXprivate final int BASICALLYprivate final int REALLY= 10;= 0; // levels of irritation= 1;public void start(){MediaImage mi = MediaManager.getImage("resource:///symbian.gif");try{mi.use();}catch(ConnectionException e){}Image image = mi.getImage();int level = BASICALLY;// parse command linetry{String[] args = getArgs();if(args[0] != null && args[0].equals("/i") && (args[1] != null)){level = Integer.parseInt(args[1]);if(level < BASICALLY | | level > REALLY) level = BASICALLY;}}catch(Exception e){level = REALLY;}MainPanel mainPanel = new MainPanel(level, image);mainPanel.setSoftLabel(Frame.SOFT_KEY_1, "END");mainPanel.setSoftLabel(Frame.SOFT_KEY_2, "");mainPanel.setSoftKeyListener(this);Display.setCurrent(mainPanel);}public void softKeyPressed(int no){}// from SoftKeyListenerpublic void softKeyReleased(int no){if(no == Frame.SOFT_KEY_1)IApplication.getCurrentApp().terminate();}class MainPanel extends Panel implements ComponentListener{private int iLevel;private Label iLabel = new Label("Enter a number from "+ BOUND_MIN + " to " + BOUND_MAX + ":");private TextBox iNumBox = new TextBox("",5,1,TextBox.DISPLAY_ANY);private Button iBtnOK = new Button("OK");private String appTitle = "Irritant v1.0";private Random random = new Random();public MainPanel(int irritationLevel, Image image){iLevel = irritationLevel;ImageLabel imageLabel = new ImageLabel(image);add(imageLabel);add(iLabel);add(iNumBox);add(iBtnOK);setComponentListener(this);}public void componentAction(Component source, int type, int param){if(source == iBtnOK){int entry = getEntry();if(entry != -1){int guess = Math.abs(random.nextInt()) % BOUND_MAX;int answer = ask("Was the number " + guess + "?");DOJA 2.5 OVERVIEW307switch(iLevel){case BASICALLY:{showError((answer == Dialog.BUTTON_YES)? "No it wasn't" : "Yes it was");break;}case REALLY:{showError((answer == Dialog.BUTTON_YES)? "Fine - I win." : "You should have picked " + guess);IApplication.getCurrentApp().terminate();break;}} // switchiNumBox.setText("");} //if} // if}private int getEntry(){int entry = -1;String attempt = null;try{attempt = iNumBox.getText().trim();int value = Integer.parseInt(attempt);if(value < BOUND_MIN | | value > BOUND_MAX)throw new IllegalArgumentException();elseentry = value;}catch(Exception e){showError("I said between " + BOUND_MIN + " and " + BOUND_MAX);}return entry;}private int ask(String question){Dialog dialog = new Dialog(Dialog.DIALOG_YESNO, appTitle);dialog.setText(question);return dialog.show();}private void showError(String message){Dialog dialog = new Dialog(Dialog.DIALOG_ERROR, appTitle);dialog.setText(message);dialog.show();}} // private class} // classOnce the code has been entered, save and close the file, and selectBuild from the toolbar.

If the build fails with the error message ‘javac:target release 1.1 conflicts with default source release. . .,’ it means thatyou are not compiling with 1.1 class file compatibility. As a work around,go to the Edit menu and select ‘Use sun.tools.javac.Main.’ Youshould now be able to compile the project without error. Start the gameby clicking ‘Run’ on the toolbar.308GAMES IN JAPANFigure 10.5The Irritant demo applicationThe DoJa emulator, shown in Figure 10.5, can be a bit disconcertingwhen you’re used to working with S60 or UIQ SDKs, and it takes somegetting used to. To enter a number in the text box you need to select thetext control first and then click it using the navigation keys. This thenopens up an edit screen (akin to the Avkon Settings list default screen fortext input) where you enter data and choose ‘OK’ from the softkeys.

Thispopulates the main screen and you can go on from there.Irritant, while contrived (and irritating), actually demonstrates a number of useful techniques for DoJa application development:• how to load and display a local resource such as an image• how to read command line arguments from the ADF file (see below)• how to terminate the application in response to an action• how to set the softkeys (there are only two allowed in DoJa) and listenfor any events fired by them• use of basic widgets to build an event-driven GUI• use of dialogs for user feedback and input.Two other points – first, it’s important for a game to deliver whatit promises (usually inferred from the title) and second, Irritant alsohighlights how easy it can be to frustrate or annoy a user when designing a game (or indeed any software).

Confrontational responses elicitDOJA 2.5 OVERVIEW309emotional reactions and are always a bad idea in game development soare best avoided.As mentioned above, you can set command line arguments via the ADF(although this is limited to 255 bytes only). To do this for Irritant clickthe ADF Configuration button or select the Project->ADF Configurationsmenu item.

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

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

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

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