Главная » Просмотр файлов » John.Wiley.and.Sons.Rapid.Mobile.Enterprise.Development.for.Symbian.OS.An.Introduction.to.OPL.Application.Design.and.Programming.May.2005.eBook-LinG

John.Wiley.and.Sons.Rapid.Mobile.Enterprise.Development.for.Symbian.OS.An.Introduction.to.OPL.Application.Design.and.Programming.May.2005.eBook-LinG (779881), страница 16

Файл №779881 John.Wiley.and.Sons.Rapid.Mobile.Enterprise.Development.for.Symbian.OS.An.Introduction.to.OPL.Application.Design.and.Programming.May.2005.eBook-LinG (Symbian Books) 16 страницаJohn.Wiley.and.Sons.Rapid.Mobile.Enterprise.Development.for.Symbian.OS.An.Introduction.to.OPL.Application.Design.and.Programming.May.2005.eBook-LinG2018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

Thiswill be through another dialog, using dTEXT. You should be able tofollow this easily, but note we’re using some text in the prompt field tohelp with the formatting:dINIT "Conversion Complete"IF ConversionDirection%=1dTEXT "Miles:",FIX$(ConversionValue,3,10),2dTEXT "Km:",FIX$(ConversionReturn,3,10),2ELSEdTEXT "Km:",FIX$(ConversionValue,3,10),2dTEXT "Miles:",FIX$(ConversionReturn,3,10),2ENDIFdBUTTONS "OK",KdBUTTONEnter% OR KdBUTTONNoLabel% OR KdBUTTONPlainKey%LOCK ON :DIALOG :LOCK OFFHere’s a good example of using an IF statement to help construct a dialogbox.

The program flow will only reach one pair of dTEXT commands.One of them shows miles to kilometers, the other shows the reverse.FIX$ is a built-in command to turn a number value into a string soit can be printed. The number is the first argument, then the number ofdecimal places (here limited to three), and finally the maximum length ofthe string (10 in this case). You should look this up, along with NUM$ andGEN$, which perform similar functions.dBUTTONS does exactly what it says, it displays a button, with textinside it, that can be pressed.

When pressed it pretends to be a key,SUMMARY77which is then used to process the DIALOG command. The command list(as usual) has more details on any new command you will come across.We’re using the DIALOG command here without storing the returnedvalue in a variable – because we don’t need to know how (or why) theuser dismisses this particular dialog box.Extending ConvertAs described in this chapter, Convert isn’t quite complete.

For example,the procedures for the other three types of conversion (short distances,weights and temperature) need to be written. There’s also scope to notonly add new conversions in the menu system, but to rework the dialogboxes to perhaps display a choice of more than two units (e.g. miles,kilometers, and furlongs).What you should do now is complete Convert, and perhaps add in afeature or two of your own to ensure that you understand how Convertworks, and how easy it is to (a) adapt it to your own needs and (b) createa quick and easy program that will process some information that isinputted by a user.4.2 SummaryThis chapter took what we learned previously about Event Core, andshowed how to build a program around it. The last two main ways tointeract with the user (dialogs and menus) were explained, and you sawhow you can use the Appendix command list to look up and learn aboutnew commands.The ‘Convert’ program showed you how to use the menus and dialogto create your first useful program, and left you scope to extend it yourself.5Using Graphics in an Othello GameConvert was your first practical OPL program, but it was limited togathering information from the user and presenting new informationback to them using the dialog box system.

Our next program will use agraphical interface to gather and present information.Gaming has advanced computing more than any other field. We’regoing to program the game Othello (the classic board game). During thisyou’ll learn about handling graphics, reading in pen taps, controlling acursor, and creating rules for a computer Othello player.So, in the same way as we started Convert, let’s create a new directoryand a ‘Source’ folder, copy over the Event Core source code, and changethe filename and constants to reflect that this will be "Othello".We need to talk about four areas of OPL programming to put everything together:• how OPL uses graphics• representing an Othello board• using pen taps or a cursor to read in the player’s move• programming rules to make the computer’s move.5.1 Using Graphics in OPLUp until now, we’ve only used dialogs to show textual information.Almost every computer nowadays has the ability to display graphics(small pictures) on the screen.

