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

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

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

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

The class renders the game in a newThread using the run() method. Each cycle renders the graphics andthen calls the tick() method of RacerLayerManager to move onto the next frame of the scene. The way in which the while loop iswritten ensures that the graphics are rendered at equal time intervals sothat the game speed does not depend on how long individual paint(),flushGraphics() or tick() methods take to complete.The implementation of the GameCanvas paint() method simplycalls the draw() method of LayerManager, passing in the Graphicsobject.The RacerGameCanvas also accepts user input via the keyPressed() method of GameCanvas to exit the application.5.3.6The RacerMIDlet Classpackage demoracer;import javax.microedition.lcdui.*;import javax.microedition.midlet.*;import java.io.IOException;public class RacerMidlet extends MIDlet{private RacerGameCanvas gameCanvas;private Display display;private Displayable displayable;public RacerMidlet() {// get the current display context.display = Display.getDisplay(this);}protected void startApp() {// get the Canvas and then set it as the current displaytry {getCanvasDisplay();display.setCurrent(displayable);}catch(Exception e) {Alert alert = new Alert("Error", e.getMessage(), null,THE DEMO RACER GAME293AlertType.ERROR);display.setCurrent(alert);try {Thread.sleep(2000);}catch (InterruptedException ie) {}notifyDestroyed();}}protected void pauseApp() {if(displayable != null) {display.setCurrent(displayable);}releaseResource();}protected void destroyApp(boolean unconditional) {releaseResource();}public void releaseResource() {if(gameCanvas != null) {gameCanvas.stop();}}private void getCanvasDisplay() throws Exception{try{// if there is no canvas then create oneif(gameCanvas == null) {gameCanvas = new RacerGameCanvas(this);}// if the canvas is not running then start itif(!gameCanvas.isRunning()) {gameCanvas.start();}//set the canvas as the "global" displayable objectdisplayable = gameCanvas;}catch(IOException ioe) {throw new Exception("Unable to load image!!");}}}This implements the MIDlet lifecycle methods in such a way asto release resources (notably stopping the RacerGameCanvas clockthread) when the AMS causes the MIDlet to move into the PAUSEDstate.

Similarly, calling startApp will cause the MIDlet to resumewhere it left off if it was previously put into the PAUSED state by a callto pauseApp.The full source code for the Demo Racer MIDlet is available todownload from Symbian’s website at www.symbian.com/books.294MIDP 2.0 CASE STUDIES5.4 The Picture PuzzleThis case study describes a simple game that uses the Mobile MediaAPI to take photographs using a camera phone. The sample MIDlet alsoillustrates using the RMS store to save, load and delete persistent recordsand makes use of a TiledLayer from the Game API.The Picture Puzzle MIDlet is a variation on the familiar Mix Pix nativeapplication that ships on Nokia Series 60 phones.

In this sample MIDletwe use the on-board camera to capture a snapshot that acts as the originalimage. The MIDlet automatically displays this as a scrambled 4 × 4 grid(Figure 5.18). The user has to unscramble the image by re-arranging thetiles to complete the game (Figure 5.19).The MIDlet stores newly captured images in the RMS record store sothat they are available for subsequent games, as shown in Figure 5.20.The Picture Puzzle MIDlet comprises the classes shown in Figure 5.21.Figure 5.18The Picture Puzzle MIDlet running on a Nokia 6600.Figure 5.19 The completed Picture Puzzle game.THE PICTURE PUZZLE295Figure 5.20 Starting a new game: the user can create a new image or load an existingimage from the RMS.javax.microedition.lcdui.Formjavax.microedition.lcdui.TextBoxjavax.microedition.lcdui.CanvasImageNameBoxChoiceFormPuzzleCanvasHintCanvasGameMIDletCaptureCanvasRMSHandlerCapturerApplicationExceptionFigure 5.21 A UML class diagram of the Picture Puzzle MIDlet.5.4.1The GameMIDlet Classpackage picturepuzzle;import javax.microedition.midlet.MIDlet ;import javax.microedition.lcdui.* ;import java.io.* ;296MIDP 2.0 CASE STUDIESpublic class GameMIDlet extends MIDlet {private Display display;private ChoiceForm choiceForm;private CaptureCanvas captureCanvas;private PuzzleCanvas puzzleCanvas;private Capturer capturer;private RMSHandler rms;public GameMIDlet() {rms = new RMSHandler();display = Display.getDisplay(this);choiceForm = new ChoiceForm(this);}public void startApp() {Displayable current = display.getCurrent();try{rms.openRecordStore();}catch(ApplicationException ae){showAlert(ae);}if (current == null) {// first calldisplayChoiceForm();}else {//called after a pausedisplay.setCurrent(current);//player will have been discarded so recreate.try{capturer.createPlayer();}catch(ApplicationException ae) {showAlert(ae);}}}public void pauseApp() {try{rms.closeRecordStore();}catch(ApplicationException ae){}if(capturer != null){capturer.discardPlayer();}}public void destroyApp(boolean unconditional) {try{rms.closeRecordStore();}catch(ApplicationException ae){}if(capturer != null){capturer.discardPlayer();}}public void displayChoiceForm() {try {THE PICTURE PUZZLE297String[] imageNames = loadImageNames();choiceForm.setImageNames(imageNames);}catch(ApplicationException ae) {showAlert(ae);}display.setCurrent(choiceForm);}public void displayHintCanvas(Image image){HintCanvas hintCanvas = new HintCanvas(image);display.setCurrent(hintCanvas);try {Thread.sleep(1500);}catch (InterruptedException ie) {}display.setCurrent(puzzleCanvas);}public void displayCaptureCanvas() {if (captureCanvas == null) {//create CaptureCanvas and associated player (Capturer)captureCanvas = new CaptureCanvas(this);try{capturer = new Capturer(this, captureCanvas);capturer.startPlayer();display.setCurrent(captureCanvas);}catch(final ApplicationException ae){//set to null if unable to create playercaptureCanvas = null;showAlert(ae);}} else {//CaptureCanvas and associated player (Capturer) already existdisplay.setCurrent(captureCanvas);}}public void displayPuzzleCanvas(byte[] imageData) {Image image = Image.createImage(imageData, 0, imageData.length);puzzleCanvas = new PuzzleCanvas(this, image);display.setCurrent(puzzleCanvas);}public void takePhoto(){try {byte[] data = capturer.takeSnapshot();capturer.stopPlayer();ImageNameBox imageNameBox = new ImageNameBox(this, data);display.setCurrent(imageNameBox);}catch(final ApplicationException ae) {showAlert(ae);}}public void loadAndDisplayImage(String imageName){try{byte[] imageData = rms.retrieveImageFromStore(imageName);displayPuzzleCanvas(imageData);}catch(ApplicationException ae){298MIDP 2.0 CASE STUDIESshowAlert(ae);}}public String[] loadImageNames() throws ApplicationException {String[] images = rms.retrieveStoredImageNames();return images;}public void saveImage(String imageName, byte[] data) {try {rms.addImageToStore(imageName, data);}catch(ApplicationException ae) {showAlert(ae);}}public void deleteImage(String imageName) {try{rms.deleteImageFromStore(imageName);}catch(ApplicationException ae){showAlert(ae);}}public void showAlert(final ApplicationException ae){new Thread() {public void run() {Alert alert = new Alert(ae.getExceptionType(),ae.getMessage(), null, AlertType.ERROR);alert.setTimeout(1500);display.setCurrent(alert);}}.start();}public void exit(){try{rms.closeRecordStore();}catch(ApplicationException ae){}if(capturer != null){capturer.discardPlayer();}notifyDestroyed();}}The GameMidlet class extends MIDlet and provides implementations for the MIDlet lifecycle methods.

The startApp() and pauseApp() methods are worth looking at in more detail.When the MIDlet is requested to move into the PAUSED state, thepauseApp() method (listed below) closes the RMS record store andreleases any resources associated with the VideoPlayer used to capturephotos by calling the discardPlayer() method of the Capturerclass. This is important since no other application can access the camerawhile the MIDlet holds the VideoPlayer.THE PICTURE PUZZLE299public void pauseApp() {try{rms.closeRecordStore();}catch(ApplicationException ae){}if(capturer != null){capturer.discardPlayer();}}The startApp() method (listed below) opens the record store andthen determines whether the current invocation is the first call to startApp(), in which case it displays the first application screen by callingdisplayChoiceForm.

If, on the other hand, startApp() has beeninvoked after a previous call to pauseApp(), it sets the display to thelast Displayable that was shown prior to the MIDlet moving intothe PAUSED state. In addition, it recreates the VideoPlayer that wasdiscarded when the MIDlet moved into the PAUSED state.public void startApp() {Displayable current = display.getCurrent();try{rms.openRecordStore();}catch(ApplicationException ae){showAlert(ae);}if (current == null) {// first calldisplayChoiceForm();}else {//called after a pausedisplay.setCurrent(current);//player will have been discarded so recreate.try{capturer.createPlayer();}catch(ApplicationException ae) {showAlert(ae);}}}The GameMIDlet class also acts as the application controller.

It provides a number of callback methods that are invoked by the application’suser interface objects in response to user interaction. This helps to isolatethe UI objects from tasks that are not related to the user interface, suchas accessing the RMS record store. The GameMIDlet class handles theflow of control of the application using the following methods:public void displayChoiceForm() {...}public void displayHintCanvas(Image image){...}300MIDP 2.0 CASE STUDIESpublic void displayCaptureCanvas() {...}public void displayPuzzleCanvas(Image image) {...}public void takePhoto(){...}public void loadAndDisplayImage(String imageName){...}public String[] loadImageNames() throws ApplicationException {...}public void saveImage(String imageName, byte[] data) {...}public void deleteImage(String imageName) {...}public void showAlert(final ApplicationException ae){...}public void exit(){...}5.4.2The ChoiceForm ClassThe first action performed by the GameMIDlet when it starts is to callthe displayChoiceForm() method:public void displayChoiceForm() {try {String[] imageNames = loadImageNames();choiceForm.setImageNames(imageNames);}catch(ApplicationException ae) {showAlert(ae);}display.setCurrent(choiceForm);}This loads the names of any stored images and displays them in aninstance of ChoiceForm.

The user has the option of creating a newimage or using a previous image stored in the RMS (if any exist). Thesource code for ChoiceForm is listed below.package picturepuzzle;import javax.microedition.lcdui.*;import java.io.*;/*** Displays names of images stored in the record store and provides the* user with the option to create a new image.*/public class ChoiceForm extends Form implements CommandListener {privateprivateprivateprivateprivateGameMIDlet midlet;ChoiceGroup cg;Command startCommand;Command deleteCommand;Command exitCommand;THE PICTURE PUZZLE301// Creates the ChoiceForm.

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

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

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

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