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

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

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

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

−2)relative to the co-ordinate system of the object upon which it is ultimatelyrendered (in this case the GameCanvas). When the TiledLayer hasbeen offset by an amount equal to the width of two cells of the backgroundgrid (120 pixels requiring 60 redraw cycles – enough for the pattern torepeat itself), the position of the TiledLayer is re-set to the origin of theco-ordinate system of the rendering object.5.3.2The Puddle ClassA Puddle is an instance of Sprite to facilitate easy collision detection.The Puddle Sprite is created from an image consisting of just oneframe (Figure 5.15).Figure 5.15The image used to build up the puddle Sprite.THE DEMO RACER GAME285package demoracer;import javax.microedition.lcdui.Image;import javax.microedition.lcdui.game.Sprite;public class Puddle extends Sprite {static final int FRAME_COLS = 1;static final int FRAME_WIDTH = 1;private int xInitial;private int yInitial;private int repPeriodpublic Puddle(Image image, int width, int height, int x, int y) {super(image, width, height);setPosition(x, y);xInitial = x;yInitial = y;repPeriod = 2*Background.TILE_WIDTH;}public void tick() {if (repPeriod == 0) {setPosition(xInitial, yInitial);repPeriod = 2*Background.TILE_WIDTH;} else{move(Background.xMove, Background.yMove);}// set visible to false if it is off screenif(getX() + getWidth() <= 0) {//definitely outside Canvas clip areasetVisible(false);} else {if( !isVisible() ) {setVisible(true);}}repPeriod--;}}The tick() method, called by the application clock, moves thepuddle Sprite in step with the background layer, so that the puddlesappear to remain stationary on the race track.

The cycle length of 120(repPeriod = 2*Background.CELL_WIDTH) is half that required tocomplete a lap, so the puddle appears twice per lap. At the end ofthe cycle the puddle is repositioned with setPosition(xInitial,yInitial) (remember setPosition positions the Sprite in theco-ordinate system of the painting object, here a GameCanvas). Whenthe puddle Sprite is definitely outside the clip area displayed by theCanvas, its visibility is set to false.286MIDP 2.0 CASE STUDIESFigure 5.16 The image used to build the Sprite for the start–finish line.5.3.3The StartFinish ClassThis is similar to Puddle, again extending Sprite to facilitate ease ofcollision detection. Once more, the Sprite is created from an imageconsisting of a single frame (Figure 5.16).package demoracer;import javax.microedition.lcdui.Image;import javax.microedition.lcdui.game.Sprite;public class StartFinish extends Sprite {static final int FRAME_COLS = 1;static final int FRAME_WIDTH = 1;private int xInitial;private int yInitial;private int repPeriod;private boolean lapComplete = false;public StartFinish(Image image, int width, int height, int x, int y) {super(image,width,height);this.setPosition(x,y);xInitial = x;yInitial = y;repPeriod = 4*Background.TILE_WIDTH;}public boolean getLapComplete(){return lapComplete;}public void setLapComplete(boolean bln){lapComplete = bln;}public void tick() {if (repPeriod == 0) {setPosition(xInitial, yInitial);repPeriod = 4*Background.TILE_WIDTH;} else{move(Background.xMove, Background.yMove);}// set to invisible if the sprite is off screen.if(getX() + getWidth() <= 0) {//definitely outside Canvas clip areasetVisible(false);} else {if( !isVisible() ) {setVisible(true);}}repPeriod--;}}THE DEMO RACER GAME287A tick() method is called by the application clock to keep the positionof the start finish line in step with the background layer (and thus appear toremain stationary on the race track).

The cycle length of 240 (repPeriod= 4*Background.CELL_WIDTH) defines the length of a lap.5.3.4The Car classpackage demoracer;import javax.microedition.lcdui.Image;import javax.microedition.lcdui.game.Sprite;public class Car extends Sprite {static final int RAW_FRAMES = 4;static final int DRIVE_NORMAL = 0;static final int DRIVE_WET = 1;private int frameOrder[][] = {{0, 1}, {2, 3}};private StartFinish startFinish;private Puddle puddle;private RacerLayerManager layerManager;private int puddleCount;private boolean wet = false;public Car(Image image, int width, int height, int x, int y,RacerLayerManager layerManager) {super(image, width, height);setFrameSequence(frameOrder[DRIVE_NORMAL]);setPosition(x, y);defineCollisionRectangle(getWidth()-1,0,1,getHeight());layerManager = layerManager;puddle = layerManager.getPuddle();startFinish = layerManager.getStartFinish();}public void tick() {checkCollisions();nextFrame();}public void checkCollisions() {if(startFinish.isVisible()) {if (this.collidesWith(startFinish, true)) {startFinish.setLapComplete(true);} else {startFinish.setLapComplete(false);}}if(puddle.isVisible()) {if (!wet && this.collidesWith(puddle, true)) {setFrameSequence(frameOrder[DRIVE_WET]);puddleCount = puddle.getWidth()/2;wet = true;} else if (--puddleCount == 0) {setFrameSequence(frameOrder[DRIVE_NORMAL]);wet = false;}}}}288MIDP 2.0 CASE STUDIESFigure 5.17 The image used to build up the car Sprite.The constructor creates the Sprite from an image consisting of fourframes (Figure 5.17).The top two frames generate the car moving in the dry.

The bottomtwo frames generate the car in the wet (as it moves through the puddle).On each application cycle, the tick() method is invoked to checkfor collisions with the Puddle and the StartFinish sprites. If the caris in collision with the puddle the set of frames used to generate themoving car is switched from the dry to the wet. If the car intersects withthe start–finish line, a flag is set.

Collision detection is on a pixel levelbasis, e.g. collidesWith(puddle, true). If opaque pixels withinthe collision rectangle of the Sprite (by default the dimensions of theSprite unless explicitly set) collide with opaque pixels of the targetSprite then a collision is detected.5.3.5The RacerLayerManager ClassNow that we have introduced the Layers that make up the application,let’s look at the RacerLayerManager class that manages the renderingof the composite scene.package demoracer;import javax.microedition.lcdui.game.*;import javax.microedition.lcdui.*;import java.io.IOException;public class RacerLayerManager extends LayerManager {privateprivateprivateprivateprivateprivateprivateprivateprivateprivateprivateprivateBackground backGround;Car car;Puddle puddle;StartFinish startFinish;int xWindow;int yWindow;RacerGameCanvas gameCanvas;final String LAP_COMPLETE = "Lap Complete";final String PAUSED = "PAUSED";int yOffset = 0;int xOffset = 0;Font font = Font.getFont(Font.FACE_PROPORTIONAL,Font.STYLE_BOLD, Font.SIZE_LARGE);public RacerLayerManager(RacerGameCanvas gameCanvas)throws IOException {// get the GameCanvas and set it to full screen modethis.gameCanvas = gameCanvas;THE DEMO RACER GAME289gameCanvas.setFullScreenMode(true);// create the sprites and then add them to the layer managerbackGround = createBackground();startFinish = createStartFinishSprite();puddle = createPuddleSprite();car = createCarSprite();append(car);append(puddle);append(startFinish);append(backGround);}// move the sprite objects on to the next frame.public void tick() {backGround.tick();car.tick();puddle.tick();startFinish.tick();}public Puddle getPuddle(){return puddle;}public StartFinish getStartFinish(){return startFinish;}// this draws all the Sprites to the displaypublic void draw(Graphics g) {g.setClip(0,0,gameCanvas.getWidth(),gameCanvas.getHeight());paint(g, xOffset, yOffset);drawMessage(g);}private void drawMessage(Graphics g) {int x;int y;g.setFont(font);// draw a "lap complete" message on screen according to the// toggle.if(startFinish.getLapComplete()) {g.setColor(200,0,0);x = gameCanvas.getWidth()/2;y = gameCanvas.getHeight()/2;g.setClip(0,y, gameCanvas.getWidth(), font.getHeight());g.drawString(LAP_COMPLETE,x,y,Graphics.TOP|Graphics.HCENTER);}if(!gameCanvas.isRunning()) {g.setColor(200,0,0);x = gameCanvas.getWidth()/2;y = gameCanvas.getHeight() / 2;g.drawString(PAUSED, x, y, Graphics.TOP | Graphics.HCENTER);}// draw the "Exit" button on the screenx = 0;g.setColor(0,0,0);y = gameCanvas.getHeight()-font.getHeight();g.setClip(0,y, gameCanvas.getWidth(), font.getHeight());g.drawString("Exit",2,y,Graphics.TOP|Graphics.LEFT);290MIDP 2.0 CASE STUDIESy = 20;g.setClip(0,y, gameCanvas.getWidth(), font.getHeight());}private Background createBackground() throws IOException {Image image = Image.createImage("/background.png");return new Background(Background.WIDTH, Background.HEIGHT, image,Background.TILE_WIDTH, Background.TILE_HEIGHT);}private Car createCarSprite() throws IOException {Image image = Image.createImage("/car.png");int width = image.getWidth() / 2;int height = image.getHeight() / 2;int x = gameCanvas.getWidth()/5;int y = backGround.getCellHeight()*4-(int)(height*2);return new Car(image, width, height, x, y, this);}public StartFinish createStartFinishSprite() throws IOException {Image image = Image.createImage("/startfinish.png");int width = image.getWidth() / StartFinish.FRAME_COLS;int height = image.getHeight() / StartFinish.FRAME_WIDTH;int x = backGround.getCellWidth() * 4;int y = backGround.getCellHeight() * 3;return new StartFinish(image, width, height, x, y);}public Puddle createPuddleSprite() throws IOException {Image image = Image.createImage("/puddle.png");int width = image.getWidth() / Puddle.FRAME_COLS;int height = image.getHeight() / Puddle.FRAME_WIDTH;int x = backGround.getCellWidth() * 3;int y = backGround.getCellHeight() * 3;return new Puddle(image, width, height, x, y);}}The RacerLayerManager constructor creates the Backgroundinstance, and instances of the Car, Puddle and StartFinish sprites.These are appended to the RacerLayerManager instance, with theCar Sprite being appended first (lowest z-value) and the Backgroundlast (highest z-value).The tick() method, invoked by the application clock, simply invokesthe corresponding tick() methods of the managed layers.

The othermajor function of the RacerLayerManager is to render the view of thecomposite scene. This is performed in the draw() method:public void draw(Graphics g) {g.setClip(0,0,gameCanvas.getWidth(),gameCanvas.getHeight());paint(g, xOffset, yOffset);drawMessage(g);}THE DEMO RACER GAME291This takes a Graphics object, g (from the RacerGameCanvas) anduses it to set the clip area equal to the dimensions of the Canvas. Torender the composite view, the paint() method of LayerManager isinvoked. Additionally, the drawMessage() method is called to add the‘‘Lap Complete’’ message to the scene when a lap has been completed.The scene is rendered to screen in the RacerGameCanvas class:package demoracer;import javax.microedition.lcdui.game.*;import javax.microedition.lcdui.*;import java.io.IOException;public class RacerGameCanvas extends GameCanvas implements Runnable {private RacerMidlet midlet;private RacerLayerManager layerManager;private Thread thread;private boolean running;private final int SLEEP = 0;public RacerGameCanvas(RacerMidlet midlet) throws IOException {super(false);this.midlet = midlet;layerManager = new RacerLayerManager(this);}public boolean isRunning(){return running;}synchronized void start() {running = true;thread = new Thread(this);thread.start();}public void run() {Graphics graphics = getGraphics();try {while (running) {//repaints at equal time intervalslong start = System.currentTimeMillis();// draw the current frame for each Sprite on screenpaint(graphics);flushGraphics();// set the next frame to be displayed.layerManager.tick();long end = System.currentTimeMillis();long snooze = SLEEP-(end-start);if (snooze > 0) {Thread.sleep(snooze);}}}catch(InterruptedException ie) {System.out.println(ie.toString());}}synchronized void stop() {running = false;}292MIDP 2.0 CASE STUDIESpublic void paint(Graphics g) {layerManager.draw(g);}public void keyPressed(int keyCode) {if(keyCode == -6) {midlet.releaseResource();midlet.notifyDestroyed();}}}This class extends GameCanvas and hence renders the game onto aCanvas using double buffering.

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

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

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

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