These can be used in games (e.g. torepresent a ghost in Pac Man), or to make a clean and easy to use ‘UserInterface’ with folders and files to open, just like you see on your SymbianOS phone.We briefly touched on graphics in Chapter 3 when discussing theEvent Core. As you may remember, the two main elements to graphicalwork in OPL are windows and bitmaps.80USING GRAPHICS IN AN OTHELLO GAME5.1.1 WindowsA window is where you will place your graphics.

Consider it the sheet ofpaper you’re going to work with. One of the great things about windowsis that you can have more than one of them, so if your screen is split intotwo views, you would see a window on the left and a window on the right.You can also have hidden windows where you can draw, place graphics,etc.

before showing it to the user all at once – like a finished picture.5.1.2BitmapsYour bitmap is the graphic that you create in a graphics or drawingpackage and include with your program. You can have lots of littlepictures, or one big one and copy over only the part you need onto thepaper (the window).

The first thing you need to do is load the bitmapinto the memory of the phone. Just because it has been copied onto thedisk (e.g. when the user installed your program), that doesn’t mean theprogram can use it directly. Instead, we call:Id%(9)=gLOADBIT(Data$+MbmFiles$,0,3)This will load the bitmap from the filename and path previously workedout in the Event Core code. Although we’ve briefly touched on loadingbitmaps before, let’s recap. The two numbers at the end are very important,and will change depending on the file. The second number (3) tells OPLwhat bitmap to use from the MBM file. MBM files can hold multiplebitmaps (hence .mbm).

The first bitmap is bitmap 0, the second is bitmap1, and so on.The first number determines if you can alter or edit the bitmap withinthe program. Unless you are writing some kind of art package, or needto manipulate the .mbm for some reason, you would normally alwaysleave this as read only, which requires the value 0; to be able to edit thebitmap, you would put a 1 here instead.5.1.3 Closing Graphical ElementsWhenever you finish with a graphical window or bitmap, you shouldclose it. This makes sure that the memory it occupied is reclaimed by thephone, and your program is more efficient. This is done simply with:gCLOSE Id%(Foo%)where Foo% is the array index number required.

A good idea at the endof every program (in PROC Exit:) is to double check all the elementsare closed:USING GRAPHICS IN OPL81Foo%=0DOFoo%=Foo%+1IF Id%(Foo%) : TRAP gCLOSE Id%(Foo%)ENDIFUNTIL Foo%=KMaxWindows%TRAP will, of course, make sure an error is not raised if the graphicalelement isn’t in use.5.1.4 Copying MBMs to WindowsLet’s break down the command that allows you to copy bitmapsto windows:gUSE Id%(1)gCOPY Id%(9),100,0,40,50,3The first command (gUSE) tells OPL what graphical window is to beset as the current window.

When you gCREATE a new window, it isautomatically made the current (or active) window, but it is always bestto use the gUSE command before any graphical operation to make sureyou’ll be working with the window you really want to.Next is the gCOPY command. The first number, Id%(9), tells OPLwhich bitmap is to be copied into the current window. You now specifyan area of that bitmap to copy.

The next two numbers (100,0) say wherethe top left corner is (in pixels), measured from the top left corner of thebitmap overall bitmap. The next two numbers (40,50) specify the widthand height of the portion of the bitmap which is to be copied, as inFigure 5.1. The final number determines how the bitmap is to be copied.Here’s the different ways you can copy images. The checkerboard isFigure 5.1 Width and height portion of bitmap to be copied82USING GRAPHICS IN AN OTHELLO GAMEFigure 5.2 The four graphics modesbeing copied in these examples onto the straight lines, and only the finalnumber is changed to show you what you can do (see Figure 5.2).5.1.5Creating MBMsAs with our previous programs, let’s do a sketch of what we want Othelloto look like (see Figure 5.3).From the above, we’re now able to break it down into windows andbitmaps.

The window part is the easiest. The outside status bars, titles,and CBA bars are something controlled by the runtime and so do notneed dedicated graphical windows. Our main display can be representedby one window.Looking at the bitmaps we’ll need, we find the following are neededfor Othello.Figure 5.3 Othello emptyUSING GRAPHICS IN OPL83The Playing PiecesCunningly, we can store all our balls in one strip, along with an initialblank grid square in the first space, and a template (or ‘mask’) in thesecond space that we can use to effectively punch out a hole in thebackground so the individual balls can be copied over whilst preservingwhat’s already there.

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

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

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

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