Главная » Просмотр файлов » Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007

Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (779890), страница 63

Файл №779890 Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (Symbian Books) 63 страницаWiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (779890) страница 632018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

In order to restore the support, you need to overridethe OpenFileL() function to call CEikDocument’s implementation ofOpenFileL():CFileStore* COandXDocument::OpenFileL(TBool aDoOpen,const TDesC& aFilename, RFs& aFs){return CEikDocument::OpenFileL(aDoOpen, aFilename, aFs);}The Application UI ClassThe application UI class normally forms the core of an application, andthe COandXAppUi class is no exception.

In addition to its standard roleof handling much of the interaction with the user, COandXAppUi ownsthe application’s view, controller and engine instances and supplies thecentral logic for saving and restoring the application’s persistent data.class COandXAppUi : public CAknAppUi{public:COandXAppUi();virtual ∼COandXAppUi();// New functionsvoid ReportWhoseTurn();void ReportWinnerL(TInt aWinner);// From CEikAppUi, for persistent dataTStreamId StoreL(CStreamStore& aStore) const;void RestoreL(const CStreamStore& aStore, TStreamId aStreamId);void ExternalizeL(RWriteStream& aStream) const;void InternalizeL(RReadStream& aStream);private:// From MEikMenuObserver336A SIMPLE GRAPHICAL APPLICATIONvoid DynInitMenuPaneL(TInt aResourceId, CEikMenuPane* aMenuPane);// From CEikAppUivoid HandleCommandL(TInt aCommand);void ConstructL();public:// AppUi owns the engine, controller and application view.COandXEngine* iEngine;COandXController* iController;private:COandXAppView* iAppView;// Set if the application view was added to the control stack.TBool iStacked;};As you can see from the above class definition, part of the userinteraction consists of reporting significant events such as whose turn it isand, at the end of a game, who (if anyone) has won.

In the case of the S60version, the application UI class also handles all aspects of using menucommands, including dynamically setting the menu content according tothe current state of the game. We have more to say about using menuslater in this chapter.The second-phase constructor and the destructor make it clear that theapplication UI class owns the engine, the controller and the view, whichare all created in a leave-safe way:void COandXAppUi::ConstructL(){BaseConstructL(EAknEnableSkin);iEngine = COandXEngine::NewL();iController = COandXController::NewL();iAppView = COandXAppView::NewL(ClientRect());AddToStackL(iAppView); // Enable keypresses to the viewiStacked = ETrue;ReportWhoseTurn();}COandXAppUi::∼COandXAppUi(){if (iStacked){RemoveFromStack(iAppView);}delete iAppView;delete iController;delete iEngine;}It is worth noting that, it is the responsibility of the application UIclass to ensure that the view is added to the control stack, via a call toAddToStackL(), to ensure that it has the opportunity to receive andprocess keypresses.

Since this call can fail, it is necessary to set a flag ifIMPLEMENTING THE GAME ON S60337it succeeds, so that the flag can be tested (in this case, since there is onlyone view, in the destructor) before the view is removed from the controlstack.This application uses two different ways to report events to the user.Reporting whose turn it is to play, which happens between every movein the game, is delegated to the view:void COandXAppUi::ReportWhoseTurn(){iAppView->ShowTurn();}If either player wins, which obviously happens no more than onceper game, the application UI class reports the winner by means ofa UI-specific dialog that displays the appropriate text, read from theapplication’s resource file. The S60 version uses an information note:void COandXAppUi::ReportWinnerL(TInt aWinner){TBuf<MaxInfoNoteTextLen> text;iEikonEnv->ReadResource(text, aWinner==ETileCross? R_OANDX_X_WINS : R_OANDX_O_WINS);CAknInformationNote* infoNote = new (ELeave) CAknInformationNote;infoNote->ExecuteLD(text);}The application’s persistent data is saved and restored via theStoreL() and RestoreL() functions of the application UI class which,you may recall, are called from the application’s document class.TStreamId COandXAppUi::StoreL(CStreamStore& aStore) const{RStoreWriteStream stream;TStreamId id = stream.CreateLC(aStore);stream << *this; // alternatively, use ExternalizeL(stream)stream.CommitL();CleanupStack::PopAndDestroy();return id;}void COandXAppUi::RestoreL(const CStreamStore& aStore,TStreamId aStreamId){RStoreReadStream stream;stream.OpenLC(aStore, aStreamId);stream >> *this; // alternatively use InternalizeL(stream)CleanupStack::PopAndDestroy();}Store() and Restore(), respectively, call the ExternalizeL()and InternalizeL() functions of the application UI class via the338A SIMPLE GRAPHICAL APPLICATION<< and >> operators.

As you can see from the following listing, theapplication UI class itself has no persistent data. The functions dealdirectly with the view’s data, which is simply the ID of the control thatcurrently has focus, and leave the engine and the controller to take careof their own data.void COandXAppUi::ExternalizeL(RWriteStream& aStream) const{iEngine->ExternalizeL(aStream);iController->ExternalizeL(aStream);aStream.WriteInt8L(iAppView->IdOfFocusControl());}void COandXAppUi::InternalizeL(RReadStream& aStream){iEngine->InternalizeL(aStream);iController->InternalizeL(aStream);ReportWhoseTurn();iAppView->MoveFocusTo(aStream.ReadInt8L());}The S60 application UI class is also responsible for handling menucommands, via the DynInitMenuPaneL() and HandleCommandL()functions.

We discuss them – and the differences between the ways theyare handled in S60 and UIQ – later in this chapter.Finally, it is worth pointing out that we provide access to the controllerand engine via global static functions, declared (in oandxappui.h) as:GLREF_C COandXAppUi* OandXAppUi();GLREF_C COandXController& Controller();GLREF_C COandXEngine& Engine();The implementations of these functions are:GLDEF_C COandXAppUi* OandXAppUi(){return static_cast<COandXAppUi*>(CEikonEnv::Static()->AppUi());}GLDEF_C COandXController& Controller(){return *OandXAppUi()->iController;}GLDEF_C COandXEngine& Engine(){return *OandXAppUi()->iEngine;}We have chosen to use global functions in this example becausethey accurately represent the intention that these functions should beIMPLEMENTING THE GAME ON S60339accessible from anywhere in the program.

Furthermore, they do not needverbose source text to call them, which is useful in example code. Wewould not use them in production code, since there is no control of whenand from where they are called. Additionally, calling a global functioninvolves accessing thread-local storage, which is slow compared withother function calls. We could improve the efficiency by implementingthem as static members of a class, but this relies on the availability ofwritable static data and so would not work on all phones.

The bestsolution would be to implement them as normal member functions of,for example, the application UI class and pass a (non-owning) referenceto the constructor of each class that needs to access them. We have notdone that in this example because it would add a significant amount ofincidental complexity to each of the constructors concerned.The Controller ClassThe controller class, whose definition is listed below, is responsible formanaging the state of the game and its logic, including updating the datain the engine class.class COandXController : public CBase{public:static COandXController* NewL();virtual ∼COandXController();enum TState{ENewGame, EPlaying, EFinished};// stateinline TBool IsNewGame() const;// game controlvoid Reset();// stream persistencevoid ExternalizeL(RWriteStream& aStream) const;void InternalizeL(RReadStream& aStream);TBool HitSquareL(TInt aIndex);TBool IsCrossTurn() const;void SwitchTurn();private:void ConstructL();private: // private persistent stateTState iState;TBool iCrossTurn;};In this stand-alone, non-communicating, version, the game state issimply one of the three values ENewGame, EPlaying or EFinished,together with a flag that indicates which player is next to play.

The onlyexternally accessible state-query functions needed are IsCrossTurn(),340A SIMPLE GRAPHICAL APPLICATIONwhich simply returns the value of iCrossTurn, and IsNewGame(),coded as:inline TBool COandXController::IsNewGame() const{ return iState==ENewGame; }The central logic of the controller is contained in the HitSquareL()function:TBool COandXController::HitSquareL(TInt aIndex){if (iState == EFinished){return EFalse;}if (iState == ENewGame){iState = EPlaying;}if (Engine().TryMakeMove(aIndex, IsCrossTurn())){SwitchTurn();TInt winner = Engine().GameWonBy();if (winner){iState = EFinished;OandXAppUi()->ReportWinnerL(winner);}return ETrue;}return EFalse;}This function is called from the application’s board view whenever aplayer attempts to make a move. It disallows the move if the game stateis EFinished; if this is the first move in the game (i.e. the game stateis ENewGame), it sets the state to EPlaying.

If the game is in play, itcalls the TryMakeMove() function of the engine class to check if themove is valid; if so, it records the move and switches whose turn it is. Acall to the GameWonBy() function of the engine class checks if the lastmove resulted in a win by either player and, if it did, the game state isset to EFinished and a call to the ReportWinner() function of theapplication UI class displays the result.In its current form, HitSquareL() does not check for, or report,a drawn game.

If there is no winner, the game continues until all tilescontain a nought or a cross (or a player uses a menu item to start a newgame). The functionality for a drawn game is added in the communicatingversion of the game, described in Chapter 20.The controller is reset for a new game by calling Reset(), whichcancels the current game, clears the board (by calling the Reset()function of the engine class) and sets Noughts as the current player:IMPLEMENTING THE GAME ON S60341void COandXController::Reset(){Engine().Reset();iState = ENewGame;if (IsCrossTurn()){SwitchTurn();}}The SwitchTurn() function simply negates the flag held iniCrossTurn and calls the ReportWhoseTurn() function of the application UI class:void COandXController::SwitchTurn(){iCrossTurn = !iCrossTurn;OandXAppUi()->ReportWhoseTurn();}Persistence of the state of the controller class is handled by theExternalizeL() and InternalizeL() functions, which are calledfrom the application UI class.

Their actions are, respectively, to write andread the controller’s member data to or from the passed stream:void COandXController::ExternalizeL(RWriteStream& aStream) const{aStream.WriteUint8L(iState);aStream.WriteInt8L(iCrossTurn);}void COandXController::InternalizeL(RReadStream& aStream){iState = static_cast<TState>(aStream.ReadUint8L());iCrossTurn = static_cast<TBool>(aStream.ReadInt8L());}The controller is created via a call to its static NewL() function, whichis coded as:COandXController* COandXController::NewL(){COandXController* self=new(ELeave) COandXController;CleanupStack::PushL(self);self->ConstructL();CleanupStack::Pop();return self;}342A SIMPLE GRAPHICAL APPLICATIONThe second-phase constructor is simply:void COandXController::ConstructL(){Reset();}We have coded it in this way to preserve the standard form ofclass construction, as described in Chapter 4. However, since – in thiscase – ConstructL() does not leave, it is worth pointing out that wecould have simplified matters by not defining a ConstructL() functionand doing everything in the NewL() function.The Engine ClassThe engine class, whose class definition is listed below, represents thegame data and contains the functions that operate on that data.

SinceNoughts and Crosses is a simple game, the engine class is correspondinglystraightforward. The class itself has no knowledge of the overall state ofthe game, nor of whose turn it is to make a move. As you saw in theprevious section, both of these are the responsibility of the controller.class COandXEngine : public CBase{public:static COandXEngine* NewL();virtual ∼COandXEngine();void Reset();TInt TileStatus(TInt aIndex) const;TBool TryMakeMove(TInt aIndex, TBool aCrossTurn);TTileState GameWonBy() const;// persistencevoid ExternalizeL(RWriteStream& aStream) const;void InternalizeL(RReadStream& aStream);private:COandXEngine();TInt TileState(TInt aX, TInt aY) const;private:TFixedArray<TTileState, KNumberOfTiles> iTileStates;};The current state of the board is represented by a simple array of tilestates, one for each component tile.

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

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

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

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