summaryrefslogtreecommitdiff
authorchicken <chicken>2004-03-01 20:30:56 (UTC)
committer chicken <chicken>2004-03-01 20:30:56 (UTC)
commit7b0bdb05e4ae29b2643d73e3b8f20a86a86dcccc (patch) (side-by-side diff)
tree0ec283bce345770910a2630e868afcde3d7c3dc9
parent054b3c3e032bdb0a6061a3345487b4ff877eebfd (diff)
downloadopie-7b0bdb05e4ae29b2643d73e3b8f20a86a86dcccc.zip
opie-7b0bdb05e4ae29b2643d73e3b8f20a86a86dcccc.tar.gz
opie-7b0bdb05e4ae29b2643d73e3b8f20a86a86dcccc.tar.bz2
fix includes
Diffstat (more/less context) (ignore whitespace changes)
-rw-r--r--noncore/games/backgammon/backgammon.cpp3
-rw-r--r--noncore/games/backgammon/filedialog.cpp4
-rw-r--r--noncore/games/backgammon/main.cpp1
-rw-r--r--noncore/games/backgammon/moveengine.cpp1
-rw-r--r--noncore/games/backgammon/themedialog.cpp2
-rw-r--r--noncore/games/bounce/game.cpp1
-rw-r--r--noncore/games/bounce/kbounce.cpp4
-rw-r--r--noncore/games/bounce/main.cpp1
-rw-r--r--noncore/games/buzzword/buzzword.cpp1
-rw-r--r--noncore/games/buzzword/main.cpp1
-rw-r--r--noncore/games/fifteen/fifteen.cpp5
-rw-r--r--noncore/games/go/gowidget.cpp4
-rw-r--r--noncore/games/go/main.cpp1
-rw-r--r--noncore/games/kbill/MCursor.cc5
-rw-r--r--noncore/games/kbill/Picture.cc2
-rw-r--r--noncore/games/kbill/UI.cpp3
-rw-r--r--noncore/games/kbill/field.cpp1
-rw-r--r--noncore/games/kbill/inputbox.cpp1
-rw-r--r--noncore/games/kbill/kbill.cpp4
-rw-r--r--noncore/games/kcheckers/kcheckers.cpp1
-rw-r--r--noncore/games/kcheckers/main.cpp2
-rw-r--r--noncore/games/kpacman/board.cpp3
-rw-r--r--noncore/games/kpacman/keys.cpp5
-rw-r--r--noncore/games/kpacman/kpacman.cpp5
-rw-r--r--noncore/games/kpacman/kpacmanwidget.cpp5
-rw-r--r--noncore/games/kpacman/monster.cpp1
-rw-r--r--noncore/games/kpacman/pacman.cpp1
-rw-r--r--noncore/games/kpacman/painter.cpp10
-rw-r--r--noncore/games/kpacman/referee.cpp9
-rw-r--r--noncore/games/kpacman/score.cpp6
-rw-r--r--noncore/games/kpacman/status.cpp2
-rw-r--r--noncore/games/mindbreaker/mindbreaker.cpp4
-rw-r--r--noncore/games/minesweep/main.cpp1
-rw-r--r--noncore/games/minesweep/minefield.cpp4
-rw-r--r--noncore/games/minesweep/minesweep.cpp5
-rw-r--r--noncore/games/oyatzee/oyatzee.cpp6
-rw-r--r--noncore/games/parashoot/base.cpp2
-rw-r--r--noncore/games/parashoot/cannon.cpp1
-rw-r--r--noncore/games/parashoot/helicopter.cpp1
-rw-r--r--noncore/games/parashoot/interface.cpp4
-rw-r--r--noncore/games/parashoot/main.cpp1
-rw-r--r--noncore/games/parashoot/man.cpp1
-rw-r--r--noncore/games/qasteroids/main.cpp1
-rw-r--r--noncore/games/qasteroids/toplevel.cpp2
-rw-r--r--noncore/games/qasteroids/view.cpp3
-rw-r--r--noncore/games/sfcave/helpwindow.cpp2
-rw-r--r--noncore/games/snake/interface.cpp4
-rw-r--r--noncore/games/snake/main.cpp1
-rw-r--r--noncore/games/snake/snake.cpp2
-rw-r--r--noncore/games/solitaire/canvascard.cpp5
-rw-r--r--noncore/games/solitaire/canvascardgame.cpp8
-rw-r--r--noncore/games/solitaire/canvascardwindow.cpp5
-rw-r--r--noncore/games/solitaire/canvasshapes.cpp2
-rw-r--r--noncore/games/solitaire/card.cpp3
-rw-r--r--noncore/games/solitaire/cardpile.cpp2
-rw-r--r--noncore/games/solitaire/chicanecardgame.cpp1
-rw-r--r--noncore/games/solitaire/freecellcardgame.cpp1
-rw-r--r--noncore/games/solitaire/harpcardgame.cpp1
-rw-r--r--noncore/games/solitaire/main.cpp1
-rw-r--r--noncore/games/solitaire/patiencecardgame.cpp1
-rw-r--r--noncore/games/solitaire/teeclubcardgame.cpp1
-rw-r--r--noncore/games/tetrix/main.cpp1
-rw-r--r--noncore/games/tetrix/ohighscoredlg.cpp3
-rw-r--r--noncore/games/tetrix/qtetrix.cpp3
-rw-r--r--noncore/games/tetrix/qtetrixb.cpp2
-rw-r--r--noncore/games/tictac/main.cpp1
-rw-r--r--noncore/games/tictac/tictac.cpp4
-rw-r--r--noncore/games/wordgame/main.cpp1
-rw-r--r--noncore/games/wordgame/wordgame.cpp9
-rw-r--r--noncore/games/zlines/ballpainter.cpp3
-rw-r--r--noncore/games/zlines/field.cpp1
-rw-r--r--noncore/games/zlines/klines.cpp9
-rw-r--r--noncore/games/zlines/linesboard.cpp3
-rw-r--r--noncore/games/zlines/main.cpp1
-rw-r--r--noncore/games/zlines/mwidget.cpp1
-rw-r--r--noncore/games/zsame/StoneWidget.cpp5
-rw-r--r--noncore/games/zsame/ZSameWidget.cpp7
77 files changed, 2 insertions, 223 deletions
diff --git a/noncore/games/backgammon/backgammon.cpp b/noncore/games/backgammon/backgammon.cpp
index e9e5467..51020a0 100644
--- a/noncore/games/backgammon/backgammon.cpp
+++ b/noncore/games/backgammon/backgammon.cpp
@@ -1,974 +1,971 @@
#include "backgammon.h"
#include "aidialog.h"
#include "filedialog.h"
#include "playerdialog.h"
#include "rulesdialog.h"
#include "themedialog.h"
-#include <qdatetime.h>
#include <qfile.h>
#include <qlayout.h>
#include <qmessagebox.h>
-#include <qstring.h>
#include <qtimer.h>
-#include <qmainwindow.h>
#include <qpe/qpeapplication.h>
#include <qpe/config.h>
#include <qmenubar.h>
#include <qpe/resource.h>
#include <stdlib.h>
BackGammon::BackGammon(QWidget* parent, const char* name, WFlags fl)
: QMainWindow(parent, name, fl)
{
if (!name) setName("BackGammon");
setCaption(tr( "Backgammon") );
setIcon( Resource::loadPixmap( "backgammon" ) );
//general counter varaible
int a=0;
//the game engine
move=new MoveEngine();
//load the default theme
Config conf("backgammon");
if(!conf.isValid())
{
qDebug("config file does not exist");
conf.setGroup("general");
conf.writeEntry("theme","default");
conf.setGroup("rules");
conf.writeEntry("move_with_pieces_out",false);
conf.writeEntry("nice_dice",false);
conf.setGroup("display");
conf.writeEntry("small",false);
conf.writeEntry("warning",true);
conf.setGroup("ai");
conf.writeEntry("rescue",6);
conf.writeEntry("eliminate",4);
conf.writeEntry("expose",1);
conf.writeEntry("protect",5);
conf.writeEntry("safe",3);
conf.writeEntry("empty",2);
}
conf.setGroup("general");
theme_name=conf.readEntry("theme","default");
QString theme_file=QPEApplication::qpeDir()+"/backgammon/"+theme_name+".theme";
//the rules
conf.setGroup("rules");
rules.move_with_pieces_out=conf.readBoolEntry("move_with_pieces_out",false);
rules.generous_dice=conf.readBoolEntry("nice_dice",false);
move->setRules(rules);
//get the AI settings
AISettings ai;
conf.setGroup("ai");
ai.rescue=conf.readNumEntry("rescue",6);
ai.eliminate=conf.readNumEntry("eliminate",4);
ai.expose=conf.readNumEntry("expose",1);
ai.protect=conf.readNumEntry("protect",5);
ai.safe=conf.readNumEntry("safe",3);
ai.empty=conf.readNumEntry("empty",2);
move->setAISettings(ai);
//get the theme component names
Config theme(theme_file,Config::File);
if(!theme.isValid())
{
qDebug("theme file does not exist");
theme.setGroup("theme");
theme.writeEntry("board","casino_board_1");
theme.writeEntry("pieces1","casino_pieces_blue");
theme.writeEntry("pieces2","casino_pieces_white");
theme.writeEntry("dice1","casino_dice");
theme.writeEntry("dice2","casino_dice");
theme.writeEntry("table","casino_table_green");
theme.writeEntry("odds","casino_odds");
}
theme.setGroup("theme");
board_name=theme.readEntry("board","casino_board_1");
piecesA_name=theme.readEntry("pieces1","casino_pieces_blue");
piecesB_name=theme.readEntry("pieces2","casino_pieces_white");
diceA_name=theme.readEntry("dice1","casino_dice");
diceB_name=theme.readEntry("dice2","casino_dice");
table_name=theme.readEntry("table","casino_table_green");
odds_name=theme.readEntry("odds","casino_odds");
//the menu
QMenuBar* menuBar = new QMenuBar(this);
QPopupMenu* gamemenu= new QPopupMenu(this);
gamemenu->insertItem(tr( "New" ),this,SLOT(newgame()));
gamemenu->insertSeparator();
gamemenu->insertItem(tr( "Load" ),this,SLOT(loadgame()));
gamemenu->insertItem(tr( "Save" ),this,SLOT(savegame()));
gamemenu->insertSeparator();
gamemenu->insertItem(tr( "Delete" ),this,SLOT(deletegame()));
menuBar->insertItem(tr( "Game" ),gamemenu);
QPopupMenu* thememenu= new QPopupMenu(this);
thememenu->insertItem(tr( "New" ),this,SLOT(newtheme()));
thememenu->insertSeparator();
thememenu->insertItem(tr( "Load"),this,SLOT(loadtheme()));
thememenu->insertItem(tr( "Save" ),this,SLOT(savetheme()));
thememenu->insertSeparator();
thememenu->insertItem(tr( "Default"),this,SLOT(themedefault()));
thememenu->insertItem(tr( "Delete" ),this,SLOT(deletetheme()));
menuBar->insertItem(tr( "Theme" ),thememenu);
QPopupMenu* optionmenu=new QPopupMenu(this);
optionmenu->insertItem(tr( "Player" ),this,SLOT(playerselect()));
optionmenu->insertSeparator();
optionmenu->insertItem(tr( "AI" ),this,SLOT(modify_AI()));
optionmenu->insertItem(tr( "Rules" ),this,SLOT(setrules()));
menuBar->insertItem(tr( "Options"),optionmenu);
QWidget* mainarea=new QWidget(this);
setCentralWidget(mainarea);
//the main area
QBoxLayout* layout=new QBoxLayout(mainarea,QBoxLayout::TopToBottom);
area=new QCanvas(235,235);
boardview=new BackGammonView(area,mainarea);
boardview->setMaximumHeight(240);
layout->addWidget(boardview);
connect(boardview,SIGNAL(mouse(int,int)),this,SLOT(mouse(int,int)));
//status bar
message=new QLabel("<b>Backgammon</b>",mainarea);
message->setAlignment(AlignHCenter);
layout->addWidget(message);
//the marker
marker_current=new QCanvasRectangle(area);
marker_current->setBrush(QColor(0,0,255));
marker_current->setSize(15,5);
marker_current->setZ(1);
for(a=0;a<4;a++)
{
marker_next[a]=new QCanvasRectangle(area);
marker_next[a]->setBrush(QColor(0,255,0));
marker_next[a]->setSize(15,5);
marker_next[a]->setZ(1);
}
connect(move,SIGNAL(done_dice1()),this,SLOT(done_dice1()));
connect(move,SIGNAL(done_dice2()),this,SLOT(done_dice2()));
connect(move,SIGNAL(done_dice3()),this,SLOT(done_dice3()));
connect(move,SIGNAL(done_dice4()),this,SLOT(done_dice4()));
connect(move,SIGNAL(nomove()),this,SLOT(nomove()));
connect(move,SIGNAL(player_finished(int)),this,SLOT(finished(int)));
//the pieces
p1=new CanvasImageItem*[15];
p1_side=new CanvasImageItem*[15];
QImage piece_1_all(Resource::loadImage("backgammon/pieces/"+piecesA_name));
QImage piece_1_front=piece_1_all.copy(0,0,15,15);
QImage piece_1_side=piece_1_all.copy(0,15,15,5);
p2=new CanvasImageItem*[15];
p2_side=new CanvasImageItem*[15];
QImage piece_2_all(Resource::loadImage("backgammon/pieces/"+piecesB_name));
QImage piece_2_front=piece_2_all.copy(0,0,15,15);
QImage piece_2_side=piece_2_all.copy(0,15,15,5);
for(a=0;a<15;a++)
{
p1[a]=new CanvasImageItem(piece_1_front,area);
p1[a]->setSize(15,15);
p1_side[a]=new CanvasImageItem(piece_1_side,area);
p1_side[a]->setSize(15,5);
p2[a]=new CanvasImageItem(piece_2_front,area);
p2[a]->setSize(15,15);
p2_side[a]=new CanvasImageItem(piece_2_side,area);
p2_side[a]->setSize(15,5);
}
draw();
//the dice
QImage dicebgA_all(Resource::loadImage("backgammon/dice/"+diceA_name));
diceA1=new CanvasImageItem*[7];
diceA2=new CanvasImageItem*[7];
QImage dicebgB_all(Resource::loadImage("backgammon/dice/"+diceB_name));
diceB1=new CanvasImageItem*[7];
diceB2=new CanvasImageItem*[7];
QImage oddsbg_all=(Resource::loadImage("backgammon/odds/"+odds_name));
//oddsDice=new CanvasImageItem*[6];
for(a=0;a<7;a++)
{
QImage dicebgA=dicebgA_all.copy(a*25,0,25,25);
diceA1[a]=new CanvasImageItem(dicebgA,area);
diceA1[a]->setX(5);
diceA1[a]->setY(205-2);
diceA1[a]->setZ(1);
diceA1[a]->setSize(25,25);
diceA2[a]=new CanvasImageItem(dicebgA,area);
diceA2[a]->setX(35);
diceA2[a]->setY(205-2);
diceA2[a]->setZ(1);
diceA2[a]->setSize(25,25);
QImage dicebgB=dicebgB_all.copy(a*25,0,25,25);
diceB1[a]=new CanvasImageItem(dicebgB,area);
diceB1[a]->setX(175);
diceB1[a]->setY(205-2);
diceB1[a]->setZ(1);
diceB1[a]->setSize(25,25);
diceB2[a]=new CanvasImageItem(dicebgB,area);
diceB2[a]->setX(205);
diceB2[a]->setY(205-2);
diceB2[a]->setZ(1);
diceB2[a]->setSize(25,25);
/*
if(a<6)
{
QImage oddsbg=oddsbg_all.copy(a*15,0,15,15);
oddsDice[a]=new CanvasImageItem(oddsbg,area);
oddsDice[a]->setX(110);
oddsDice[a]->setY(210-2);
oddsDice[a]->setZ(1);
oddsDice[a]->setSize(15,15);
oddsDice[a]->hide();
}
*/
}
//oddsDice[0]->show();
//set the board
QImage boardbg(Resource::loadImage("backgammon/boards/"+board_name));
board=new CanvasImageItem(boardbg,area);
board->setX(0);
board->setY(0);
board->setZ(0);
board->setSize(235-2,200-2);
board->show();
//the table
QImage tablebg(Resource::loadImage("backgammon/table/"+table_name));
table=new CanvasImageItem(tablebg,area);
table->setX(0);
table->setY(200-2);
table->setZ(0);
table->setSize(235-2,20);
table->show();
//the no move marker
QImage nomovebg(Resource::loadImage("backgammon/no_move"));
nomove_marker=new CanvasImageItem(nomovebg,area);
nomove_marker->setX(0);
nomove_marker->setY(200);
nomove_marker->setZ(2);
nomove_marker->hide();
//default human against computer
player1_auto=false;
player2_auto=true;
//start new game
newgame();
}
BackGammon::~BackGammon()
{
//DESTRUCTOR
}
void BackGammon::newgame()
{
gameFinished=false;
QDateTime now=QDateTime::currentDateTime();
game_name=now.date().toString()+"_"+now.time().toString();
move->reset();
draw();
diceA1_value=7;
diceA2_value=7;
diceA3_value=7;
diceA4_value=7;
diceB1_value=7;
diceB2_value=7;
diceB3_value=7;
diceB4_value=7;
showdice();
player=2;
dice1_played=true;
dice2_played=true;
dice3_played=true;
dice4_played=true;
dice_rolled=false;
setplayer();
area->update();
}
void BackGammon::playerselect()
{
PlayerDialog* playerdialog=new PlayerDialog(this);
playerdialog->setAuto1(player1_auto);
playerdialog->setAuto2(player2_auto);
if(!playerdialog->exec())
return;
player1_auto=playerdialog->getAuto1();
player2_auto=playerdialog->getAuto2();
}
void BackGammon::loadgame()
{
FileDialog* file=new FileDialog(this,"Load Game",".game");
if(!file->exec())
return;
game_name=file->filename();
QString game_file=QPEApplication::qpeDir()+"/backgammon/"+game_name+".game";
Config game(game_file,Config::File);
game.setGroup("dice");
diceA1_value=game.readNumEntry("diceA1_value");
diceA2_value=game.readNumEntry("diceA2_value");
diceA3_value=game.readNumEntry("diceA3_value");
diceA4_value=game.readNumEntry("diceA4_value");
diceB1_value=game.readNumEntry("diceB1_value");
diceB2_value=game.readNumEntry("diceB2_value");
diceB3_value=game.readNumEntry("diceB3_value");
diceB4_value=game.readNumEntry("diceB4_value");
player=game.readNumEntry("player");
dice1_played=game.readBoolEntry("dice1_played");
dice2_played=game.readBoolEntry("dice2_played");
dice3_played=game.readBoolEntry("dice3_played");
dice4_played=game.readBoolEntry("dice4_played");
dice_rolled=game.readBoolEntry("dice_rolled");
player1_auto=game.readBoolEntry("player1_auto");
player2_auto=game.readBoolEntry("player2_auto");
game.setGroup("pieces");
QString label;
LoadSave load;
for(int a=0;a<28;a++)
{
label.setNum(a);
load.pop[a].total = game.readNumEntry(label,0);
}
move->loadGame(load);
setplayer();
showdice();
draw();
area->update();
}
void BackGammon::savegame()
{
QString game_file=QPEApplication::qpeDir()+"/backgammon/"+game_name+".game";
Config game(game_file,Config::File);
game.setGroup("dice");
game.writeEntry("diceA1_value",diceA1_value);
game.writeEntry("diceA2_value",diceA2_value);
game.writeEntry("diceA3_value",diceA3_value);
game.writeEntry("diceA4_value",diceA4_value);
game.writeEntry("diceB1_value",diceB1_value);
game.writeEntry("diceB2_value",diceB3_value);
game.writeEntry("diceB3_value",diceB4_value);
game.writeEntry("diceB4_value",diceB4_value);
game.writeEntry("player",player);
game.writeEntry("dice1_played",dice1_played);
game.writeEntry("dice2_played",dice2_played);
game.writeEntry("dice3_played",dice3_played);
game.writeEntry("dice4_played",dice4_played);
game.writeEntry("dice_rolled",dice_rolled);
game.writeEntry("player1_auto",player1_auto);
game.writeEntry("player2_auto",player2_auto);
game.setGroup("pieces");
QString label;
LoadSave save=move->saveGame();
for(int a=0;a<28;a++)
{
label.setNum(a);
game.writeEntry(label,save.pop[a].total);
}
QMessageBox::information(this,"Backgammon","Game saved","OK");
}
void BackGammon::deletegame()
{
FileDialog* file=new FileDialog(this,"Delete Game",".game");
if(!file->exec())
return;
game_name=file->filename();
QString game_file=QPEApplication::qpeDir()+"/backgammon/"+game_name+".game";
if(!QMessageBox::warning(this,"Backgammon","deleted game\n"+game_name+" ?","OK","Cancel"))
{
QFile(game_file).remove();
}
}
void BackGammon::newtheme()
{
ThemeDialog* theme=new ThemeDialog(this);
ImageNames names;
names.theme=theme_name;
names.board=board_name;
names.pieces1=piecesA_name;
names.pieces2=piecesB_name;
names.dice1=diceA_name;
names.dice2=diceB_name;
names.odds=odds_name;
names.table=table_name;
theme->setCurrent(names);
if(!theme->exec())
return;
names=theme->getNames();
theme_name=names.theme;
board_name=names.board;
piecesA_name=names.pieces1;
piecesB_name=names.pieces2;
diceA_name=names.dice1;
diceB_name=names.dice2;
odds_name=names.odds;
table_name=names.table;
applytheme();
}
void BackGammon::loadtheme()
{
FileDialog* file=new FileDialog(this,"Load Theme",".theme");
if(!file->exec())
return;
theme_name=file->filename();
QString theme_file=QPEApplication::qpeDir()+"/backgammon/"+theme_name+".theme";
Config theme(theme_file,Config::File);
theme.setGroup("theme");
board_name=theme.readEntry("board","board_1");
piecesA_name=theme.readEntry("pieces1","pieces_1");
piecesB_name=theme.readEntry("pieces2","pieces_2");
diceA_name=theme.readEntry("dice1","dice_1");
diceB_name=theme.readEntry("dice2","dice_2");
table_name=theme.readEntry("table","table_1");
odds_name=theme.readEntry("odds","odds_1");
applytheme();
}
void BackGammon::savetheme()
{
if(theme_name=="default")
{
QMessageBox::information(this,"Backgammon","Sorry\nCannot overwrite default.theme","OK");
return;
}
QString theme_file=QPEApplication::qpeDir()+"/backgammon/"+theme_name+".theme";
if(QMessageBox::information(this,"Backgammon","Save Theme\n"+theme_name,"Yes","No"))
return;
Config theme(theme_file,Config::File);
theme.setGroup("theme");
theme.writeEntry("board",board_name);
theme.writeEntry("pieces1",piecesA_name);
theme.writeEntry("pieces2",piecesB_name);
theme.writeEntry("dice1",diceA_name);
theme.writeEntry("dice2",diceB_name);
theme.writeEntry("table",table_name);
theme.writeEntry("odds",odds_name);
}
void BackGammon::themedefault()
{
if(QMessageBox::information(this,"Backgammon","Make Theme\n"+theme_name+"\nthe default theme","Yes","No"))
return;
Config conf("backgammon");
conf.setGroup("general");
conf.writeEntry("theme",theme_name);
}
void BackGammon::deletetheme()
{
FileDialog* file=new FileDialog(this,"Delete Theme",".theme");
if(!file->exec())
return;
theme_name=file->filename();
QString theme_file=QPEApplication::qpeDir()+"/backgammon/"+theme_name+".theme";
if(!QMessageBox::warning(this,tr( "Backgammon" ),tr( "deleted theme %1?").arg(theme_name),tr( "OK" ),tr( "Cancel" )))
{
QFile(theme_file).remove();
}
}
void BackGammon::modify_AI()
{
AI_Dialog* ai_mod=new AI_Dialog(this,tr( "Load Theme" ),".theme");
ai_mod->setAISettings(move->getAISettings());
if(!ai_mod->exec())
return;
//get the AI settings
AISettings ai=ai_mod->getAISettings();
move->setAISettings(ai);
//write new settings to conf file
Config conf("backgammon");
conf.setGroup("ai");
conf.writeEntry("rescue",ai.rescue);
conf.writeEntry("eliminate",ai.eliminate);
conf.writeEntry("expose",ai.expose);
conf.writeEntry("protect",ai.protect);
conf.writeEntry("safe",ai.safe);
conf.writeEntry("empty",ai.empty);
}
void BackGammon::setrules()
{
RulesDialog* rulesdialog=new RulesDialog(this,tr( "Load Theme" ),".theme");
rulesdialog->setRules(rules);
if(!rulesdialog->exec())
return;
rules=rulesdialog->getRules();
Config conf("backgammon");
conf.setGroup("rules");
conf.writeEntry("move_with_pieces_out",rules.move_with_pieces_out);
conf.writeEntry("nice_dice",rules.generous_dice);
move->setRules(rules);
}
void BackGammon::draw()
{
Pieces pieces;
move->position(pieces);
for(int a=0;a<15;a++)
{
if(!pieces.player1[a].side)
{
p1[a]->setX(pieces.player1[a].x);
p1[a]->setY(pieces.player1[a].y);
p1[a]->setZ(pieces.player1[a].z);
p1[a]->show();
p1_side[a]->hide();
}
else
{
p1_side[a]->setX(pieces.player1[a].x);
p1_side[a]->setY(pieces.player1[a].y);
p1_side[a]->setZ(pieces.player1[a].z);
p1_side[a]->show();
p1[a]->hide();
}
if(!pieces.player2[a].side)
{
p2[a]->setX(pieces.player2[a].x);
p2[a]->setY(pieces.player2[a].y);
p2[a]->setZ(pieces.player2[a].z);
p2[a]->show();
p2_side[a]->hide();
}
else
{
p2_side[a]->setX(pieces.player2[a].x);
p2_side[a]->setY(pieces.player2[a].y);
p2_side[a]->setZ(pieces.player2[a].z);
p2_side[a]->show();
p2[a]->hide();
}
}
}
void BackGammon::mouse(int x,int y)
{
if(gameFinished)
{
newgame();
return;
}
if(y<=200) //move pieces
{
if((player==1 && player1_auto) || (player==2 && player2_auto))
return;
Marker marker;
move->boardpressed(x,y,marker);
if(marker.visible_current)
{
marker_current->setX(marker.x_current);
marker_current->setY(marker.y_current);
marker_current->show();
}
else
{
marker_current->hide();
}
for(int a=0;a<4;a++)
{
if(marker.visible_next[a])
{
marker_next[a]->setX(marker.x_next[a]);
marker_next[a]->setY(marker.y_next[a]);
marker_next[a]->show();
}
else
{
marker_next[a]->hide();
}
}
area->update();
}
else //roll dice
{
if(x>=10 && x<=65 && player==1 && !dice_rolled)
{
dice1_played=false;
dice2_played=false;
dice3_played=false;
dice4_played=false;
dice_rolled=true;
srand(QTime::currentTime().msec());
diceA1_value=1+(int) (6.0*rand()/(RAND_MAX+1.0));
diceA2_value=1+(int) (6.0*rand()/(RAND_MAX+1.0));
if(diceA1_value==diceA2_value)
{
diceA3_value=diceA1_value;
diceA4_value=diceA1_value;
}
else
{
diceA3_value=7;
dice3_played=true;
diceA4_value=7;
dice4_played=true;
}
showdice();
area->update();
move->diceroll(1,diceA1_value,diceA2_value,diceA3_value,diceA4_value,player1_auto);
}
else if(x>=160 && x<=225 && player==2 && !dice_rolled)
{
dice1_played=false;
dice2_played=false;
dice3_played=false;
dice4_played=false;
dice_rolled=true;
srand(QTime::currentTime().msec());
diceB1_value=1+(int) (6.0*rand()/(RAND_MAX+1.0));
diceB2_value=1+(int) (6.0*rand()/(RAND_MAX+1.0));
if(diceB1_value==diceB2_value)
{
diceB3_value=diceB1_value;
diceB4_value=diceB1_value;
}
else
{
diceB3_value=7;
dice3_played=true;
diceB4_value=7;
dice4_played=true;
}
showdice();
area->update();
move->diceroll(2,diceB1_value,diceB2_value,diceB3_value,diceB4_value,player2_auto);
}
}
}
void BackGammon::done_dice1()
{
dice1_played=true;
if(player==1)
diceA1_value=7;
else
diceB1_value=7;
setplayer();
showdice();
draw();
area->update();
if(!dice2_played || !dice3_played || !dice4_played)
{
if(player==1)
{
move->diceroll(1,diceA1_value,diceA2_value,diceA3_value,diceA4_value,player1_auto);
}
else
{
move->diceroll(2,diceB1_value,diceB2_value,diceB3_value,diceB4_value,player2_auto);
}
}
}
void BackGammon::done_dice2()
{
dice2_played=true;
if(player==1)
diceA2_value=7;
else
diceB2_value=7;
setplayer();
showdice();
draw();
area->update();
if(!dice1_played || !dice3_played || !dice4_played)
{
if(player==1)
{
move->diceroll(1,diceA1_value,diceA2_value,diceA3_value,diceA4_value,player1_auto);
}
else
{
move->diceroll(2,diceB1_value,diceB2_value,diceB3_value,diceB4_value,player2_auto);
}
}
}
void BackGammon::done_dice3()
{
dice3_played=true;
if(player==1)
diceA3_value=7;
else
diceB3_value=7;
setplayer();
showdice();
draw();
area->update();
if(!dice1_played || !dice2_played || !dice4_played)
{
if(player==1)
{
move->diceroll(1,diceA1_value,diceA2_value,diceA3_value,diceA4_value,player1_auto);
}
else
{
move->diceroll(2,diceB1_value,diceB2_value,diceB3_value,diceB4_value,player2_auto);
}
}
}
void BackGammon::done_dice4()
{
dice4_played=true;
if(player==1)
diceA4_value=7;
else
diceB4_value=7;
setplayer();
showdice();
draw();
area->update();
if(!dice1_played || !dice2_played || !dice3_played)
{
if(player==1)
{
move->diceroll(1,diceA1_value,diceA2_value,diceA3_value,diceA4_value,player1_auto);
}
else
{
move->diceroll(2,diceB1_value,diceB2_value,diceB3_value,diceB4_value,player2_auto);
}
}
}
void BackGammon::nomove()
{
if(player==1)
nomove_marker->setX(0);
else
nomove_marker->setX(170);
nomove_marker->show();
message->setText(tr( "<b>no move</b>" ));
dice1_played=true;
dice2_played=true;
dice3_played=true;
dice4_played=true;
if(player==1)
{
diceA1_value=7;
diceA2_value=7;
diceA3_value=7;
diceA4_value=7;
}
else
{
diceB1_value=7;
diceB2_value=7;
diceB3_value=7;
diceB4_value=7;
}
area->update();
QTimer::singleShot(2000,this,SLOT(nomove2()));
}
void BackGammon::nomove2()
{
nomove_marker->hide();
setplayer();
showdice();
draw();
area->update();
}
void BackGammon::finished(int theplayer)
{
nomove_marker->hide();
if(theplayer==1)
message->setText(tr( "<b>Player 1 wins. Click on board for new game.</b>" ));
else
message->setText(tr( "<b>Player 2 wins. Click on board for new game.</b>" ));
diceA1_value=7;
diceA2_value=7;
diceB1_value=7;
diceB2_value=7;
player=0;
showdice();
draw();
area->update();
gameFinished=true;
}
void BackGammon::showdice()
{
int value_diceA1=diceA1_value-1;
if(diceA1_value==7 && diceA3_value!=7)
value_diceA1=diceA3_value-1;
int value_diceA2=diceA2_value-1;
if(diceA2_value==7 && diceA4_value!=7)
value_diceA2=diceA4_value-1;
int value_diceB1=diceB1_value-1;
if(diceB1_value==7 && diceB3_value!=7)
value_diceB1=diceB3_value-1;
int value_diceB2=diceB2_value-1;
if(diceB2_value==7 && diceB4_value!=7)
value_diceB2=diceB4_value-1;
for(int index=0;index<7;index++)
{
if(value_diceA1==index)
diceA1[index]->show();
else
diceA1[index]->hide();
if(value_diceA2==index)
diceA2[index]->show();
else
diceA2[index]->hide();
if(value_diceB1==index)
diceB1[index]->show();
else
diceB1[index]->hide();
if(value_diceB2==index)
diceB2[index]->show();
else
diceB2[index]->hide();
}
}
void BackGammon::setplayer()
{
if(dice1_played && dice2_played && dice3_played && dice4_played && player==1)
{
message->setText(tr( "<b>P2 turn</b>", "P means player" ));
dice_rolled=false;
player=2;
if(player2_auto)
QTimer::singleShot(2000,this,SLOT(autoroll_dice2()));
}
else if(dice1_played && dice2_played && dice3_played && dice4_played && player==2)
{
message->setText(tr( "<b>P1 turn</b>", "P means player" ));
dice_rolled=false;
player=1;
if(player1_auto)
QTimer::singleShot(2000,this,SLOT(autoroll_dice1()));
}
}
void BackGammon::autoroll_dice1()
{
mouse(20,210);
}
void BackGammon::autoroll_dice2()
{
mouse(170,210);
}
void BackGammon::applytheme()
{
QImage boardbg(Resource::loadImage("backgammon/boards/"+board_name));
board->setImage(boardbg);
QImage tablebg(Resource::loadImage("backgammon/table/"+table_name));
table->setImage(tablebg);
QImage piece_1_all(Resource::loadImage("backgammon/pieces/"+piecesA_name));
QImage piece_1_front=piece_1_all.copy(0,0,15,15);
QImage piece_1_side=piece_1_all.copy(0,15,15,5);
QImage piece_2_all(Resource::loadImage("backgammon/pieces/"+piecesB_name));
QImage piece_2_front=piece_2_all.copy(0,0,15,15);
QImage piece_2_side=piece_2_all.copy(0,15,15,5);
int a=0;
for(a=0;a<15;a++)
{
p1[a]->setImage(piece_1_front);
p1_side[a]->setImage(piece_1_side);
p2[a]->setImage(piece_2_front);
p2_side[a]->setImage(piece_2_side);
}
draw();
QImage dicebgA_all(Resource::loadImage("backgammon/dice/"+diceA_name));
QImage dicebgB_all(Resource::loadImage("backgammon/dice/"+diceB_name));
QImage oddsbg_all=(Resource::loadImage("backgammon/odds/"+odds_name));
for(a=0;a<7;a++)
{
QImage dicebgA=dicebgA_all.copy(a*25,0,25,25);
diceA1[a]->setImage(dicebgA);
diceA2[a]->setImage(dicebgA);
QImage dicebgB=dicebgB_all.copy(a*25,0,25,25);
diceB1[a]->setImage(dicebgB);
diceB2[a]->setImage(dicebgB);
/*
if(a<6)
{
QImage oddsbg=oddsbg_all.copy(a*15,0,15,15);
oddsDice[a]->setImage(oddsbg);
}
*/
}
}
diff --git a/noncore/games/backgammon/filedialog.cpp b/noncore/games/backgammon/filedialog.cpp
index a5e71c9..e0a2914 100644
--- a/noncore/games/backgammon/filedialog.cpp
+++ b/noncore/games/backgammon/filedialog.cpp
@@ -1,65 +1,61 @@
#include "filedialog.h"
#include <qdir.h>
-#include <qfileinfo.h>
-#include <qmessagebox.h>
-#include <qpixmap.h>
-#include <qpushbutton.h>
#include <qpe/qpeapplication.h>
FileDialog::FileDialog(QWidget* parent,QString header,QString extension,const char* name,bool modal,WFlags f)
:QDialog(parent,name,modal,f)
{
setCaption(header);
ext=extension;
dirselector=new QListView(this);
dirselector->setGeometry(1,10,235,200);
dirselector->addColumn("Files");
connect(dirselector,SIGNAL(clicked(QListViewItem*)),this,SLOT(selectorclicked(QListViewItem*)));
getCurrentDir();
file_name="user";
fileinput=new QLineEdit(file_name,this);
fileinput->setGeometry(1,220,235,20);
QPEApplication::showDialog( this );
}
FileDialog::~FileDialog()
{}
void FileDialog::selectorclicked(QListViewItem* entry)
{
if(entry==NULL)
return;
file_name=entry->text(0);
fileinput->setText(file_name);
}
void FileDialog::getCurrentDir()
{
dirselector->clear();
QDir dir(QPEApplication::qpeDir()+"/backgammon");
dir.setFilter(QDir::Files);
QFileInfoListIterator it(*(dir.entryInfoList()));
QFileInfo* fi;
int ext_length=ext.length();
while((fi=it.current())) // go through all file and subdirs
{
QString file=fi->fileName();
if(file.right(ext_length)==ext && file)
{
file=file.left(file.length()-ext_length);
new QListViewItem(dirselector,file);
}
++it;
}
}
QString FileDialog::filename()
{
return file_name;
}
diff --git a/noncore/games/backgammon/main.cpp b/noncore/games/backgammon/main.cpp
index 58ced10..6316040 100644
--- a/noncore/games/backgammon/main.cpp
+++ b/noncore/games/backgammon/main.cpp
@@ -1,8 +1,7 @@
-#include <qpe/qpeapplication.h>
#include "backgammon.h"
#include <opie/oapplicationfactory.h>
OPIE_EXPORT_APP( OApplicationFactory<BackGammon> )
diff --git a/noncore/games/backgammon/moveengine.cpp b/noncore/games/backgammon/moveengine.cpp
index 37b73a6..7de7147 100644
--- a/noncore/games/backgammon/moveengine.cpp
+++ b/noncore/games/backgammon/moveengine.cpp
@@ -1,558 +1,557 @@
#include "moveengine.h"
-#include <qmessagebox.h>
#include <qtimer.h>
#include <stdlib.h>
MoveEngine::MoveEngine()
: QObject()
{
int offset=7;
int a=0; //counter variable
int xfill[]={210,185,170,155,140,125,110,85,70,55,40,25,10,10,25,40,55,70,85,110,125,140,155,170,185,210};
for(a=0;a<26;a++)
{
x_coord[a]=xfill[a];
}
int yfill[]={10,25,40,55,70,10+offset,25+offset,40+offset,55+offset,25,40,55, 25+offset,40+offset,40};
int zfill[]={1,1,1,1,1,2,2,2,2,3,3,3,4,4,5};
for(a=0;a<15;a++)
{
yup_coord[a]=yfill[a];
ylow_coord[a]=185-(yfill[a]);
z_coord[a]=zfill[a];
}
for(a=0;a<5;a++)
{
if(a<3)
{
x_fin1[a]=65+a*15;
x_fin2[a]=155-a*15;
}
y_fin[a]=225-a*5;
}
z_fin=1;
reset();
}
MoveEngine::~MoveEngine()
{}
void MoveEngine::position(Pieces& pieces,bool non_qte)
{
int player1_counter=0;
int player2_counter=0;
//non qte styles are smaller !!
int offset=(non_qte) ? 5 : 0;
for(int a=0;a<28;a++)
{
for(int b=0;b<abs(population[a].total);b++)
{
if(population[a].total>0) //player 1 pieces
{
pieces.player1[player1_counter].x=x_coord[a]-offset;
if(a>=0 && a<13)
{
pieces.player1[player1_counter].y=yup_coord[b]-offset;
pieces.player1[player1_counter].z=z_coord[b];
pieces.player1[player1_counter].side=false;
player1_counter++;
}
else if(a>12 && a<26)
{
pieces.player1[player1_counter].y=ylow_coord[b]-offset;
pieces.player1[player1_counter].z=z_coord[b];
pieces.player1[player1_counter].side=false;
player1_counter++;
}
else if(a==26)
{
if(b<5)
{
pieces.player1[player1_counter].x=x_fin1[0]-offset;
pieces.player1[player1_counter].y=y_fin[b]-offset;
pieces.player1[player1_counter].z=z_fin;
}
else if(b>=5 && b<10)
{
pieces.player1[player1_counter].x=x_fin1[1]-offset;
pieces.player1[player1_counter].y=y_fin[b-5]-offset;
pieces.player1[player1_counter].z=z_fin;
}
else
{
pieces.player1[player1_counter].x=x_fin1[2]-offset;
pieces.player1[player1_counter].y=y_fin[b-10]-offset;
pieces.player1[player1_counter].z=z_fin;
}
pieces.player1[player1_counter].side=true;
player1_counter++;
}
}
else if(population[a].total<0) //player 2 pieces
{
pieces.player2[player2_counter].x=x_coord[a]-offset;
if(a>=0 && a<13)
{
pieces.player2[player2_counter].y=yup_coord[b]-offset;
pieces.player2[player2_counter].z=z_coord[b];
pieces.player2[player2_counter].side=false;
player2_counter++;
}
else if(a>12 && a<26)
{
pieces.player2[player2_counter].y=ylow_coord[b]-offset;
pieces.player2[player2_counter].z=z_coord[b];
pieces.player2[player2_counter].side=false;
player2_counter++;
}
else if(a==27)
{
if(b<5)
{
pieces.player2[player2_counter].x=x_fin2[0]-offset;
pieces.player2[player2_counter].y=y_fin[b]-offset;
pieces.player2[player2_counter].z=z_fin;
}
else if(b>=5 && b<10)
{
pieces.player2[player2_counter].x=x_fin2[1]-offset;
pieces.player2[player2_counter].y=y_fin[b-5]-offset;
pieces.player2[player2_counter].z=z_fin;
}
else
{
pieces.player2[player2_counter].x=x_fin2[2]-offset;
pieces.player2[player2_counter].y=y_fin[b-10]-offset;
pieces.player2[player2_counter].z=z_fin;
}
pieces.player2[player2_counter].side=true;
player2_counter++;
}
}
}
}
}
void MoveEngine::diceroll(const int& newplayer,const int& face1,const int& face2,const int& face3,const int& face4,bool computer)
{
checkstate();
player=newplayer;
otherplayer=(player==1) ? 2 : 1;
dice[0]=face1;
dice[1]=face2;
dice[2]=face3;
dice[3]=face4;
marker_current=-1;
if(getPossibleMoves()==0)
{
emit nomove();
return; // player will be changed
}
if(!computer)
return; //human intervention required
QTimer::singleShot(2000,this,SLOT(automove()));
}
void MoveEngine::automove()
{
//the maximimum possibility
int maxpos=0;
//the position in the moves array
int from=-1;
int to=-1;
//dice1 or dice 2 ??
int index_dice=0;
for(int counter=0;counter<26;counter++)
{
int a=(player==1) ? counter : 25-counter;
for(int b=0;b<4;b++)
{
if(moves[a].weight[b]>maxpos)
{
maxpos=moves[a].weight[b];
from=a;
to=moves[a].to[b];
index_dice=b+1;
}
}
}
move(from,to,index_dice);
}
void MoveEngine::boardpressed(const int& x,const int& y,Marker& marker,bool non_qte)
{
//get the position of the mouse click
bool upper=true;
bool found=false;
int offset=(non_qte) ? 5 : 0;
if(y<=85) // board slots 0 to 12
marker.y_current=0;
else if(y>=105) //board slots 13 to 25
{
marker.y_current=195-2*offset;
upper=false;
}
int index=13; // the clicked board slot
while(index<25 && !found)
{
if(x>=x_coord[index] && x<x_coord[index+1])
{
marker.x_current=x_coord[index];
found=true;
;
}
else
{
index++;
}
}
if(!found)
{
marker.x_current=x_coord[25];
index=25;
}
if(upper)
{
index=25-index;
}
int a=0;
int usedice=-1;
int dice_value=7;
for(a=0;a<4;a++)
{
if(index==marker_next[a] && marker_next[a]!=-1 && dice_value>dice[a])
{
usedice=a;
dice_value=dice[0];
}
}
if(usedice!=-1)
{
move(marker_current,marker_next[usedice],usedice+1);
nomarker(marker);
return;
}
if(dice[0]==7 && dice[1]==7 && dice[2]==7 && dice[3]==7) //no dice rolled
{
nomarker(marker);
return;
}
else if(fieldColor(index)==player)
{
marker.visible_current=true;
marker_current=index;
}
else
{
nomarker(marker);
return;
}
for(a=0;a<4;a++)
{
if(moves[index].weight[a]>0)
{
int nextfield=moves[index].to[a];
marker.x_next[a]=x_coord[nextfield];
marker_next[a]=nextfield;
if(nextfield<13) //upper half
marker.y_next[a]=0;
else //lower half
marker.y_next[a]=195-2*offset;
marker.visible_next[a]=true;
}
else
{
marker.x_next[a]=0;
marker.y_next[a]=0;
marker_next[a]=-1;
marker.visible_next[a]=false;
}
}
return;
}
void MoveEngine::reset()
{
int a=0;
for(a=0;a<28;a++)
{
population[a].total=0;
}
int p1_index[]={1,1,12,12,12,12,12,17,17,17,19,19,19,19,19};
int p2_index[]={24,24,13,13,13,13,13,8,8,8,6,6,6,6,6};
//int p1_index[]={19,20,21,22,22,23,23,18,18,23,24,24,24,24,24};
//int p2_index[]={6,5,4,3,3,2,2,2,2,2,1,7,7,1,1};
for(a=0;a<15;a++)
{
population[p1_index[a]].total++;
population[p2_index[a]].total--;
}
player=0;
dice[0]=7;
dice[1]=7;
dice[2]=7;
dice[3]=7;
marker_current=-1;
marker_next[0]=-1;
marker_next[1]=-1;
marker_next[2]=-1;
marker_next[3]=-1;
//allclear[0]==false;
allclear[1]=false;
allclear[2]=false;
last_piece[1]=0;
last_piece[2]=25;
}
void MoveEngine::loadGame(const LoadSave& load)
{
for(int a=0;a<28;a++)
{
population[a].total=load.pop[a].total;
}
checkstate();
}
LoadSave MoveEngine::saveGame()
{
LoadSave save;
for(int a=0;a<28;a++)
{
save.pop[a].total=population[a].total;
}
return save;
}
AISettings MoveEngine::getAISettings()
{
return ai;
}
void MoveEngine::setAISettings(const AISettings& new_ai)
{
ai=new_ai;
}
void MoveEngine::setRules(Rules rules)
{
move_with_pieces_out=rules.move_with_pieces_out;
nice_dice=rules.generous_dice;
}
int MoveEngine::getPossibleMoves()
{
int homezone[]={0,25,0};
int lastToHomeZone=abs(last_piece[player]-homezone[player]);
for(int field=0;field<26;field++)
{
for(int b=0;b<4;b++)
{
int dice_tmp=dice[b];
if(dice[b]!=7 && dice[b]> lastToHomeZone)
dice_tmp=lastToHomeZone;
int nextfield=(player==1) ? field+dice_tmp : field-dice_tmp;
if(nice_dice)
{
if(player==1 && nextfield>homezone[1])
nextfield=homezone[1];
else if(player==2 && nextfield<homezone[2])
nextfield=homezone[2];
}
moves[field].weight[b]=0;
moves[field].to[b]=nextfield;
int out_of_board[]={-1,0,25};
if(!move_with_pieces_out && field!=out_of_board[player] && pieces_out[player])
{
continue;
}
if(dice[b]!=7 && fieldColor(field)==player ) //player can only move his own pieces
{
if((player==1 && nextfield > homezone[1]) || (player==2 && nextfield < homezone[2]))
{
moves[field].weight[b]=0; //movement would be far out of board
}
else if(nextfield==homezone[player] && !allclear[player])
{
moves[field].weight[b]=0; //can not rescue pieces until all are in the endzone
}
else if(nextfield==homezone[player] && allclear[player])
{
moves[field].weight[b]=ai.rescue; //rescue your pieces : nuff said ;-)
}
else if(fieldColor(nextfield)==otherplayer)
{
if(abs(population[nextfield].total)>1) //can not move to this field
moves[field].weight[b]=0;
else if(abs(population[nextfield].total)==1) //eliminate opponent : very nice
moves[field].weight[b]=ai.eliminate;
}
else if(fieldColor(nextfield)==player) //nextfield already occupied by player
{
if(abs(population[field].total)==2) //expose own piece : not diserable
moves[field].weight[b]=ai.expose;
else if(abs(population[nextfield].total)>1) //own pices already there : safe
moves[field].weight[b]=ai.safe;
else if(abs(population[nextfield].total)==1) //protect own piece : most importatnt
moves[field].weight[b]=ai.protect;
}
else if(population[nextfield].total==0) //nextfield empty
{
if(abs(population[field].total)==2) //expose own piece : not diserable
moves[field].weight[b]=ai.expose;
else
moves[field].weight[b]=ai.empty;
}
else
moves[field].weight[b]=0; //default.
}
else
moves[field].weight[b]=0; //dice already used or field not used by player
}
}
int total=0;
for(int field=0;field<26;field++)
{
total+=moves[field].weight[0]+moves[field].weight[1]+moves[field].weight[2]+moves[field].weight[3];
}
return total;
}
void MoveEngine::move(const int& from, int to, const int& dice)
{
//qDebug("%d moves from %d to %d (%d) with dice %d",player,from,to,to-from,dice);
if(player==1 && to==25)
to=26;
if(player==2 && to==0)
to=27;
//if space is occupied by enemy move pieces to startzone
if(fieldColor(to)==otherplayer)
{
population[to].total=0;
if(otherplayer==1)
population[0].total++;
else
population[25].total--;
}
if(player==1)
{
population[from].total--;
population[to].total++;
}
else //player=2
{
population[from].total++;
population[to].total--;
}
if(dice==1)
emit done_dice1();
else if(dice==2)
emit done_dice2();
else if(dice==3)
emit done_dice3();
else
emit done_dice4();
if(abs(population[26].total)==15)
emit player_finished(1);
if(abs(population[27].total)==15)
emit player_finished(2);
}
void MoveEngine::checkstate()
{
//check if pieces are out
pieces_out[1]=(population[0].total>0) ? true : false;
pieces_out[2]=(population[25].total<0) ? true : false;
//check if all pieces are in the endzones
allclear[1]=true;
allclear[2]=true;
last_piece[1]=25;
bool found_last_piece1=false;
last_piece[2]=0;
for(int a=0;a<26;a++)
{
if(a<19 && population[a].total>0)
allclear[1]=false;
if(a>6 && population[a].total<0)
allclear[2]=false;
if(population[a].total>0 && !found_last_piece1)
{
last_piece[1]=a;
found_last_piece1=true;
}
if(population[a].total<0)
last_piece[2]=a;
}
}
void MoveEngine::nomarker(Marker& marker)
{
marker.visible_current=false;
marker_current=-1;
for(int a=0;a<4;a++)
{
marker.x_next[a]=0;
marker.y_next[a]=0;
marker_next[a]=-1;
marker.visible_next[a]=false;
}
}
int MoveEngine::fieldColor(const int& index) const
{
if(population[index].total>0)
return 1;
else if(population[index].total<0)
return 2;
else
return 0;
}
diff --git a/noncore/games/backgammon/themedialog.cpp b/noncore/games/backgammon/themedialog.cpp
index f342381..afd6a1b 100644
--- a/noncore/games/backgammon/themedialog.cpp
+++ b/noncore/games/backgammon/themedialog.cpp
@@ -1,163 +1,161 @@
#include "themedialog.h"
#include <qdir.h>
-#include <qfileinfo.h>
#include <qlabel.h>
-#include <qpushbutton.h>
#include <qpe/qpeapplication.h>
ThemeDialog::ThemeDialog(QWidget* parent,const char* name,bool modal,WFlags f)
:QDialog(parent,name,modal,f)
{
setCaption("Theme Dialog");
QLabel* labelname=new QLabel("name",this);
labelname->setGeometry(0,5,40,20);
lineName=new QLineEdit("user",this);
lineName->setGeometry(40,5,195,20);
QLabel* labelboard=new QLabel("board",this);
labelboard->setGeometry(0,30,40,20);
boxboard=new QComboBox(this,"");
boxboard->setGeometry(40,30,195,20);
fillBox("boards",boxboard);
QLabel* labelpiecesA=new QLabel("pieces1",this);
labelpiecesA->setGeometry(0,70,40,20);
boxpiecesA=new QComboBox(this);
boxpiecesA->setGeometry(40,70,195,20);
fillBox("pieces",boxpiecesA);
QLabel* labelpiecesB=new QLabel("pieces2",this);
labelpiecesB->setGeometry(0,95,40,20);
boxpiecesB=new QComboBox(this);
boxpiecesB->setGeometry(40,95,195,20);
fillBox("pieces",boxpiecesB);
QLabel* labeldiceA=new QLabel("dice1",this);
labeldiceA->setGeometry(0,135,40,20);
boxdiceA=new QComboBox(this);
boxdiceA->setGeometry(40,135,195,20);
fillBox("dice",boxdiceA);
QLabel* labeldiceB=new QLabel("dice2",this);
labeldiceB->setGeometry(0,160,40,20);
boxdiceB=new QComboBox(this);
boxdiceB->setGeometry(40,160,195,20);
fillBox("dice",boxdiceB);
QLabel* labelodds=new QLabel("odds",this);
labelodds->setGeometry(0,200,40,20);
boxodds=new QComboBox(this);
boxodds->setGeometry(40,200,195,20);
fillBox("odds",boxodds);
boxodds->setEnabled(false);
QLabel* labeltable=new QLabel("table",this);
labeltable->setGeometry(0,225,40,20);
boxtable=new QComboBox(this);
boxtable->setGeometry(40,225,195,20);
fillBox("table",boxtable);
QPEApplication::showDialog( this );
}
ThemeDialog::~ThemeDialog()
{}
ImageNames ThemeDialog::getNames()
{
ImageNames names;
names.theme=lineName->text();
names.board=boxboard->currentText();
names.pieces1=boxpiecesA->currentText();
names.pieces2=boxpiecesB->currentText();
names.dice1=boxdiceA->currentText();
names.dice2=boxdiceB->currentText();
names.odds=boxodds->currentText();
names.table=boxtable->currentText();
return names;
}
void ThemeDialog::setCurrent(const ImageNames& current)
{
int a=0;
lineName->setText(current.theme);
for(a=0;a<boxboard->count();a++)
{
if(boxboard->text(a)==current.board)
{
boxboard->setCurrentItem(a);
break;
}
}
for(a=0;a<boxpiecesA->count();a++)
{
if(boxpiecesA->text(a)==current.pieces1)
{
boxpiecesA->setCurrentItem(a);
break;
}
}
for(a=0;a<boxpiecesB->count();a++)
{
if(boxpiecesB->text(a)==current.pieces2)
{
boxpiecesB->setCurrentItem(a);
break;
}
}
for(a=0;a<boxdiceA->count();a++)
{
if(boxdiceA->text(a)==current.dice1)
{
boxdiceA->setCurrentItem(a);
break;
}
}
for(a=0;a<boxdiceB->count();a++)
{
if(boxdiceB->text(a)==current.dice2)
{
boxdiceB->setCurrentItem(a);
break;
}
}
for(a=0;a<boxodds->count();a++)
{
if(boxodds->text(a)==current.odds)
{
boxodds->setCurrentItem(a);
break;
}
}
for(a=0;a<boxtable->count();a++)
{
if(boxtable->text(a)==current.table)
{
boxtable->setCurrentItem(a);
break;
}
}
}
void ThemeDialog::fillBox(QString dirname,QComboBox* thebox)
{
thebox->clear();
QDir dir(QPEApplication::qpeDir()+"/pics/backgammon/"+dirname);
dir.setFilter(QDir::Dirs | QDir::Files);
QFileInfoListIterator it(*(dir.entryInfoList()));
QFileInfo* fi;
while((fi=it.current())) // go through all file and subdirs
{
QString file=fi->fileName();
if(file.right(4)==".png")
{
thebox->insertItem(file.left(file.find(".png")));
}
++it;
}
delete fi;
}
diff --git a/noncore/games/bounce/game.cpp b/noncore/games/bounce/game.cpp
index 6ded218..c07f453 100644
--- a/noncore/games/bounce/game.cpp
+++ b/noncore/games/bounce/game.cpp
@@ -1,606 +1,605 @@
/*
* Copyright (C) 2000 Stefan Schimanski <1Stein@gmx.de>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <stdlib.h>
#include <qtimer.h>
#include <qpe/qpeapplication.h>
-#include <qimage.h>
#include "game.h"
#define TILE_SIZE 9
#define TILE_FIRST ((FIELD_WIDTH-2)*(FIELD_HEIGHT-2))
#define TILE_FREE (TILE_FIRST + 0)
#define TILE_BORDER (TILE_FIRST + 1)
#define TILE_WALLEND (TILE_FIRST + 2)
#define TILE_WALLUP (TILE_FIRST + 3)
#define TILE_WALLDOWN (TILE_FIRST + 4)
#define TILE_WALLLEFT (TILE_FIRST + 5)
#define TILE_WALLRIGHT (TILE_FIRST + 6)
#define GAME_DELAY 15
#define BALL_ANIM_DELAY 60
#define WALL_DELAY 100
#define MS2TICKS( ms ) ((ms)/GAME_DELAY)
Arrow::Arrow(QCanvasPixmapArray* array, QCanvas* canvas)
: QCanvasSprite( array, canvas )
{
m_vertical = true;
move(3,3);
}
void Arrow::update()
{
if ( m_vertical )
setFrame( 0 );
else
setFrame( 1 );
}
void Arrow::changeDirection()
{
m_vertical = ! m_vertical;
update();
}
Ball::Ball(QCanvasPixmapArray* array, QCanvas* canvas)
: QCanvasSprite( array, canvas ), m_animDelay( 0 ), m_soundDelay( MS2TICKS(BALL_ANIM_DELAY)/2 )
{
}
void Ball::update()
{
m_animDelay--;
if ( m_animDelay<=0 )
{
m_animDelay = MS2TICKS(BALL_ANIM_DELAY);
int frameNum = frame();
frameNum++;
if ( frameNum>=frameCount() )
frameNum = 0;
setFrame( frameNum );
}
}
void Ball::advance(int stage)
{
bool reflectX = false;
bool reflectY = false;
// check for collisions
if ( collide(xVelocity(), 0) ) reflectX = true;
if ( collide(0, yVelocity()) ) reflectY = true;
if ( !reflectX && !reflectY && collide(xVelocity(), yVelocity()) ) reflectX = reflectY = true;
// emit collision
QRect r = boundingRect();
r.moveBy( xVelocity(), yVelocity() );
JezzField* field = (JezzField *)canvas();
int ul = field->tile( r.left() / TILE_SIZE, r.top() / TILE_SIZE );
int ur = field->tile( r.right() / TILE_SIZE, r.top() / TILE_SIZE );
int bl = field->tile( r.left() / TILE_SIZE, r.bottom() / TILE_SIZE );
int br = field->tile( r.right() / TILE_SIZE, r.bottom() / TILE_SIZE );
if ( ul!=TILE_FREE ) field->emitBallCollisiton( this, r.left() / TILE_SIZE, r.top() / TILE_SIZE, ul ); else
if ( ur!=TILE_FREE ) field->emitBallCollisiton( this, r.right() / TILE_SIZE, r.top() / TILE_SIZE, ur ); else
if ( bl!=TILE_FREE ) field->emitBallCollisiton( this, r.left() / TILE_SIZE, r.bottom() / TILE_SIZE, bl ); else
if ( br!=TILE_FREE ) field->emitBallCollisiton( this, r.right() / TILE_SIZE, r.bottom() / TILE_SIZE, br );
// apply reflection
if ( reflectX ) setXVelocity( -xVelocity() );
if ( reflectY ) setYVelocity( -yVelocity() );
// update field
update();
QCanvasSprite::advance( stage );
}
bool Ball::collide( double dx, double dy )
{
QRect r = boundingRect();
r.moveBy( dx, dy );
JezzField* field = (JezzField *)canvas();
int ul = field->tile( r.left() / TILE_SIZE, r.top() / TILE_SIZE );
int ur = field->tile( r.right() / TILE_SIZE, r.top() / TILE_SIZE );
int bl = field->tile( r.left() / TILE_SIZE, r.bottom() / TILE_SIZE );
int br = field->tile( r.right() / TILE_SIZE, r.bottom() / TILE_SIZE );
return ( ul!=TILE_FREE || ur!=TILE_FREE || bl!=TILE_FREE || br!=TILE_FREE );
}
/*************************************************************************/
Wall::Wall( JezzField *field, int x, int y, Direction dir, int tile, QObject *parent, const char *name )
: QObject( parent, name ), m_dir( dir ), m_field( field ), m_startX( x ), m_startY( y ),
m_tile( tile ), m_delay( MS2TICKS(WALL_DELAY)/2 ), m_active( true )
{
// setup position and direction
m_dx = 0;
m_dy = 0;
switch ( m_dir )
{
case Up: m_dy = -1; break;
case Down: m_dy = 1; break;
case Left: m_dx = -1; break;
case Right: m_dx = 1; break;
}
m_x = m_startX;
m_y = m_startY;
m_field->setTile( m_x, m_y, m_tile );
}
void Wall::finish()
{
m_active = false;
}
bool Wall::isFree( int x, int y )
{
if ( m_field->tile(x, y)==TILE_FREE )
{
// check whether there is a ball at the moment
QCanvasItemList cols = m_field->collisions( QRect(x*TILE_SIZE, y*TILE_SIZE,
TILE_SIZE, TILE_SIZE) );
if ( cols.count()==0 )
return true;
}
return false;
}
void Wall::update()
{
}
void Wall::advance()
{
update();
// move wall
if ( m_active )
{
m_delay--;
if ( m_delay<=0 )
{
m_delay = MS2TICKS(WALL_DELAY);
// set previous tile
m_field->setTile( m_x, m_y, m_tile );
// check whether next place is still free
if ( isFree(m_x+m_dx, m_y+m_dy) )
{
// move ball
m_x += m_dx;
m_y += m_dy;
// set tile
m_field->setTile( m_x, m_y, TILE_WALLEND );
} else
{
finish();
emit finished( this, m_field->tile( m_x+m_dx, m_y+m_dy ) );
}
}
}
}
void Wall::fill( bool black )
{
if ( m_dx )
{
for ( int x=m_startX ; x!=m_x; x+=m_dx )
if ( m_field->tile(x, m_startY)==m_tile )
m_field->setGameTile( x, m_startY, black );
m_field->setGameTile( m_x, m_startY, black );
} else
{
for ( int y=m_startY ; y!=m_y; y+=m_dy )
if ( m_field->tile(m_startX, y)==m_tile )
m_field->setGameTile( m_startX, y, black );
m_field->setGameTile( m_startX, m_y, black );
}
}
/*************************************************************************/
JezzField::JezzField( QPixmap tiles, QObject* parent, const char* name )
: QCanvas( parent, name ), m_tiles( tiles )
{
setPixmaps( tiles );
}
void JezzField::setGameTile( int x, int y, bool black )
{
setTile( x, y, black ? TILE_BORDER : TILE_FREE );
}
void JezzField::setPixmaps( QPixmap tiles )
{
// create new tiles
QPixmap allTiles( TILE_SIZE*(FIELD_WIDTH-2), TILE_SIZE*(FIELD_HEIGHT-1) );
// handle default tiles
bitBlt( &allTiles, 0, TILE_SIZE*(FIELD_HEIGHT-2),
&tiles, 0, 0, tiles.width(), tiles.height() );
// load tiles into canvas
setTiles( allTiles, FIELD_WIDTH, FIELD_HEIGHT, TILE_SIZE, TILE_SIZE );
}
/*************************************************************************/
JezzView::JezzView(QCanvas* viewing, QWidget* parent, const char* name, WFlags f)
: QCanvasView( viewing, parent, name, f ), m_vertical( false )
{
setResizePolicy( AutoOne );
setHScrollBarMode( AlwaysOff );
setVScrollBarMode( AlwaysOff );
setCursor( sizeHorCursor );
}
void JezzView::viewportMouseReleaseEvent( QMouseEvent *ev )
{
if ( ev->button() & LeftButton )
{
emit buildWall( ev->x()/TILE_SIZE, ev->y()/TILE_SIZE, m_vertical );
}
}
void JezzView::changeCursor()
{
m_vertical = !m_vertical;
if ( m_vertical )
{
setCursor( sizeVerCursor );
}
else
{
setCursor( sizeHorCursor );
}
}
/*************************************************************************/
JezzGame::JezzGame( int ballNum, QWidget *parent, const char *name )
: QWidget( parent, name ), m_wall1( 0 ), m_wall2( 0 ),
m_text( 0 ), m_running( false ), m_percent( 0 ), m_pictured( false )
{
QString path = QPEApplication::qpeDir()+"pics/bounce/";
// load gfx
m_ballPixmaps = new QCanvasPixmapArray( path + "ball%1.png", 25 );
for ( unsigned n=0; n < m_ballPixmaps->count(); n++ )
m_ballPixmaps->image(n)->setOffset( 0, 0 );
m_arrowPixmaps = new QCanvasPixmapArray( path + "arrow%1.png", 2 );
for ( unsigned n=0; n < m_arrowPixmaps->count(); n++ )
m_arrowPixmaps->image(n)->setOffset( 0, 0 );
QPixmap tiles( path + "tiles.png" );
// create field
m_field = new JezzField( tiles, this, "m_field" );
m_field->resize( TILE_SIZE*FIELD_WIDTH, TILE_SIZE*FIELD_HEIGHT );
for ( int x=0; x<FIELD_WIDTH; x++ )
m_field->setTile( x, 0, TILE_BORDER );
for ( int y=1; y<FIELD_HEIGHT-1; y++ )
{
m_field->setTile( 0, y, TILE_BORDER );
for ( int x=1; x<FIELD_WIDTH-1; x++ )
m_field->setTile( x, y, TILE_FREE );
m_field->setTile( FIELD_WIDTH-1, y, TILE_BORDER );
}
for ( int x=0; x<FIELD_WIDTH; x++ )
m_field->setTile( x, FIELD_HEIGHT-1, TILE_BORDER );
connect( m_field, SIGNAL(ballCollision(Ball *, int, int, int)), this, SLOT(ballCollision(Ball *, int, int, int)) );
// create view
m_view = new JezzView( m_field, this, "m_view" );
m_view->move( 0, 0 );
m_view->adjustSize();
connect( m_view, SIGNAL(buildWall(int, int, bool)), this, SLOT(buildWall(int, int, bool)) );
// create balls
for ( int n=0; n<ballNum; n++ )
{
Ball *ball = new Ball( m_ballPixmaps, m_field );
m_balls.append( ball );
ball->setVelocity( ((rand() & 1)*2-1)*2, ((rand() & 1)*2-1)*2 );
ball->setFrame( rand() % 25 );
ball->move( 4*TILE_SIZE + ( rand() - 50 ) % ( (FIELD_WIDTH-8)*TILE_SIZE ),
4*TILE_SIZE + rand() % ( (FIELD_HEIGHT-8)*TILE_SIZE ) );
ball->show();
}
// create arrow
arrow = new Arrow( m_arrowPixmaps, m_field );
arrow->show();
// create text label
m_text = new QCanvasText( m_field );
// create game clock
m_clock = new QTimer( this );
connect( m_clock, SIGNAL(timeout()), this, SLOT(tick()) );
m_clock->start( GAME_DELAY );
// setup geometry
setFixedSize( m_view->size() );
}
JezzGame::~JezzGame()
{
m_balls.clear();
delete m_view;
delete m_field;
delete m_ballPixmaps;
}
void JezzGame::display( QString text, int size )
{
qDebug("This function \"display\" shouldn't be called!!!");
if ( !text.isEmpty() )
{
QFont font( "Helvetica", size, QFont::Bold );
font.setStyleHint( QFont::Helvetica );
m_text->setFont( font );
m_text->setText( text );
QRect size = m_text->boundingRect();
m_text->move( ( FIELD_WIDTH*TILE_SIZE - size.width() ) / 2,
( FIELD_HEIGHT*TILE_SIZE - size.height() ) / 2 );
m_text->show();
} else
{
m_text->hide();
}
}
void JezzGame::start()
{
m_running = true;
}
void JezzGame::stop()
{
m_running = false;
}
void JezzGame::makeBlack()
{
// copy current field into buffer
for ( int y=0; y<FIELD_HEIGHT; y++ )
for ( int x=0; x<FIELD_WIDTH; x++ )
m_buf[x][y] = m_field->tile( x, y );
// fill areas that contains a ball
for ( Ball *ball=m_balls.first(); ball!=0; ball=m_balls.next() )
fill( ball->x()/TILE_SIZE, ball->y()/TILE_SIZE );
// areas still free can be blacked now
for ( int y=0; y<FIELD_HEIGHT; y++ )
for ( int x=0; x<FIELD_WIDTH; x++ )
{
if ( m_buf[x][y]==TILE_FREE )
m_field->setGameTile( x, y, true );
}
m_field->update();
m_view->repaint();
// count percent value of occupied area
int p = percent();
if ( p!=m_percent )
{
m_percent = p;
emit newPercent( m_percent );
}
}
int JezzGame::percent()
{
int notFree = 0;
for ( int y=1; y<FIELD_HEIGHT-1; y++ )
for ( int x=1; x<FIELD_WIDTH-1; x++ )
{
if ( m_field->tile(x,y)!=TILE_FREE )
notFree++;
}
return 100 * notFree / ( (FIELD_WIDTH-1) * (FIELD_HEIGHT-1) );
}
void JezzGame::fill( int x, int y )
{
if ( m_buf[x][y]!=TILE_FREE) return;
// go left
int _x=x;
for ( ; m_buf[_x][y]==TILE_FREE; _x-- )
m_buf[_x][y] = TILE_BORDER;
int stopx = _x;
// fill above
for ( _x=x; _x>stopx; _x-- )
if ( m_buf[_x][y-1]==TILE_FREE ) fill( _x, y-1 );
// fill below
for ( _x=x; _x>stopx; _x-- )
if ( m_buf[_x][y+1]==TILE_FREE ) fill( _x, y+1 );
// go right
for ( _x=x+1; m_buf[_x][y]==TILE_FREE; _x++ )
m_buf[_x][y] = TILE_BORDER;
stopx = _x;
// fill above
for ( _x=x+1; _x<stopx; _x++ )
if ( m_buf[_x][y-1]==TILE_FREE ) fill( _x, y-1 );
// fill below;
for ( _x=x+1; _x<stopx; _x++ )
if ( m_buf[_x][y+1]==TILE_FREE ) fill( _x, y+1 );
}
void JezzGame::ballCollision( Ball*, int, int, int tile )
{
if ( tile!=TILE_BORDER && tile>TILE_FREE && tile!=TILE_WALLEND )
{
// stop walls
if ( (tile==TILE_WALLUP || tile==TILE_WALLLEFT) && m_wall1 )
{
m_wall1->finish();
m_wall1->fill( false );
delete m_wall1;
m_wall1 = 0;
}
if ( (tile==TILE_WALLDOWN || tile==TILE_WALLRIGHT) && m_wall2 )
{
m_wall2->finish();
m_wall2->fill( false );
delete m_wall2;
m_wall2 = 0;
}
// update view
m_field->update();
m_view->repaint();
// send death msg
emit died();
}
}
void JezzGame::buildWall( int x, int y, bool vertical )
{
if ( !m_running ) return;
if ( m_field->tile(x, y)==TILE_FREE )
{
// check whether there is a ball at the moment
QCanvasItemList cols = m_field->collisions( QRect(x*TILE_SIZE, y*TILE_SIZE, TILE_SIZE, TILE_SIZE) );
if ( cols.count()>0 )
{
//kdDebug() << "Direct collision" << endl;
emit ballCollision( (Ball*)cols.first(), x, y, TILE_WALLUP );
return;
}
// start walls
if ( !m_wall1 )
{
m_wall1 = new Wall( m_field, x, y,
vertical? Wall::Up : Wall::Left,
vertical? TILE_WALLUP : TILE_WALLLEFT,
this, "m_wall1" );
connect( m_wall1, SIGNAL(finished(Wall *, int)),
this, SLOT(wallFinished(Wall *, int)) ); }
if ( !m_wall2 )
{
m_wall2 = new Wall( m_field, x, y,
vertical? Wall::Down: Wall::Right,
vertical? TILE_WALLDOWN : TILE_WALLRIGHT,
this, "m_wall2" );
connect( m_wall2, SIGNAL(finished(Wall *, int)),
this, SLOT(wallFinished(Wall *, int)) );
}
}
}
void JezzGame::wallFinished( Wall *wall, int tile )
{
if ( tile==TILE_WALLEND )
{
if ( m_wall1 )
{
m_wall1->fill( false );
delete m_wall1;
m_wall1 = 0;
}
if ( m_wall2 )
{
m_wall2->fill( false );
delete m_wall2;
m_wall2 = 0;
}
} else
{
if ( m_wall1==wall && m_wall1 )
{
m_wall1->fill( true );
delete m_wall1;
m_wall1 = 0;
}
if ( m_wall2==wall && m_wall2 )
{
m_wall2->fill( true );
delete m_wall2;
m_wall2 = 0;
}
}
m_field->update();
m_view->repaint();
makeBlack();
}
void JezzGame::tick()
{
if ( m_running )
{
if ( m_field ) m_field->advance();
if ( m_wall1 ) m_wall1->advance();
if ( m_wall2 ) m_wall2->advance();
} else
{
for ( Ball *ball=m_balls.first(); ball!=0; ball=m_balls.next() )
ball->update();
if ( m_field ) m_field->update();
if ( m_wall1 ) m_wall1->update();
if ( m_wall2 ) m_wall2->update();
}
}
void JezzGame::changeCursor()
{
arrow->changeDirection();
m_view->changeCursor();
}
diff --git a/noncore/games/bounce/kbounce.cpp b/noncore/games/bounce/kbounce.cpp
index 211f0ff..3b0cb6f 100644
--- a/noncore/games/bounce/kbounce.cpp
+++ b/noncore/games/bounce/kbounce.cpp
@@ -1,312 +1,308 @@
/*
* Copyright (C) 2000 Stefan Schimanski <1Stein@gmx.de>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License,Life or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <qlayout.h>
#include <qtimer.h>
-#include <qlcdnumber.h>
#include <qmessagebox.h>
-#include <qmainwindow.h>
-#include <qpe/qpeapplication.h>
#include "kbounce.h"
#include "game.h"
-#include <qlabel.h>
KJezzball::KJezzball(QWidget *p, const char* n, WFlags f)
: QMainWindow(p,n,f), m_gameWidget( 0 )
{
setCaption(tr("Bounce"));
// setup variables
m_game.level = 1;
m_game.score = 0;
m_state = Idle;
menu = menuBar();
game = new QPopupMenu;
game->insertItem(tr("&New game"), this, SLOT(newGame()), Key_N );
game->insertItem(tr("&Pause game"), this, SLOT(pauseGame()), Key_P );
game->insertSeparator();
game->insertItem(tr("&About"), this, SLOT(about()));
menu->insertItem( tr("&Game"), game );
// create widgets
m_view = new QWidget( this, "m_view" );
setCentralWidget( m_view );
m_layout = new QGridLayout( m_view );
m_layout->setSpacing( 0 );
m_layout->setMargin( 0 );
ScoreLabel = new QLabel( m_view, "ScoreLabel" );
ScoreLabel->setText( tr( "Score: 00" ) );
ScoreLabel->setAlignment( int( QLabel::AlignCenter ) );
m_layout->addWidget( ScoreLabel, 1, 0 );
LivesLabel = new QLabel( m_view, "LivesLabel" );
LivesLabel->setText( tr( "Lives: 0%" ) );
LivesLabel->setAlignment( int( QLabel::AlignCenter ) );
m_layout->addWidget( LivesLabel, 1, 2 );
FilledLabel = new QLabel( m_view, "FilledLabel" );
FilledLabel->setText( tr( "Filled: 00%" ) );
FilledLabel->setAlignment( int( QLabel::AlignCenter ) );
m_layout->addWidget( FilledLabel, 1, 1 );
TimeLabel = new QLabel( m_view, "TimeLabel" );
TimeLabel->setText( tr( "Time: 00" ) );
TimeLabel->setAlignment( int( QLabel::AlignCenter ) );
m_layout->addWidget( TimeLabel, 1, 3 );
// create timers
m_nextLevelTimer = new QTimer( this, "m_nextLevelTimer" );
connect( m_nextLevelTimer, SIGNAL(timeout()), this, SLOT(switchLevel()) );
m_gameOverTimer = new QTimer( this, "m_gameOverTimer" );
connect( m_gameOverTimer, SIGNAL(timeout()), this, SLOT(gameOverNow()) );
m_timer = new QTimer( this, "m_timer" );
connect( m_timer, SIGNAL(timeout()), this, SLOT(second()) );
// create demo game
createLevel( 1 );
}
void KJezzball::newGame()
{
// Check for running game
closeGame();
if ( m_state==Idle )
{
// update displays
m_game.level = 1;
m_game.score = 0;
setCaption(tr("Bounce Level %1").arg(m_game.level));
ScoreLabel->setText( tr( "Score: %1" ).arg(m_game.score) );
// start new game
m_state = Running;
createLevel( m_game.level );
startLevel();
}
}
void KJezzball::about()
{
QMessageBox::information( this, tr("About"),
tr("Written by: Stefan Schimanski\n"
"Ported by: Martin Imobersteg\n"
"\n"
"Click to form walls.\n"
"Hit space to switch wall direction.\n"
"Try to reduce total space by 75%.\n"
"\n"
"This program is distributed under\n"
"the terms of the GPL v2.") );
}
void KJezzball::closeGame()
{
if ( m_state!=Idle )
{
stopLevel();
m_state = Idle;
}
}
void KJezzball::pauseGame()
{
switch ( m_state )
{
case Running:
m_state = Paused;
m_gameWidget->display( tr("Game paused.\nPress P to continue!") );
stopLevel();
break;
case Paused:
case Suspend:
m_state = Running;
m_gameWidget->display( QString::null );
startLevel();
break;
case Idle:
break;
}
}
void KJezzball::gameOver()
{
stopLevel();
m_gameOverTimer->start( 100, TRUE );
}
void KJezzball::gameOverNow()
{
m_state = Idle;
QString score;
score.setNum( m_game.score );
QMessageBox::information( this, "Game Over", tr("Game Over!\nScore: %1").arg(score) );
}
void KJezzball::focusOutEvent( QFocusEvent *ev )
{
if ( m_state==Running )
{
stopLevel();
m_state = Suspend;
}
QMainWindow::focusOutEvent( ev );
}
void KJezzball::focusInEvent ( QFocusEvent *ev )
{
if ( m_state==Suspend )
{
startLevel();
m_state = Running;
}
QMainWindow::focusInEvent( ev );
}
void KJezzball::second()
{
m_level.time--;
TimeLabel->setText( tr( "Time: %1" ).arg(m_level.time) );
if ( m_level.time<=0 )
{
gameOver();
}
}
void KJezzball::died()
{
m_level.lifes--;
LivesLabel->setText( tr( "Lives: %1" ).arg(m_level.lifes) );
if ( m_level.lifes==0 ) gameOver();
}
void KJezzball::newPercent( int percent )
{
FilledLabel->setText( tr( "Filled: %1%" ).arg(percent) );
if ( percent>=75 )
{
m_level.score = m_level.lifes*15 + (percent-75)*2*(m_game.level+5);
nextLevel();
}
}
void KJezzball::createLevel( int level )
{
// destroy old game
if ( m_gameWidget ) delete m_gameWidget;
m_gameWidget = new JezzGame( level+1, m_view, "m_gameWidget" );
m_gameWidget->show();
m_layout->addMultiCellWidget( m_gameWidget, 0, 0, 0, 3 );
connect( m_gameWidget, SIGNAL(died()), this, SLOT(died()) );
connect( m_gameWidget, SIGNAL(newPercent(int)), this, SLOT(newPercent(int)) );
// update displays
m_level.lifes = level+1;
LivesLabel->setText( tr( "Lives: %1" ).arg(m_level.lifes) );
FilledLabel->setText( tr( "Filled: 0%" ) );
m_level.time = (level+2)*30;
TimeLabel->setText( tr( "Time: %1" ).arg(m_level.time) );
m_level.score = 0;
}
void KJezzball::startLevel()
{
if ( m_gameWidget )
{
m_timer->start( 1000 );
m_gameWidget->start();
}
}
void KJezzball::stopLevel()
{
if ( m_gameWidget )
{
m_gameWidget->stop();
m_timer->stop();
}
}
void KJezzball::nextLevel()
{
stopLevel();
m_nextLevelTimer->start( 100, TRUE );
}
void KJezzball::switchLevel()
{
m_game.score += m_level.score;
ScoreLabel->setText( tr( "Score: %1" ).arg(m_game.score) );
QString score;
score.setNum( m_level.score );
QString level;
level.setNum( m_game.level );
QString foo = QString(
tr("Successfully cleared more than 75%.\n") +
tr("%1 points: 15 points per life\n").arg(m_level.lifes*15) +
tr("%1 points: Bonus\n").arg((m_gameWidget->percent()-75)*2*(m_game.level+5)) +
tr("%1 points: Total score\n").arg(score) +
tr("On to level %1.\nYou get %2 lives this time!")).arg(m_game.level+1).arg(m_game.level+2);
QMessageBox::information( this, "Success", foo );
m_game.level++;
createLevel( m_game.level );
startLevel();
}
void KJezzball::keyPressEvent( QKeyEvent *ev )
{
if ( ev->key() == Key_Space ||
ev->key() == Key_Up ||
ev->key() == Key_Down ||
ev->key() == Key_Right ||
ev->key() == Key_Left )
{
m_gameWidget->changeCursor();
}
else
{
ev->ignore();
}
}
diff --git a/noncore/games/bounce/main.cpp b/noncore/games/bounce/main.cpp
index 9ea86a6..a070c4b 100644
--- a/noncore/games/bounce/main.cpp
+++ b/noncore/games/bounce/main.cpp
@@ -1,24 +1,23 @@
/*
* Copyright (C) 2000 Stefan Schimanski <schimmi@kde.org>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
-#include <qpe/qpeapplication.h>
#include "kbounce.h"
#include <opie/oapplicationfactory.h>
OPIE_EXPORT_APP( OApplicationFactory<KJezzball> )
diff --git a/noncore/games/buzzword/buzzword.cpp b/noncore/games/buzzword/buzzword.cpp
index f746065..13eb481 100644
--- a/noncore/games/buzzword/buzzword.cpp
+++ b/noncore/games/buzzword/buzzword.cpp
@@ -1,182 +1,181 @@
/*
* Copyright (C) 2002 Martin Imobersteg <imm@gmx.ch>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License,Life or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <qlayout.h>
-#include <qmessagebox.h>
#include <qmainwindow.h>
#include <qlabel.h>
#include <qgrid.h>
#include <qcolor.h>
#include <qbutton.h>
#include <qfile.h>
#include <qtextstream.h>
#include <qstringlist.h>
#include <qmessagebox.h>
#include <qdir.h>
#include <math.h>
#include <stdlib.h>
#include <qpe/qpeapplication.h>
#include "buzzword.h"
BuzzLabel::BuzzLabel( QWidget *parent, const char *name )
: QLabel( parent, name )
{
}
void BuzzLabel::mousePressEvent(QMouseEvent *e)
{
if(e->button() == LeftButton)
{
emit clicked();
}
}
BuzzItem::BuzzItem( int row, int column, QString text, QWidget *parent, const char *name )
: QVBox( parent, name ), _row(row), _column(column)
{
setFrameStyle( QFrame::Panel | QFrame::Raised );
setLineWidth( 1 );
label = new BuzzLabel(this, "label");
label->setText(text);
label->setAlignment( int( QLabel::AlignCenter ) );
connect( label, SIGNAL(clicked()), this, SLOT(flip()) );
}
void BuzzItem::flip()
{
setLineWidth( 1 );
label->setBackgroundColor(label->colorGroup().highlight());
emit clicked(_row, _column);
}
BuzzWord::BuzzWord(QWidget* parent, const char* name, WFlags fl ) : QMainWindow( parent, name, fl )
{
setCaption(tr("buZzword"));
menu = menuBar();
game = new QPopupMenu;
game->insertItem(tr("&New game"), this, SLOT(newGame()), Key_N );
menu->insertItem( tr("&Game"), game );
gridVal = 4;
grid = NULL;
gameOver = false;
newGame();
}
void BuzzWord::drawGrid()
{
QStringList l;
QString path = QPEApplication::qpeDir()+"share/buzzword/";
QFile f( path + "buzzwords" );
if ( !f.open( IO_ReadOnly ) )
return;
QTextStream t( &f );
while (!t.atEnd())
{
l << t.readLine();
}
f.close();
grid = new QGrid(gridVal, this);
// grid->setFixedSize( 480, 480 );
for( int c = 0 ; c < gridVal ; c++ )
{
for( int r = 0 ; r < gridVal ; r++ )
{
uint pos = rand() % l. count();
QString word = QStringList::split(" ", l[pos]).join("\n");
BuzzItem* bi = new BuzzItem( c, r, word, grid );
connect( bi, SIGNAL(clicked(int, int)), this, SLOT(clicked(int,int)) );
map[c][r] = 0;
l.remove( l.at( pos ));
}
}
}
void BuzzWord::clicked(int row, int column)
{
if ( ! gameOver )
{
int rowTotal = 0;
int columnTotal = 0;
map[column][row] = 1;
for( int c = 0 ; c < gridVal ; c++ )
{
for( int r = 0 ; r < gridVal ; r++ )
{
if ( map[c][r] == 1 )
rowTotal++;
if ( rowTotal == 4 )
{
bingo();
}
}
rowTotal = 0;
}
for( int r = 0 ; r < gridVal ; r++ )
{
for( int c = 0 ; c < gridVal ; c++ )
{
if ( map[c][r] == 1 )
columnTotal++;
if ( columnTotal == 4 )
{
bingo();
}
}
columnTotal = 0;
}
if ( map[0][0] && map[1][1] && map[2][2] && map[3][3] )
bingo();
if ( map[0][3] && map[1][2] && map[2][1] && map[3][0] )
bingo();
}
}
void BuzzWord::bingo()
{
gameOver = true;
QMessageBox::information( this, "BUZZWORD", tr("<h1><b>BINGO !</b></h1>"));
}
void BuzzWord::newGame()
{
gameOver = false;
delete grid;
drawGrid();
setCentralWidget(grid);
}
diff --git a/noncore/games/buzzword/main.cpp b/noncore/games/buzzword/main.cpp
index 67f2c26..95b3176 100644
--- a/noncore/games/buzzword/main.cpp
+++ b/noncore/games/buzzword/main.cpp
@@ -1,24 +1,23 @@
/*
* Copyright (C) 2002 Martin Imobersteg <imm@gmx.ch>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License,Life or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
-#include <qpe/qpeapplication.h>
#include <opie/oapplicationfactory.h>
#include "buzzword.h"
OPIE_EXPORT_APP( OApplicationFactory<BuzzWord> )
diff --git a/noncore/games/fifteen/fifteen.cpp b/noncore/games/fifteen/fifteen.cpp
index b4e0308..506e87a 100644
--- a/noncore/games/fifteen/fifteen.cpp
+++ b/noncore/games/fifteen/fifteen.cpp
@@ -1,391 +1,386 @@
/**********************************************************************
** Copyright (C) 2000-2002 Trolltech AS. All rights reserved.
**
** This file is part of the Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include "fifteen.h"
#include <qtopia/resource.h>
#include <qtopia/config.h>
#include <qvbox.h>
#include <qaction.h>
-#include <qlayout.h>
#include <qpainter.h>
-#include <qpopupmenu.h>
#include <qmessagebox.h>
#include <qtoolbar.h>
#include <qmenubar.h>
-#include <qstringlist.h>
-#include <qapplication.h>
-#include <qtoolbutton.h>
#include <stdlib.h>
#include <time.h>
FifteenMainWindow::FifteenMainWindow(QWidget *parent, const char* name, WFlags fl)
: QMainWindow( parent, name, fl )
{
// random seed
srand(time(0));
setCaption( tr("Fifteen Pieces") );
QToolBar *toolbar = new QToolBar(this);
toolbar->setHorizontalStretchable( FALSE );
QMenuBar *menubar = new QMenuBar( toolbar );
menubar->setMargin(0);
QPopupMenu *game = new QPopupMenu( this );
QWidget *spacer = new QWidget( toolbar );
spacer->setBackgroundMode( PaletteButton );
toolbar->setStretchableWidget( spacer );
setToolBarsMovable( FALSE );
QVBox *vbox = new QVBox( this );
PiecesTable *table = new PiecesTable( vbox );
setCentralWidget(vbox);
QAction *a = new QAction( tr( "Randomize" ), Resource::loadPixmap( "new" ),
QString::null, 0, this, 0 );
connect( a, SIGNAL( activated() ), table, SLOT( slotRandomize() ) );
a->addTo( game );
a->addTo( toolbar );
/* This is pointless and confusing.
a = new QAction( tr( "Solve" ), Resource::loadIconSet( "repeat" ),
QString::null, 0, this, 0 );
connect( a, SIGNAL( activated() ), table, SLOT( slotReset() ) );
a->addTo( game );
a->addTo( toolbar );
*/
menubar->insertItem( tr( "Game" ), game );
}
PiecesTable::PiecesTable(QWidget* parent, const char* name )
: QTableView(parent, name), _menu(0), _randomized(false)
{
// setup table view
setFrameStyle(StyledPanel | Sunken);
setBackgroundMode(NoBackground);
setMouseTracking(true);
setNumRows(4);
setNumCols(4);
// init arrays
initMap();
readConfig();
initColors();
// set font
QFont f = font();
f.setPixelSize(18);
f.setBold( TRUE );
setFont(f);
}
PiecesTable::~PiecesTable()
{
writeConfig();
}
void PiecesTable::writeConfig()
{
Config cfg("Fifteen");
cfg.setGroup("Game");
QStringList map;
for (int i = 0; i < 16; i++)
map.append( QString::number( _map[i] ) );
cfg.writeEntry("Map", map, '-');
cfg.writeEntry("Randomized", _randomized );
}
void PiecesTable::readConfig()
{
Config cfg("Fifteen");
cfg.setGroup("Game");
QStringList map = cfg.readListEntry("Map", '-');
_randomized = cfg.readBoolEntry( "Randomized", FALSE );
int i = 0;
for ( QStringList::Iterator it = map.begin(); it != map.end(); ++it ) {
_map[i] = (*it).toInt();
i++;
if ( i > 15 ) break;
}
}
void PiecesTable::paintCell(QPainter *p, int row, int col)
{
int w = cellWidth();
int h = cellHeight();
int x2 = w - 1;
int y2 = h - 1;
int number = _map[col + row * numCols()] + 1;
// draw cell background
if(number == 16)
p->setBrush(colorGroup().background());
else
p->setBrush(_colors[number-1]);
p->setPen(NoPen);
p->drawRect(0, 0, w, h);
if (number == 16) return;
// draw borders
if (height() > 40) {
p->setBrush(_colors[number-1].light(130));
p->drawPolygon(light_border);
p->setBrush(_colors[number-1].dark(130));
p->drawPolygon(dark_border);
}
// draw number
p->setPen(black);
p->drawText(0, 0, x2, y2, AlignHCenter | AlignVCenter, QString::number(number));
}
void PiecesTable::resizeEvent(QResizeEvent *e)
{
QTableView::resizeEvent(e);
setCellWidth(contentsRect().width()/ numRows());
setCellHeight(contentsRect().height() / numCols());
//
// Calculate 3d-effect borders
//
int cell_w = cellWidth();
int cell_h = cellHeight();
int x_offset = cell_w - int(cell_w * 0.9); // 10% should be enough
int y_offset = cell_h - int(cell_h * 0.9);
light_border.setPoints(6,
0, 0,
cell_w, 0,
cell_w - x_offset, y_offset,
x_offset, y_offset,
x_offset, cell_h - y_offset,
0, cell_h);
dark_border.setPoints(6,
cell_w, 0,
cell_w, cell_h,
0, cell_h,
x_offset, cell_h - y_offset,
cell_w - x_offset, cell_h - y_offset,
cell_w - x_offset, y_offset);
}
void PiecesTable::initColors()
{
_colors.resize(numRows() * numCols());
for (int r = 0; r < numRows(); r++)
for (int c = 0; c < numCols(); c++)
_colors[c + r *numCols()] = QColor(255 - 70 * c,255 - 70 * r, 150);
}
void PiecesTable::initMap()
{
_map.resize(16);
for ( int i = 0; i < 16; i++)
_map[i] = i;
_randomized = false;
}
void PiecesTable::randomizeMap()
{
initMap();
_randomized = true;
// find the free position
int pos = _map.find(15);
int move = 0;
while ( move < 333 ) {
int frow = pos / numCols();
int fcol = pos - frow * numCols();
// find click position
int row = rand()%4;
int col = rand()%4;
// sanity check
if ( row < 0 || row >= numRows() ) continue;
if ( col < 0 || col >= numCols() ) continue;
if ( row != frow && col != fcol ) continue;
move++;
// rows match -> shift pieces
if(row == frow) {
if (col < fcol) {
for(int c = fcol; c > col; c--) {
_map[c + row * numCols()] = _map[ c-1 + row *numCols()];
}
}
else if (col > fcol) {
for(int c = fcol; c < col; c++) {
_map[c + row * numCols()] = _map[ c+1 + row *numCols()];
}
}
}
// cols match -> shift pieces
else if (col == fcol) {
if (row < frow) {
for(int r = frow; r > row; r--) {
_map[col + r * numCols()] = _map[ col + (r-1) *numCols()];
}
}
else if (row > frow) {
for(int r = frow; r < row; r++) {
_map[col + r * numCols()] = _map[ col + (r+1) *numCols()];
}
}
}
// move free cell to click position
_map[pos=(col + row * numCols())] = 15;
}
repaint();
}
void PiecesTable::checkwin()
{
if(!_randomized) return;
int i;
for (i = 0; i < 16; i++)
if(i != _map[i])
break;
if (i == 16) {
QMessageBox::information(this, tr("Fifteen Pieces"),
tr("Congratulations!\nYou win the game!"));
_randomized = FALSE;
}
}
void PiecesTable::slotRandomize()
{
randomizeMap();
}
void PiecesTable::slotReset()
{
initMap();
repaint();
}
void PiecesTable::mousePressEvent(QMouseEvent* e)
{
QTableView::mousePressEvent(e);
if (e->button() == RightButton) {
// setup RMB pupup menu
if(!_menu) {
_menu = new QPopupMenu(this);
_menu->insertItem(tr("R&andomize Pieces"), mRandomize);
_menu->insertItem(tr("&Reset Pieces"), mReset);
_menu->adjustSize();
}
// execute RMB popup and check result
switch(_menu->exec(mapToGlobal(e->pos()))) {
case mRandomize:
randomizeMap();
break;
case mReset:
initMap();
repaint();
break;
default:
break;
}
}
else {
// GAME LOGIC
// find the free position
int pos = _map.find(15);
if(pos < 0) return;
int frow = pos / numCols();
int fcol = pos - frow * numCols();
// find click position
int row = findRow(e->y());
int col = findCol(e->x());
// sanity check
if (row < 0 || row >= numRows()) return;
if (col < 0 || col >= numCols()) return;
if ( row != frow && col != fcol ) return;
// valid move?
if(row != frow && col != fcol) return;
// rows match -> shift pieces
if(row == frow) {
if (col < fcol) {
for(int c = fcol; c > col; c--) {
_map[c + row * numCols()] = _map[ c-1 + row *numCols()];
updateCell(row, c, false);
}
}
else if (col > fcol) {
for(int c = fcol; c < col; c++) {
_map[c + row * numCols()] = _map[ c+1 + row *numCols()];
updateCell(row, c, false);
}
}
}
// cols match -> shift pieces
else if (col == fcol) {
if (row < frow) {
for(int r = frow; r > row; r--) {
_map[col + r * numCols()] = _map[ col + (r-1) *numCols()];
updateCell(r, col, false);
}
}
else if (row > frow) {
for(int r = frow; r < row; r++) {
_map[col + r * numCols()] = _map[ col + (r+1) *numCols()];
updateCell(r, col, false);
}
}
}
// move free cell to click position
_map[col + row * numCols()] = 15;
updateCell(row, col, false);
// check if the player wins with this move
checkwin();
}
}
diff --git a/noncore/games/go/gowidget.cpp b/noncore/games/go/gowidget.cpp
index cf89267..79820b1 100644
--- a/noncore/games/go/gowidget.cpp
+++ b/noncore/games/go/gowidget.cpp
@@ -1,464 +1,460 @@
/**********************************************************************
** Copyright (C) 2000 Trolltech AS. All rights reserved.
**
** This file is part of Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include "gowidget.h"
#include <qpe/config.h>
#include <qpe/resource.h>
#include <qpainter.h>
-#include <qpixmap.h>
#include <qpe/qpetoolbar.h>
#include <qmenubar.h>
-#include <qpopupmenu.h>
#include <qaction.h>
#include <qapplication.h> //processEvents()
#include <qlabel.h>
//#include <stdio.h>
-#include "amigo.h"
-#include "goplayutils.h"
static const enum bVal computer_color = BLACK;
static int current_handicap = 1;
static QBrush *goBrush;
//static QImage *newBlackStone;
//static QImage *blackStone;
//static QImage *whiteStone;
static QPixmap *newBlackStone;
static QPixmap *blackStone;
static QPixmap *whiteStone;
static bool smallStones = FALSE;
GoMainWidget::GoMainWidget( QWidget *parent, const char* name, WFlags fl) :
QMainWindow( parent, name, fl )
{
setToolBarsMovable( FALSE );
GoWidget *go = new GoWidget(this);
setCentralWidget(go);
toolbar = new QToolBar(this);
toolbar->setHorizontalStretchable( TRUE );
addToolBar(toolbar);
QMenuBar *mb = new QMenuBar( toolbar );
mb->setMargin(0);
QPopupMenu *file = new QPopupMenu( this );
QAction *a = new QAction( tr( "New Game" ), QString::null, 0, this, 0 );
connect( a, SIGNAL( activated() ), go, SLOT( newGame() ) );
a->addTo( file );
a = new QAction( tr( "Pass" ), Resource::loadPixmap( "pass" ), QString::null, 0, this, 0 );
connect( a, SIGNAL( activated() ), go, SLOT( pass() ) );
a->addTo( file );
a->addTo( toolbar );
a = new QAction( tr( "Resign" ), Resource::loadPixmap( "reset" ), QString::null, 0, this, 0 );
connect( a, SIGNAL( activated() ), go, SLOT( resign() ) );
a->addTo( file );
a = new QAction( tr( "Two player option" ), QString::null, 0, this, 0 );
a->setToggleAction( TRUE );
connect( a, SIGNAL( toggled(bool) ), go, SLOT( setTwoplayer(bool) ) );
a->addTo( file );
mb->insertItem( tr( "Game" ), file );
QLabel *turnLabel = new QLabel( toolbar );
turnLabel->setBackgroundMode( PaletteButton );
connect( go, SIGNAL(showTurn(const QPixmap&)),
turnLabel, SLOT(setPixmap(const QPixmap&)) );
QLabel * scoreLabel = new QLabel( toolbar );
scoreLabel->setBackgroundMode( PaletteButton );
connect( go, SIGNAL(showScore(const QString&)),
scoreLabel, SLOT(setText(const QString&)) );
toolbar->setStretchableWidget( scoreLabel );
go->readConfig();
}
void GoMainWidget::resizeEvent( QResizeEvent * )
{
//### this won't work because of the text label...
/*
if ( width() > height() )
moveToolBar( toolbar, Left );
else
moveToolBar( toolbar, Top );
*/
}
GoWidget *GoWidget::self = 0;
GoWidget::GoWidget( QWidget *parent, const char* name) :
QWidget( parent, name )
{
if ( self )
fatal( "Only one Go widget allowed" );
self = this;
twoplayer = FALSE;
d = bx = by = 1;
QPixmap pix = Resource::loadPixmap( "go/pine" );
goBrush = new QBrush( black, pix );
/*
QString fn = Resource::findPixmap("Go-black");
blackStone = new QImage( fn );
fn = Resource::findPixmap("Go-black-highlight");
newBlackStone = new QImage( fn );
fn = Resource::findPixmap("Go-white");
whiteStone = new QImage( fn );
*/
blackStone = new QPixmap(Resource::loadPixmap( "Go-black" ));
whiteStone = new QPixmap(Resource::loadPixmap( "Go-white" ));
newBlackStone = new QPixmap(Resource::loadPixmap( "Go-black-highlight" ));
init();
}
GoWidget::~GoWidget()
{
writeConfig();
}
void GoWidget::writeConfig()
{
Config cfg("Go");
cfg.setGroup("Game");
cfg.writeEntry("TwoPlayer", twoplayer);
cfg.writeEntry("CurrentPlayer", currentPlayer);
cfg.writeEntry("NPassed", nPassed);
QString b;
for (int i=0; i<19; i++)
for (int j=0; j<19; j++)
b += board[i][j] == BLACK ? 'B' : board[i][j] == WHITE ? 'W' : '.';
cfg.writeEntry("Board", b);
cfg.writeEntry("LastX", lastX);
cfg.writeEntry("LastY", lastY);
extern int blackPrisoners, whitePrisoners;
cfg.writeEntry("BlackPrisoners", blackPrisoners);
cfg.writeEntry("WhitePrisoners", whitePrisoners);
}
void GoWidget::readConfig()
{
init();
Config cfg("Go");
cfg.setGroup("Game");
twoplayer = cfg.readBoolEntry("TwoPlayer");
currentPlayer = (bVal)cfg.readNumEntry("CurrentPlayer",1);
nPassed = cfg.readNumEntry("NPassed",0);
QString b = cfg.readEntry("Board");
if ( b.length() == 19*19 )
for (int i=0; i<19; i++)
for (int j=0; j<19; j++) {
QChar ch = b[j+19*i];
if ( ch != '.' )
GoPlaceStone( ch == 'B' ? BLACK : WHITE, i, j );
}
lastX = cfg.readNumEntry("LastX");
lastY = cfg.readNumEntry("LastY");
extern int blackPrisoners, whitePrisoners;
blackPrisoners = cfg.readNumEntry("BlackPrisoners",0);
whitePrisoners = cfg.readNumEntry("WhitePrisoners",0);
reportPrisoners(blackPrisoners,whitePrisoners);
emit showTurn( currentPlayer == WHITE ? *whiteStone : *blackStone );
}
void GoWidget::resizeEvent( QResizeEvent * )
{
d = QMIN(width(),height())/19;
// int r = (d/2-1);
bx = (width() - 18*d)/2 ;
by = (height() - 18*d)/2 ;
if ( d < 10 && !smallStones ) {
blackStone->convertFromImage( blackStone->convertToImage().smoothScale(8,8) );
whiteStone->convertFromImage( whiteStone->convertToImage().smoothScale(8,8) );
newBlackStone->convertFromImage( newBlackStone->convertToImage().smoothScale(8,8) );
smallStones = TRUE;
} else if ( d >= 10 && smallStones ) {
blackStone = new QPixmap(Resource::loadPixmap( "Go-black" ));
whiteStone = new QPixmap(Resource::loadPixmap( "Go-white" ));
newBlackStone = new QPixmap(Resource::loadPixmap( "Go-black-highlight" ));
smallStones = FALSE;
}
}
void GoWidget::init()
{
lastX = lastY = newX = newY = -1;
nPassed = 0;
for ( int i = 0; i < 19; i++ )
for ( int j = 0; j < 19; j++ )
board[i][j]=-1;
gameActive = TRUE;
goRestart(current_handicap);
if ( twoplayer ) {
currentPlayer = BLACK;
} else {
doComputerMove();
currentPlayer = WHITE;
}
emit showTurn( currentPlayer == WHITE ? *whiteStone : *blackStone );
}
void GoWidget::paintEvent( QPaintEvent *e )
{
int i,j;
int r = whiteStone->width()/2;
QPainter p(this);
p.fillRect( bx - d/2, by - d/2, 19*d, 19*d, *goBrush );
int xMin = QMAX( x2board(e->rect().left()), 0 );
int xMax = QMIN( x2board(e->rect().right()), 18 );
int yMin = QMAX( y2board(e->rect().top()), 0 );
int yMax = QMIN( y2board(e->rect().bottom()), 18 );
QColor pine( 255, 186, 89 );
p.setPen( pine.dark() );
for ( i = xMin; i < xMax+1 ; i ++ ) {
p.drawLine( bx+i*d, by, bx+i*d, by+18*d );
}
for ( j = yMin; j < yMax+1 ; j ++ ) {
p.drawLine( bx, by+j*d, bx+18*d, by+j*d);
}
// dots are at (3,3), (3,9), (3,15) and so on
p.setBrush( black );
for ( i = 3; i < xMax+1; i+=6 )
for ( j = 3; j < yMax+1; j+=6 )
p.drawEllipse( bx+i*d-2, by+j*d-2, 5, 5 );
for ( i = xMin; i < xMax+1; i++ )
for ( j = yMin; j < yMax+1; j++ ) {
if ( board[i][j] == WHITE ||
currentPlayer==WHITE && newX == i && newY == j )
p.drawPixmap( bx+i*d - r, by+j*d - r, *whiteStone );
else if ( i == lastX && j == lastY )
p.drawPixmap( bx+i*d - r, by+j*d - r, *newBlackStone );
else if ( board[i][j] == BLACK ||
currentPlayer==BLACK && newX == i && newY == j)
p.drawPixmap( bx+i*d - r, by+j*d - r, *blackStone );
}
}
void GoWidget::doMove( int x, int y )
{
if ( !GoPlaceStone( currentPlayer, x, y ) ) {
//printf( "Illegal move (%d,%d)\n", x, y );
return;
}
//printf( "you do (%d,%d)\n", x, y );
nPassed = 0;
if ( twoplayer )
currentPlayer = (currentPlayer==WHITE) ? BLACK : WHITE;
else
doComputerMove();
emit showTurn( currentPlayer == WHITE ? *whiteStone : *blackStone );
}
void GoWidget::pass()
{
if ( !gameActive )
return;
nPassed++;
if ( nPassed >= 2 )
endGame();
else if ( !twoplayer )
doComputerMove();
}
void GoWidget::resign()
{
if ( gameActive )
endGame();
}
void GoWidget::newGame()
{
init();
update();
}
void GoWidget::endGame()
{
gameActive = FALSE;
int w,b;
CountUp( &w, &b);
QString s = tr("White %1, Black %2. ").arg(w).arg(b);
if ( w > b )
s += tr("White wins.");
else if ( w < b )
s += tr("Black wins.");
else
s += tr("A draw.");
emit showScore( s );
}
void GoWidget::doComputerMove()
{
int ox = lastX;
int oy = lastY;
lastX = lastY = -1;
emit showTurn( *blackStone );
refresh( ox, oy);
qApp->processEvents();
short int x,y;
if ( genMove( computer_color, &x, &y ) ) {
lastX = x;
lastY = y;
//printf( "I do (%d,%d)\n", x, y );
GoPlaceStone(computer_color,x,y);
nPassed = 0;
} else {
emit showScore( tr("I pass") );
nPassed++;
if ( nPassed >= 2 )
endGame();
}
}
void GoWidget::mousePressEvent( QMouseEvent *me )
{
if ( !gameActive )
return;
int x = x2board(me->x());
int y = y2board(me->y());
showStone(x,y,currentPlayer);
}
void GoWidget::mouseMoveEvent( QMouseEvent *me )
{
if ( !gameActive )
return;
int x = x2board(me->x());
int y = y2board(me->y());
if ( x != newX || y != newY )
showStone(x,y,currentPlayer);
}
void GoWidget::showStone( int x, int y, enum bVal c )
{
if ( newX > -1 ) {
refresh( newX, newY );
newY = newX = -1;
}
if ( x < 0 || x > 18 || y < 0 || y > 18 ) {
newX = newY = -1;
return;
}
if ( board[x][y] == -1 && !Suicide( c, x, y ) ) {
newX = x;
newY = y;
refresh(x,y);
}
}
void GoWidget::mouseReleaseEvent( QMouseEvent * )
{
if ( gameActive && newX > -1 )
doMove( newX, newY );
newX = newY = -1;
}
void GoWidget::refresh( int x, int y )
{
update( bx+d*x-d/2-1, by+d*y-d/2-1, d+2, d+2 );
}
void GoWidget::removeStone(short x, short y)
{
board[x][y]=-1;
refresh( x, y );
}
void GoWidget::placeStone (enum bVal c, short x, short y )
{
board[x][y]=c;
refresh( x, y );
}
void GoWidget::reportPrisoners( int blackcnt, int whitecnt )
{
QString s = tr( "Prisoners: black %1, white %2" ).arg(blackcnt).arg(whitecnt);
emit showScore( s );
}
void GoWidget::setTwoplayer( bool b )
{
twoplayer = b;
}
void GoWidget::setHandicap( int h )
{
current_handicap = h;
}
extern "C" {
void removestone(short x, short y)
{
GoWidget::self->removeStone(x,y);
}
void placestone (enum bVal c, short x, short y )
{
GoWidget::self->placeStone(c,x,y);
}
void intrMoveReport(enum bVal c ,char *coord ,char *reason )
{
qDebug( "intrMoveReport colour %d, %s %s", c, coord, reason );
}
void intrPrisonerReport( short blackcnt, short whitecnt )
{
GoWidget::self->reportPrisoners(blackcnt,whitecnt);
}
}
diff --git a/noncore/games/go/main.cpp b/noncore/games/go/main.cpp
index f24e3c3..66f34ab 100644
--- a/noncore/games/go/main.cpp
+++ b/noncore/games/go/main.cpp
@@ -1,28 +1,27 @@
/**********************************************************************
** Copyright (C) 2000 Trolltech AS. All rights reserved.
**
** This file is part of Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include "gowidget.h"
-#include <qpe/qpeapplication.h>
#include <opie/oapplicationfactory.h>
OPIE_EXPORT_APP( OApplicationFactory<GoMainWidget> )
diff --git a/noncore/games/kbill/MCursor.cc b/noncore/games/kbill/MCursor.cc
index a3cb340..c581693 100644
--- a/noncore/games/kbill/MCursor.cc
+++ b/noncore/games/kbill/MCursor.cc
@@ -1,69 +1,64 @@
/***************************************************************************
MCursor.cc - description
-------------------
begin : Thu Dec 30 1999
copyright : (C) 1999 by Jurrien Loonstra
email : j.h.loonstra@st.hanze.nl
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "MCursor.h"
-#include "objects.h"
-#include <qcursor.h>
-#include <qbitmap.h>
-#include <qwidget.h>
-#include <qstring.h>
#ifdef KDEVER
#include <kapp.h>
#include <kstandarddirs.h>
#endif
#include <iostream>
#include <qpe/resource.h>
MCursor::~MCursor() {
delete cursor;
}
void MCursor::load(const char *name, int masked) {
#ifdef KDEVER
QString file, mfile;
KStandardDirs dirs;
file = dirs.findResource("data","kbill/bitmaps/" + QString::fromLocal8Bit(name) + ".xbm");
QBitmap bitmap, mask;
if (bitmap.load(file) == FALSE) {
std::cerr << "cannot open " << file << std::endl;
exit(1);
}
if (masked == SEP_MASK) {
// mfile.sprintf ("%sbitmaps/%s_mask.xbm", (const char*)dir, name);
mfile = file = dirs.findResource("data","kbill/bitmaps/" + QString::fromLocal8Bit(name) + "_mask.xbm");
if (mask.load(mfile) == FALSE) {
std::cerr << "cannot open " << file << std::endl;
exit(1);
}
}
else
mask = bitmap;
#endif
QBitmap bitmap, mask;
bitmap = Resource::loadBitmap("kbill/bitmaps/" + QString::fromLocal8Bit(name));
if (masked == SEP_MASK)
mask = bitmap = Resource::loadBitmap("kbill/bitmaps/" + QString::fromLocal8Bit(name) + "_mask.xbm");
else
mask = bitmap;
cursor = new QCursor(bitmap, mask, bitmap.width() / 2, bitmap.height() / 2);
}
diff --git a/noncore/games/kbill/Picture.cc b/noncore/games/kbill/Picture.cc
index fe0eff8..9d46257 100644
--- a/noncore/games/kbill/Picture.cc
+++ b/noncore/games/kbill/Picture.cc
@@ -1,72 +1,70 @@
/***************************************************************************
Picture.cc - description
-------------------
begin : Thu Dec 30 1999
copyright : (C) 1999 by Jurrien Loonstra
email : j.h.loonstra@st.hanze.nl
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "Picture.h"
-#include "objects.h"
#include <iostream>
-#include <qstring.h>
#include <qpe/resource.h>
#ifdef KDEVER
#include <kapp.h>
#include <kstandarddirs.h>
#include <kdebug.h>
#endif
void Picture::load(const char *name, int index) {
//QString dir = KApplication::kde_datadir(), file;
// QString dir = locate("data",""),file;
// dir += "/kbill/";
// if (index>=0)
// file.sprintf ("%spixmaps/%s_%d.xpm", (const char *)dir, name, index);
// else
// file.sprintf("%spixmaps/%s.xpm", (const char *)dir, name);
#ifdef KDEVER
KStandardDirs dirs;
QString file;
if (index>=0) {
//kdDebug() << "Here";
QString sindex;
sindex.setNum(index);
// kdDebug() << "kbill/pixmaps/" + QString::fromLocal8Bit(name) + "_" + sindex + ".xpm";
file = dirs.findResource("data","kbill/pixmaps/" + QString::fromLocal8Bit(name) + "_" + sindex + ".xpm");
} else {
file = dirs.findResource("data","kbill/pixmaps/" + QString::fromLocal8Bit(name) + ".xpm");
}
kdDebug() << file << std::endl;
pix = new QPixmap();
if (pix->load(file) == FALSE)
std::cerr << "cannot open " << file << std::endl;
width = pix->width();
height = pix->height();
#endif
QString sindex;
pix = new QPixmap();
sindex.setNum(index);
if (index>=0)
pix->load(Resource::findPixmap("kbill/pixmaps/" + QString::fromLocal8Bit(name) +"_"+ sindex));
else
pix->load(Resource::findPixmap("kbill/pixmaps/" + QString::fromLocal8Bit(name)));
width = pix->width();
height = pix->height();
}
QPixmap* Picture::getPixmap() {
return pix;
}
diff --git a/noncore/games/kbill/UI.cpp b/noncore/games/kbill/UI.cpp
index 2afaf9b..611cebf 100644
--- a/noncore/games/kbill/UI.cpp
+++ b/noncore/games/kbill/UI.cpp
@@ -1,175 +1,172 @@
/***************************************************************************
UI.cc - description
-------------------
begin : Thu Dec 30 1999
copyright : (C) 1999 by Jurrien Loonstra
email : j.h.loonstra@st.hanze.nl
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
-#include "kbill.h"
#include "objects.h"
#include "Strings.h"
#ifdef KDEVER
#include <kapplication.h>
#endif
-#include <qpixmap.h>
#include <qmessagebox.h>
-#include <qnamespace.h>
#include "inputbox.h"
/**************************/
/* Timer control routines */
/**************************/
UI::~UI() {
paint.end();
delete pix;
}
void UI::restart_timer() {
field->startTimer();
}
void UI::kill_timer() {
field->stopTimer();
}
/*******************/
/* Window routines */
/*******************/
void UI::initialize(int *argc, char **argv) {
#ifdef KDEVER
app = new KApplication(*argc, argv, "kbill");
#endif
app = new QPEApplication(*argc, argv);
}
void UI::graph_init() {
pix = new QPixmap(Game::scrwidth, Game::scrheight);
paint.begin(pix, field);
paint.setPen(QPen(Qt::black, 3));
}
void UI::make_mainwin() {
main = new KBill();
app->showMainWidget(main,true);
main->showMaximized();
field = main->getField();
}
void UI::popup_dialog (int dialog) {
kill_timer();
switch (dialog) {
case Game::ENDGAME:
QMessageBox::message(("Endgame"), QT_TR_NOOP(endgamestr));
break;
case Game::HIGHSCORE:
// QMessageBox::message(("HighScore"), highscorestr);
break;
case Game::ENTERNAME: {
InputBox b(main, 0, ("Enter Name"), QT_TR_NOOP(enternamestr));
bool state = b.exec() == 2;
char str[20], *nl;
strcpy(str, b.getText());
if (!str[0] || state)
strcpy(str, "Anonymous");
else if ((nl = strchr(str, '\n')))
*nl = '\0';
if (strlen(str) > 20)
str[20] = 0; /* truncate string if too long */
// scores.recalc(str);
}
break;
case Game::SCORE:
QMessageBox::message(("Score"), scorestr);
break;
}
restart_timer();
}
/*********************/
/* Graphics routines */
/*********************/
void UI::set_cursor(int cursor) {
QCursor *cur;
switch (cursor) {
case Game::BUCKETC:
cur = bucket.cursor.cursor;
break;
case Game::DOWNC:
cur = downcursor.cursor;
break;
case Game::DEFAULTC:
cur = defaultcursor.cursor;
break;
default:
cur = OS.cursor[cursor].cursor;
}
field->setCursor(*cur);
}
void UI::load_cursors() {
defaultcursor.load("hand_up", MCursor::SEP_MASK);
field->setCursor(*defaultcursor.cursor);
downcursor.load("hand_down", MCursor::SEP_MASK);
}
void UI::clear() {
paint.eraseRect(0, 0, field->width(), field->height());
}
void UI::refresh() {
paint.flush();
field->setPixmap(pix);
field->repaint(FALSE);
}
void UI::draw (Picture pict, int x, int y) {
paint.drawPixmap(x, y, *pict.pix);
}
void UI::draw_centered (Picture pict) {
draw(pict, (field->width() - pict.width) / 2, (field->height() - pict.height) / 2);
}
void UI::draw_line(int x1, int y1, int x2, int y2) {
paint.drawLine(x1, y1, x2, y2);
}
void UI::draw_str(char *str, int x, int y) {
paint.drawText(x, y, str);
}
/******************/
/* Other routines */
/******************/
void UI::set_pausebutton (int action) {
main->file->setItemEnabled(main->pauseid, action);
}
int UI::MainLoop() {
return app->exec();
}
void UI::update_hsbox(char *str) {
highscorestr = str;
}
void UI::update_scorebox(int level, int score) {
scorestr.sprintf ("%s %d:\n%s: %d", QT_TR_NOOP("After Level"), level, QT_TR_NOOP("Your score"), score);
}
diff --git a/noncore/games/kbill/field.cpp b/noncore/games/kbill/field.cpp
index a1b3560..a974ab2 100644
--- a/noncore/games/kbill/field.cpp
+++ b/noncore/games/kbill/field.cpp
@@ -1,84 +1,83 @@
/***************************************************************************
field.cpp - description
-------------------
begin : Thu Dec 30 1999
copyright : (C) 1999 by Jurrien Loonstra
email : j.h.loonstra@st.hanze.nl
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
-#include <qpainter.h>
#include "objects.h"
#include "field.h"
Field::Field(QWidget *parent, const char *name ) : QWidget(parent,name) {
setFixedSize(game.scrwidth, game.scrheight);
setBackgroundColor(white);
timer = new QTimer(this);
playing = false;
connect(timer, SIGNAL(timeout()), SLOT(Timer()));
}
Field::~Field(){
delete timer;
}
void Field::setPixmap(QPixmap *pix) {
this->pix = pix;
}
// --------------------------------------------------------
void Field::mousePressEvent(QMouseEvent *e){
game.button_press(e->x(), e->y());
}
void Field::mouseReleaseEvent(QMouseEvent *e){
game.button_release(e->x(), e->y());
}
void Field::enterEvent(QEvent *) {
if (playing && !timer->isActive()) {
playing = true;
timer->start(250, FALSE);
}
}
void Field::leaveEvent(QEvent *) {
if (timer->isActive() && playing) {
playing = true;
timer->stop();
}
}
void Field::stopTimer() {
playing = false;
if (timer->isActive())
timer->stop();
}
void Field::startTimer() {
playing = true;
if (!timer->isActive())
timer->start(250, FALSE);
}
void Field::Timer(){
game.update();
}
void Field::paintEvent(QPaintEvent *) {
bitBlt(this, 0, 0, pix);
} \ No newline at end of file
diff --git a/noncore/games/kbill/inputbox.cpp b/noncore/games/kbill/inputbox.cpp
index b191ea8..5087fbb 100644
--- a/noncore/games/kbill/inputbox.cpp
+++ b/noncore/games/kbill/inputbox.cpp
@@ -1,51 +1,50 @@
/***************************************************************************
inputbox.cpp - description
-------------------
begin : Sat Jan 1 2000
copyright : (C) 2000 by Jurrien Loonstra
email : j.h.loonstra@st.hanze.nl
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "inputbox.h"
-#include <qdialog.h>
InputBox::InputBox(QWidget *parent, const char *name, const char *caption, const char *text) : QDialog(parent, name, TRUE) {
// setCaption(caption);
//
// question = new QLabel(this);
// question->setText(text);
// question->setGeometry(10, 10, 240, 50);
//
// input = new QLineEdit(this);
// input->setGeometry(10, 60, 240, 30);
// input->setFocus();
// input->setMaxLength(19);
//
// ok = new QPushButton( "Ok", this );
// ok->setGeometry(10, 100, 100,30 );
// ok->setDefault(TRUE);
// connect( ok, SIGNAL(clicked()), SLOT(accept()) );
//
// cancel = new QPushButton( "Cancel", this );
// cancel->setGeometry(150, 100, 100,30 );
// connect( cancel, SIGNAL(clicked()), SLOT(reject()) );
}
InputBox::~InputBox(){
delete ok;
delete cancel;
delete question;
delete input;
}
QString InputBox::getText() const{
return input->text();
}
diff --git a/noncore/games/kbill/kbill.cpp b/noncore/games/kbill/kbill.cpp
index 18a6875..74d7c75 100644
--- a/noncore/games/kbill/kbill.cpp
+++ b/noncore/games/kbill/kbill.cpp
@@ -1,132 +1,128 @@
/***************************************************************************
kbill.cpp - description
-------------------
begin : Thu Dec 30 16:55:55 CET 1999
copyright : (C) 1999 by Jurrien Loonstra
email : j.h.loonstra@st.hanze.nl
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include <qmessagebox.h>
-#include <qmultilinedit.h>
#include <qmenubar.h>
#include <qtextbrowser.h>
-#include <qfont.h>
-#include <qwidget.h>
#include "kbill.h"
-#include "inputbox.h"
#include "helpdialog.h"
#include "objects.h"
#include "Strings.h"
KBill::KBill() : QMainWindow() {
setCaption(tr("kBill"));
file = new QPopupMenu();
file->insertItem(tr("New game"), this, SLOT(NewGame()));
pauseid = file->insertItem(tr("Pause game"), this, SLOT(Pause()));
//these are dissabled until I fix them
//file->insertItem(tr("Warp to level..."), this, SLOT(WarpTo()));
//file->insertItem(tr("View high scores"), this, SLOT(ViewHighScores()));
help = new QPopupMenu();
help->insertItem(tr("Story of kBill"), this, SLOT(Story()));
help->insertItem(tr("Rules"), this, SLOT(Rules()));
menu = new QMenuBar(this);
menu->insertItem(tr("&File"), file);
menu->insertSeparator();
menu->insertItem(tr("&Help"), help);
field = new Field(this);
//setView(field);
//setMainWidget(field);
//setMenu(menu);
}
KBill::~KBill() {
}
Field* KBill::getField() {
return field;
}
// -----------------------------------------------------------------------
void KBill::Quit() {
field->stopTimer();
qApp->quit();
}
void KBill::About(){
// field->stopTimer();
// AboutBox about(this);
// about.exec();
// field->startTimer();
}
void KBill::NewGame() {
field->stopTimer();
// if (KMsgBox::yesNo(this, i18n("New Game"), i18n(newgamestr), KMsgBox::QUESTION) == 1)
game.start(1);
// else
field->startTimer();
}
void KBill::Pause() {
field->stopTimer();
QMessageBox::message(tr("Pause Game"), tr(pausestr), 0);
field->startTimer();
}
void KBill::WarpTo() {
/* field->stopTimer();
InputBox b(this, 0, "Warp To Level", tr(warpstr));
bool status = b.exec() == 1;
field->startTimer();
if (status) {
bool ok;
int level = b.getText().toUInt(&ok);
if (ok) {
field->startTimer();
game.warp_to_level(level);
return;
}
}*/
}
void KBill::ViewHighScores() {
//ui.popup_dialog(Game::HIGHSCORE);
}
void KBill::Story() {
field->stopTimer();
HelpDialog *stryDialog = new HelpDialog(this,"helpdialog",1);
QString stryString = tr("<b>The Story</b><p>Yet again, the fate of the world rests in your hands! An evil computer hacker, known only by his handle 'Bill', has created the ultimate computer virus. A virus so powerful that it has the power to transmute an ordinary computer into a toaster oven. (oooh!) 'Bill' has cloned himself into a billion-jillion micro-Bills. Their sole purpose is to deliver the nefarious virus, which has been cleverly disguised as a popular operating system. As System Administrator and Exterminator, your job is to keep Bill from succeeding at his task.");
stryDialog->setCaption(tr("The story of KBill"));
stryDialog->TextBrowser1->setText(stryString);
stryDialog->resize(200,200);
stryDialog->show();
field->startTimer();
}
void KBill::Rules() {
field->stopTimer();
HelpDialog *rulesDialog = new HelpDialog(this,"helpdialog",1);
rulesDialog->setCaption(tr("The rules of KBill"));
QString rulesStr = tr("<b>The Rules</b><p>kBill has been painstakingly designed and researched in order to make it as easy to use for the whole family as it is for little Sally. Years - nay - days of beta testing and consulting with the cheapest of human interface designers have resulted in a game that is easy to use, yet nothing at all like a Macintosh.<p><UL><LI>Whack the Bills (click)</LI><LI>Restart the computer (click)</LI><LI>Pick up stolen OSes & return (drag) them to their respective computers</LI><LI>Drag the bucket to extinguish sparks</LI><LI>Scoring is based on total uptime, with bonuses for killing Bills.</LI></UL><P>As for the rest, you can probably work it out for yourself. We did, so it can't be too hard");
rulesDialog->TextBrowser1->setText(rulesStr);
rulesDialog->resize(200,200);
rulesDialog->show();
field->startTimer();
}
diff --git a/noncore/games/kcheckers/kcheckers.cpp b/noncore/games/kcheckers/kcheckers.cpp
index 2eb37e5..a27dd18 100644
--- a/noncore/games/kcheckers/kcheckers.cpp
+++ b/noncore/games/kcheckers/kcheckers.cpp
@@ -1,587 +1,586 @@
#include <qimage.h>
-#include <qframe.h>
#include <qlayout.h>
#include <qmenubar.h>
#include <qtoolbar.h>
#include <qpe/config.h>
#include <qwhatsthis.h>
#include <qtoolbutton.h>
#include <qmessagebox.h>
#include <qapplication.h>
#include "kcheckers.h"
#include "echeckers.h"
#include "rcheckers.h"
#include "pics/logo.xpm"
#include "pics/undo.xpm"
#include "pics/exit.xpm"
#include "pics/help.xpm"
#include "pics/wood1.xpm"
#include "pics/wood2.xpm"
#include "pics/wood3.xpm"
#include "pics/green1.xpm"
#include "pics/green2.xpm"
#include "pics/green3.xpm"
#include "pics/marble1.xpm"
#include "pics/marble2.xpm"
#include "pics/marble3.xpm"
#include "pics/biglogo.xpm"
#include "pics/man_black.xpm"
#include "pics/man_white.xpm"
#include "pics/king_black.xpm"
#include "pics/king_white.xpm"
#include "pics/contexthelp.xpm"
QString KCheckers::enNumeration="1 2 3 4 5 6 7 8 9 1011121314151617181920212223242526272829303132";
QString KCheckers::ruNumeration="B8D8F8H8A7C7E7G7B6D6F6H6A5C5E5G5B4D4F4H4A3C3E3G3B2D2F2H2A1C1E1G1";
const int KCheckers::t[]={6,7,8,9,11,12,13,14,17,18,19,20,22,23,
24,25,28,29,30,31,33,34,35,36,39,40,41,42,44,45,46,47};
KCheckers::KCheckers(QWidget *p, const char* n, WFlags )
:QMainWindow(p,n,WStyle_DialogBorder)
{
setCaption(tr("KCheckers") );
setIcon(QPixmap(biglogo_xpm));
setToolBarsMovable(false);
// Make a menubar
gameMenu=new QPopupMenu;
CHECK_PTR(gameMenu);
gameMenu->insertItem(QPixmap(logo_xpm),tr("&New"),this,SLOT(newGame()),CTRL+Key_N);
gameMenu->insertSeparator();
undoID=gameMenu->insertItem(QPixmap(undo_xpm),tr("&Undo Move"),this,SLOT(undoMove()),CTRL+Key_Z);
gameMenu->insertSeparator();
gameMenu->insertItem(QPixmap(exit_xpm),tr("&Quit"),qApp,SLOT(closeAllWindows()),CTRL+Key_Q);
skillMenu=new QPopupMenu;
CHECK_PTR(skillMenu);
skillMenu->insertItem(tr("&Beginner"),this,SLOT(setSkillBeginner()),CTRL+Key_1,BEGINNER);
skillMenu->insertItem(tr("&Novice"), this,SLOT(setSkillNovice()), CTRL+Key_2,NOVICE);
skillMenu->insertItem(tr("&Average"), this,SLOT(setSkillAverage()), CTRL+Key_3,AVERAGE);
skillMenu->insertItem(tr("&Good"), this,SLOT(setSkillGood()), CTRL+Key_4,GOOD);
skillMenu->insertItem(tr("&Expert"), this,SLOT(setSkillExpert()), CTRL+Key_5,EXPERT);
skillMenu->insertItem(tr("&Master"), this,SLOT(setSkillMaster()), CTRL+Key_6,MASTER);
optionsMenu=new QPopupMenu;
CHECK_PTR(optionsMenu);
numID=optionsMenu->insertItem(tr("&Show Numeration"),this,SLOT(showNumeration()));
optionsMenu->insertSeparator();
optionsMenu->insertItem(tr("&English Rules"),this,SLOT(setRulesEnglish()),0,ENGLISH);
optionsMenu->insertItem(tr("&Russian Rules"),this,SLOT(setRulesRussian()),0,RUSSIAN);
optionsMenu->insertSeparator();
optionsMenu->insertItem(tr("&Green Board"), this,SLOT(setPatternGreen()), 0,GREEN);
optionsMenu->insertItem(tr("&Marble Board"),this,SLOT(setPatternMarble()),0,MARBLE);
optionsMenu->insertItem(tr("&Wooden Board"),this,SLOT(setPatternWooden()),0,WOODEN);
QPopupMenu* helpMenu=new QPopupMenu;
CHECK_PTR(helpMenu);
helpMenu->insertItem(QPixmap(contexthelp_xpm),tr("What's This"),this,SLOT(whatsThis()),SHIFT+Key_F1);
helpMenu->insertItem(QPixmap(help_xpm),tr("&Rules of Play"),this,SLOT(help()),Key_F1);
helpMenu->insertSeparator();
helpMenu->insertItem(QPixmap(logo_xpm),tr("&About KCheckers"),this,SLOT(about()));
helpMenu->insertItem(tr("About &Qt"),this,SLOT(aboutQt()));
QToolBar* menuToolBar=new QToolBar(this);
CHECK_PTR(menuToolBar);
QMenuBar* menuBar=new QMenuBar(menuToolBar);
CHECK_PTR(menuBar);
menuBar->insertItem(tr("&Game"), gameMenu);
menuBar->insertItem(tr("&Skill"), skillMenu);
menuBar->insertItem(tr("&Options"),optionsMenu);
menuBar->insertItem(tr("&Help"), helpMenu);
// Restore a settings
readConfig();
skillMenu->setItemChecked(skill,true);
optionsMenu->setItemChecked(rules,true);
optionsMenu->setItemChecked(numID,false);
// Make a toolbar
QToolBar* emptyToolBar=new QToolBar(this);
emptyToolBar->setHorizontalStretchable(true);
QToolBar* toolBar=new QToolBar(this);
CHECK_PTR(toolBar);
QSize buttonSize(24,24);
QToolButton* gameButton=new QToolButton(QPixmap(logo_xpm),tr(" New Game ") ,"",this,SLOT(newGame()),toolBar);
CHECK_PTR(gameButton);
gameButton->setMinimumSize(buttonSize);
undoButton=new QToolButton(QPixmap(undo_xpm),tr(" Undo Move "),"",this,SLOT(undoMove()),toolBar);
CHECK_PTR(undoButton);
undoButton->setMinimumSize(buttonSize);
QToolButton* helpButton=new QToolButton(QPixmap(help_xpm),tr(" Rules of Play "),"",this,SLOT(help()),toolBar);
CHECK_PTR(helpButton);
helpButton->setMinimumSize(buttonSize);
// Make a checkers board
imageMan1=new QImage(man_black_xpm); CHECK_PTR(imageMan1);
imageMan2=new QImage(man_white_xpm); CHECK_PTR(imageMan2);
imageKing1=new QImage(king_black_xpm); CHECK_PTR(imageKing1);
imageKing2=new QImage(king_white_xpm); CHECK_PTR(imageKing2);
imageWood1=new QImage(wood1_xpm); CHECK_PTR(imageWood1);
imageWood2=new QImage(wood2_xpm); CHECK_PTR(imageWood2);
imageWood3=new QImage(wood3_xpm); CHECK_PTR(imageWood3);
imageGreen1=new QImage(green1_xpm); CHECK_PTR(imageGreen1);
imageGreen2=new QImage(green2_xpm); CHECK_PTR(imageGreen2);
imageGreen3=new QImage(green3_xpm); CHECK_PTR(imageGreen3);
imageMarble1=new QImage(marble1_xpm); CHECK_PTR(imageMarble1);
imageMarble2=new QImage(marble2_xpm); CHECK_PTR(imageMarble2);
imageMarble3=new QImage(marble3_xpm); CHECK_PTR(imageMarble3);
QWidget* centralWidget=new QWidget(this);
setCentralWidget(centralWidget);
QFrame* frame=new QFrame(centralWidget);
CHECK_PTR(frame);
frame->setFrameStyle(QFrame::Box|QFrame::Plain);
frame->setFixedSize(SIZE*8+2,SIZE*8+2);
statusLabel = new QLabel(centralWidget);
statusLabel->setAlignment(Qt::AlignHCenter);
QVBoxLayout* vlayout=new QVBoxLayout(centralWidget);
vlayout->addStretch();
vlayout->addWidget(frame);
vlayout->addStretch();
vlayout->addWidget(statusLabel);
vlayout->addStretch();
for(int i=0;i<64;i++)
{
field[i]=new Field(frame,i);
CHECK_PTR(field[i]);
}
QGridLayout* grid=new QGridLayout(frame,8,8,1,0);
CHECK_PTR(grid);
for(int i=0;i<4;i++)
{
for(int k=0;k<4;k++)
{
grid->addWidget(field[i*8+k+32],i*2, k*2 );
grid->addWidget(field[i*8+k ],i*2, k*2+1);
grid->addWidget(field[i*8+k+4 ],i*2+1,k*2 );
grid->addWidget(field[i*8+k+36],i*2+1,k*2+1);
}
}
for(int i=0;i<32;i++)
connect(field[i],SIGNAL(click(int)),this,SLOT(click(int)));
selected=false;
setPattern(pattern);
QWhatsThis::add(frame,"A checkers board");
userFirst=false;
game=NULL;
newGame();
}
void KCheckers::readConfig()
{
Config config("KCheckers");
config.setGroup("KCheckers");
QString entry;
entry=config.readEntry("skill","novice");
if(entry=="beginner") skill=BEGINNER;
else if(entry=="average") skill=AVERAGE;
else if(entry=="good") skill=GOOD;
else if(entry=="expert") skill=EXPERT;
else if(entry=="master") skill=MASTER;
else skill=NOVICE;
entry=config.readEntry("rules","english");
if(entry=="russian") rules=RUSSIAN;
else rules=ENGLISH;
entry=config.readEntry("theme","wooden");
if(entry=="green") pattern=GREEN;
else if(entry=="marble") pattern=MARBLE;
else pattern=WOODEN;
}
void KCheckers::closeEvent(QCloseEvent* event)
{
Config config("KCheckers");
config.setGroup("KCheckers");
QString entry;
if(skill==BEGINNER) entry="beginner";
if(skill==NOVICE) entry="novice";
if(skill==AVERAGE) entry="average";
if(skill==GOOD) entry="good";
if(skill==EXPERT) entry="expert";
if(skill==MASTER) entry="master";
config.writeEntry("skill",entry);
if(rules==ENGLISH) entry="english";
if(rules==RUSSIAN) entry="russian";
config.writeEntry("rules",entry);
if(pattern==GREEN) entry="green";
if(pattern==MARBLE) entry="marble";
if(pattern==WOODEN) entry="wooden";
config.writeEntry("theme",entry);
event->accept();
}
void KCheckers::setSkill(int set)
{
skillMenu->setItemChecked(skill,false);
skill=set;
skillMenu->setItemChecked(skill,true);
game->setLevel(skill);
}
void KCheckers::setRules(int set)
{
optionsMenu->setItemChecked(rules,false);
rules=set;
optionsMenu->setItemChecked(rules,true);
colorChange();
newGame();
}
void KCheckers::setPattern(int set)
{
optionsMenu->setItemChecked(pattern,false);
pattern=set;
optionsMenu->setItemChecked(pattern,true);
switch(pattern)
{
case GREEN:
imagePat1=imageGreen1;
imagePat2=imageGreen2;
imageFrame=imageGreen3;
break;
case MARBLE:
imagePat1=imageMarble1;
imagePat2=imageMarble2;
imageFrame=imageMarble3;
break;
case WOODEN:
imagePat1=imageWood1;
imagePat2=imageWood2;
imageFrame=imageWood3;
}
for(int i=0; i<32;i++) field[i]->setPattern(imagePat2);
for(int i=32;i<64;i++) field[i]->setPattern(imagePat1);
if(selected) field[from]->setFrame(imageFrame);
}
void KCheckers::showNumeration()
{
if(optionsMenu->isItemChecked(numID))
{
optionsMenu->setItemChecked(numID,false);
for(int i=0;i<32;i++) field[i]->setLabel("");
}
else
{
optionsMenu->setItemChecked(numID,true);
drawNumeration();
}
}
void KCheckers::drawNumeration()
{
if(rules==ENGLISH)
{
if(userFirst)
for(int i=0;i<32;i++)
field[i]->setLabel(enNumeration.mid(i*2,2));
else
for(int i=0;i<32;i++)
field[i]->setLabel(enNumeration.mid(62-i*2,2));
}
else
{
if(userFirst)
for(int i=0;i<32;i++)
field[i]->setLabel(ruNumeration.mid(i*2,2));
else
for(int i=0;i<32;i++)
field[i]->setLabel(ruNumeration.mid(62-i*2,2));
}
}
void KCheckers::drawBoard(int i)
{
switch(game->board[t[i]])
{
case MAN1:
field[i]->setPicture(imageMan1);
break;
case MAN2:
field[i]->setPicture(imageMan2);
break;
case KING1:
field[i]->setPicture(imageKing1);
break;
case KING2:
field[i]->setPicture(imageKing2);
break;
default:
field[i]->setPicture(NULL);
}
}
void KCheckers::help()
{
QMessageBox::information(this,"Rules of Play",
"In the beginning of game you have\n"
"12 checkers (men).\n"
"The men move forward only.\n"
"The men can capture:\n"
"- by jumping forward only (english\n"
" rules);\n"
"- by jumping forward or backward\n"
" (russian rules).\n"
"A man which reaches the far side of\n"
"the board becomes a king.\n"
"The kings move forward or\n"
"backward:\n"
"- to one square only (english rules);\n"
"- to any number of squares (russian\n"
" rules).\n"
"The kings capture by jumping\n"
"forward or backward.\n"
"Whenever a player is able to make a\n"
"capture he must do so.",
QMessageBox::Ok|QMessageBox::Default);
}
void KCheckers::about()
{
QMessageBox::about(this,"About KCheckers",
"KCheckers, a board game. Ver 0.3\n"
"(C) 2002, A. Peredri <andi@ukr.net>\n\n"
"http://kcheckers.tuxfamily.org\n\n"
"Contributors:\n"
"S. Rosen <srosen@erols.com>\n\n"
"Qtopia version: S.Prud'homme\n"
"<prudhomme@laposte.net>\n\n"
"This program is distributed under the\n"
"terms of the GNU General Public\n"
"License.");
}
void KCheckers::aboutQt()
{
QMessageBox::aboutQt(this);
}
void KCheckers::newGame()
{
if(game) delete game;
switch(rules)
{
case ENGLISH:
game=new ECheckers(skill);
CHECK_PTR(game);
break;
case RUSSIAN:
game=new RCheckers(skill);
CHECK_PTR(game);
}
unselect();
gameOver=false;
gameMenu->setItemEnabled(undoID,false);
undoButton->setEnabled(false);
colorChange();
for(int i=0;i<32;i++) drawBoard(i);
if(optionsMenu->isItemChecked(numID)) drawNumeration();
if(!userFirst) compGo();
statusLabel->setText(tr("Go!"));
}
// Undo the last computer and user moves
void KCheckers::undoMove()
{
for(int i=0;i<32;i++)
{
game->board[t[i]]=undoBoard[i];
drawBoard(i);
}
unselect();
gameOver=false;
gameMenu->setItemEnabled(undoID,false);
undoButton->setEnabled(false);
statusLabel->setText(tr("Go!"));
}
void KCheckers::colorChange()
{
userFirst=!userFirst;
QImage* image;
image=imageMan1;
imageMan1=imageMan2;
imageMan2=image;
image=imageKing1;
imageKing1=imageKing2;
imageKing2=image;
}
void KCheckers::unselect()
{
if(selected) field[from]->setFrame(NULL);
selected=false;
}
void KCheckers::click(int fieldNumber)
{
if(gameOver) return;
switch(game->board[t[fieldNumber]])
{
case MAN1:
case KING1:
// User selected
if(!selected)
{
from=fieldNumber;
selected=true;
field[fieldNumber]->setFrame(imageFrame);
return;
}
// User reselected
else
{
field[from]->setFrame(NULL);
from=fieldNumber;
field[fieldNumber]->setFrame(imageFrame);
return;
}
case FREE:
if(!selected) return;
if(!userGo(fieldNumber)) return;
unselect();
if(!(game->checkMove2() || game->checkCapture2()))
{
gameOver=true;
statusLabel->setText(tr("Congratulation! You have won!"));
return;
}
statusLabel->setText(tr("Please wait..."));
qApp->processEvents();
compGo();
if(!(game->checkMove1() || game->checkCapture1()))
{
gameOver=true;
statusLabel->setText(tr("You have lost. Game over."));
return;
}
statusLabel->setText(tr("Go!"));
}
}
void KCheckers::compGo()
{
int save[32];
for(int i=0;i<32;i++) save[i]=game->board[t[i]];
game->go2();
for(int i=0;i<32;i++)
{
if(game->board[t[i]]==save[i]) continue;
drawBoard(i);
}
}
bool KCheckers::userGo(int to)
{
int save[32];
for(int i=0;i<32;i++) save[i]=game->board[t[i]];
if(!game->go1(t[from],t[to]))
{
statusLabel->setText(tr("Incorrect course."));
return false;
}
for(int i=0;i<32;i++) undoBoard[i]=save[i];
gameMenu->setItemEnabled(undoID,true);
undoButton->setEnabled(true);
for(int i=0;i<32;i++)
{
if(game->board[t[i]]==save[i]) continue;
drawBoard(i);
}
return true;
}
diff --git a/noncore/games/kcheckers/main.cpp b/noncore/games/kcheckers/main.cpp
index 6ac570a..e22dbcc 100644
--- a/noncore/games/kcheckers/main.cpp
+++ b/noncore/games/kcheckers/main.cpp
@@ -1,10 +1,8 @@
-#include <qpe/qpeapplication.h>
-#include <qfont.h>
#include "kcheckers.h"
#include <opie/oapplicationfactory.h>
OPIE_EXPORT_APP( OApplicationFactory<KCheckers> )
diff --git a/noncore/games/kpacman/board.cpp b/noncore/games/kpacman/board.cpp
index f95f699..f82b5f9 100644
--- a/noncore/games/kpacman/board.cpp
+++ b/noncore/games/kpacman/board.cpp
@@ -1,425 +1,422 @@
-#include "portable.h"
#if defined( KDE2_PORT )
#include <kapp.h>
#include <klocale.h>
#endif
-#include <qrect.h>
-#include <qregexp.h>
#include <qmessagebox.h>
#include <qfile.h>
#include <qtextstream.h>
#include "board.h"
#include "bitmaps.h"
Board::Board(int size) : QArray<int> (size)
{
sz = size; // set size of board
map = "";
mapName = ""; // no map loaded so far
init(None); // initialize varibales
}
void Board::init(Image image, QString levelName)
{
prisonEntry = OUT;
prisonExit = OUT;
fruitHome = OUT;
fruitPosition = OUT;
pacmanHome = OUT;
pacmanPosition = OUT;
for (int m = 0; m < 8; m++) {
monsterHome[m] = OUT;
monsterPosition[m] = OUT;
}
for (int e = 0; e < 8; e++) {
energizerPosition[e] = OUT;
}
for (int e = 0; e < 8; e++) {
tunnelPosition[e] = OUT;
}
fill(0);
numPoints = 0;
numEnergizers = 0;
numMonsters = 0;
numTunnels = 0;
if (!levelName.isNull() && !levelName.isEmpty())
if (mapName == levelName)
image = File;
else {
QFile levelFile(levelName);
if (!levelFile.open(IO_ReadOnly)) {
QString msg = "The levelmap could not be constructed.\n\n"
"The file '@LEVELNAME@' does not exist,\n"
"or could not be opened for reading.";
msg.replace(QRegExp("@LEVELNAME@"), levelName);
// QMessageBox::information(0, tr("Initialization Error"), msg);
printf("%s\n", msg.data());
} else {
map.fill(' ', BoardHeight*BoardWidth);
int height = 0;
QTextStream levelStream(&levelFile);
while (!levelStream.eof() && height < BoardHeight) {
QString line = levelStream.readLine();
if (line.find(QRegExp("^ *;")) == -1) {
line.replace(QRegExp(";.*"), ""); // strip off comments
line.replace(QRegExp("\" *$"), ""); // strip off trailing "
line.replace(QRegExp("^ *\""), ""); // strip off leading "
map.replace(height*BoardWidth,
(line.length() > BoardWidth) ? BoardWidth : line.length(),
line.data());
height++;
}
}
mapName = levelName;
levelFile.close();
image = File;
}
}
switch (image) {
case Intro : // setup(demo_bits);
break;
case Demo : setup(demo_bits);
break;
case Level : setup(demo_bits);
break;
case File : setup((uchar *) map.data());
break;
default : break;
}
}
void Board::setup(const uchar *buf)
{
for ( int index = 0; buf[index] != 0 && index < BoardWidth*BoardHeight; index++ ) {
switch (buf[index]) {
case '*' : set(index, brick); break;
case '+' : set(index, out); break;
case '#' : set(index, prison); break;
case '-' : set(index, gate); break;
case 'E' : set(index, tunnel); break;
case '.' : set(index, Point); break;
case 'o' : set(index, energizer); break;
case 'I' : set(index, prisonentry); break;
case 'O' : set(index, prisonexit); break;
case 'F' : set(index, fruithome); break;
case 'P' : set(index, pacmanhome); break;
default : if (buf[index] >= '0' && buf[index] <= '7') {
set(index, monsterhome, buf[index]-(uchar)'0');
}
}
}
}
bool Board::inBounds(int pos)
{
return ( pos < 0 || pos > sz-1 ? FALSE : TRUE);
}
void Board::set(int pos, Square sq, int m)
{
if (inBounds(pos))
switch (sq) {
case out : at(pos) = OUT; break;
case Point : at(pos) |= pointBit; numPoints++; break;
case tunnel : at(pos) = sq;
for (int e = 0; e < numTunnels; e++) { // if tunnel is already on board
if (tunnelPosition[e] == pos) // don't do it again.
pos = OUT;
}
if (pos != OUT) {
tunnelPosition[numTunnels] = pos;
numTunnels++;
}
break;
case energizer : at(pos) |= energizerBit;
for (int e = 0; e < numEnergizers; e++) {
if (energizerPosition[e] == pos)
pos = OUT;
}
if (pos != OUT) {
energizerPosition[numEnergizers] = pos;
numEnergizers++;
}
break;
case fruit : at(pos) |= fruitBit; fruitPosition = pos; break;
case pacman : at(pos) |= pacmanBit; pacmanPosition = pos; break;
case monster : at(pos) |= (monsterBit << m);
monsterPosition[m] = pos; break;
case prisonentry : prisonEntry = pos; at(pos) = empty; break;
case prisonexit : prisonExit = pos; at(pos) = empty; break;
case fruithome : fruitHome = pos; at(pos) = empty; break;
case pacmanhome : pacmanHome = pos; at(pos) = empty; break;
case monsterhome : monsterHome[m] = pos; at(pos) = empty;
if (m == 0 && prisonExit == OUT)
prisonExit = pos;
if (m == 1 && prisonEntry == OUT)
prisonEntry = pos;
numMonsters++;
break;
default : at(pos) = sq;
}
}
void Board::reset(int pos, Square sq, int m)
{
bool found = FALSE;
if (inBounds(pos))
switch (sq) {
case out : at(pos) = empty; break;
case Point : at(pos) &= ~ pointBit; numPoints--; break;
case energizer : at(pos) &= ~ energizerBit;
for (int e = 0; e < numEnergizers; e++) { // delete the position of the eaten
if (found) // energizer in the position array
energizerPosition[e-1] = energizerPosition[e];
if (energizerPosition[e] == pos)
found = TRUE;
}
energizerPosition[numEnergizers--] = OUT;
break;
case fruit : at(pos) &= ~ fruitBit; fruitPosition = OUT; break;
case pacman : at(pos) &= ~ pacmanBit; pacmanPosition = OUT; break;
case monster : at(pos) &= ~ (monsterBit << m);
monsterPosition[m] = OUT; break;
default : at(pos) = at(pos) & varBits;
}
}
int Board::position(Square sq, int m)
{
switch(sq) {
case prisonentry : return prisonEntry;
case prisonexit : return prisonExit;
case fruit : return fruitPosition;
case fruithome : return fruitHome;
case pacman : return pacmanPosition;
case pacmanhome : return pacmanHome;
case monster : return monsterPosition[m];
case monsterhome : return monsterHome[m];
case energizer : return energizerPosition[m];
case tunnel : return tunnelPosition[m];
default : return OUT;
}
}
bool Board::isOut(int pos)
{
if (inBounds(pos))
return (at(pos) == OUT ? TRUE : FALSE);
return TRUE;
}
bool Board::isEmpty(int pos)
{
if (inBounds(pos))
return ((at(pos) & fixBits) == empty ? TRUE : FALSE);
return TRUE;
}
bool Board::isBrick(int pos)
{
if (inBounds(pos))
return ((at(pos) & fixBits) == brick ? TRUE : FALSE);
return FALSE;
}
bool Board::isPrison(int pos)
{
if (inBounds(pos))
return ((at(pos) & fixBits) == prison ? TRUE : FALSE);
return FALSE;
}
bool Board::isGate(int pos)
{
if (inBounds(pos))
return ((at(pos) & fixBits) == gate ? TRUE : FALSE);
return FALSE;
}
bool Board::isTunnel(int pos)
{
if (inBounds(pos))
return ((at(pos) & fixBits) == tunnel ? TRUE : FALSE);
return FALSE;
}
bool Board::isPoint(int pos)
{
if (inBounds(pos) && at(pos) != OUT)
return ((at(pos) & pointBit) != 0 ? TRUE : FALSE);
return FALSE;
}
bool Board::isEnergizer(int pos)
{
if (inBounds(pos) && at(pos) != OUT)
return ((at(pos) & energizerBit) != 0 ? TRUE : FALSE);
return FALSE;
}
bool Board::isFruit(int pos)
{
if (inBounds(pos) && at(pos) != OUT)
return ((at(pos) & fruitBit) != 0 ? TRUE : FALSE);
return FALSE;
}
bool Board::isPacman(int pos)
{
if (inBounds(pos) && at(pos) != OUT)
return ((at(pos) & pacmanBit) != 0 ? TRUE : FALSE);
return FALSE;
}
bool Board::isMonster(int pos)
{
if (inBounds(pos) && at(pos) != OUT)
return ((at(pos) & monsterBits) != 0 ? TRUE : FALSE);
return FALSE;
}
bool Board::isWay(int pos, int dir, Square sq) {
int p1 = move(pos, dir, 2);
if (p1 == OUT)
return (sq == out ? TRUE : FALSE);
int p2, p3;
if (dir == N || dir == S) {
p2 = move(p1, E);
p3 = move(p1, W);
} else {
p2 = move(p1, N);
p3 = move(p1, S);
}
switch (sq) {
case out : return isOut(p1) | isOut(p2) | isOut(p3);
case empty : return isEmpty(p1) & isEmpty(p2) & isEmpty(p3);
case brick : return isBrick(p1) | isBrick(p2) | isBrick(p3);
case prison : return isPrison(p1) | isPrison(p2) | isPrison(p3);
case gate : return isGate(p1) & isGate(p2) & isGate(p3);
case tunnel : return isTunnel(p1) &
(isTunnel(p2) || isEmpty(p2)) &
(isTunnel(p3) || isEmpty(p3));
default : return FALSE;
}
}
bool Board::isJump(int pos, int dir) {
switch (dir) {
case NW: return pos < BoardWidth || x(pos) == 0;
case N: return pos < BoardWidth;
case NE: return pos < BoardWidth || x(pos) == BoardWidth-1;
case W: return x(pos) == 0;
case E: return x(pos) == BoardWidth-1;
case SW: return pos >= sz-BoardWidth || x(pos) == 0;
case S: return pos >= sz-BoardWidth;
case SE: return pos >= sz-BoardWidth || x(pos) == BoardWidth-1;
}
return FALSE;
}
int Board::move(int pos, int dir, int steps)
{
if (steps < 0) { // move backwards
dir = turn(dir); // turn around and do your steps
steps *= -1;
}
while (steps-- != 0) { // until all steps are gone
switch (dir) {
case NW: pos = pos >= BoardWidth && x(pos) > 0 ? (pos-BoardWidth)-1 : sz-1;
break;
case N: pos = pos >= BoardWidth ? pos-BoardWidth : (sz-BoardWidth)+x(pos);
break;
case NE: pos = pos >= BoardWidth && x(pos) < BoardWidth-1 ?
(pos-BoardWidth)+1 : sz-BoardWidth;
break;
case W: pos = x(pos) > 0 ? pos-1 : pos+(BoardWidth-1);
break;
case E: pos = x(pos) < BoardWidth-1 ? pos+1 : pos-(BoardWidth-1);
break;
case SW: pos = pos < sz-BoardWidth && x(pos) > 0 ? (pos+BoardWidth)-1 : BoardWidth-1;
break;
case S: pos = pos < sz-BoardWidth ? pos+BoardWidth : x(pos);
break;
case SE: pos = pos < sz-BoardWidth && x(pos) < BoardWidth-1 ? (pos+BoardWidth)+1 : 0;
break;
}
}
return pos; // here we are
}
int Board::closeup(int pos, int dir, int target)
{
if (dir == N || dir == S) {
if (x(target) < x(pos))
return W;
if (x(target) > x(pos))
return E;
} else {
if (y(target) < y(pos))
return N;
if (y(target) > y(pos))
return S;
}
return dir;
}
int Board::x(int pos)
{
return pos % BoardWidth;
}
int Board::y(int pos)
{
return pos/BoardWidth;
}
int Board::turn(int dir)
{
switch (dir) {
case N : return S;
case NE : return SW;
case E : return W;
case SE : return NW;
case S : return N;
case SW : return NE;
case W : return E;
case NW : return SE;
default : return dir;
}
}
int Board::points()
{
return numPoints;
}
int Board::energizers()
{
return numEnergizers;
}
int Board::monsters()
{
return numMonsters;
}
int Board::tunnels()
{
return numTunnels;
}
diff --git a/noncore/games/kpacman/keys.cpp b/noncore/games/kpacman/keys.cpp
index 07ce135..5200bc2 100644
--- a/noncore/games/kpacman/keys.cpp
+++ b/noncore/games/kpacman/keys.cpp
@@ -1,205 +1,200 @@
#include "portable.h"
#if defined( KDE2_PORT )
#include <kapp.h>
#include <kconfig.h>
#include <klocale.h>
#include <kstddirs.h>
#include <kaccel.h>
#include <keys.h>
#include <keys.moc>
#elif defined( QPE_PORT )
#include <qaccel.h>
#include <qpe/qpeapplication.h>
#include <qpe/config.h>
#include "keys.h"
#endif
#include <qpushbt.h>
-#include <qlabel.h>
-#include <qframe.h>
-#include <qkeycode.h>
-#include <qpixmap.h>
-#include <qstring.h>
Keys::Keys( QWidget *parent, const char *name)
: QDialog( parent, name, TRUE )
{
//KStandardDirs *dirs = KGlobal::dirs();
QPushButton *okButton = new QPushButton(this);
okButton->setText(tr("Ok"));
okButton->setFixedSize(okButton->size());
connect( okButton, SIGNAL(clicked()),this, SLOT(ok()) );
okButton->move(20,210);
QPushButton *defaultButton = new QPushButton(this);
defaultButton->setText(tr("Defaults"));
defaultButton->setFixedSize(defaultButton->size());
connect( defaultButton, SIGNAL(clicked()),this, SLOT(defaults()) );
defaultButton->move(140,210);
QPushButton *cancelButton = new QPushButton(this);
cancelButton->setText(tr("Cancel"));
cancelButton->setFixedSize(cancelButton->size());
connect( cancelButton, SIGNAL(clicked()),this, SLOT(reject()) );
cancelButton->move(260,210);
QFrame *separator = new QFrame(this);
separator->setFrameStyle( QFrame::HLine | QFrame::Sunken );
separator->setGeometry( 20, 190, 340, 4 );
for ( int x = 0; x < 4; x++) {
QLabel *l = new QLabel(this);
l->setAlignment(AlignCenter);
labels[x] = l;
}
labels[0]->setGeometry(120, 20, 140, 20 );
labels[1]->setGeometry(120,160, 140, 20 );
labels[2]->setGeometry( 20, 92, 100, 20 );
labels[3]->setGeometry(265, 92, 100, 20 );
QString pixPath;
QPushButton *up = new QPushButton(this);
pixPath = FIND_APP_DATA( "pics/up.xpm" );
up->setPixmap( QPixmap(pixPath));
up->setFixedSize(up->pixmap()->size());
connect( up, SIGNAL(clicked()),this, SLOT(butUp()) );
up->move(180, 50);
QPushButton *down = new QPushButton(this);
pixPath = FIND_APP_DATA( "pics/down.xpm");
down->setPixmap( QPixmap(pixPath));
down->setFixedSize(down->pixmap()->size());
connect( down, SIGNAL(clicked()),this, SLOT(butDown()) );
down->move(180, 130);
QPushButton *left = new QPushButton(this);
pixPath = FIND_APP_DATA( "pics/left.xpm");
left->setPixmap( QPixmap(pixPath));
left->setFixedSize(left->pixmap()->size());
connect( left, SIGNAL(clicked()),this, SLOT(butLeft()) );
left->move(140, 90);
QPushButton *right = new QPushButton(this);
pixPath = FIND_APP_DATA( "pics/right.xpm");
right->setPixmap( QPixmap(pixPath));
right->setFixedSize(right->pixmap()->size());
connect( right, SIGNAL(clicked()),this, SLOT(butRight()) );
right->move(220, 90);
setCaption(tr("Change Direction Keys"));
setFixedSize(380, 260);
lab = 0;
init();
}
void Keys::keyPressEvent( QKeyEvent *e )
{
uint kCode = e->key() & ~(SHIFT | CTRL | ALT);
QString string = KAccel::keyToString(kCode);
if (lab != 0) {
if ( string.isNull() )
lab->setText(tr("Undefined key"));
else
lab->setText(string);
}
else if ( lab == 0 && e->key() == Key_Escape)
reject();
}
void Keys::butUp()
{
getKey(0);
}
void Keys::butDown()
{
getKey(1);
}
void Keys::butLeft()
{
getKey(2);
}
void Keys::butRight()
{
getKey(3);
}
void Keys::getKey(int i)
{
if ( lab != 0)
focusOut(lab);
focusIn(labels[i]);
}
void Keys::focusOut(QLabel *l)
{
l->setFrameStyle( QFrame::NoFrame );
l->setBackgroundColor(backgroundColor());
l->repaint();
}
void Keys::focusIn(QLabel *l)
{
lab = l;
lab->setFrameStyle( QFrame::Panel | QFrame::Sunken );
lab->setBackgroundColor(white);
lab->repaint();
}
void Keys::defaults()
{
if ( lab != 0)
focusOut(lab);
lab = 0;
labels[0]->setText("Up");
labels[1]->setText("Down");
labels[2]->setText("Left");
labels[3]->setText("Right");
}
void Keys::init()
{
APP_CONFIG_BEGIN( cfg );
QString up("Up");
up = cfg->readEntry("upKey", (const char*) up);
labels[0]->setText(up);
QString down("Down");
down = cfg->readEntry("downKey", (const char*) down);
labels[1]->setText(down);
QString left("Left");
left = cfg->readEntry("leftKey", (const char*) left);
labels[2]->setText(left);
QString right("Right");
right = cfg->readEntry("rightKey", (const char*) right);
labels[3]->setText(right);
APP_CONFIG_END( cfg );
}
void Keys::ok()
{
/*
APP_CONFIG_BEGIN( cfg );
cfg->writeEntry("upKey", (const char*) labels[0]->text() );
cfg->writeEntry("downKey", (const char*) labels[1]->text() );
cfg->writeEntry("leftKey", (const char*) labels[2]->text() );
cfg->writeEntry("rightKey",(const char*) labels[3]->text() );
APP_CONFIG_END( cfg );
*/
accept();
}
diff --git a/noncore/games/kpacman/kpacman.cpp b/noncore/games/kpacman/kpacman.cpp
index df27c76..be2e46d 100644
--- a/noncore/games/kpacman/kpacman.cpp
+++ b/noncore/games/kpacman/kpacman.cpp
@@ -1,368 +1,363 @@
#include "portable.h"
#if defined( KDE2_PORT )
#include <kpacman.h>
#include <kpacman.moc>
#include <kcolordlg.h>
#elif defined( QPE_PORT )
#include <qmenubar.h>
#include <qpe/config.h>
#include <qapplication.h>
#include "kpacman.h"
#endif
-#include <qkeycode.h>
-#include <qcolor.h>
-#include <qstring.h>
-#include <qpopmenu.h>
-#include <qmsgbox.h>
Kpacman::Kpacman(QWidget *parent, const char *name)
: KTMainWindow(parent, name)
{
schemesPopup = new QList<QPopupMenu>;
schemesPopup->setAutoDelete(TRUE);
menu();
m_view = new QWidget( this, "m_view" );
m_view->setBackgroundColor( black );
m_layout = new QGridLayout( m_view );
m_layout->setMargin( 7 );
view = new KpacmanWidget( this, QString(name)+"widget");
m_layout->addWidget( view, 0, 0 );
setCaption( tr("KPacman") );
view->referee->setFocus();
connect(view->referee, SIGNAL(setScore(int, int)),
view->score, SLOT(setScore(int, int)));
connect(view->referee, SIGNAL(setPoints(int)),
view->score, SLOT(set(int)));
connect(view->referee, SIGNAL(setLifes(int)),
view->status, SLOT(setLifes(int)));
connect(view->referee, SIGNAL(setLevel(int)),
view->status, SLOT(setLevel(int)));
connect(view->referee, SIGNAL(forcedHallOfFame(bool)),
this, SLOT(forcedHallOfFame(bool)));
connect(view->referee, SIGNAL(togglePaused()), this, SLOT(togglePaused()));
connect(view->referee, SIGNAL(toggleNew()), this, SLOT(toggleNew()));
connect(view->score, SIGNAL(toggleNew()), this, SLOT(toggleNew()));
connect(view->score, SIGNAL(forcedHallOfFame(bool)),
this, SLOT(forcedHallOfFame(bool)));
APP_CONFIG_BEGIN( cfg );
focusOutPause = !cfg->readBoolEntry("FocusOutPause", TRUE);
focusInContinue = !cfg->readBoolEntry("FocusInContinue", TRUE);
hideMouseCursor = !cfg->readBoolEntry("HideMouseCursor", TRUE);
APP_CONFIG_END( cfg );
toggleFocusOutPause();
toggleFocusInContinue();
toggleHideMouseCursor();
setCentralWidget( m_view );
}
Kpacman::~Kpacman()
{
/* APP_CONFIG_BEGIN( cfg );
cfg->writeEntry("FocusOutPause", focusOutPause);
cfg->writeEntry("FocusInContinue", focusInContinue);
cfg->writeEntry("HideMouseCursor", hideMouseCursor);
APP_CONFIG_END( cfg );
*/
delete _menuBar;
}
void Kpacman::menu()
{
gamePopup = new QPopupMenu();
CHECK_PTR( gamePopup );
newID = gamePopup->insertItem(tr("&New"), this, SLOT(newKpacman()),Key_F2);
pauseID = gamePopup->insertItem(tr("&Pause"),
this, SLOT(pauseKpacman()), Key_F3);
hofID = gamePopup->insertItem(tr("&Hall of fame"),
this, SLOT(toggleHallOfFame()), Key_F4);
gamePopup->insertSeparator();
gamePopup->insertItem(tr("&Quit"), this, SLOT(quitKpacman()), CTRL+Key_Q);
gamePopup->setCheckable(TRUE);
optionsPopup = new QPopupMenu();
CHECK_PTR(optionsPopup);
modesPopup = new QPopupMenu();
CHECK_PTR(modesPopup);
hideMouseCursorID = optionsPopup->insertItem(tr("&Hide Mousecursor"),
this, SLOT(toggleHideMouseCursor()),
CTRL+Key_H);
optionsPopup->insertSeparator();
if (lookupSchemes() > 0) {
optionsPopup->insertItem(tr("&Select graphic scheme"), modesPopup);
optionsPopup->insertSeparator();
}
focusOutPauseID = optionsPopup->insertItem(tr("&Pause in Background"),
this, SLOT(toggleFocusOutPause()));
focusInContinueID = optionsPopup->insertItem(tr("&Continue in Foreground"),
this, SLOT(toggleFocusInContinue()));
optionsPopup->insertSeparator();
optionsPopup->insertItem(tr("Change &keys..."), this, SLOT(confKeys()));
#ifndef QPE_PORT
QString aboutText = tr("@PACKAGE@ - @VERSION@\n\n"
"Joerg Thoennissen (joe@dsite.de)\n\n"
"A pacman game for the KDE Desktop\n\n"
"The program based on the source of ksnake\n"
"by Michel Filippi (mfilippi@sade.rhein-main.de).\n"
"The design was strongly influenced by the pacman\n"
"(c) 1980 MIDWAY MFG.CO.\n\n"
"I like to thank my girlfriend Elke Krueers for\n"
"the last 10 years of her friendship.\n");
aboutText.replace(QRegExp("@PACKAGE@"), PACKAGE);
aboutText.replace(QRegExp("@VERSION@"), VERSION);
QPopupMenu *helpPopup = helpMenu(aboutText, FALSE);
#endif
//_menuBar = new KMenuBar(this);
//CHECK_PTR( _menuBar );
//_menuBar->insertItem(tr("&Game"), gamePopup);
//_menuBar->insertItem(tr("&Options"), optionsPopup);
//_menuBar->insertSeparator();
#ifndef QPE_PORT
_menuBar->insertItem(tr("&Help"), helpPopup);
#endif
}
int Kpacman::lookupSchemes()
{
APP_CONFIG_BEGIN( cfg );
int ModeCount = cfg->readNumEntry("ModeCount", 0);
int Mode = cfg->readNumEntry("Mode", 0);
int SchemeCount = cfg->readNumEntry("SchemeCount", 0);
int Scheme = cfg->readNumEntry("Scheme", 0);
/*
if (SchemeCount == 0 || Scheme == -1) {
QMessageBox::warning(this, tr("Configuration Error"),
tr("There are no schemes defined,\n"
"or no scheme is selected."));
APP_CONFIG_END( cfg );
return 0;
}
*/
connect(modesPopup, SIGNAL(activated(int)), this, SLOT(schemeChecked(int)));
modeID.resize(ModeCount > 0 ? ModeCount : 0);
if (!schemesPopup->isEmpty())
schemesPopup->clear();
SAVE_CONFIG_GROUP( cfg, oldgroup );
QString ModeGroup;
QString ModeName;
for (int m = 0; m < ModeCount; m++) {
ModeGroup.sprintf("Mode %d", m);
cfg->setGroup(ModeGroup);
ModeName = cfg->readEntry("Description", ModeGroup);
QPopupMenu *p = new QPopupMenu;
p->setCheckable(TRUE);
connect(p, SIGNAL(activated(int)), this, SLOT(schemeChecked(int)));
schemesPopup->append(p);
modeID[m] = modesPopup->insertItem(ModeName, schemesPopup->at(m));
modesPopup->setItemEnabled(modeID[m], FALSE);
modesPopup->setItemChecked(modeID[m], m == Mode);
}
schemeID.resize(SchemeCount);
schemeMode.resize(SchemeCount);
QString SchemeGroup;
QString SchemeName;
int SchemeMode;
for (int i = 0; i < SchemeCount; i++) {
SchemeGroup.sprintf("Scheme %d", i);
cfg->setGroup(SchemeGroup);
SchemeName = cfg->readEntry("Description", SchemeGroup);
SchemeMode = cfg->readNumEntry("Mode", -1);
schemeMode[i] = SchemeMode;
if (SchemeMode == -1) {
schemeID[i] = modesPopup->insertItem(SchemeName);
modesPopup->setItemChecked(schemeID[i], i == Scheme);
} else {
schemeID[i] = schemesPopup->at(SchemeMode)->insertItem(SchemeName);
schemesPopup->at(SchemeMode)->
setItemChecked(schemeID[i], i == Scheme);
modesPopup->setItemEnabled(modeID[SchemeMode], TRUE);
}
}
RESTORE_CONFIG_GROUP( cfg, oldgroup );
APP_CONFIG_END( cfg );
return SchemeCount;
}
void Kpacman::quitKpacman()
{
APP_QUIT();
}
void Kpacman::newKpacman()
{
if (!gamePopup->isItemEnabled(hofID))
gamePopup->setItemEnabled(hofID, TRUE);
if (gamePopup->isItemChecked(hofID))
toggleHallOfFame();
if (gamePopup->isItemChecked(pauseID))
pauseKpacman();
view->referee->play();
}
void Kpacman::pauseKpacman()
{
view->referee->pause();
view->score->setPause(gamePopup->isItemChecked(pauseID));
}
void Kpacman::toggleHallOfFame()
{
gamePopup->setItemChecked(hofID, !gamePopup->isItemChecked(hofID));
view->referee->toggleHallOfFame();
if (gamePopup->isItemChecked(hofID)) {
view->referee->lower();
view->status->lower();
} else {
view->status->raise();
view->referee->raise();
view->referee->setFocus();
}
}
/*
* Disable or enable the "Hall of fame"-menuitem if the referee says so.
* This is done, to disable turning off the "hall of fame"-display, in the automated
* sequence of displaying the introduction, the demonstration (or playing) and the
* hall of fame.
* If on == TRUE then also lower the referee and the status widgets.
*/
void Kpacman::forcedHallOfFame(bool on)
{
if (!on && !gamePopup->isItemChecked(hofID))
return;
gamePopup->setItemEnabled(hofID, !on);
gamePopup->setItemChecked(hofID, on);
view->referee->toggleHallOfFame();
if (on) {
view->referee->lower();
view->status->lower();
} else {
view->status->raise();
view->referee->raise();
view->referee->setFocus();
view->referee->intro();
}
}
void Kpacman::togglePaused()
{
static bool checked = FALSE;
checked = !checked;
gamePopup->setItemChecked( pauseID, checked );
view->score->setPause(gamePopup->isItemChecked(pauseID));
}
/*
* This disables the "New Game" menuitem to prevent interruptions of the current
* play.
*/
void Kpacman::toggleNew()
{
gamePopup->setItemEnabled(newID, !gamePopup->isItemEnabled(newID));
}
void Kpacman::toggleHideMouseCursor()
{
hideMouseCursor = !hideMouseCursor;
optionsPopup->setItemChecked(hideMouseCursorID, hideMouseCursor);
if (hideMouseCursor)
view->setCursor(blankCursor);
else
view->setCursor(arrowCursor);
}
void Kpacman::toggleFocusOutPause()
{
focusOutPause = !focusOutPause;
optionsPopup->setItemChecked(focusOutPauseID, focusOutPause);
view->referee->setFocusOutPause(focusOutPause);
}
void Kpacman::toggleFocusInContinue()
{
focusInContinue = !focusInContinue;
optionsPopup->setItemChecked(focusInContinueID, focusInContinue);
view->referee->setFocusInContinue(focusInContinue);
}
void Kpacman::confKeys()
{
Keys *keys = new Keys();
if (keys->exec() == QDialog::Accepted) {
view->referee->initKeys();
view->score->initKeys();
}
delete keys;
}
void Kpacman::schemeChecked(int id)
{
int mode = 0, scheme = -1;
for (uint s = 0; s < schemeID.size(); s++) {
if (schemeID[s] == id) {
scheme = s;
mode = schemeMode[s];
}
if (schemeMode[s] == -1) {
modesPopup->setItemChecked(schemeID[s], schemeID[s] == id);
} else {
modesPopup->setItemChecked(modeID[schemeMode[s]], schemeMode[s] == mode);
schemesPopup->at(schemeMode[s])->setItemChecked(schemeID[s], schemeID[s] == id);
}
}
/*
APP_CONFIG_BEGIN( cfg );
cfg->writeEntry("Scheme", scheme);
cfg->writeEntry("Mode", mode);
APP_CONFIG_END( cfg );
*/
view->setScheme(scheme, mode);
view->updateGeometry();
updateGeometry();
update();
repaint(TRUE);
show();
}
diff --git a/noncore/games/kpacman/kpacmanwidget.cpp b/noncore/games/kpacman/kpacmanwidget.cpp
index 823d2bf..9631495 100644
--- a/noncore/games/kpacman/kpacmanwidget.cpp
+++ b/noncore/games/kpacman/kpacmanwidget.cpp
@@ -1,158 +1,153 @@
#include "portable.h"
#if defined( KDE2_PORT )
#include <kapp.h>
#include <kconfig.h>
#include <kstddirs.h>
#include <kpacmanwidget.h>
#include <kpacmanwidget.moc>
#elif defined( QPE_PORT )
#include <qpe/qpeapplication.h>
#include <qpe/config.h>
#include "kpacmanwidget.h"
#endif
-#include <qmessagebox.h>
-#include "bitfont.h"
-#include "score.h"
-#include "referee.h"
-#include "status.h"
KpacmanWidget::KpacmanWidget( QWidget *parent, const char *name)
: QWidget( parent, name )
{
score = 0l;
referee = 0l;
status = 0l;
bitfont = NULL;
fontName = "";
scheme = mode = -1;
confScheme();
score = new Score(this, name, scheme, mode, bitfont);
referee = new Referee( this, name, scheme, mode, bitfont);
status = new Status(this, name, scheme, mode);
setBackgroundColor( black );
}
KpacmanWidget::~KpacmanWidget()
{
}
void KpacmanWidget::confMisc(bool defGroup)
{
APP_CONFIG_BEGIN( cfg );
//KStandardDirs *dirs = KGlobal::dirs();
QString findPath;
if (defGroup || cfg->hasKey("Font")) {
fontName = cfg->readEntry("Font");
if (fontName.left(1) != "/" && fontName.left(1) != "~")
fontName.insert(0, "fonts/");
if (fontName.right(1) == "/")
fontName.append("font.xbm");
//findPath = dirs->findResource("appdata", fontName);
findPath = FIND_APP_DATA( fontName );
if (!findPath.isEmpty())
fontName = findPath;
bitfontFirstChar = cfg->readNumEntry("FontFirstChar", 0x0e);
bitfontLastChar = cfg->readNumEntry("FontLastChar", 0x5f);
}
APP_CONFIG_END( cfg );
}
void KpacmanWidget::confScheme()
{
APP_CONFIG_BEGIN( cfg );
QString lastFontName = fontName;
SAVE_CONFIG_GROUP( cfg, oldgroup );
QString newgroup;
// if not set, read mode and scheme from the configfile
if (mode == -1 && scheme == -1) {
scheme = cfg->readNumEntry("Scheme", -1);
mode = cfg->readNumEntry("Mode", -1);
// if mode is not set in the defGroup-group, lookup the scheme group
if (scheme != -1 || mode == -1) {
newgroup.sprintf("Scheme %d", scheme);
cfg->setGroup(newgroup);
mode = cfg->readNumEntry("Mode", -1);
RESTORE_CONFIG_GROUP( cfg, oldgroup );
}
}
confMisc();
if (mode != -1) {
newgroup.sprintf("Mode %d", mode);
cfg->setGroup(newgroup);
confMisc(FALSE);
}
if (scheme != -1) {
newgroup.sprintf("Scheme %d", scheme);
cfg->setGroup(newgroup);
confMisc(FALSE);
}
if (lastFontName != fontName) {
if (bitfont != 0)
delete bitfont;
bitfont = new Bitfont(fontName, bitfontFirstChar, bitfontLastChar);
if (bitfont->width() == 0 || bitfont->height() == 0) {
QString msg = tr("The bitfont could not be contructed.\n\n"
"The file '@FONTNAME@' does not exist,\n"
"or is of an unknown format.");
msg.replace(QRegExp("@FONTNAME@"), fontName);
// QMessageBox::critical(this, tr("Initialization Error"), msg);
printf("%s\n", msg.data());
}
}
RESTORE_CONFIG_GROUP( cfg, oldgroup );
APP_CONFIG_END( cfg );
}
void KpacmanWidget::setScheme(int Scheme, int Mode)
{
mode = Mode;
scheme = Scheme;
confScheme();
score->setScheme(Scheme, Mode, bitfont);
referee->setScheme(Scheme, Mode, bitfont);
status->setScheme(Scheme, Mode);
score->repaint(FALSE);
referee->repaint(FALSE);
status->repaint(FALSE);
}
void KpacmanWidget::resizeEvent( QResizeEvent * )
{
qWarning("Resize");
referee->setGeometry(0, bitfont->height()*3, referee->width(), referee->height());
referee->setBackgroundColor(BLACK);
if(!status ) return;
status->setGeometry(0, bitfont->height()*3+referee->height(), referee->width(),
status->height());
status->setBackgroundColor(BLACK);
score->setGeometry(0, 0, referee->width(), bitfont->height()*3+referee->height()+status->height());
score->setBackgroundColor(BLACK);
}
diff --git a/noncore/games/kpacman/monster.cpp b/noncore/games/kpacman/monster.cpp
index 2f402b4..80b4655 100644
--- a/noncore/games/kpacman/monster.cpp
+++ b/noncore/games/kpacman/monster.cpp
@@ -1,262 +1,261 @@
#include "monster.h"
-#include "board.h"
Monster::Monster(Board *b, int mid)
{
board = b;
ID = mid;
setREM(0);
setHarmless(0, 0, 0);
setArrested(0, 0);
setFreedom(board->position(prisonexit));
if (mid == 0)
setPrison(board->position(prisonentry));
else
setPrison(board->position(monsterhome, mid));
actualPosition = lastPosition = OUT;
feetPosition = 0;
IQ = 0;
maxBodyPixmaps = 0;
maxEyesPixmaps = 0;
}
void Monster::setMaxPixmaps(int maxBody, int maxEyes)
{
if (feetPosition >= (maxBody/10))
feetPosition = 0;
maxBodyPixmaps = maxBody;
maxEyesPixmaps = maxEyes;
}
void Monster::setArrested(int ticks, int duration)
{
actualState = dangerous;
pauseDuration = ticks;
pause = 0;
arrestDuration = arrestLeft = duration;
arrestPause = ticks;
harmlessLeft = 0;
}
void Monster::setDangerous(int ticks, int iq)
{
actualState = dangerous;
pauseDuration = ticks;
pause = 0;
dangerousPause = ticks;
harmlessLeft = 0;
IQ = iq;
}
void Monster::setHarmless(int ticks, int hDuration, int wDuration)
{
actualState = harmless;
pauseDuration = ticks;
pause = 0;
harmlessDuration = harmlessLeft = hDuration;
warningDuration = wDuration;
}
void Monster::setREM(int ticks)
{
actualState = rem;
pauseDuration = ticks;
pause = 0;
}
void Monster::setPosition(int pos)
{
board->reset(lastPosition, monster, ID); // reset old position on the board
actualPosition = lastPosition = pos; // set position of monster
board->set(actualPosition, monster, ID);
feetPosition = 0;
}
void Monster::setPrison(int pos)
{
prisonPosition = pos;
}
void Monster::setFreedom(int pos)
{
freedomPosition = pos;
}
void Monster::setDirection(int dir)
{
if (dir == X)
lastDirection = actualDirection;
actualDirection = dir;
}
monsterState Monster::state()
{
return actualState;
}
int Monster::position()
{
return actualPosition;
}
int Monster::direction()
{
return actualDirection;
}
int Monster::id()
{
return ID;
}
bool Monster::move()
{
if (arrestLeft > 1)
arrestLeft--;
if (harmlessLeft > 0) {
harmlessLeft--;
if (harmlessLeft == 0 && actualState == harmless) {
actualState = dangerous;
pauseDuration = dangerousPause;
}
}
if (pause-- > 0)
return FALSE;
else
pause = pauseDuration;
if (actualPosition == OUT)
return FALSE;
if (actualDirection == X) {
if (++feetPosition >= (maxBodyPixmaps/10))
feetPosition = 0;
return TRUE;
}
lastPosition = actualPosition;
int d = actualDirection;
if (arrestLeft > 1) { // during the arrest, only up and down
if (!board->isWay(actualPosition, d, empty) &&
!board->isWay(actualPosition, d, tunnel))
d = board->turn(actualDirection);
}
if (arrestLeft == 1) { // going out of the prison
if (((d == W || d == E) &&
board->x(actualPosition) == board->x(freedomPosition)) ||
((d == S || d == N) &&
board->y(actualPosition) == board->y(freedomPosition)) ||
board->isWay(actualPosition, d, brick) ||
board->isWay(actualPosition, d, prison)) {
d = board->closeup(actualPosition, d, freedomPosition);
}
while (board->isWay(actualPosition, d, brick) ||
board->isWay(actualPosition, d, prison)) {
if (d == actualDirection)
d = rand() % 4;
else
d = actualDirection;
}
if (actualState == dangerous)
pauseDuration = dangerousPause;
}
if (arrestLeft == 0)
if (actualState == rem) { // on the way to prison
d = board->closeup(actualPosition, d, prisonPosition);
while (board->isWay(actualPosition, d, brick) ||
board->isWay(actualPosition, d, prison)) {
if (d != actualDirection) // if new direction is not possible,
d = actualDirection; // try current direction first.
else
d = rand() % 4;
}
} else { // dangerous or harmless movement
if (rand() % (int) ((190-IQ)/10) == 0) {
d = board->closeup(actualPosition, d, board->position(pacman));
if (actualState == harmless)
d = board->turn(d);
} else
do // try new direction, but not the opposite
d = rand() % 4; // direction, to prevent hectic movement.
while (d == board->turn(actualDirection));
while ((!board->isWay(actualPosition, d, empty) &&
!board->isWay(actualPosition, d, tunnel)) ||
d == board->turn(actualDirection)) {
if (d != actualDirection) // if new direction is not possible,
d = actualDirection; // try current direction first.
else
d = rand() % 4;
}
}
actualDirection = d;
actualPosition = board->move(actualPosition, actualDirection);
if (arrestLeft == 1 && actualPosition == freedomPosition)
arrestLeft = 0;
if (actualState == rem && actualPosition == prisonPosition) {
actualState = dangerous;
pauseDuration = arrestPause;
arrestLeft = arrestDuration+1;
actualDirection = S;
}
if (actualPosition != lastPosition) {
board->reset(lastPosition, monster, ID);
board->set(actualPosition, monster, ID);
}
if (++feetPosition >= (maxBodyPixmaps/10))
feetPosition = 0;
return TRUE;
}
int Monster::body()
{
if (actualState == rem || actualPosition == OUT)
return -1;
else
if (actualState == harmless)
if (harmlessLeft > warningDuration ||
harmlessLeft % (int) (warningDuration/4.5) > (int) (warningDuration/9))
return ((maxBodyPixmaps/10)*8)+feetPosition;
else
return ((maxBodyPixmaps/10)*9)+feetPosition;
else
return ((maxBodyPixmaps/10)*ID)+feetPosition;
}
int Monster::eyes()
{
if (actualState == harmless || actualPosition == OUT)
return -1;
else
switch (actualDirection) {
case N : return 0;
case E : return 1;
case S : return 2;
case W : return 3;
case X : switch (lastDirection) {
case N : return 0;
case E : return 1;
case S : return 2;
default : return 3;
}
default : return -1;
}
}
diff --git a/noncore/games/kpacman/pacman.cpp b/noncore/games/kpacman/pacman.cpp
index 40f60a8..82524b4 100644
--- a/noncore/games/kpacman/pacman.cpp
+++ b/noncore/games/kpacman/pacman.cpp
@@ -1,147 +1,146 @@
#include "pacman.h"
-#include "board.h"
Pacman::Pacman(Board *b)
{
board = b;
setDemo(FALSE);
setAlive(0);
actualPosition = lastPosition = OUT;
mouthPosition = 0;
lastPix = 0;
maxPixmaps = 0;
}
void Pacman::setMaxPixmaps(int max)
{
if (actualDirection == X && lastPix >= 0) {
actualDirection = lastPix / (maxPixmaps/4);
if (max < maxPixmaps)
mouthPosition = 0;
else
mouthPosition = lastPix % (maxPixmaps/4);
maxPixmaps = max;
lastPix = pix();
actualDirection = X;
} else
maxPixmaps = max;
}
void Pacman::setAlive(int ticks)
{
actualState = alive;
pauseDuration = ticks;
pause = 0;
}
void Pacman::setPosition(int pos)
{
board->reset(lastPosition, pacman);
actualPosition = lastPosition = pos;
board->set(actualPosition, pacman);
mouthPosition = 0;
}
void Pacman::setDirection(int dir, bool forced)
{
if (forced ||
board->isWay(actualPosition, dir, empty) ||
board->isWay(actualPosition, dir, tunnel)) {
if (dir == X)
lastPix = pix();
actualDirection = dir;
nextDirection = X;
} else
nextDirection = dir;
}
void Pacman::setDemo(bool yes)
{
demo = yes;
}
pacmanState Pacman::state()
{
return actualState;
}
int Pacman::position()
{
return actualPosition;
}
int Pacman::direction()
{
return actualDirection;
}
bool Pacman::move()
{
if (pause-- > 0)
return FALSE;
else
pause = pauseDuration;
if (actualDirection == X || actualPosition == OUT)
return FALSE;
lastPosition = actualPosition;
if (demo) {
int d = actualDirection;
do // try new direction, but not the opposite
d = rand() % 4; // direction, to prevent hectic movement.
while (d == board->turn(actualDirection));
while (!board->isWay(actualPosition, d, empty) &&
!board->isWay(actualPosition, d, tunnel)) {
if (d != actualDirection) // if new actualDirection is not possible,
d = actualDirection; // try current actualDirection first.
else
d = rand() % 4;
}
actualDirection = d;
actualPosition = board->move(actualPosition, actualDirection);
} else {
if (nextDirection != X)
if (board->isWay(actualPosition, nextDirection, empty) ||
board->isWay(actualPosition, nextDirection, tunnel)) {
actualDirection = nextDirection;
nextDirection = X;
}
if (board->isWay(actualPosition, actualDirection, empty) ||
board->isWay(actualPosition, actualDirection, tunnel))
actualPosition = board->move(actualPosition, actualDirection);
}
if (actualPosition != lastPosition) {
board->reset(lastPosition, pacman);
board->set(actualPosition, pacman);
if (++mouthPosition >= (maxPixmaps/4))
mouthPosition = 0;
}
return TRUE;
}
int Pacman::pix()
{
if (actualPosition != OUT && maxPixmaps > 0)
switch (actualDirection) {
case N : return ((maxPixmaps/4)*0)+mouthPosition;
case E : return ((maxPixmaps/4)*1)+mouthPosition;
case S : return ((maxPixmaps/4)*2)+mouthPosition;
case W : return ((maxPixmaps/4)*3)+mouthPosition;
case X : return lastPix;
}
return -1;
}
diff --git a/noncore/games/kpacman/painter.cpp b/noncore/games/kpacman/painter.cpp
index d8c7460..410d3f5 100644
--- a/noncore/games/kpacman/painter.cpp
+++ b/noncore/games/kpacman/painter.cpp
@@ -1,972 +1,964 @@
#include "portable.h"
#if defined( KDE2_PORT )
#include <kapp.h>
#include <kconfig.h>
#include <kstddirs.h>
#elif defined( QPE_PORT )
#include <qpe/qpeapplication.h>
#include <qpe/config.h>
#endif
-#include <qcolor.h>
-#include <qpainter.h>
-#include <qpixmap.h>
-#include <qbitmap.h>
-#include <qrect.h>
-#include <qstring.h>
-
-#include <qmessagebox.h>
+
#include <qfileinfo.h>
#include "painter.h"
-#include "board.h"
Painter::Painter( Board *b, QWidget *parent, int Scheme, int Mode, Bitfont *font)
{
w = parent;
board = b;
pointPix = NULL;
wallPix = NULL;
prisonPix = NULL;
energizerPix = NULL;
fruitPix = NULL;
pacmanPix = NULL;
dyingPix = NULL;
eyesPix = NULL;
monsterPix = NULL;
fruitScorePix = NULL;
monsterScorePix = NULL;
lastPointPixmapName = "";
lastWallPixmapName = "";
lastPrisonPixmapName = "";
lastEnergizerPixmapName = "";
lastFruitPixmapName = "";
lastPacmanPixmapName = "";
lastDyingPixmapName = "";
lastEyesPixmapName = "";
lastMonsterPixmapName = "";
lastFruitScorePixmapName = "";
lastMonsterScorePixmapName = "";
bitfont = font;
scheme = Scheme;
mode = Mode;
level = 0;
confScheme();
}
QList<QPixmap> *Painter::loadPixmap(QWidget*, QString pixmapName,
QList<QPixmap> *pixmaps)
{
if (pixmaps == NULL) {
pixmaps = new QList<QPixmap>;
pixmaps->setAutoDelete(TRUE);
}
if (!pixmaps->isEmpty())
pixmaps->clear();
QPixmap PIXMAP(pixmapName);
if (PIXMAP.isNull() || PIXMAP.mask() == NULL) {
QString msg = "The pixmap could not be contructed.\n\n"
"The file '@PIXMAPNAME@' does not exist,\n"
"or is of an unknown format.";
msg.replace(QRegExp("@PIXMAPNAME@"), pixmapName);
// QMessageBox::critical(parent, tr("Initialization Error"), msg);
printf("%s\n", msg.data());
return 0;
}
int height = PIXMAP.height();
int width = (height == 0) ? 0 : PIXMAP.width()/(PIXMAP.width()/height);
QBitmap BITMAP;
QBitmap MASK;
BITMAP = *PIXMAP.mask();
MASK.resize(width, height);
for (int x = 0; x < PIXMAP.width()/width; x++) {
QPixmap *pixmap = new QPixmap(width, height);
pixmaps->append(pixmap);
bitBlt(pixmap, 0, 0, &PIXMAP, x*width, 0, width, height, QPixmap::CopyROP, TRUE);
bitBlt(&MASK, 0, 0, &BITMAP, x*width, 0, width, height, QPixmap::CopyROP, TRUE);
pixmap->setMask(MASK);
}
return pixmaps;
}
QList<QPixmap> *Painter::textPixmap(QStrList &str, QList<QPixmap> *pixmaps,
QColor fg, QColor bg)
{
if (pixmaps == NULL) {
pixmaps = new QList<QPixmap>;
pixmaps->setAutoDelete(TRUE);
}
if (!pixmaps->isEmpty())
pixmaps->clear();
for (uint s = 0; s < str.count(); s++) {
QPixmap *pixmap = new QPixmap(bitfont->text(str.at(s), fg, bg));
pixmaps->append(pixmap);
}
return pixmaps;
}
QList<QPixmap> *Painter::textPixmap(QString str, QList<QPixmap> *pixmaps,
QColor fg, QColor bg)
{
if (pixmaps == NULL) {
pixmaps = new QList<QPixmap>;
pixmaps->setAutoDelete(TRUE);
}
if (!pixmaps->isEmpty())
pixmaps->clear();
QPixmap *pixmap = new QPixmap(bitfont->text(str, fg, bg));
pixmaps->append(pixmap);
return pixmaps;
}
/* Return the point of the upperleft pixel of the block representing that position
* on the board.
*/
QPoint Painter::point(int pos)
{
return QPoint((board->x(pos)-1)*BlockWidth, (board->y(pos)-1)*BlockHeight);
}
QRect Painter::rect(int pos, PixMap pix, uint i)
{
if (pos == OUT)
return QRect();
QPixmap *PIXMAP = NULL;
switch (pix) {
case PacmanPix : PIXMAP = pacmanPix->
at(checkRange(i, pacmanPix->count()-1));
break;
case DyingPix : PIXMAP = dyingPix->
at(checkRange(i, dyingPix->count()-1));
break;
case MonsterPix : PIXMAP = monsterPix->
at(checkRange(i, monsterPix->count()-1));
break;
case EyesPix : PIXMAP = eyesPix->
at(checkRange(i, eyesPix->count()-1));
break;
case FruitPix : PIXMAP = fruitPix->
at(checkRange(i, fruitPix->count()-1));
break;
case PointPix : PIXMAP = pointPix->
at(checkRange(i, pointPix->count()-1));
break;
case EnergizerPix : PIXMAP = energizerPix->
at(checkRange(i, energizerPix->count()-1));
break;
case FruitScorePix : PIXMAP = fruitScorePix->
at(checkRange(i, fruitScorePix->count()-1));
break;
case MonsterScorePix : PIXMAP = monsterScorePix->
at(checkRange(i,monsterScorePix->count()-1));
break;
default : PIXMAP = wallPix->
at(checkRange(i, wallPix->count()-1));
}
if (PIXMAP == NULL)
return QRect();
QRect rect = PIXMAP->rect();
QPoint point = this->point(pos);
rect.moveCenter(QPoint(point.x()-1, point.y()-1));
return rect;
}
QRect Painter::rect(int pos, QString str, int align)
{
if (pos == OUT) // return an empty rect if the position
return QRect(); // is invalid
QPoint point = this->point(pos);
QRect rect = bitfont->rect(str);
rect.moveCenter(QPoint(point.x()-1, point.y()-1));
int dx = 0;
int dy = 0;
if (align & QLabel::AlignLeft || align & QLabel::AlignRight) {
dx = (str.length()-1) * (bitfont->width()/2);
if (align & QLabel::AlignRight)
dx *= -1;
}
if (align & QLabel::AlignTop || align & QLabel::AlignBottom) {
dy = bitfont->height()/2;
if (align & QLabel::AlignBottom)
dy *= -1;
}
if (dx != 0 || dy != 0)
rect.moveBy(dx, dy);
return rect;
}
QRect Painter::rect(QRect r1, QRect r2)
{
QRect rect;
rect.setLeft(r1.left() < r2.left() ? r1.left() : r2.left());
rect.setTop(r1.top() < r2.top() ? r1.top() : r2.top());
rect.setRight(r1.right() > r2.right() ? r1.right() : r2.right());
rect.setBottom(r1.bottom() > r2.bottom() ? r1.bottom() : r2.bottom());
return rect;
}
void Painter::erase(int pos, PixMap pix, uint i)
{
if (pos == OUT)
return;
QRect rect = this->rect(pos, pix, i);
bitBlt(&roomPix, rect.x(), rect.y(), &backPix,
rect.x(), rect.y(), rect.width(), rect.height());
}
int Painter::maxPixmaps(PixMap pix)
{
switch (pix) {
case WallPix : return (int) wallPix->count();
case PrisonPix : return (int) prisonPix->count();
case PointPix : return (int) pointPix->count();
case EnergizerPix : return (int) energizerPix->count();
case FruitPix : return (int) fruitPix->count();
case PacmanPix : return (int) pacmanPix->count();
case DyingPix : return (int) dyingPix->count();
case EyesPix : return (int) eyesPix->count();
case MonsterPix : return (int) monsterPix->count();
case FruitScorePix : return (int) fruitScorePix->count();
case MonsterScorePix : return (int) monsterScorePix->count();
default : return 0;
}
}
void Painter::draw(QPoint point, DrawWidget where, QPixmap pix)
{
switch (where) {
case Widget : bitBlt(w, point.x(), point.y(), &pix);
break;
case RoomPix : bitBlt(&roomPix, point.x(), point.y(), &pix);
break;
case BackPix : bitBlt(&backPix, point.x(), point.y(), &pix);
break;
}
}
void Painter::draw(QRect rect, DrawWidget where, QPixmap pix)
{
draw(QPoint(rect.x(), rect.y()), where, pix);
}
void Painter::draw(int pos, DrawWidget where, PixMap pix, uint i)
{
QPixmap *PIXMAP = NULL;
switch (pix) {
case PacmanPix : PIXMAP = pacmanPix->
at(checkRange(i, pacmanPix->count()-1));
break;
case DyingPix : PIXMAP = dyingPix->
at(checkRange(i, dyingPix->count()-1));
break;
case MonsterPix : PIXMAP = monsterPix->
at(checkRange(i, monsterPix->count()-1));
break;
case EyesPix : PIXMAP = eyesPix->
at(checkRange(i, eyesPix->count()-1));
break;
case FruitPix : PIXMAP = fruitPix->
at(checkRange(i, fruitPix->count()-1));
break;
case EnergizerPix : PIXMAP = energizerPix->
at(checkRange(i, energizerPix->count()-1));
break;
case FruitScorePix : PIXMAP = fruitScorePix->
at(checkRange(i, fruitScorePix->count()-1));
break;
case MonsterScorePix : PIXMAP = monsterScorePix->
at(checkRange(i,monsterScorePix->count()-1));
break;
default : ;
}
if (PIXMAP == NULL)
return;
QRect rect = PIXMAP->rect();
QPoint point = this->point(pos);
rect.moveCenter(QPoint(point.x()-1, point.y()-1));
switch (where) {
case Widget : bitBlt(w, rect.x(), rect.y(), PIXMAP);
break;
case RoomPix : bitBlt(&roomPix, rect.x(), rect.y(), PIXMAP);
break;
case BackPix : bitBlt(&backPix, rect.x(), rect.y(), PIXMAP);
break;
}
}
QPixmap Painter::draw(int pos, DrawWidget where,
QString str, QColor fg, QColor bg, int align)
{
QPixmap TEXT = bitfont->text(str, fg, bg);
QRect rect = this->rect(pos, str, align);
QPixmap SAVE = QPixmap(rect.width(), rect.height());
switch (where) {
case Widget : bitBlt(&SAVE, 0, 0, w, rect.x(), rect.y());
bitBlt(w, rect.x(), rect.y(), &TEXT);
break;
case RoomPix : bitBlt(&SAVE, 0, 0, &roomPix, rect.x(), rect.y());
bitBlt(&roomPix, rect.x(), rect.y(), &TEXT);
break;
case BackPix : bitBlt(&SAVE, 0, 0, &backPix, rect.x(), rect.y());
bitBlt(&backPix, rect.x(), rect.y(), &TEXT);
break;
}
return SAVE;
}
QRect Painter::draw(int col, int row, DrawWidget where,
QString str, QColor fg, QColor bg, int align)
{
QPixmap TEXT = bitfont->text(str, fg, bg);
QRect rect = this->rect(row*BoardWidth+col, str, align);
draw(rect, where, TEXT);
return rect;
}
void Painter::initPixmaps()
{
if (lastPointPixmapName != pointPixmapName.at(level)) {
pointPix = loadPixmap(w, pointPixmapName.at(level), pointPix);
lastPointPixmapName = pointPixmapName.at(level);
}
if (lastPrisonPixmapName != prisonPixmapName.at(level)) {
prisonPix = loadPixmap(w, prisonPixmapName.at(level), prisonPix);
lastPrisonPixmapName = prisonPixmapName.at(level);
}
if (lastEnergizerPixmapName != energizerPixmapName.at(level)) {
energizerPix = loadPixmap(w, energizerPixmapName.at(level), energizerPix);
lastEnergizerPixmapName = energizerPixmapName.at(level);
}
if (lastFruitPixmapName != fruitPixmapName.at(level)) {
fruitPix = loadPixmap(w, fruitPixmapName.at(level), fruitPix);
lastFruitPixmapName = fruitPixmapName.at(level);
}
if (lastPacmanPixmapName != pacmanPixmapName.at(level)) {
pacmanPix = loadPixmap(w, pacmanPixmapName.at(level), pacmanPix);
lastPacmanPixmapName = pacmanPixmapName.at(level);
}
if (lastDyingPixmapName != dyingPixmapName.at(level)) {
dyingPix = loadPixmap(w, dyingPixmapName.at(level), dyingPix);
lastDyingPixmapName = dyingPixmapName.at(level);
}
if (lastEyesPixmapName != eyesPixmapName.at(level)) {
eyesPix = loadPixmap(w, eyesPixmapName.at(level), eyesPix);
lastEyesPixmapName = eyesPixmapName.at(level);
}
if (lastMonsterPixmapName != monsterPixmapName.at(level)) {
monsterPix = loadPixmap(w, monsterPixmapName.at(level), monsterPix);
lastMonsterPixmapName = monsterPixmapName.at(level);
}
if (lastFruitScorePixmapName != fruitScorePixmapName.at(level) ||
(const char *) *fruitScorePixmapName.at(level) == '\0') {
if ((const char *) *fruitScorePixmapName.at(level) == '\0') {
fruitScorePix = textPixmap(fruitScoreString, fruitScorePix, PINK);
} else {
fruitScorePix = loadPixmap(w, fruitScorePixmapName.at(level),
fruitScorePix);
lastFruitScorePixmapName = fruitScorePixmapName.at(level);
}
}
if (lastMonsterScorePixmapName != monsterScorePixmapName.at(level) ||
(const char *) *monsterScorePixmapName.at(level) == '\0') {
if ((const char *) *monsterScorePixmapName.at(level) == '\0') {
monsterScorePix = textPixmap(monsterScoreString, monsterScorePix, CYAN);
} else {
monsterScorePix = loadPixmap(w, monsterScorePixmapName.at(level),
monsterScorePix);
lastMonsterScorePixmapName = monsterScorePixmapName.at(level);
}
}
if (lastWallPixmapName != wallPixmapName.at(level)) {
wallPix = loadPixmap(w, wallPixmapName.at(level), wallPix);
if (wallPix->isEmpty()) {
BlockWidth = 0;
BlockHeight = 0;
} else {
BlockWidth = wallPix->at(0)->width();
BlockHeight = wallPix->at(0)->height();
}
lastWallPixmapName = wallPixmapName.at(level);
}
}
void Painter::initbackPixmaps()
{
backgroundColor = BLACK;
backPix.resize((BoardWidth-3)*BlockWidth, (BoardHeight-3)*BlockHeight );
backPix.fill(backgroundColor);
}
void Painter::initRoomPixmap()
{
roomPix.resize((BoardWidth-3)*BlockWidth, (BoardHeight-3)*BlockHeight );
bitBlt(&roomPix,0,0, &backPix);
for (unsigned int x = 0; x < board->size(); x++) {
if (board->isBrick(x))
drawBrick(x);
if (board->isPrison(x) || board->isGate(x))
drawPrison(x);
if (board->isPoint(x))
drawPoint(x);
}
}
void Painter::drawBrick(int pos)
{
int border = 0;
if (board->isBrick(board->move(pos, N ))) border |= (1 << 0);
if (board->isBrick(board->move(pos, NE))) border |= (1 << 1);
if (board->isBrick(board->move(pos, E ))) border |= (1 << 2);
if (board->isBrick(board->move(pos, SE))) border |= (1 << 3);
if (board->isBrick(board->move(pos, S ))) border |= (1 << 4);
if (board->isBrick(board->move(pos, SW))) border |= (1 << 5);
if (board->isBrick(board->move(pos, W ))) border |= (1 << 6);
if (board->isBrick(board->move(pos, NW))) border |= (1 << 7);
if (board->isOut(board->move(pos, N ))) border |= (1 << 8);
if (board->isOut(board->move(pos, NE))) border |= (1 << 9);
if (board->isOut(board->move(pos, E ))) border |= (1 << 10);
if (board->isOut(board->move(pos, SE))) border |= (1 << 11);
if (board->isOut(board->move(pos, S ))) border |= (1 << 12);
if (board->isOut(board->move(pos, SW))) border |= (1 << 13);
if (board->isOut(board->move(pos, W ))) border |= (1 << 14);
if (board->isOut(board->move(pos, NW))) border |= (1 << 15);
switch (border & 0xFF) {
case 31 : border = 0; break;
case 159 : border = 0; break;
case 63 : border = 0; break;
case 191 : border = 0; break;
case 241 : border = 1; break;
case 249 : border = 1; break;
case 243 : border = 1; break;
case 251 : border = 1; break;
case 124 : border = 2; break;
case 252 : border = 2; break;
case 126 : border = 2; break;
case 199 : border = 3; break;
case 231 : border = 3; break;
case 207 : border = 3; break;
case 28 : if ((border >> 8) > 0)
border = 24;
else
border = 4;
break;
case 112 : if ((border >> 8) > 0)
border = 27;
else
border = 5;
break;
case 7 : if ((border >> 8) > 0)
border = 25;
else
border = 6;
break;
case 193 : if ((border >> 8) > 0)
border = 26;
else
border = 7;
break;
case 247 : if ((border & (1 << 11)) > 0)
border = 23;
else
border = 8;
break;
case 119 : if ((border & (1 << 15)) > 0)
border = 8;
if ((border & (1 << 11)) > 0)
border = 11;
break;
case 223 : if ((border & (1 << 13)) > 0)
border = 20;
else
border = 9;
break;
case 221 : if ((border & (1 << 13)) > 0)
border = 10;
if ((border & (1 << 9)) > 0)
border = 9;
break;
case 253 : if ((border & (1 << 9)) > 0)
border = 21;
else
border = 10;
break;
case 127 : if ((border & (1 << 15)) > 0)
border = 22;
else
border = 11;
break;
case 30 : border = 12; break;
case 240 : border = 13; break;
case 15 : border = 14; break;
case 225 : border = 15; break;
case 135 : border = 16; break;
case 195 : border = 17; break;
case 60 : border = 18; break;
case 120 : border = 19; break;
case 255 : border = 28; break;
default : border = -1;
}
if (border != -1 && border < (int) wallPix->count()) {
QRect rect = this->rect(pos, WallPix);
bitBlt(&roomPix, rect.x(), rect.y(), wallPix->at((uint) border));
}
}
void Painter::drawPrison(int pos)
{
int border = 0;
if (board->isPrison(board->move(pos, N ))) border |= (1 << 0);
if (board->isPrison(board->move(pos, NE))) border |= (1 << 1);
if (board->isPrison(board->move(pos, E ))) border |= (1 << 2);
if (board->isPrison(board->move(pos, SE))) border |= (1 << 3);
if (board->isPrison(board->move(pos, S ))) border |= (1 << 4);
if (board->isPrison(board->move(pos, SW))) border |= (1 << 5);
if (board->isPrison(board->move(pos, W ))) border |= (1 << 6);
if (board->isPrison(board->move(pos, NW))) border |= (1 << 7);
if (board->isGate(board->move(pos, N ))) border |= (1 << 8);
if (board->isGate(board->move(pos, NE))) border |= (1 << 9);
if (board->isGate(board->move(pos, E ))) border |= (1 << 10);
if (board->isGate(board->move(pos, SE))) border |= (1 << 11);
if (board->isGate(board->move(pos, S ))) border |= (1 << 12);
if (board->isGate(board->move(pos, SW))) border |= (1 << 13);
if (board->isGate(board->move(pos, W ))) border |= (1 << 14);
if (board->isGate(board->move(pos, NW))) border |= (1 << 15);
switch (border & 0xFF) {
case 31 : border = 0; break;
case 159 : border = 0; break;
case 63 : border = 0; break;
case 241 : border = 1; break;
case 249 : border = 1; break;
case 243 : border = 1; break;
case 124 : border = 2; break;
case 252 : border = 2; break;
case 126 : border = 2; break;
case 199 : border = 3; break;
case 231 : border = 3; break;
case 207 : border = 3; break;
case 28 : if ((border >> 8) != 0)
border = 12;
else
border = 4;
break;
case 112 : if ((border >> 8) != 0)
border = 13;
else
border = 5;
break;
case 7 : if ((border >> 8) != 0)
border = 14;
else
border = 6;
break;
case 193 : if ((border >> 8) != 0)
border = 15;
else
border = 7;
break;
case 247 : border = 8; break;
case 223 : border = 9; break;
case 253 : border = 10; break;
case 127 : border = 11; break;
default : border = -1;
}
if (board->isGate(pos)) {
if (board->isGate(board->move(pos, N)))
border = 17;
else
border = 16;
}
if (border != -1 && border < (int) prisonPix->count()) {
QRect rect = this->rect(pos, PrisonPix);
bitBlt(&roomPix, rect.x(), rect.y(), prisonPix->at((uint) border));
}
}
void Painter::drawPoint(int pos)
{
if (!pointPix->isEmpty()) {
QRect rect = this->rect(pos, PointPix);
bitBlt(&roomPix, rect.x(), rect.y(), pointPix->at(0));
}
}
QString Painter::decodeHexOctString(QString s)
{
QString value;
QString valids;
int pos, xpos = 0, opos = 0;
int v, len, leadin;
const char *ptr;
uchar c;
while (((xpos = s.find(QRegExp("\\\\x[0-9a-fA-F]+"), xpos)) != -1) ||
((opos = s.find(QRegExp("\\\\[0-7]+"), opos)) != -1)) {
if (xpos != -1) {
valids = "0123456789abcdef";
leadin = 2;
pos = xpos;
} else {
valids = "01234567";
leadin = 1;
pos = opos;
}
c = '\0';
len = 0;
value = s.mid(pos+leadin, 3);
ptr = (const char *) value;
while (*ptr != '\0' && (v = valids.find(*ptr++, 0, FALSE)) != -1) {
c = (c * valids.length()) + v;
len++;
}
value.fill(c, 1);
s.replace(pos, len+leadin, value);
}
return s;
}
void Painter::fillScoreString(QStrList &list, QArray<int> &values)
{
if( !list.isEmpty())
list.clear();
QString s;
for (uint i = 0; i < values.size(); i++) {
if (values[i] < 10 || values[i] > 10000)
s = "?";
else if (values[i] == 1600)
s = "\x1a\x1b";
else if (values[i] < 100) {
s = "\x0e";
s.insert(0, char (values[i] / 10 + 0x10));
} else if (values[i] < 1000) {
s = "\x0f";
s.insert(0, char (values[i] / 100 + 0x10));
} else {
s = "\x0f\x10";
s.insert(0, char (values[i] / 1000 + 0x10));
}
list.append(s.data());
}
}
void Painter::fillArray(QArray<int> &array, QString values, int max)
{
array.resize(max);
int last = 0;
bool ok;
QString value;
for (uint i = 0; i < array.size(); i++) {
if (values.find(',') < 0 && values.length() > 0) {
value = values;
values = "";
}
if (values.find(',') >= 0) {
value = values.left(values.find(','));
values.remove(0,values.find(',')+1);
}
array[i] = value.toInt(&ok);
if (ok)
last = array[i];
else
array[i] = last;
}
}
void Painter::fillStrList(QStrList &list, QString values, int max)
{
if (!list.isEmpty())
list.clear();
QString last = "";
QString value;
for (uint i = 0; i < (uint) max; i++) {
if (values.find(',') < 0 && values.length() > 0) {
value = values;
values = "";
}
if (values.find(',') >= 0) {
value = values.left(values.find(','));
values.remove(0,values.find(',')+1);
}
if (!value.isEmpty())
last = decodeHexOctString(value);
list.append(last);
}
}
void Painter::fillPixmapName(QStrList &pixmapName)
{
QStrList list = pixmapName;
if (!pixmapName.isEmpty())
pixmapName.clear();
QString pixmap;
QFileInfo fileInfo;
for (uint i = 0; i < list.count(); i++) {
pixmap = list.at(i);
if (pixmap.left(1) != "/" && pixmap.left(1) != "~")
pixmap = FIND_APP_DATA( pixmapDirectory+pixmap );
fileInfo.setFile(pixmap);
if (!fileInfo.isReadable() || !fileInfo.isFile())
pixmap = "";
pixmapName.append(pixmap);
}
}
void Painter::confLevels(bool defGroup)
{
APP_CONFIG_BEGIN( cfg );
if (defGroup || cfg->hasKey("Levels"))
maxLevel = cfg->readNumEntry("Levels", 13);
APP_CONFIG_END( cfg );
}
void Painter::confMisc(bool defGroup)
{
APP_CONFIG_BEGIN( cfg );
if (defGroup || cfg->hasKey("PixmapDirectory")) {
pixmapDirectory = cfg->readEntry("PixmapDirectory");
if (pixmapDirectory.left(1) != "/" && pixmapDirectory.left(1) != "~")
pixmapDirectory.insert(0, "pics/");
if (pixmapDirectory.right(1) != "/")
pixmapDirectory.append("/");
}
if (defGroup || cfg->hasKey("PointPixmapName"))
fillStrList(pointPixmapName,
cfg->readEntry("PointPixmapName", "point.xpm"), maxLevel+1);
if (defGroup || cfg->hasKey("WallPixmapName"))
fillStrList(wallPixmapName,
cfg->readEntry("WallPixmapName", "wall.xpm"), maxLevel+1);
if (defGroup || cfg->hasKey("PrisonPixmapName"))
fillStrList(prisonPixmapName,
cfg->readEntry("PrisonPixmapName", "prison.xpm"), maxLevel+1);
if (defGroup || cfg->hasKey("EnergizerPixmapName"))
fillStrList(energizerPixmapName,
cfg->readEntry("EnergizerPixmapName", "switch.xpm"),maxLevel+1);
if (defGroup || cfg->hasKey("FruitPixmapName"))
fillStrList(fruitPixmapName,
cfg->readEntry("FruitPixmapName", "fruit.xpm"), maxLevel+1);
if (defGroup || cfg->hasKey("PacmanPixmapName"))
fillStrList(pacmanPixmapName,
cfg->readEntry("PacmanPixmapName", "pacman.xpm"), maxLevel+1);
if (defGroup || cfg->hasKey("DyingPixmapName"))
fillStrList(dyingPixmapName,
cfg->readEntry("DyingPixmapName", "dying.xpm"), maxLevel+1);
if (defGroup || cfg->hasKey("EyesPixmapName"))
fillStrList(eyesPixmapName,
cfg->readEntry("EyesPixmapName", "eyes.xpm"), maxLevel+1);
if (defGroup || cfg->hasKey("MonsterPixmapName"))
fillStrList(monsterPixmapName,
cfg->readEntry("MonsterPixmapName", "monster.xpm"), maxLevel+1);
if (defGroup || cfg->hasKey("FruitScorePixmapName"))
fillStrList(fruitScorePixmapName,
cfg->readEntry("FruitScorePixmapName"), maxLevel+1);
if (defGroup || cfg->hasKey("MonsterScorePixmapName"))
fillStrList(monsterScorePixmapName,
cfg->readEntry("MonsterScorePixmapName"), maxLevel+1);
APP_CONFIG_END( cfg );
}
void Painter::confScoring(bool defGroup)
{
APP_CONFIG_BEGIN( cfg );
if (defGroup || cfg->hasKey("FruitScore"))
fillArray(fruitScore,
cfg->readEntry("FruitScore",
"100,300,500,,700,,1000,,2000,,3000,,5000"),
maxLevel+1);
if (defGroup || cfg->hasKey("MonsterScore"))
fillArray(monsterScore,
cfg->readEntry("MonsterScore", "200,400,800,1600"), 4);
if (defGroup || cfg->hasKey("FruitScoreString"))
fillStrList(fruitScoreString,
cfg->readEntry("FruitScoreString"), maxLevel+1);
if (defGroup || cfg->hasKey("MonsterScoreString"))
fillStrList(monsterScoreString,
cfg->readEntry("MonsterScoreString"), 4);
APP_CONFIG_END( cfg );
}
void Painter::confScheme()
{
APP_CONFIG_BEGIN( cfg );
SAVE_CONFIG_GROUP( cfg, oldgroup );
QString newgroup;
// if not set, read mode and scheme from the configfile
if (mode == -1 && scheme == -1) {
scheme = cfg->readNumEntry("Scheme", -1);
mode = cfg->readNumEntry("Mode", -1);
// if mode is not set in the defGroup-group, lookup the scheme group
if (scheme != -1 || mode == -1) {
newgroup.sprintf("Scheme %d", scheme);
cfg->setGroup(newgroup);
mode = cfg->readNumEntry("Mode", -1);
RESTORE_CONFIG_GROUP( cfg, oldgroup );
}
}
confLevels();
if (mode != -1) {
newgroup.sprintf("Mode %d", mode);
cfg->setGroup(newgroup);
confLevels(FALSE);
}
if (scheme != -1) {
newgroup.sprintf("Scheme %d", scheme);
cfg->setGroup(newgroup);
confLevels(FALSE);
}
RESTORE_CONFIG_GROUP( cfg, oldgroup );
confMisc();
confScoring();
if (mode != -1) {
newgroup.sprintf("Mode %d", mode);
cfg->setGroup(newgroup);
confMisc(FALSE);
confScoring(FALSE);
}
if (scheme != -1) {
newgroup.sprintf("Scheme %d", scheme);
cfg->setGroup(newgroup);
confMisc(FALSE);
confScoring(FALSE);
}
if ((const char *) *fruitScoreString.at(0) == '\0')
fillScoreString(fruitScoreString, fruitScore);
if ((const char *) *monsterScoreString.at(0) == '\0')
fillScoreString(monsterScoreString, monsterScore);
fillPixmapName(pointPixmapName);
fillPixmapName(wallPixmapName);
fillPixmapName(prisonPixmapName);
fillPixmapName(energizerPixmapName);
fillPixmapName(fruitPixmapName);
fillPixmapName(pacmanPixmapName);
fillPixmapName(dyingPixmapName);
fillPixmapName(eyesPixmapName);
fillPixmapName(monsterPixmapName);
fillPixmapName(fruitScorePixmapName);
fillPixmapName(monsterScorePixmapName);
initPixmaps();
initbackPixmaps();
initRoomPixmap();
RESTORE_CONFIG_GROUP( cfg, oldgroup );
APP_CONFIG_END( cfg );
}
void Painter::setScheme(int Scheme, int Mode, Bitfont *font)
{
bitfont = font;
mode = Mode;
scheme = Scheme;
confScheme();
}
void Painter::setLevel(int Level)
{
level = Level;
initPixmaps();
initbackPixmaps();
initRoomPixmap();
}
int Painter::checkRange(int value, int max, int min)
{
if (value < min) {
printf("Painter::checkRange (value = %d, max = %d, min = %d)\n",
value, max, min);
return min;
} else if (value > max) {
printf("Painter::checkRange (value = %d, max = %d, min = %d)\n",
value, max, min);
return max;
} else
return value;
}
diff --git a/noncore/games/kpacman/referee.cpp b/noncore/games/kpacman/referee.cpp
index 1b810d8..2d0f3be 100644
--- a/noncore/games/kpacman/referee.cpp
+++ b/noncore/games/kpacman/referee.cpp
@@ -1,1417 +1,1408 @@
#include "portable.h"
#if defined( KDE2_PORT )
#include <kapp.h>
#include <kconfig.h>
#include <kstddirs.h>
#include <kaccel.h>
#include <referee.h>
#include <referee.moc>
#elif defined( QPE_PORT )
#include <qaccel.h>
#include <qpe/qpeapplication.h>
#include <qpe/config.h>
#include "referee.h"
#endif
-#include <qdatetm.h>
#include <stdlib.h>
#include <qtimer.h>
-#include <qevent.h>
-#include <qcolor.h>
-#include <qkeycode.h>
#include <qfileinfo.h>
-#include "board.h"
-#include "pacman.h"
-#include "monster.h"
-#include "fruit.h"
-#include "painter.h"
Referee::Referee( QWidget *parent, const char *name, int Scheme, int Mode, Bitfont *font)
: QWidget( parent, name )
{
gameState.resize(12);
gameTimer = 0;
energizerTimer = 0;
focusedPause = FALSE;
setFocusPolicy(QWidget::StrongFocus);
initKeys();
scheme = Scheme;
mode = Mode;
confScheme();
board = new Board(BoardWidth*BoardHeight);
pix = new Painter(board, this, scheme, mode, font);
setFixedSize(pix->levelPix().size());
pacman = new Pacman(board);
fruit = new Fruit(board);
monsters = new QList<Monster>;
monsters->setAutoDelete(TRUE);
monsterRect = new QList<QRect>;
monsterRect->setAutoDelete(TRUE);
energizers = new QList<Energizer>;
energizers->setAutoDelete(TRUE);
energizerRect = new QList<QRect>;
energizerRect->setAutoDelete(TRUE);
pacmanRect.setRect(0, 0, 0, 0);
fruitRect.setRect(0, 0, 0, 0);
QTime midnight( 0, 0, 0 );
srand( midnight.secsTo(QTime::currentTime()) );
lifes = 0;
points = 0;
emit setLifes(lifes);
emit setPoints(points);
intro();
}
void Referee::paintEvent( QPaintEvent *e)
{
if (gameState.testBit(HallOfFame))
return;
QRect rect = e->rect();
if (!rect.isEmpty()) {
QPixmap p = pix->levelPix();
bitBlt(this, rect.x(), rect.y(),
&p, rect.x(), rect.y(), rect.width(), rect.height());
}
if ((gameState.testBit(GameOver) || gameState.testBit(Demonstration)) &&
rect.intersects(pix->rect(board->position(fruithome), tr("GAME OVER"))))
pix->draw(board->position(fruithome), Widget, tr("GAME OVER"), RED);
for (Energizer *e = energizers->first(); e != 0; e = energizers->next()) {
if (e && e->state() == on &&
rect.intersects(pix->rect(e->position(), EnergizerPix)) &&
!(e->position() == pacman->position() && gameState.testBit(Scoring))) {
if (e->pix() != -1)
pix->draw(e->position(), Widget, EnergizerPix, e->pix());
}
}
if (!gameState.testBit(Init)) {
if (!gameState.testBit(Dying) && (fruit->pix() != -1))
if (fruit->state() != active) {
if (rect.intersects(pix->rect(fruit->position(), FruitScorePix, fruit->pix())))
pix->draw(fruit->position(), Widget, FruitScorePix, fruit->pix());
} else {
if (rect.intersects(pix->rect(fruit->position(), FruitPix, fruit->pix())))
pix->draw(fruit->position(), Widget, FruitPix, fruit->pix());
}
for (Monster *m = monsters->first(); m != 0; m = monsters->next())
if (m && m->state() == harmless &&
rect.intersects(pix->rect(m->position(), MonsterPix)) &&
!(m->position() == pacman->position() && gameState.testBit(Scoring))) {
if (m->body() != -1)
pix->draw(m->position(), Widget, MonsterPix, m->body());
if (m->eyes() != -1)
pix->draw(m->position(), Widget, EyesPix, m->eyes());
}
if (!gameState.testBit(Scoring) && !gameState.testBit(LevelDone) &&
rect.intersects(pix->rect(pacman->position(), PacmanPix)) && pacman->pix() != -1)
pix->draw(pacman->position(), Widget, PacmanPix, pacman->pix());
for (Monster *m = monsters->first(); m != 0; m = monsters->next())
if (m && m->state() != harmless &&
rect.intersects(pix->rect(m->position(), MonsterPix)) &&
!(m->position() == pacman->position() && gameState.testBit(Scoring))) {
if (m->body() != -1)
pix->draw(m->position(), Widget, MonsterPix, m->body());
if (m->eyes() != -1)
pix->draw(m->position(), Widget, EyesPix, m->eyes());
}
}
if (gameState.testBit(Scoring) &&
rect.intersects(pix->rect(pacman->position(), MonsterScorePix, monstersEaten-1)))
pix->draw(pacman->position(), Widget, MonsterScorePix, monstersEaten-1);
if (gameState.testBit(Init) && gameState.testBit(Dying) &&
timerCount < pix->maxPixmaps(DyingPix) &&
rect.intersects(pix->rect(pacman->position(), PacmanPix)))
pix->draw(pacman->position(), Widget, DyingPix, timerCount);
if (gameState.testBit(LevelDone) &&
rect.intersects(pix->rect(pacman->position(), PacmanPix)))
pix->draw(pacman->position(), Widget, PacmanPix, pacman->pix());
if (gameState.testBit(Player) &&
rect.intersects(pix->rect(board->position(monsterhome, 0), tr("PLAYER ONE"))))
pix->draw(board->position(monsterhome, 0), Widget, tr("PLAYER ONE"), CYAN);
if (gameState.testBit(Ready) &&
rect.intersects(pix->rect(board->position(fruithome), tr("READY!"))))
pix->draw(board->position(fruithome), Widget, tr("READY!"), YELLOW);
if (gameState.testBit(Paused) &&
rect.intersects(pix->rect((BoardWidth*BoardHeight)/2-BoardWidth, tr("PAUSED"))))
pix->draw((BoardWidth*BoardHeight)/2-BoardWidth, Widget, tr("PAUSED"), RED, BLACK);
}
void Referee::timerEvent( QTimerEvent *e )
{
if (gameState.testBit(HallOfFame))
return;
QRect lastRect;
int lastPix;
bool moved = FALSE;
int eated = 0;
if (e->timerId() == energizerTimer) {
for (int e = 0; e < board->energizers(); e++) {
lastRect = pix->rect(energizers->at(e)->position(), EnergizerPix);
lastPix = energizers->at(e)->pix();
if (energizers->at(e)->move()) {
moved = TRUE;
*energizerRect->at(e) = pix->rect(energizers->at(e)->position(), EnergizerPix);
if (lastPix == energizers->at(e)->pix() &&
lastRect == pix->rect(energizers->at(e)->position(), EnergizerPix))
energizerRect->at(e)->setRect(0, 0, 0, 0);
else
*energizerRect->at(e) = pix->rect(*energizerRect->at(e), lastRect);
}
}
for (int e = 0; e < board->energizers(); e++)
if (!energizerRect->at(e)->isNull())
repaint(*energizerRect->at(e), FALSE);
return;
}
timerCount++;
lastRect = pix->rect(pacman->position(), PacmanPix);
lastPix = pacman->pix();
if (moved = pacman->move()) { // pacman really moved
pacmanRect = pix->rect(pacman->position(), PacmanPix);
if (lastPix == pacman->pix() &&
lastRect == pix->rect(pacman->position(), PacmanPix))
pacmanRect.setRect(0, 0, 0, 0); // nothing to do, because the pixmap
else // and the position isn't changed.
pacmanRect = pix->rect(pacmanRect, lastRect);
} else
pacmanRect.setRect(0, 0, 0, 0);
int pos = pacman->position();
if (moved && board->isMonster(pos) && !gameState.testBit(Dying)) {
for (Monster *m = monsters->first(); m != 0; m = monsters->next())
if (m && m->position() == pos) {
if (m->state() == harmless && !gameState.testBit(Dying)) {
m->setREM(remTicks[level]);
m->setDirection(X); // prevent movement before eaten()
eated++;
if (gameState.testBit(Introducing))
m->setPosition(OUT);
}
if (m->state() == dangerous && !gameState.testBit(Dying))
killed();
}
}
if (moved && !gameState.testBit(Dying)) {
if (board->isPoint(pos)) {
board->reset(pos, Point);
score(pointScore);
pix->erase(pos, PointPix);
}
if (board->isEnergizer(pos)) {
for (int e = 0; e < board->energizers();e++) {
if (energizers->at(e)->position() == pos) {
energizers->at(e)->setOff();
energizers->remove(e);
energizerRect->remove(e);
e = board->energizers();
}
}
board->reset(pos, energizer);
score(energizerScore);
monstersEaten = 0;
for (Monster *m = monsters->first(); m != 0; m = monsters->next())
if (m && m->state() != rem) {
m->setHarmless(harmlessTicks[level], harmlessDurTicks[level],
harmlessWarnTicks[level]);
if (gameState.testBit(Introducing))
m->setDirection(board->turn(m->direction()));
}
}
if (pos == fruit->position() && fruit->state() == active) {
fruit->setEaten(fruitScoreDurTicks[level]);
initFruit(FALSE);
score(fruitScore[fruit->pix()]);
}
}
if (!gameState.testBit(Introducing)) {
if (fruit->state() != active && fruit->pix() >= 0)
lastRect = pix->rect(fruit->position(), FruitScorePix, fruit->pix());
else
lastRect = pix->rect(fruit->position(), FruitPix, fruit->pix());
lastPix = fruit->pix();
if (fruit->move()) {
if (pos == fruit->position() && fruit->state() == active) {
fruit->setEaten(fruitScoreDurTicks[level]);
initFruit(FALSE);
score(fruitScore[fruit->pix()]);
}
if (fruit->state() != active && fruit->pix() >= 0)
fruitRect = pix->rect(fruit->position(), FruitScorePix, fruit->pix());
else
fruitRect = pix->rect(fruit->position(), FruitPix, fruit->pix());
if (lastPix == fruit->pix() && lastRect == fruitRect)
fruitRect.setRect(0, 0, 0, 0);
else
fruitRect = pix->rect(fruitRect, lastRect);
} else
fruitRect.setRect(0, 0, 0, 0);
} else
fruitRect.setRect(0, 0, 0, 0);
int lastBodyPix;
int lastEyesPix;
for (Monster *m = monsters->first(); m != 0; m = monsters->next())
if (m) {
lastRect = pix->rect(m->position(), MonsterPix);
lastBodyPix = m->body();
lastEyesPix = m->eyes();
if (m->move()) {
moved = TRUE;
*monsterRect->at(m->id()) = pix->rect(m->position(), MonsterPix);
if (lastBodyPix == m->body() && lastEyesPix == m->eyes() &&
lastRect == pix->rect(m->position(), MonsterPix))
monsterRect->at(m->id())->setRect(0, 0, 0, 0);
else
*monsterRect->at(m->id()) = pix->rect(*monsterRect->at(m->id()), lastRect);
if (m->position() == pos && !gameState.testBit(Dying)) {
if (m->state() == harmless && !gameState.testBit(Dying)) {
m->setREM(remTicks[level]);
eated++;
if (gameState.testBit(Introducing)) {
m->setPosition(OUT);
m->setDirection(X);
}
}
if (m->state() == dangerous && !gameState.testBit(Dying))
killed();
}
} else
monsterRect->at(m->id())->setRect(0, 0, 0, 0);
}
for (int m = 0; m < board->monsters(); m++)
if (pacmanRect.intersects(*monsterRect->at(m))) {
pacmanRect = pix->rect(pacmanRect, *monsterRect->at(m));
monsterRect->at(m)->setRect(0, 0, 0, 0);
} else
for (int im = m+1; im < board->monsters(); im++)
if (monsterRect->at(m)->intersects(*monsterRect->at(im))) {
*monsterRect->at(m) = pix->rect(*monsterRect->at(m), *monsterRect->at(im));
monsterRect->at(im)->setRect(0, 0, 0, 0);
}
if (!pacmanRect.isNull())
repaint(pacmanRect, FALSE);
if (!fruitRect.isNull())
repaint(fruitRect, FALSE);
for (int m = 0; m < board->monsters(); m++)
if (!monsterRect->at(m)->isNull())
repaint(*monsterRect->at(m), FALSE);
if (board->points() == 0 && !gameState.testBit(Dying))
levelUp();
if (eated > 0 && !gameState.testBit(Dying)) {
timerCount = eated;
eaten();
}
if (gameState.testBit(Introducing) && moved)
introPlay();
}
void Referee::repaintFigures()
{
pacmanRect = pix->rect(pacman->position(), PacmanPix);
for (int e = 0; e < board->energizers(); e++) {
*energizerRect->at(e) = pix->rect(board->position(energizer, e), EnergizerPix);
if (pacmanRect.intersects(*energizerRect->at(e))) {
pacmanRect = pix->rect(pacmanRect, *energizerRect->at(e));
energizerRect->at(e)->setRect(0, 0, 0, 0);
} else
for (int ie = e+1; ie < board->energizers(); ie++)
if (energizerRect->at(e)->intersects(*energizerRect->at(ie))) {
*energizerRect->at(e) = pix->rect(*energizerRect->at(e), *energizerRect->at(ie));
energizerRect->at(ie)->setRect(0, 0, 0, 0);
}
}
if (fruit->pix() != -1 && fruit->state() != active)
fruitRect = pix->rect(fruit->position(), FruitScorePix, fruit->pix());
else
fruitRect = pix->rect(fruit->position(), FruitPix, fruit->pix());
if (pacmanRect.intersects(fruitRect)) {
pacmanRect = pix->rect(pacmanRect, fruitRect);
fruitRect.setRect(0, 0, 0, 0);
}
for (int m = 0; m < board->monsters(); m++) {
*monsterRect->at(m) = pix->rect(board->position(monster, m), MonsterPix);
if (pacmanRect.intersects(*monsterRect->at(m))) {
pacmanRect = pix->rect(pacmanRect, *monsterRect->at(m));
monsterRect->at(m)->setRect(0, 0, 0, 0);
} else
for (int im = m+1; im < board->monsters(); im++)
if (monsterRect->at(m)->intersects(*monsterRect->at(im))) {
*monsterRect->at(m) = pix->rect(*monsterRect->at(m), *monsterRect->at(im));
monsterRect->at(im)->setRect(0, 0, 0, 0);
}
}
if (!pacmanRect.isNull())
repaint(pacmanRect, FALSE);
if (!fruitRect.isNull())
repaint(fruitRect, FALSE);
for (int m = 0; m < board->monsters(); m++)
if (!monsterRect->at(m)->isNull())
repaint(*monsterRect->at(m), FALSE);
for (int e = 0; e < board->energizers(); e++)
if (!energizerRect->at(e)->isNull())
repaint(*energizerRect->at(e), FALSE);
}
void Referee::initKeys()
{
APP_CONFIG_BEGIN( cfg );
QString up("Up");
up = cfg->readEntry("upKey", (const char*) up);
UpKey = KAccel::stringToKey(up);
QString down("Down");
down = cfg->readEntry("downKey", (const char*) down);
DownKey = KAccel::stringToKey(down);
QString left("Left");
left = cfg->readEntry("leftKey", (const char*) left);
LeftKey = KAccel::stringToKey(left);
QString right("Right");
right = cfg->readEntry("rightKey", (const char*) right);
RightKey = KAccel::stringToKey(right);
APP_CONFIG_END( cfg );
}
void Referee::fillArray(QArray<int> &array, QString values, int max)
{
if (max < 0)
max = values.contains(',')+1;
array.resize(max);
int last = 0;
bool ok;
QString value;
for (uint i = 0; i < array.size(); i++) {
if (values.find(',') < 0 && values.length() > 0) {
value = values;
values = "";
}
if (values.find(',') >= 0) {
value = values.left(values.find(','));
values.remove(0,values.find(',')+1);
}
array[i] = value.toInt(&ok);
if (ok)
last = array[i];
else
array[i] = last;
}
}
void Referee::fillStrList(QStrList &list, QString values, int max)
{
if (!list.isEmpty())
list.clear();
QString last = "";
QString value;
for (uint i = 0; i < (uint) max; i++) {
if (values.find(',') < 0 && values.length() > 0) {
value = values;
values = "";
}
if (values.find(',') >= 0) {
value = values.left(values.find(','));
values.remove(0,values.find(',')+1);
}
if (!value.isEmpty())
last = value;
list.append(last);
}
}
void Referee::fillMapName()
{
QStrList list = mapName;
if (!mapName.isEmpty())
mapName.clear();
QString map;
QFileInfo fileInfo;
for (uint i = 0; i < list.count(); i++) {
map = list.at(i);
if (map.left(1) != "/" && map.left(1) != "~")
map = FIND_APP_DATA( mapDirectory+map );
fileInfo.setFile(map);
if (!fileInfo.isReadable())
map = "";
mapName.append(map);
}
}
void Referee::confLevels(bool defGroup)
{
APP_CONFIG_BEGIN( cfg );
if (defGroup || cfg->hasKey("Levels"))
maxLevel = cfg->readNumEntry("Levels", 13);
APP_CONFIG_END( cfg );
}
void Referee::confMisc(bool defGroup)
{
APP_CONFIG_BEGIN( cfg );
if (defGroup || cfg->hasKey("PixmapDirectory")) {
pixmapDirectory = cfg->readEntry("PixmapDirectory");
if (pixmapDirectory.left(1) != "/" && pixmapDirectory.left(1) != "~")
pixmapDirectory.insert(0, "pics/");
if (pixmapDirectory.right(1) != "/")
pixmapDirectory.append("/");
}
if (defGroup || cfg->hasKey("MapDirectory")) {
mapDirectory = cfg->readEntry("MapDirectory");
if (mapDirectory.left(1) != "/" && mapDirectory.left(1) != "~")
mapDirectory.insert(0, "maps/");
if (mapDirectory.right(1) != "/")
mapDirectory.append("/");
}
if (defGroup || cfg->hasKey("MapName"))
fillStrList(mapName, cfg->readEntry("MapName", "map"), maxLevel+1);
if (defGroup || cfg->hasKey("MonsterIQ"))
fillArray(monsterIQ, cfg->readEntry("MonsterIQ", "0,170,180,170,180,170,180"), maxLevel+1);
if (defGroup || cfg->hasKey("FruitIQ"))
fillArray(fruitIQ, cfg->readEntry("FruitIQ", "0,170,180,170,180,170,180"), maxLevel+1);
if (defGroup || cfg->hasKey("FruitIndex"))
fillArray(fruitIndex, cfg->readEntry("FruitIndex", "0"), maxLevel+1);
APP_CONFIG_END( cfg );
}
void Referee::confTiming(bool defGroup)
{
APP_CONFIG_BEGIN( cfg );
if (defGroup || cfg->hasKey("SpeedMS"))
fillArray(speed, cfg->readEntry("SpeedMS", "20"), maxLevel+1);
if (defGroup || cfg->hasKey("PacmanTicks"))
fillArray(pacmanTicks,cfg->readEntry("PacmanTicks", "3"), maxLevel+1);
if (defGroup || cfg->hasKey("RemTicks"))
fillArray(remTicks, cfg->readEntry("RemTicks", "1"), maxLevel+1);
if (defGroup || cfg->hasKey("DangerousTicks"))
fillArray(dangerousTicks, cfg->readEntry("DangerousTicks", "3"), maxLevel+1);
if (defGroup || cfg->hasKey("HarmlessTicks"))
fillArray(harmlessTicks, cfg->readEntry("HarmlessTicks", "7,6,,5,,4"), maxLevel+1);
if (defGroup || cfg->hasKey("HarmlessDurationTicks"))
fillArray(harmlessDurTicks, cfg->readEntry("HarmlessDurationTicks", "375,,,300,,250,200,150"), maxLevel+1);
if (defGroup || cfg->hasKey("HarmlessWarningTicks"))
fillArray(harmlessWarnTicks, cfg->readEntry("HarmlessWarningTicks", "135"), maxLevel+1);
if (defGroup || cfg->hasKey("ArrestTicks"))
fillArray(arrestTicks, cfg->readEntry("ArrestTicks", "6"), maxLevel+1);
if (defGroup || cfg->hasKey("ArrestDurationTicks"))
fillArray(arrestDurTicks, cfg->readEntry("ArrestDurationTicks", "200,,,150"), maxLevel+1);
if (defGroup || cfg->hasKey("FruitTicks"))
fillArray(fruitTicks, cfg->readEntry("FruitTicks", "7,6,,5,,4"), maxLevel+1);
if (defGroup || cfg->hasKey("FruitAppearsTicks"))
fillArray(fruitAppearsTicks, cfg->readEntry("FruitAppearsTicks", "1000,,1500,2000,2500,3000,3500,4000"), maxLevel+1);
if (defGroup || cfg->hasKey("FruitDurationTicks"))
fillArray(fruitDurTicks, cfg->readEntry("FruitDurationTicks", "500,,,400,350,300,,250,200,150"), maxLevel+1);
if (defGroup || cfg->hasKey("FruitScoreDurationTicks"))
fillArray(fruitScoreDurTicks, cfg->readEntry("FruitScoreDurationTicks", "150"), maxLevel+1);
if (defGroup || cfg->hasKey("MonsterScoreDurationMS"))
monsterScoreDurMS = cfg->readNumEntry("MonsterScoreDurationMS", 1000);
if (defGroup || cfg->hasKey("PlayerDurationMS"))
playerDurMS = cfg->readNumEntry("PlayerDurationMS", 3000);
if (defGroup || cfg->hasKey("ReadyDurationMS"))
readyDurMS = cfg->readNumEntry("ReadyDurationMS", 2000);
if (defGroup || cfg->hasKey("GameOverDurationMS"))
gameOverDurMS = cfg->readNumEntry("GameOverDurationMS", 3000);
if (defGroup || cfg->hasKey("AfterPauseMS"))
afterPauseMS = cfg->readNumEntry("AfterPauseMS", 1000);
if (defGroup || cfg->hasKey("DyingPreAnimationMS"))
dyingPreAnimationMS = cfg->readNumEntry("DyingPreAnimationMS", 1000);
if (defGroup || cfg->hasKey("DyingAnimationMS"))
dyingAnimationMS = cfg->readNumEntry("DyingAnimationMS", 100);
if (defGroup || cfg->hasKey("DyingPostAnimationMS"))
dyingPostAnimationMS = cfg->readNumEntry("DyingPostAnimationMS", 500);
if (defGroup || cfg->hasKey("IntroAnimationMS"))
introAnimationMS = cfg->readNumEntry("IntroAnimationMS", 800);
if (defGroup || cfg->hasKey("IntroPostAnimationMS"))
introPostAnimationMS = cfg->readNumEntry("IntroPostAnimationMS", 1000);
if (defGroup || cfg->hasKey("LevelUpPreAnimationMS"))
levelUpPreAnimationMS = cfg->readNumEntry("LevelUpPreAnimationMS", 2000);
if (defGroup || cfg->hasKey("LevelUpAnimationMS"))
levelUpAnimationMS = cfg->readNumEntry("LevelUpAnimationMS", 2000);
if (defGroup || cfg->hasKey("EnergizerAnimationMS"))
energizerAnimationMS = cfg->readNumEntry("EnergizerAnimationMS", 200);
APP_CONFIG_END( cfg );
}
void Referee::confScoring(bool defGroup)
{
APP_CONFIG_BEGIN( cfg );
if (defGroup || cfg->hasKey("PointScore"))
pointScore = cfg->readNumEntry("PointScore", 10);
if (defGroup || cfg->hasKey("EnergizerScore"))
energizerScore = cfg->readNumEntry("EnergizerScore", 50);
if (defGroup || cfg->hasKey("FruitScore"))
fillArray(fruitScore, cfg->readEntry("FruitScore", "100,300,500,,700,,1000,,2000,,3000,,5000"), maxLevel+1);
if (defGroup || cfg->hasKey("MonsterScore"))
fillArray(monsterScore, cfg->readEntry("MonsterScore", "200,400,800,1600"), 4);
if (defGroup || cfg->hasKey("ExtraLifeScore"))
fillArray(extraLifeScore, cfg->readEntry("ExtraLifeScore", "10000"), -1);
APP_CONFIG_END( cfg );
}
void Referee::confScheme()
{
APP_CONFIG_BEGIN( cfg );
SAVE_CONFIG_GROUP( cfg, oldgroup );
QString newgroup;
// if not set, read mode and scheme from the configfile
if (mode == -1 && scheme == -1) {
scheme = cfg->readNumEntry("Scheme", -1);
mode = cfg->readNumEntry("Mode", -1);
// if mode is not set in the defGroup-group, lookup the scheme group
if (scheme != -1 || mode == -1) {
newgroup.sprintf("Scheme %d", scheme);
cfg->setGroup(newgroup);
mode = cfg->readNumEntry("Mode", -1);
RESTORE_CONFIG_GROUP( cfg, oldgroup );
}
}
confLevels();
if (mode != -1) {
newgroup.sprintf("Mode %d", mode);
cfg->setGroup(newgroup);
confLevels(FALSE);
}
if (scheme != -1) {
newgroup.sprintf("Scheme %d", scheme);
cfg->setGroup(newgroup);
confLevels(FALSE);
}
RESTORE_CONFIG_GROUP( cfg, oldgroup );
confMisc();
confTiming();
confScoring();
if (mode != -1) {
newgroup.sprintf("Mode %d", mode);
cfg->setGroup(newgroup);
confMisc(FALSE);
confTiming(FALSE);
confScoring(FALSE);
}
if (scheme != -1) {
newgroup.sprintf("Scheme %d", scheme);
cfg->setGroup(newgroup);
confMisc(FALSE);
confTiming(FALSE);
confScoring(FALSE);
}
fillMapName();
RESTORE_CONFIG_GROUP( cfg, oldgroup );
APP_CONFIG_END( cfg );
}
void Referee::setScheme(int Scheme, int Mode, Bitfont *font)
{
mode = Mode;
scheme = Scheme;
confScheme();
pix->setScheme(scheme, mode, font);
pacman->setMaxPixmaps(pix->maxPixmaps(PacmanPix));
fruit->setMaxPixmaps(pix->maxPixmaps(FruitPix));
for (Monster *m = monsters->first(); m != 0; m = monsters->next())
if (m)
m->setMaxPixmaps(pix->maxPixmaps(MonsterPix), pix->maxPixmaps(EyesPix));
for (Energizer *e = energizers->first(); e != 0; e = energizers->next())
if (e)
e->setMaxPixmaps(pix->maxPixmaps(EnergizerPix));
if (gameState.testBit(Introducing))
for (int i = 0; i < (gameState.testBit(Init) ? timerCount : 15); i++)
introPaint(i);
setFixedSize(pix->levelPix().size());
repaint();
}
void Referee::keyPressEvent( QKeyEvent *k )
{
uint key = k->key();
if ( !gameState.testBit(Playing) && ( key == Key_Up || key == Key_Down || key == Key_Left || key == Key_Right ) )
play();
if (gameState.testBit(Paused) || gameState.testBit(HallOfFame) ||
gameState.testBit(Demonstration) || gameState.testBit(Dying) ||
gameState.testBit(Ready) || gameState.testBit(LevelDone) ||
!gameState.testBit(Playing))
return;
if (key == UpKey)
pacman->setDirection(N);
else if (key == DownKey)
pacman->setDirection(S);
else if (key == RightKey)
pacman->setDirection(E);
else if (key == LeftKey)
pacman->setDirection(W);
#ifdef CHEATS
else if (key == Key_L) { printf("levelUp()\n"); levelUp(); }
else if (key == Key_F) { printf("fruit->move(TRUE)\n"); fruit->move(TRUE); repaint(FALSE); }
else if (key == Key_E) { printf("setLifes(++lifes)\n"); emit setLifes(++lifes); }
#endif
else {
k->ignore();
return;
}
k->accept();
}
void Referee::score(int p)
{
if (!gameState.testBit(Playing))
return;
if ((points += p) < 0)
points = 0;
emit setPoints(points);
if (points >= nextExtraLifeScore) {
emit setLifes(++lifes);
if (extraLifeScoreIndex < (int) extraLifeScore.size()-1)
extraLifeScoreIndex++;
if (extraLifeScore[extraLifeScoreIndex] < 0)
nextExtraLifeScore = extraLifeScore[extraLifeScoreIndex] * -1;
else
nextExtraLifeScore += extraLifeScore[extraLifeScoreIndex];
}
}
void Referee::eaten()
{
if (gameState.testBit(Ready))
return;
stop();
if (monstersEaten < 4)
monstersEaten++;
gameState.setBit(Scoring);
score(monsterScore[monstersEaten-1]);
repaint(pix->rect(pix->rect(pacman->position(), MonsterPix),
pix->rect(pacman->position(), MonsterScorePix, monstersEaten-1)));
if (--timerCount > 0)
QTimer::singleShot( monsterScoreDurMS, this, SLOT(eaten()));
else {
for (Monster *m = monsters->first(); m != 0; m = monsters->next())
if (m && m->direction() == X && !gameState.testBit(Introducing))
m->setDirection(N);
if (monstersEaten != 4 || !gameState.testBit(Introducing))
QTimer::singleShot( monsterScoreDurMS, this, SLOT(start()));
}
}
void Referee::toggleHallOfFame()
{
gameState.toggleBit(HallOfFame);
}
void Referee::hallOfFame()
{
if (gameState.testBit(HallOfFame)) // If the HallOfFame is switched on manually, toggle the
toggleHallOfFame(); // bit twice.
emit setLevel(0); // Clear status display for hall of fame
emit setScore(level, 0);
emit forcedHallOfFame(TRUE);
}
void Referee::pause()
{
static int pausedTimer = 0;
if (!gameState.testBit(Paused)) {
pausedTimer = gameTimer;
stop();
stopEnergizer();
gameState.setBit(Paused);
repaint(pix->rect((BoardWidth*BoardHeight)/2-BoardWidth, tr("PAUSED")), FALSE);
} else {
gameState.clearBit(Paused);
repaint(pix->rect((BoardWidth*BoardHeight)/2-BoardWidth, tr("PAUSED")), FALSE);
if (pausedTimer) {
pausedTimer = 0;
start();
}
}
emit togglePaused();
}
void Referee::intro()
{
stop();
stopEnergizer();
bool paused = gameState.testBit(Paused);
gameState.fill(FALSE);
gameState.setBit(Introducing);
gameState.setBit(Init);
if (paused)
gameState.setBit(Paused);
level = 0;
emit setLevel(level);
board->init(Intro);
pix->setLevel(level);
initPacman();
initFruit();
initMonsters();
initEnergizers();
repaint();
monstersEaten = 0;
timerCount = 0;
introPlay();
}
void Referee::introMonster(int id)
{
Monster *m = new Monster(board, id);
m->setPosition((10+id*6)*BoardWidth+10);
m->setDirection(E);
m->setDangerous(dangerousTicks[level], monsterIQ[level]);
m->setMaxPixmaps(pix->maxPixmaps(MonsterPix), pix->maxPixmaps(EyesPix));
if (m->body() != -1)
pix->draw(m->position(), RoomPix, MonsterPix, m->body());
if (m->eyes() != -1)
pix->draw(m->position(), RoomPix, EyesPix, m->eyes());
repaint(pix->rect(m->position(), MonsterPix), FALSE);
m->setPosition(OUT);
}
void Referee::introPaint(int t)
{
QString pts;
switch (t) {
case 0 : repaint(pix->draw(16, 6, RoomPix, tr("CHARACTER"), WHITE, QColor(), AlignLeft), FALSE);
repaint(pix->draw(36, 6, RoomPix, tr("/"), WHITE, QColor(), AlignLeft), FALSE);
repaint(pix->draw(40, 6, RoomPix, tr("NICKNAME"), WHITE, QColor(), AlignLeft), FALSE);
break;
case 1 : introMonster(0);
break;
case 2 : repaint(pix->draw(16, 10, RoomPix, tr("-SHADOW"), RED, QColor(), AlignLeft), FALSE);
break;
case 3 : repaint(pix->draw(38, 10, RoomPix, tr("\"BLINKY\""), RED, QColor(), AlignLeft), FALSE);
break;
case 4 : introMonster(1);
break;
case 5 : repaint(pix->draw(16, 16, RoomPix, tr("-SPEEDY"), PINK, QColor(), AlignLeft), FALSE);
break;
case 6 : repaint(pix->draw(38, 16, RoomPix, tr("\"PINKY\""), PINK, QColor(), AlignLeft), FALSE);
break;
case 7 : introMonster(2);
break;
case 8 : repaint(pix->draw(16, 22, RoomPix, tr("-BASHFUL"), CYAN, QColor(), AlignLeft), FALSE);
break;
case 9 : repaint(pix->draw(38, 22, RoomPix, tr("\"INKY\""), CYAN, QColor(), AlignLeft), FALSE);
break;
case 10 : introMonster(3);
break;
case 11 : repaint(pix->draw(16, 28, RoomPix, tr("-POKEY"), ORANGE, QColor(), AlignLeft), FALSE);
break;
case 12 : repaint(pix->draw(38, 28, RoomPix, tr("\"CLYDE\""), ORANGE, QColor(), AlignLeft), FALSE);
break;
case 13 : pts.sprintf("%d", pointScore);
repaint(pix->draw(28, 44, RoomPix, pts.data(), WHITE, QColor(), AlignRight), FALSE);
repaint(pix->draw(31, 44, RoomPix, "\x1C\x1D\x1E", WHITE, QColor(), AlignLeft), FALSE);
pts.sprintf("%d", energizerScore);
repaint(pix->draw(28, 48, RoomPix, pts.data(), WHITE, QColor(), AlignRight), FALSE);
repaint(pix->draw(31, 48, RoomPix, "\x1C\x1D\x1E", WHITE, QColor(), AlignLeft), FALSE);
break;
case 14 : // "@ 1980 MIDWAY MFG.CO."
#if defined( KDE2_PORT )
repaint(pix->draw(30, 58, RoomPix, "© 1998-2002 J.THÖNNISSEN", PINK), FALSE);
#elif defined( QPE_PORT )
repaint(pix->draw(30, 55, RoomPix, "© 1998-2002 J.THÖNNISSEN", PINK), FALSE);
repaint(pix->draw(29, 58, RoomPix, tr("QTOPIA PORT: CATALIN CLIMOV"), GREEN), FALSE);
repaint(pix->draw(29, 61, RoomPix, tr("PRESS CURSOR TO START"), GREEN), FALSE);
#endif
break;
}
}
void Referee::introPlay()
{
if (!gameState.testBit(Introducing) || gameState.testBit(Ready))
return;
if (gameState.testBit(Paused) || gameState.testBit(HallOfFame)) {
QTimer::singleShot(afterPauseMS, this, SLOT(introPlay()));
return;
}
if (!gameState.testBit(Init)) {
if (monstersEaten == 4) {
stop();
QTimer::singleShot(introPostAnimationMS, this, SLOT(demo()));
}
if (pacman->direction() == W) {
int id = -1;
if (pacman->position() == 37*BoardWidth-6)
id = 0;
else
if (board->isMonster(37*BoardWidth-6))
for (Monster *m = monsters->first(); m != 0; m = monsters->next())
if (m && m->position() == 37*BoardWidth-6) {
id = m->id();
id++;
break;
}
if (id >= 0 && id <= 4)
for (Monster *m = monsters->first(); m != 0; m = monsters->next())
if (m && m->id() == id && m->position() == OUT) {
m->setPosition(37*BoardWidth-1);
m->setDirection(W);
m->setDangerous(dangerousTicks[level], monsterIQ[level]);
board->set(37*BoardWidth-1, monsterhome, id);
repaint(pix->rect(m->position(), MonsterPix));
break;
}
}
return;
}
if (timerCount < 15)
introPaint(timerCount);
switch (timerCount) {
case 13 : board->set(44*BoardWidth+22, Point);
pix->drawPoint(44*BoardWidth+22);
repaint(pix->rect(44*BoardWidth+22, PointPix), FALSE);
energizers->at(0)->setPosition(48*BoardWidth+22);
energizers->at(0)->setOn();
repaint(pix->rect(48*BoardWidth+22, EnergizerPix), FALSE);
break;
case 14 : energizers->at(1)->setPosition(36*BoardWidth+10);
energizers->at(1)->setOn();
repaint(pix->rect(36*BoardWidth+10, EnergizerPix), FALSE);
for (int pos = 8; pos < BoardWidth; pos++) {
board->set(34*BoardWidth+pos, out);
board->set(38*BoardWidth+pos, out);
}
board->set(36*BoardWidth+8, out);
break;
case 15 : gameState.clearBit(Init);
initPacman();
pacman->setDemo(TRUE);
pacman->setPosition(37*BoardWidth-1);
repaintFigures();
start();
return;
}
if (timerCount++ < 15)
QTimer::singleShot(introAnimationMS, this, SLOT(introPlay()));
}
void Referee::demo()
{
if (gameState.testBit(Ready))
return;
if (gameState.testBit(Paused) || gameState.testBit(HallOfFame)) {
QTimer::singleShot(afterPauseMS, this, SLOT(demo()));
return;
}
stop();
stopEnergizer();
gameState.fill(FALSE);
gameState.setBit(Init);
gameState.setBit(Demonstration);
level = 0;
emit setLevel(level);
board->init(Demo, mapName.at(0));
pix->setLevel(level);
initPacman();
initFruit();
initMonsters();
initEnergizers();
gameState.clearBit(Init);
repaint();
timerCount = 0;
QTimer::singleShot(playerDurMS, this, SLOT(start()));
}
void Referee::play()
{
stop();
stopEnergizer();
gameState.fill(FALSE);
gameState.setBit(Init);
gameState.setBit(Playing);
gameState.setBit(Player);
gameState.setBit(Ready);
lifes = 3;
level = 1;
points = 0;
extraLifeScoreIndex = 0;
nextExtraLifeScore = extraLifeScore[extraLifeScoreIndex];
if (nextExtraLifeScore < 0)
nextExtraLifeScore *= -1;
board->init(Level, mapName.at(level));
pix->setLevel(level);
initPacman();
initFruit();
initMonsters();
initEnergizers();
repaint();
emit toggleNew();
emit setLifes(lifes);
emit setLevel(level);
emit setPoints(points);
repaint(pix->rect(board->position(monsterhome, 0), tr("PLAYER ONE")), FALSE);
repaint(pix->rect(board->position(fruithome), tr("READY!")), FALSE);
timerCount = 0;
QTimer::singleShot(playerDurMS, this, SLOT(ready()));
}
void Referee::ready()
{
if (gameState.testBit(Paused) || gameState.testBit(HallOfFame)) {
QTimer::singleShot(afterPauseMS, this, SLOT(ready()));
return;
}
if (gameState.testBit(Player)) {
emit setLifes(--lifes);
gameState.clearBit(Player);
gameState.clearBit(Init);
repaint(pix->rect(board->position(monsterhome, 0), tr("PLAYER ONE")), FALSE);
repaintFigures();
QTimer::singleShot(playerDurMS, this, SLOT(ready()));
return;
}
if (gameState.testBit(Ready)) {
gameState.clearBit(Ready);
repaint(pix->rect(board->position(fruithome), tr("READY!")), FALSE);
start();
} else {
gameState.setBit(Ready);
gameState.clearBit(Init);
repaint(pix->rect(board->position(fruithome), tr("READY!")), FALSE);
QTimer::singleShot(readyDurMS, this, SLOT(ready()));
}
}
void Referee::levelUp()
{
stop();
stopEnergizer();
gameState.setBit(LevelDone);
pacman->setPosition(pacman->position()); // set mouthPosition to "0"
repaint(pix->rect(pacman->position(), PacmanPix));
timerCount = 0;
QTimer::singleShot(levelUpPreAnimationMS, this, SLOT(levelUpPlay()));
}
void Referee::levelUpPlay()
{
if (gameState.testBit(Ready))
return;
if (gameState.testBit(Paused) || gameState.testBit(HallOfFame)) {
QTimer::singleShot(afterPauseMS, this, SLOT(levelUpPlay()));
return;
}
switch (timerCount) {
case 0 : gameState.setBit(Init);
setOnEnergizers();
repaintFigures();
break;
case 1 : gameState.clearBit(LevelDone);
repaint(pix->rect(pacman->position(), PacmanPix));
break;
}
if (timerCount++ < 2) {
QTimer::singleShot(levelUpAnimationMS, this, SLOT(levelUpPlay()));
return;
}
gameState.clearBit(Init);
if (gameState.testBit(Demonstration)) {
hallOfFame();
return;
}
if (level < maxLevel)
level++;
board->init(Level, mapName.at(level));
pix->setLevel(level);
initPacman();
initFruit();
initMonsters();
initEnergizers();
repaint();
emit setLevel(level);
ready();
}
void Referee::start()
{
if (gameState.testBit(Ready))
return;
if (gameState.testBit(Paused) || gameState.testBit(HallOfFame)) {
QTimer::singleShot(afterPauseMS, this, SLOT(start()));
return;
}
if (gameState.testBit(Scoring)) {
gameState.clearBit(Scoring);
repaint(pix->rect(pix->rect(pacman->position(), MonsterPix),
pix->rect(pacman->position(), MonsterScorePix, monstersEaten-1)));
}
if (!gameTimer)
gameTimer = startTimer( speed [level] );
if (!energizerTimer)
energizerTimer = startTimer( energizerAnimationMS );
}
void Referee::start(int t)
{
gameTimer = startTimer(t);
}
void Referee::stop()
{
if (gameTimer) {
killTimer (gameTimer);
gameTimer = 0;
}
}
void Referee::stopEnergizer()
{
if (energizerTimer) {
killTimer (energizerTimer);
energizerTimer = 0;
}
}
void Referee::killed()
{
if (gameState.testBit(Ready))
return;
if (!gameState.testBit(Dying)) {
gameState.setBit(Dying);
pacman->setDirection(X, TRUE);
for (Monster *m = monsters->first(); m != 0; m = monsters->next())
if (m)
m->setDirection(X);
QTimer::singleShot(dyingPreAnimationMS, this, SLOT(killed()));
} else {
stop();
if (gameState.testBit(Paused) || gameState.testBit(HallOfFame)) {
QTimer::singleShot(afterPauseMS, this, SLOT(killed()));
return;
}
gameState.setBit(Init);
repaintFigures();
timerCount = 0;
killedPlay();
}
}
void Referee::killedPlay()
{
if (!gameState.testBit(Dying) || gameState.testBit(Ready))
return;
if (gameState.testBit(Paused) || gameState.testBit(HallOfFame)) {
QTimer::singleShot(afterPauseMS, this, SLOT(killedPlay()));
return;
}
if (timerCount <= pix->maxPixmaps(DyingPix)) {
repaint(pix->rect(pacman->position(), PacmanPix), FALSE);
if (timerCount >= pix->maxPixmaps(DyingPix)-1 || timerCount == 0)
QTimer::singleShot(dyingPostAnimationMS, this, SLOT(killedPlay()));
else
QTimer::singleShot(dyingAnimationMS, this, SLOT(killedPlay()));
timerCount++;
} else {
gameState.clearBit(Dying);
stopEnergizer();
if (lifes == 0) {
gameState.setBit(GameOver);
gameState.clearBit(Playing);
for (int e = 0; e < board->energizers(); e++) {
energizers->at(e)->setOff();
repaint(pix->rect(board->position(energizer, e), EnergizerPix), FALSE);
}
repaint(pix->rect(board->position(fruithome), tr("GAME OVER")), FALSE);
QTimer::singleShot(gameOverDurMS, this, SLOT(hallOfFame()));
} else {
gameState.clearBit(Init);
initPacman();
initFruit();
initMonsters();
initEnergizers();
emit setLifes(--lifes);
repaintFigures();
ready();
}
}
}
void Referee::initPacman()
{
pacman->setMaxPixmaps(pix->maxPixmaps(PacmanPix));
pacman->setDemo(gameState.testBit(Demonstration));
pacman->setPosition(board->position(pacmanhome));
pacman->setDirection(W, TRUE);
pacman->setAlive(pacmanTicks[level]);
}
void Referee::initFruit(bool fullInitialization)
{
if (fullInitialization) {
fruit->setMaxPixmaps(pix->maxPixmaps(FruitPix));
if (fruitIndex[level] == 0)
fruit->setLevel(level, fruitAppearsTicks[level],
fruitDurTicks[level], fruitTicks[level]);
else if (fruitIndex[level] < 0)
fruit->setLevel(pix->maxPixmaps(FruitPix)+1,
fruitAppearsTicks[level],
fruitDurTicks[level], fruitTicks[level]);
else
fruit->setLevel(fruitIndex[level], fruitAppearsTicks[level],
fruitDurTicks[level], fruitTicks[level]);
}
if (board->tunnels() > 0)
fruit->setMovement(board->position(tunnel, rand() % board->tunnels()),
board->position(tunnel, rand() % board->tunnels()),
fruitIQ[level]);
}
void Referee::initMonsters()
{
if( !monsters->isEmpty())
monsters->clear();
if( !monsterRect->isEmpty())
monsterRect->clear();
for (int id = 0; id < (gameState.testBit(Introducing) ? 4 : board->monsters()); id++) {
Monster *m = new Monster(board, id);
monsters->append(m);
QRect *r = new QRect();
monsterRect->append(r);
if (!gameState.testBit(Introducing)) {
m->setFreedom(board->position(prisonexit));
m->setDangerous(dangerousTicks[level], monsterIQ[level]);
if (id == 0)
m->setPrison(board->position(prisonentry));
else {
m->setPrison(board->position(monsterhome, id));
m->setArrested(arrestTicks[level], arrestDurTicks[level]*id);
}
m->setPosition(board->position(monsterhome, id));
switch(id) {
case 0 : m->setDirection(W); break;
case 1 : m->setDirection(N); break;
default : m->setDirection(S);
}
}
m->setMaxPixmaps(pix->maxPixmaps(MonsterPix), pix->maxPixmaps(EyesPix));
}
}
void Referee::initEnergizers()
{
if( !energizers->isEmpty())
energizers->clear();
if( !energizerRect->isEmpty())
energizerRect->clear();
for (int id = 0; id < (gameState.testBit(Introducing) ? 2 : board->energizers()); id++) {
Energizer *e = new Energizer(board);
energizers->append(e);
QRect *r = new QRect();
energizerRect->append(r);
if (!gameState.testBit(Introducing)) {
e->setPosition(board->position(energizer, id));
e->setOn();
}
e->setMaxPixmaps(pix->maxPixmaps(EnergizerPix));
}
}
void Referee::setOnEnergizers()
{
for (int e = 0; e < board->energizers(); e++) {
energizers->at(e)->setOn();
}
}
void Referee::setFocusOutPause(bool FocusOutPause)
{
focusOutPause = FocusOutPause;
}
void Referee::setFocusInContinue(bool FocusInContinue)
{
focusInContinue = FocusInContinue;
}
void Referee::focusInEvent(QFocusEvent *)
{
if (focusInContinue && focusedPause &&
gameState.testBit(Paused) && gameState.testBit(Playing)) {
pause();
}
}
void Referee::focusOutEvent(QFocusEvent *)
{
if (focusOutPause && !gameState.testBit(Paused) && gameState.testBit(Playing)) {
focusedPause = TRUE;
pause();
}
}
diff --git a/noncore/games/kpacman/score.cpp b/noncore/games/kpacman/score.cpp
index e91771b..6878b81 100644
--- a/noncore/games/kpacman/score.cpp
+++ b/noncore/games/kpacman/score.cpp
@@ -1,581 +1,575 @@
#include "portable.h"
#if defined( KDE2_PORT )
#include <score.h>
#include <score.moc>
#include <kaccel.h>
#include <kapp.h>
#include <kconfig.h>
#include <kstddirs.h>
#include <kmessagebox.h>
#elif defined( QPE_PORT )
#include <qaccel.h>
#include <qpe/config.h>
#include "score.h"
#endif
#include <stdlib.h>
#include <ctype.h>
-#include <qpixmap.h>
-#include <qstring.h>
-#include <qdstream.h>
-#include <qkeycode.h>
#include <qtimer.h>
-#include <qfileinfo.h>
-#include "bitfont.h"
Score::Score(QWidget *parent, const char *name, int Scheme, int Mode, Bitfont *font) : QWidget(parent, name)
{
setFocusPolicy(QWidget::StrongFocus);
paused = FALSE;
lastScore = -1;
lastPlayer = -1;
cursorBlinkTimer = 0;
cursorBlinkMS = -1;
cursor.x = -1;
cursor.y = -1;
cursor.on = FALSE;
cursor.chr = QChar('?');
initKeys();
scheme = Scheme;
mode = Mode;
confScheme();
bitfont = font;
highscoreFile.setName(locateHighscoreFilePath().filePath());
read();
for (int p = 0; p < maxPlayer; p++) {
playerScore[p] = 0;
playerName[p] = getenv("LOGNAME");
if (playerName[p].length() < minPlayerNameLength)
playerName[p].setExpand(minPlayerNameLength-1, ' ');
for (uint i = 0; i < playerName[p].length(); i++)
if (playerName[p].at(i) < bitfont->firstChar() ||
playerName[p].at(i) > bitfont->lastChar())
playerName[p].at(i) = playerName[p].at(i).upper();
}
}
Score::~Score()
{
// write();
}
void Score::paintEvent( QPaintEvent *e)
{
if (rect(1, 0, tr(" 1UP ")).intersects(e->rect())) {
QPixmap pix;
QColor fg = BLACK;
if (cursor.on || paused || lastPlayer != 0)
fg = WHITE;
pix = bitfont->text(tr(" 1UP "), fg, BLACK);
bitBlt(this, x(1), y(0), &pix);
}
if (rect(8, 0, tr(" HIGH SCORE ")).intersects(e->rect())) {
QPixmap pix = bitfont->text(tr(" HIGH SCORE "), WHITE, BLACK);
bitBlt(this, x(8), y(0), &pix);
}
if (maxPlayer > 1 && rect(21, 0, tr(" 2UP ")).intersects(e->rect())) {
QPixmap pix;
QColor fg = BLACK;
if (cursor.on || paused || lastPlayer != 1)
fg = WHITE;
pix = bitfont->text(tr(" 2UP "), fg, BLACK);
bitBlt(this, x(21), y(0), &pix);
}
QString s;
s.sprintf("%6d0", playerScore[0]/10);
if (rect(0, 1, s).intersects(e->rect())) {
QPixmap pix = bitfont->text(s, WHITE, BLACK);
bitBlt(this, x(0), y(1), &pix);
}
s.sprintf("%8d0", HighScore/10);
if (rect(8, 1, s).intersects(e->rect())) {
QPixmap pix = bitfont->text(s, WHITE, BLACK);
bitBlt(this, x(8), y(1), &pix);
}
if (lastScore >= 0) {
if (rect(1, 4*1.25, tr(" CONGRATULATIONS ")).intersects(e->rect())) {
QPixmap pix = bitfont->text(tr(" CONGRATULATIONS "), YELLOW, BLACK);
bitBlt(this, x(1), y(4*1.25), &pix);
}
if (rect(1, 6*1.25, tr(" YOU HAVE ARCHIEVED ")).intersects(e->rect())) {
QPixmap pix = bitfont->text(tr(" YOU HAVE ARCHIEVED "), CYAN, BLACK);
bitBlt(this, x(1), y(6*1.25), &pix);
}
if (rect(1, 7*1.25, tr(" A SCORE IN THE TOP 10. ")).intersects(e->rect())) {
QPixmap pix = bitfont->text(tr(" A SCORE IN THE TOP 10. "), CYAN, BLACK);
bitBlt(this, x(1), y(7*1.25), &pix);
}
if (rect(1, 8*1.25, tr(" ")).intersects(e->rect())) {
QPixmap pix = bitfont->text(tr(" "), CYAN, BLACK);
bitBlt(this, x(1), y(8*1.25), &pix);
}
}
if (rect(1, 9.5*1.25, tr("RNK SCORE NAME DATE")).intersects(e->rect())) {
QPixmap pix = bitfont->text(tr("RNK SCORE NAME DATE"), WHITE, BLACK);
bitBlt(this, x(1), y(9.5*1.25), &pix);
}
for (int i = 0; i < 10; i++) {
s.sprintf("%2d%9d %-3.3s %-8.8s",
i+1, hallOfFame[i].points, hallOfFame[i].name.utf8().data(),
formatDate(hallOfFame[i].moment.date()).data());
if (rect(1, (11+i)*1.25, s).intersects(e->rect())) {
QPixmap pix = bitfont->text(s, (i == lastScore) ? YELLOW : WHITE, BLACK);
bitBlt(this, x(1), y((11+i)*1.25), &pix);
}
}
if (cursor.x != -1 && cursor.y != -1 && cursor.on) {
if (rect(cursor.x, (cursor.y*1.25), cursor.chr).intersects(e->rect())) {
QPixmap pix = bitfont->text(cursor.chr, BLACK, YELLOW);
bitBlt(this, x(cursor.x), y(cursor.y*1.25), &pix);
}
}
if (paused) {
QPixmap pix = bitfont->text(tr("PAUSED"), RED, BLACK);
QRect r = bitfont->rect(tr("PAUSED"));
r.moveCenter(QPoint(this->width()/2, this->height()/2));
bitBlt(this, r.x(), r.y(), &pix);
}
}
void Score::timerEvent(QTimerEvent*)
{
cursor.on = !cursor.on;
if (paused)
return;
if (cursor.x != -1 && cursor.y != -1)
repaint(rect(cursor.x, cursor.y*1.25, cursor.chr), FALSE);
scrollRepeat = FALSE;
if (lastPlayer == 0)
repaint(rect(1, 0, tr(" 1UP ")), FALSE);
if (lastPlayer == 1)
repaint(rect(21, 0, tr(" 2UP ")), FALSE);
}
void Score::keyPressEvent(QKeyEvent *k)
{
if (lastScore < 0 || lastPlayer < 0 || lastPlayer >= maxPlayer || paused) {
k->ignore();
return;
}
int x = cursor.x;
int y = cursor.y;
uint key = k->key();
if (scrollRepeat && (key == UpKey || key == Key_Up || key == DownKey || key == Key_Down)) {
k->ignore();
return;
}
if (key != Key_Return) {
if (key == RightKey || key == Key_Right)
if (++cursor.x > 16)
cursor.x = 14;
if (key == LeftKey || key == Key_Left)
if (--cursor.x < 14)
cursor.x = 16;
if (key == UpKey || key == Key_Up)
if (cursor.chr.unicode() < bitfont->lastChar())
cursor.chr = cursor.chr.unicode()+1;
else
cursor.chr = bitfont->firstChar();
if (key == DownKey || key == Key_Down)
if (cursor.chr.unicode() > bitfont->firstChar())
cursor.chr = cursor.chr.unicode()-1;
else
cursor.chr = bitfont->lastChar();
if (cursor.x == x && cursor.y == y &&
cursor.chr == hallOfFame[lastScore].name.at(cursor.x-14)) {
uint ascii = k->ascii();
if (ascii < bitfont->firstChar() || ascii > bitfont->lastChar())
ascii = toupper(ascii);
if (ascii >= bitfont->firstChar() && ascii <= bitfont->lastChar()) {
cursor.chr = ascii;
hallOfFame[lastScore].name.at(cursor.x-14) = cursor.chr;
if (++cursor.x > 16)
cursor.x = 14;
}
}
}
if (key == Key_Return) {
playerName[lastPlayer] = hallOfFame[lastScore].name;
write();
read();
lastScore = -1;
cursor.x = -1;
cursor.y = -1;
// killTimers();
emit toggleNew();
end();
}
if (x != cursor.x || y != cursor.y) {
if (cursor.x != -1)
cursor.chr = hallOfFame[lastScore].name.at(cursor.x-14);
scrollRepeat = FALSE;
repaint(rect(x, y*1.25, cursor.chr), FALSE);
} else
hallOfFame[lastScore].name.at(cursor.x-14) = cursor.chr;
if (key == UpKey || key == Key_Up || key == DownKey || key == Key_Down)
scrollRepeat = TRUE;
else
repaint(rect(cursor.x, cursor.y*1.25, cursor.chr), FALSE);
}
void Score::initKeys()
{
APP_CONFIG_BEGIN( cfg );
QString up("Up");
up = cfg->readEntry("upKey", (const char*) up);
UpKey = KAccel::stringToKey(up);
QString down("Down");
down = cfg->readEntry("downKey", (const char*) down);
DownKey = KAccel::stringToKey(down);
QString left("Left");
left = cfg->readEntry("leftKey", (const char*) left);
LeftKey = KAccel::stringToKey(left);
QString right("Right");
right = cfg->readEntry("rightKey", (const char*) right);
RightKey = KAccel::stringToKey(right);
APP_CONFIG_END( cfg );
}
void Score::confTiming(bool defGroup)
{
APP_CONFIG_BEGIN( cfg );
if (defGroup || cfg->hasKey("CursorBlinkMS"))
cursorBlinkMS = cfg->readNumEntry("CursorBlinkMS", 250);
if (defGroup || cfg->hasKey("HallOfFameMS"))
hallOfFameMS = cfg->readNumEntry("HallOfFameMS", 7000);
if (defGroup || cfg->hasKey("AfterPauseMS"))
afterPauseMS = cfg->readNumEntry("AfterPauseMS", 1000);
APP_CONFIG_END( cfg );
}
void Score::confScheme()
{
APP_CONFIG_BEGIN( cfg );
SAVE_CONFIG_GROUP( cfg, oldgroup );
QString newgroup;
// if not set, read mode and scheme from the configfile
if (mode == -1 && scheme == -1) {
scheme = cfg->readNumEntry("Scheme", -1);
mode = cfg->readNumEntry("Mode", -1);
// if mode is not set in the defGroup-group, lookup the scheme group
if (scheme != -1 || mode == -1) {
newgroup.sprintf("Scheme %d", scheme);
cfg->setGroup(newgroup);
mode = cfg->readNumEntry("Mode", -1);
RESTORE_CONFIG_GROUP( cfg, oldgroup );
}
}
int oldCursorBlinkMS = cursorBlinkMS;
confTiming();
if (mode != -1) {
newgroup.sprintf("Mode %d", mode);
cfg->setGroup(newgroup);
confTiming(FALSE);
}
if (scheme != -1) {
newgroup.sprintf("Scheme %d", scheme);
cfg->setGroup(newgroup);
confTiming(FALSE);
}
if (cursorBlinkMS != oldCursorBlinkMS) {
if (cursorBlinkTimer)
killTimer(cursorBlinkTimer);
cursorBlinkTimer = startTimer(cursorBlinkMS);
}
RESTORE_CONFIG_GROUP( cfg, oldgroup );
APP_CONFIG_END( cfg );
}
void Score::setScheme(int Scheme, int Mode, Bitfont *font)
{
mode = Mode;
scheme = Scheme;
confScheme();
bitfont = font;
for (int p = 0; p < maxPlayer; p++)
for (uint i = 0; i < playerName[p].length(); i++)
if (playerName[p].at(i) < bitfont->firstChar() ||
playerName[p].at(i) > bitfont->lastChar())
playerName[p].at(i) = playerName[p].at(i).upper();
for (int i = 0; i < 10; i++)
for (uint j = 0; j < hallOfFame[i].name.length(); j++)
if (hallOfFame[i].name.at(j) < bitfont->firstChar() ||
hallOfFame[i].name.at(j) > bitfont->lastChar())
hallOfFame[i].name.at(j) = hallOfFame[i].name.at(j).upper();
if (cursor.chr.unicode() < bitfont->firstChar() ||
cursor.chr.unicode() > bitfont->lastChar())
cursor.chr = cursor.chr.upper();
}
void Score::set(int score)
{
set(score, 0);
}
void Score::set(int score, int player)
{
if (player < 0 || player >= maxPlayer)
return;
lastPlayer = player;
playerScore[lastPlayer] = score;
QString s;
s.sprintf("%6d0", playerScore[lastPlayer]/10);
repaint(rect(0, 1, s), FALSE);
if (score > HighScore) {
HighScore = score;
s.sprintf("%8d0", HighScore/10);
repaint(rect(8, 1, s), FALSE);
}
}
/*
* Set the score for player after the game if over. If the score is in the
* high scores then the hall of fame is updated (shifted) and the scoreboard
* is shown.
*/
void Score::setScore(int level, int player)
{
lastScore = -1;
if (player < 0 || player >= maxPlayer || level == 0) {
if (level != 0)
emit toggleNew();
QTimer::singleShot(hallOfFameMS, this, SLOT(end()));
return;
}
lastPlayer = player;
for (int i = 0; i < 10; i++)
if ( playerScore[lastPlayer] > hallOfFame[i].points) {
lastScore = i;
break;
}
if (lastScore < 0) {
emit toggleNew();
QTimer::singleShot(hallOfFameMS, this, SLOT(end()));
return;
}
for (int i = 9; i > lastScore && i > 0; i--)
hallOfFame[i] = hallOfFame[i-1];
hallOfFame[lastScore].points = playerScore[lastPlayer];
hallOfFame[lastScore].levels = level;
hallOfFame[lastScore].moment = QDateTime::currentDateTime();
hallOfFame[lastScore].name = playerName[lastPlayer];
cursor.x = 14;
cursor.y = 11+lastScore;
cursor.chr = hallOfFame[lastScore].name.at(cursor.x-14);
// startTimer(cursorBlinkMS);
setFocus();
}
/*
* Read the highscores, if no file or a file shorter than 4 bytes (versions before 0.2.4 stores only
* the points of one highscore) exists - the highscores were initialized with default values.
*/
void Score::read()
{
if (highscoreFile.exists() && highscoreFile.size() > 4) {
if (highscoreFile.open(IO_ReadOnly)) {
QDataStream s(&highscoreFile);
char *name;
for (int i = 0; i < 10; i++) {
s >> hallOfFame[i].points >> hallOfFame[i].levels >> hallOfFame[i].duration >>
hallOfFame[i].moment >> name;
hallOfFame[i].name = QString::fromLatin1(name);
delete(name);
}
highscoreFile.close();
}
} else {
for (int i = 0; i < 10; i++) {
hallOfFame[i].points = 5000;
hallOfFame[i].levels = 0;
hallOfFame[i].duration = QTime();
hallOfFame[i].moment = QDateTime();
hallOfFame[i].name = "???";
}
// write();
}
for (int i = 0; i < 10; i++)
for (uint j = 0; j < hallOfFame[i].name.length(); j++)
if (hallOfFame[i].name.at(j) < bitfont->firstChar() ||
hallOfFame[i].name.at(j) > bitfont->lastChar())
hallOfFame[i].name.at(j) = hallOfFame[i].name.at(j).upper();
HighScore = hallOfFame[0].points;
}
void Score::write()
{
if (highscoreFile.open(IO_WriteOnly)) {
QDataStream s(&highscoreFile);
for (int i = 0; i < 10; i++)
s << hallOfFame[i].points << hallOfFame[i].levels << hallOfFame[i].duration <<
hallOfFame[i].moment << hallOfFame[i].name.latin1();
highscoreFile.close();
}
}
void Score::setPause(bool Paused)
{
paused = Paused;
QRect r = bitfont->rect(tr("PAUSED"));
r.moveCenter(QPoint(this->width()/2, this->height()/2));
repaint(r, TRUE);
// repaint 1UP or 2UP
repaint(FALSE);
}
void Score::end()
{
if (paused) {
QTimer::singleShot(afterPauseMS, this, SLOT(end()));
return;
}
// repaint 1UP or 2UP
lastPlayer = -1;
repaint(FALSE);
emit forcedHallOfFame(FALSE);
}
/*
* Return the date in a formatted QString. The format can be changed using internationalization
* of the string "YY/MM/DD". Invalid QDate's where returned as "00/00/00".
*/
QString Score::formatDate(QDate date)
{
QString s = tr("@YY@/@MM@/@DD@");
QString dd;
dd.sprintf("%02d", date.isValid() ? date.year() % 100 : 0);
s.replace(QRegExp("@YY@"), dd);
dd.sprintf("%02d", date.isValid() ? date.month() : 0);
s.replace(QRegExp("@MM@"), dd);
dd.sprintf("%02d", date.isValid() ? date.day() : 0);
s.replace(QRegExp("@DD@"), dd);
return s;
}
QRect Score::rect(int col, float row, QString str, int align)
{
QRect r = bitfont->rect(str);
r.moveBy(x(col), y(row));
int dx = 0;
int dy = 0;
if (align & AlignLeft || align & AlignRight) {
dx = (str.length()-1) * (bitfont->width()/2);
if (align & AlignRight)
dx *= -1;
}
if (align & AlignTop || align & AlignBottom) {
dy = bitfont->height()/2;
if (align & AlignBottom)
dy *= -1;
}
if (dx != 0 || dy != 0)
r.moveBy(dx, dy);
return r;
}
int Score::x(int col)
{
return col*bitfont->width();
}
int Score::y(float row)
{
return (int) (row*(bitfont->height()+bitfont->height()/4));
}
/**
* Ermittelt die zu benutzende "highscore"-Datei, in die auch geschrieben werden kann.
* Über den "highscoreFilePath"-KConfig-Eintrag, kann abweichend von der Standardlokation
* der Standort der "highscore"-Datei spezifiziert werden.
* Wenn die systemweite "highscore"-Datei nicht beschrieben werden kann, wird mit einer
* privaten Datei gearbeitet.
*/
QFileInfo Score::locateHighscoreFilePath()
{
return privateHighscoreFileInfo;
}
diff --git a/noncore/games/kpacman/status.cpp b/noncore/games/kpacman/status.cpp
index 2a17c21..02ff63d 100644
--- a/noncore/games/kpacman/status.cpp
+++ b/noncore/games/kpacman/status.cpp
@@ -1,368 +1,366 @@
#include "portable.h"
#if defined( KDE2_PORT )
#include <kapp.h>
#include <klocale.h>
#include <kstddirs.h>
#include <status.h>
#include <status.moc>
#elif defined( QPE_PORT )
#include <qpe/qpeapplication.h>
#include <qpe/config.h>
#include "status.h"
#endif
-#include <qpixmap.h>
#include <qbitmap.h>
-#include <qstring.h>
#include <qmsgbox.h>
#include <qfileinfo.h>
Status::Status( QWidget *parent, const char *name, int Scheme, int Mode ) :
QWidget( parent, name )
{
qWarning("Status::Status");
actualLifes = 0;
actualLevel = 0;
lifesPix = NULL;
levelPix = NULL;
scheme = Scheme;
mode = Mode;
level = 0;
confScheme();
}
QList<QPixmap> *Status::loadPixmap(QWidget *parent, QString pixmapName,
QList<QPixmap> *pixmaps)
{
if (pixmaps == NULL) {
pixmaps = new QList<QPixmap>;
pixmaps->setAutoDelete(TRUE);
}
if (!pixmaps->isEmpty())
pixmaps->clear();
QPixmap PIXMAP(pixmapName);
if (PIXMAP.isNull() || PIXMAP.mask() == NULL) {
QString msg = tr("The pixmap could not be contructed.\n\n"
"The file '@PIXMAPNAME@' does not exist,\n"
"or is of an unknown format.");
msg.replace(QRegExp("@PIXMAPNAME@"), pixmapName);
QMessageBox::information(parent, tr("Initialization Error"),
(const char *) msg);
return 0;
}
int height = PIXMAP.height();
int width = (height == 0) ? 0 : PIXMAP.width()/(PIXMAP.width()/height);
QBitmap BITMAP;
QBitmap MASK;
BITMAP = *PIXMAP.mask();
MASK.resize(width, height);
for (int x = 0; x < PIXMAP.width()/width; x++) {
QPixmap *pixmap = new QPixmap(width, height);
pixmaps->append(pixmap);
bitBlt(pixmap, 0, 0, &PIXMAP, x*width, 0, width, height, CopyROP, TRUE);
bitBlt(&MASK, 0, 0, &BITMAP, x*width, 0, width, height, CopyROP, TRUE);
pixmap->setMask(MASK);
}
return pixmaps;
}
void Status::paintEvent( QPaintEvent *)
{
for (int x = 0; x < actualLifes && !lifesPix->isEmpty(); x++)
bitBlt(this, lifesPix->at(0)->width()+(lifesPix->at(0)->width()*x),
(height()-lifesPix->at(0)->height())/2,
lifesPix->at(0), 0, 0,
lifesPix->at(0)->width(), lifesPix->at(0)->height());
for (int x = 0; x < actualLevel && !levelPix->isEmpty(); x++) {
erase((width()-levelPix->at(x)->width()*2)-(levelPix->at(x)->width()*levelPos[x]),
(height()-levelPix->at(x)->height())/2,
levelPix->at(x)->width(), levelPix->at(x)->height());
bitBlt(this, (width()-levelPix->at(x)->width()*2)-(levelPix->at(x)->width()*levelPos[x]),
(height()-levelPix->at(x)->height())/2,
levelPix->at(x), 0, 0,
levelPix->at(x)->width(), levelPix->at(x)->height());
}
}
void Status::initPixmaps()
{
if (lastLifesPixmapName != lifesPixmapName.at(level)) {
lifesPix = loadPixmap(this, lifesPixmapName.at(level), lifesPix);
lastLifesPixmapName = lifesPixmapName.at(level);
}
if (lastLevelPixmapName != levelPixmapName.at(level)) {
levelPix = loadPixmap(this, levelPixmapName.at(level), levelPix);
lastLevelPixmapName = levelPixmapName.at(level);
}
}
QString Status::decodeHexOctString(QString s)
{
QString value;
QString valids;
int pos, xpos = 0, opos = 0;
int v, len, leadin;
const char *ptr;
uchar c;
while (((xpos = s.find(QRegExp("\\\\x[0-9a-fA-F]+"), xpos)) != -1) ||
((opos = s.find(QRegExp("\\\\[0-7]+"), opos)) != -1)) {
if (xpos != -1) {
valids = "0123456789abcdef";
leadin = 2;
pos = xpos;
} else {
valids = "01234567";
leadin = 1;
pos = opos;
}
c = '\0';
len = 0;
value = s.mid(pos+leadin, 3);
ptr = (const char *) value;
while (*ptr != '\0' && (v = valids.find(*ptr++, 0, FALSE)) != -1) {
c = (c * valids.length()) + v;
len++;
}
value.fill(c, 1);
s.replace(pos, len+leadin, value);
}
return s;
}
void Status::fillArray(QArray<int> &array, QString values, int max)
{
array.resize(max);
int last = 0;
bool ok;
QString value;
for (uint i = 0; i < array.size(); i++) {
if (values.find(',') < 0 && values.length() > 0) {
value = values;
values = "";
}
if (values.find(',') >= 0) {
value = values.left(values.find(','));
values.remove(0,values.find(',')+1);
}
array[i] = value.toInt(&ok);
if (ok)
last = array[i];
else
array[i] = last;
}
}
void Status::fillStrList(QStrList &list, QString values, int max)
{
if (!list.isEmpty())
list.clear();
QString last = "";
QString value;
for (uint i = 0; i < (uint) max; i++) {
if (values.find(',') < 0 && values.length() > 0) {
value = values;
values = "";
}
if (values.find(',') >= 0) {
value = values.left(values.find(','));
values.remove(0,values.find(',')+1);
}
if (!value.isEmpty())
last = decodeHexOctString(value);
list.append(last);
}
}
void Status::fillPixmapName(QStrList &pixmapName)
{
QStrList list = pixmapName;
if (!pixmapName.isEmpty())
pixmapName.clear();
QString pixmap;
QFileInfo fileInfo;
for (uint i = 0; i < list.count(); i++) {
pixmap = list.at(i);
if (pixmap.left(1) != "/" && pixmap.left(1) != "~")
pixmap = FIND_APP_DATA( pixmapDirectory+pixmap );
fileInfo.setFile(pixmap);
if (!fileInfo.isReadable() || !fileInfo.isFile())
pixmap = "";
pixmapName.append(pixmap);
}
}
void Status::confLevels(bool defGroup)
{
APP_CONFIG_BEGIN( cfg );
if (defGroup || cfg->hasKey("Levels"))
maxLevel = cfg->readNumEntry("Levels", 13);
APP_CONFIG_END( cfg );
}
void Status::confMisc(bool defGroup)
{
APP_CONFIG_BEGIN( cfg );
if (defGroup || cfg->hasKey("LevelPosition"))
fillArray(levelPos, cfg->readEntry("LevelPosition", "0,1,2,3,,4,,5,,6,,7"), maxLevel);
if (defGroup || cfg->hasKey("PixmapDirectory")) {
pixmapDirectory = cfg->readEntry("PixmapDirectory");
if (pixmapDirectory.left(1) != "/" && pixmapDirectory.left(1) != "~")
pixmapDirectory.insert(0, "pics/");
if (pixmapDirectory.right(1) != "/")
pixmapDirectory.append("/");
}
if (defGroup || cfg->hasKey("LifesPixmapName"))
fillStrList(lifesPixmapName,
cfg->readEntry("LifesPixmapName", "lifes.xpm"), maxLevel+1);
if (defGroup || cfg->hasKey("LevelPixmapName"))
fillStrList(levelPixmapName,
cfg->readEntry("LevelPixmapName", "fruit.xpm"), maxLevel+1);
APP_CONFIG_END( cfg );
}
void Status::confScheme()
{
APP_CONFIG_BEGIN( cfg );
SAVE_CONFIG_GROUP( cfg, oldgroup );
QString newgroup;
// if not set, read mode and scheme from the configfile
if (mode == -1 && scheme == -1) {
scheme = cfg->readNumEntry("Scheme", -1);
mode = cfg->readNumEntry("Mode", -1);
// if mode is not set in the defGroup-group, lookup the scheme group
if (scheme != -1 || mode == -1) {
newgroup.sprintf("Scheme %d", scheme);
cfg->setGroup(newgroup);
mode = cfg->readNumEntry("Mode", -1);
RESTORE_CONFIG_GROUP( cfg, oldgroup );
}
}
confLevels();
if (mode != -1) {
newgroup.sprintf("Mode %d", mode);
cfg->setGroup(newgroup);
confLevels(FALSE);
}
if (scheme != -1) {
newgroup.sprintf("Scheme %d", scheme);
cfg->setGroup(newgroup);
confLevels(FALSE);
}
RESTORE_CONFIG_GROUP( cfg, oldgroup );
confMisc();
if (mode != -1) {
newgroup.sprintf("Mode %d", mode);
cfg->setGroup(newgroup);
confMisc(FALSE);
}
if (scheme != -1) {
newgroup.sprintf("Scheme %d", scheme);
cfg->setGroup(newgroup);
confMisc(FALSE);
}
fillPixmapName(lifesPixmapName);
fillPixmapName(levelPixmapName);
initPixmaps();
setFixedHeight(minHeight());
RESTORE_CONFIG_GROUP( cfg, oldgroup );
APP_CONFIG_END( cfg );
}
void Status::setScheme(int Scheme, int Mode)
{
mode = Mode;
scheme = Scheme;
confScheme();
repaint();
}
int Status::minHeight()
{
if (lifesPix->isEmpty() && levelPix->isEmpty())
return 0;
if (levelPix->isEmpty())
return lifesPix->at(0)->height();
if (lifesPix->isEmpty())
return levelPix->at(0)->height();
return (lifesPix->at(0)->height() > levelPix->at(0)->height()) ?
lifesPix->at(0)->height() : levelPix->at(0)->height();
}
int Status::minWidth()
{
if (lifesPix->isEmpty() && levelPix->isEmpty())
return 0;
if (levelPix->isEmpty())
return lifesPix->at(0)->width();
if (lifesPix->isEmpty())
return levelPix->at(0)->width();
return (lifesPix->at(0)->width() > levelPix->at(0)->width()) ?
lifesPix->at(0)->width() : levelPix->at(0)->width();
}
void Status::setLifes(int lifes)
{
actualLifes = lifes;
repaint();
}
void Status::setLevel(int Level)
{
level = Level;
initPixmaps();
actualLevel = (level > (int) levelPix->count()) ? (int) levelPix->count() : level;
repaint();
}
diff --git a/noncore/games/mindbreaker/mindbreaker.cpp b/noncore/games/mindbreaker/mindbreaker.cpp
index e1f43d0..2b924c6 100644
--- a/noncore/games/mindbreaker/mindbreaker.cpp
+++ b/noncore/games/mindbreaker/mindbreaker.cpp
@@ -1,957 +1,953 @@
/**********************************************************************
** Copyright (C) 2000-2002 Trolltech AS. All rights reserved.
**
** This file is part of the Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include "mindbreaker.h"
#include <qtopia/resource.h>
#include <qtopia/config.h>
#include <qtopia/qpeapplication.h>
#include <qtoolbar.h>
-#include <qpainter.h>
-#include <qpixmap.h>
#include <qtoolbutton.h>
-#include <qpushbutton.h>
#include <qmessagebox.h>
-#include <qlabel.h>
#include <qlayout.h>
#include <qtimer.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
static int pegRTTI = 3393393;
static int adjusted_panel_height;
static int adjusted_panel_width;
static int adjusted_bin_margin;
static int adjusted_peg_size;
static int adjusted_answerpeg_size;
static int adjusted_title_height;
static int adjusted_title_width;
static int adjusted_first_peg_x_diff;
static int adjusted_first_peg_y_diff;
static int adjusted_peg_spacing;
static int adjusted_answerpegx;
static int adjusted_answerpegy;
static int adjusted_answerpeg_xdiff;
static int adjusted_answerpeg_ydiff;
static int adjusted_board_height;
static int adjusted_board_width;
static void setupBoardSize(int w, int h)
{
adjusted_panel_width = w * 3/4;
adjusted_title_width = w * 3/4;
adjusted_title_height = h/10;
adjusted_panel_height = (h-adjusted_title_height)/9;
adjusted_bin_margin = w * 10/240;
adjusted_peg_size = adjusted_panel_height*3/4;
adjusted_answerpeg_size = QMIN(adjusted_panel_width*15/180,adjusted_panel_height*15/25);
// looks a bit dodgy on larger sizes
if ( adjusted_peg_size > 40 )
adjusted_peg_size = 40;
adjusted_first_peg_x_diff = w * 31/240-adjusted_peg_size/2;
adjusted_first_peg_y_diff = (adjusted_panel_height - adjusted_peg_size)/2;
adjusted_peg_spacing = w * 30/240;
// looks a bit dodgy on larger sizes (still does though, but not as much...)
if ( adjusted_answerpeg_size > 22 )
adjusted_answerpeg_size = 22;
adjusted_answerpegx = adjusted_panel_width * 159/180 - adjusted_answerpeg_size/2;
adjusted_answerpegy = adjusted_panel_height/3 - adjusted_answerpeg_size/2;
adjusted_answerpeg_xdiff = adjusted_panel_width * 10/180;
adjusted_answerpeg_ydiff = adjusted_panel_height * 9/25;
adjusted_board_height = adjusted_title_height + (adjusted_panel_height * 9);
adjusted_board_width = adjusted_panel_width + (adjusted_bin_margin * 2) + adjusted_peg_size;
// qDebug("Adjusted width %d height %d", adjusted_board_width, adjusted_board_height);
}
/* helper class, */
class Peg : public QCanvasRectangle
{
public:
Peg(QCanvas *canvas, int type, int go = -1, int pos = -1);
int rtti() const {return pegRTTI; }
void advance(int phase);
bool hit( const QPoint &) const;
/* a placed peg is one that has been set down on the board correctly and
should not be moved, only copied */
bool placed() const;
void setPlaced(bool);
int pegGo() const;
int pegPos() const;
void setPegPos(int);
int type() const;
static void buildImages();
static QImage imageForType(int t);
static int eggLevel;
protected:
void drawShape(QPainter &);
private:
static QVector<QImage> normalPegs;
static QVector<QImage> specialPegs;
bool isplaced;
int pegtype;
int peg_go;
int peg_pos;
int aniStep;
};
int Peg::eggLevel = 0;
QVector<QImage> Peg::normalPegs;
QVector<QImage> Peg::specialPegs;
void Peg::buildImages()
{
QImage pegs = Resource::loadImage("mindbreaker/pegs");
int x = 0;
int y = 0;
int i;
eggLevel = 0;
normalPegs.resize(10);
for (i = 0; i < 6; i++) {
normalPegs.insert(i, new QImage(pegs.copy(x, y, peg_size, peg_size).
smoothScale(adjusted_peg_size, adjusted_peg_size) ));
x += peg_size;
}
specialPegs.resize(5);
for (i = 0; i < 5; i++) {
specialPegs.insert(i, new QImage(pegs.copy(x,y,peg_size, peg_size).
smoothScale(adjusted_peg_size, adjusted_peg_size) ));
x += peg_size;
}
QImage image = Resource::loadImage("mindbreaker/mindbreaker");
/* copy from master image to functional images */
x = 0;
y = panel_height;
normalPegs.insert(8,
new QImage( image.copy(x, y, panel_width, panel_height).
smoothScale( adjusted_panel_width, adjusted_panel_height)
));
y += panel_height;
y += title_height;
normalPegs.insert(9,
new QImage(image.copy(x, y, title_width, title_height).
smoothScale( adjusted_title_width, adjusted_title_height)
));
y += title_height;
x = 6 * peg_size;
normalPegs.insert(6,
new QImage(image.copy(x, y, answerpeg_size, answerpeg_size).
smoothScale( adjusted_answerpeg_size, adjusted_answerpeg_size) ));
x += answerpeg_size;
normalPegs.insert(7,
new QImage(image.copy(x, y, answerpeg_size, answerpeg_size).
smoothScale( adjusted_answerpeg_size, adjusted_answerpeg_size) ));
}
QImage Peg::imageForType(int t)
{
if (eggLevel > t ) {
if( t < 5) {
return *specialPegs[t];
} else {
return *normalPegs[rand() % 6];
}
}
return *normalPegs[t];
}
Peg::Peg(QCanvas *canvas , int t, int g, int p)
: QCanvasRectangle(canvas)
{
setSize(normalPegs[t]->width(), normalPegs[t]->height() );
pegtype = t;
isplaced = FALSE;
peg_pos = p;
peg_go = g;
aniStep = rand() % 6;
setAnimated(TRUE);
}
void Peg::advance(int phase) {
if (phase == 0)
aniStep = (++aniStep) % 6;
else {
hide();
show();
}
}
void Peg::drawShape(QPainter &p )
{
if ((pegtype == 5) && eggLevel > 5) {
p.drawImage(int(x()), int(y()), *normalPegs[aniStep]);
} else
p.drawImage(int(x()), int(y()), imageForType(pegtype));
}
bool Peg::hit( const QPoint &p ) const
{
int ix = p.x() - int(x());
int iy = p.y() - int(y());
if (!normalPegs[pegtype]->valid(ix, iy))
return FALSE;
QRgb pixel = normalPegs[pegtype]->pixel(ix, iy);
return (qAlpha(pixel ) != 0);
}
inline bool Peg::placed() const
{
return isplaced;
}
inline int Peg::pegGo() const
{
return peg_go;
}
inline int Peg::pegPos() const
{
return peg_pos;
}
inline void Peg::setPegPos(int p)
{
peg_pos = p;
}
inline void Peg::setPlaced(bool p)
{
isplaced = p;
}
inline int Peg::type() const
{
return pegtype;
}
/* Load the main image, copy from it the pegs, the board, and the answer image
* and use these to create the tray, answer and board
*/
MindBreaker::MindBreaker( QWidget *parent, const char *name, int wFlags )
: QMainWindow(parent, name, wFlags)
{
setCaption( tr("Mind Breaker"));
QPEApplication::setInputMethodHint( this, QPEApplication::AlwaysOff );
setMinimumSize(160,210);
QWidget *w = new QWidget( this );
w->setBackgroundColor( black );
QHBoxLayout *hb = new QHBoxLayout( w );
hb->addStretch();
board = new MindBreakerBoard(w);
hb->addWidget( board, 100 );
hb->addStretch();
setCentralWidget(w);
setToolBarsMovable( FALSE );
QToolBar *tb = new QToolBar(this);
tb->setHorizontalStretchable( TRUE );
QIconSet newicon = Resource::loadIconSet("new");
new QToolButton(newicon, tr("New Game"), 0,
board, SLOT(clear()), tb, "NewGame");
score = new QToolButton(tb);
score->setText("");
score->setMaximumHeight(20);
score->setUsesTextLabel(TRUE);
tb->setStretchableWidget(score);
connect(board, SIGNAL(scoreChanged(int,int)), this, SLOT(setScore(int,int)));
connect(score, SIGNAL(clicked()), board, SLOT(resetScore()));
int a, b;
board->getScore(&a, &b);
setScore(a,b);
layout()->setResizeMode(QLayout::FreeResize);
}
void MindBreaker::setScore(int turns, int games)
{
double average;
double total_turns = turns;
double total_games = games;
if(total_games > 0)
average = total_turns / total_games;
else
average = 0.0;
score->setText(tr("win avg: %1 turns (%2 games)").arg(average).arg(games));
}
void MindBreaker::resizeEvent( QResizeEvent *e )
{
board->fixSize();
QMainWindow::resizeEvent( e );
}
MindBreakerBoard::MindBreakerBoard( QWidget *parent,
const char *name, int wFlags )
: QCanvasView(0, parent, name, wFlags),
moving(0), game_over(FALSE), total_turns(0), total_games(0)
{
setFrameStyle( NoFrame );
setupBoardSize(qApp->desktop()->width(),qApp->desktop()->height());
cnv.resize(100,100);
setCanvas(&cnv);
setBackgroundColor( black );
struct timeval tv;
current_go = 0;
gettimeofday(&tv, 0);
srand(tv.tv_usec);
canvas()->setAdvancePeriod(500);
current_highlight = 0;
widthTimer = new QTimer( this );
connect(widthTimer, SIGNAL(timeout()), this, SLOT(doFixSize()) );
setMaximumWidth( QMIN(qApp->desktop()->height(),qApp->desktop()->width()) );
//doFixSize(); // build images... needs to be done before reading config.
//readConfig(); // first read... to ensure initial labels and side look right.
}
void MindBreakerBoard::readConfig()
{
Config c("MindBreaker", Config::User);
c.setGroup("Board");
game_over = FALSE;
int i;
if (c.readNumEntry("Answer0") < 0) {
for (i = 0; i < 4; i++) {
answer[i] = rand() % 6;
current_guess[i] = 6;
}
total_turns = 0;
total_games = 0;
} else {
int j;
c.setGroup("Score");
total_turns = c.readNumEntry("Turns");
total_games = c.readNumEntry("Games");
if(total_turns < 0)
total_turns = 0;
if(total_games < 0)
total_games = 0;
checkScores();
c.setGroup("Board");
for(i = 0; i < 4; i++)
answer[i] = c.readNumEntry(QString("Answer%1").arg(i));
/* read, and parse past guesses */
current_go = 0;
for(j=0; j < 9; j++) {
current_guess[0] = c.readNumEntry(QString("Go%1p0").arg(j));
if (current_guess[0] < 0)
break;
placeGuessPeg(0, current_guess[0]);
current_guess[1] = c.readNumEntry(QString("Go%1p1").arg(j));
placeGuessPeg(1, current_guess[1]);
current_guess[2] = c.readNumEntry(QString("Go%1p2").arg(j));
placeGuessPeg(2, current_guess[2]);
current_guess[3] = c.readNumEntry(QString("Go%1p3").arg(j));
placeGuessPeg(3, current_guess[3]);
checkGuess();
}
for(i = 0; i < 4; i++) {
current_guess[i] = c.readNumEntry(QString("CurrentGo%1").arg(i));
if (current_guess[i] != 6)
placeGuessPeg(i, current_guess[i]);
}
}
}
MindBreakerBoard::~MindBreakerBoard()
{
int i;
if (game_over) {
current_go = 0;
/* clear the answer, clear the guess */
for (i = 0; i < 4; i++) {
answer[i] = rand() % 6;
current_guess[i] = 6;
}
}
writeConfig();
}
void MindBreakerBoard::writeConfig()
{
Config c("MindBreaker", Config::User);
c.setGroup("Board");
c.clearGroup();
/* write the board */
int i,j;
for (i = 0; i < current_go; i++) {
for(j = 0; j < 4; j++)
c.writeEntry(QString("Go%1p%2").arg(i).arg(j), past_guesses[4*i+j]);
}
for(j = 0; j < 4; j++)
c.writeEntry(QString("CurrentGo%1").arg(j), current_guess[j]);
for(j = 0; j < 4; j++)
c.writeEntry(QString("Answer%1").arg(j), answer[j]);
c.setGroup("Score");
/* write the score */
c.writeEntry("Turns", total_turns);
c.writeEntry("Games", total_games);
}
void MindBreakerBoard::getScore(int *a, int *b)
{
*a = total_turns;
*b = total_games;
return;
}
void MindBreakerBoard::fixSize()
{
hide();
setMaximumWidth( parentWidget()->height() );
widthTimer->start( 20, TRUE );
}
void MindBreakerBoard::doFixSize()
{
QSize s = size();
int fw = frameWidth();
s.setWidth(s.width() - fw);
s.setHeight(s.height() - fw);
/* min size is 200 x 260 */
/*
if (s.width() < adjusted_board_width)
s.setWidth(adjusted_board_width);
if (s.height() < adjusted_board_height)
s.setHeight(adjusted_board_height);
*/
if ( current_highlight ) // non-first resize
writeConfig();
setupBoardSize(s.width() - fw, s.height() - fw);
canvas()->resize(s.width() - fw, s.height() - fw);
Peg::buildImages(); // must be done BEFORE any pegs are made
QImage image = Resource::loadImage("mindbreaker/mindbreaker");
/* copy from master image to functional images */
int x = 0;
int y = 0;
panelImage = image.copy(x, y, panel_width, panel_height).
smoothScale( adjusted_panel_width, adjusted_panel_height);
y += panel_height;
y += panel_height;
titleImage = image.copy(x, y, title_width, title_height).
smoothScale( adjusted_title_width, adjusted_title_height);
show();
delete current_highlight;
current_highlight = new Peg(canvas(), 8);
current_highlight->setPlaced(TRUE);
current_highlight->setX(0);
current_highlight->setY(adjusted_board_height - ((current_go + 1) * adjusted_panel_height));
current_highlight->setZ(0);
current_highlight->show();
/* set up the game */
//readConfig();
/* draw initial screen */
//drawBackground();
//canvas()->update();
clear();
readConfig();
}
void MindBreakerBoard::placeGuessPeg(int pos, int pegId)
{
int x = adjusted_first_peg_x_diff + (pos * adjusted_peg_spacing);
int y = adjusted_board_height - ((current_go + 1) * adjusted_panel_height)
+ adjusted_first_peg_y_diff;
Peg *peg = new Peg(canvas(), pegId, current_go, pos);
peg->setPegPos(pos);
peg->setPlaced(TRUE);
peg->setX(x);
peg->setY(y);
peg->setZ(2);
peg->show();
}
void MindBreakerBoard::drawBackground()
{
int i, j, x, y, x_gap, y_gap;
QPixmap background = QPixmap(canvas()->width(), canvas()->height());
QPainter painter(&background);
painter.fillRect(0, 0, canvas()->width(), canvas()->height(), QColor(0,0,0));
/* very first thing is to draw the bins, as everything else needs
* to be drawn over them */
QPen pen(QColor(85, 45, 27), 4);
painter.setPen(pen);
x_gap = canvas()->width() - (adjusted_panel_width + (2 * adjusted_bin_margin));
//x_gap += peg_size >> 1;
if (x_gap < 1)
x_gap = 1;
y_gap = adjusted_board_height / 6;
y_gap -= (2 * adjusted_bin_margin);
//y_gap += peg_size >> 1;
if (y_gap < 1)
y_gap = 1;
x = adjusted_panel_width + adjusted_bin_margin - (adjusted_peg_size >> 1);
y = adjusted_bin_margin - (adjusted_peg_size >> 1) + 2;
for (i = 0; i < 6; i++) {
for (j = 0; j < 10; j++) {
int rx = x + (rand() % x_gap);
int ry = y + (rand() % y_gap);
painter.drawImage(rx,ry, Peg::imageForType(i));
}
y += adjusted_board_height / 6;
}
/* now draw the surrounding boxes */
x_gap = canvas()->width() - adjusted_panel_width;
if (x_gap < 1) x_gap = 1;
y_gap = adjusted_board_height / 6;
x = adjusted_panel_width;
y = 1;
for (i = 0; i < 6; i++) {
painter.drawRect(x, y, x_gap, y_gap);
y += y_gap;
}
x = 0;
y = 0;
painter.drawImage(x,y, titleImage);
y = adjusted_title_height;
/* now nine gues panels */
for (i = 0; i < 9; i ++) {
painter.drawImage(x, y, panelImage);
y += adjusted_panel_height;
}
painter.flush();
canvas()->setBackgroundPixmap(background);
}
void MindBreakerBoard::checkGuess()
{
int i,j;
int num_white = 0;
int num_black = 0;
int copy_answer[4];
int copy_guess[4];
for(i = 0; i < 4; i++) {
copy_answer[i] = answer[i];
copy_guess[i] = current_guess[i];
if (current_guess[i] == 6)
return;
if (answer[i] == current_guess[i]) {
num_black++;
copy_answer[i] = 6;
copy_guess[i] = 7;
}
}
/* now sure that user has completed a 'guess' */
for (i = 0; i < 4; i++) {
if (copy_guess[i] == 7)
continue; // already marked for a black
for (j = 0; j < 4; j++) {
if(copy_guess[i] == copy_answer[j]) {
copy_answer[j] = 6;
num_white++;
break;
}
}
}
int x = adjusted_answerpegx;
int y = (adjusted_board_height - ((current_go + 1) * adjusted_panel_height)) + adjusted_answerpegy;
if (num_black == 4)
game_over = TRUE;
while(num_black > 0) {
Peg *p = new Peg(canvas(), 7);
p->setPlaced(TRUE);
p->setX(x);
p->setY(y);
p->setZ(1);
p->show();
num_black--;
if (x == adjusted_answerpegx)
x = adjusted_answerpegx + adjusted_answerpeg_xdiff;
else {
x = adjusted_answerpegx;
y += adjusted_answerpeg_ydiff;
}
}
while(num_white > 0){
Peg *p = new Peg(canvas(), 6);
p->setPlaced(TRUE);
p->setX(x);
p->setY(y);
p->setZ(1);
p->show();
num_white--;
if (x == adjusted_answerpegx)
x = adjusted_answerpegx + adjusted_answerpeg_xdiff;
else {
x = adjusted_answerpegx;
y += adjusted_answerpeg_ydiff;
}
}
/* move to next go */
for(i = 0; i < 4; i++) {
past_guesses[4*current_go+i] = current_guess[i];
current_guess[i] = 6;
}
current_go++;
if((current_go > 8) || game_over) {
total_games++;
if(!game_over)
total_turns += 10;
else
total_turns += current_go;
emit scoreChanged(total_turns, total_games);
Peg *p = new Peg(canvas(), 9);
game_over = TRUE;
p->setPlaced(TRUE);
p->setX(0);
p->setY(0);
p->setZ(0);
p->show();
for (i = 0; i < 4; i++) {
p = new Peg(canvas(), answer[i], -1);
p->setX(adjusted_first_peg_x_diff + (i * adjusted_peg_spacing));
p->setY(adjusted_first_peg_y_diff);
p->setZ(3);
p->show();
}
} else {
current_highlight->setY(adjusted_board_height - ((current_go + 1) * adjusted_panel_height));
}
canvas()->update();
}
void MindBreakerBoard::clear()
{
if(!game_over) {
total_games++;
total_turns += 10;
emit scoreChanged(total_turns, total_games);
}
int i;
/* reset the game board */
game_over = FALSE;
/* clear the answer, clear the guess */
for (i = 0; i < 4; i++) {
answer[i] = rand() % 6;
current_guess[i] = 6;
}
current_go = 0;
QCanvasItemList list = canvas()->allItems();
QCanvasItemList::Iterator it = list.begin();
for (; it != list.end(); ++it) {
if (*it == current_highlight)
continue;
if (*it)
delete *it;
}
current_highlight->setY(adjusted_board_height - ((current_go + 1) * adjusted_panel_height));
checkScores();
drawBackground();
canvas()->update();
}
void MindBreakerBoard::resetScore()
{
/* are u sure */
if (QMessageBox::information(this, tr( "Reset Statistics" ),
tr( "Reset the win ratio?" ),
tr( "OK" ), tr( "Cancel" ) ) == 0) {
total_turns = 0;
total_games = 0;
Peg::eggLevel = 0;
drawBackground();
canvas()->update();
emit scoreChanged(total_turns, total_games);
}
}
/* EVENTS */
void MindBreakerBoard::contentsMousePressEvent(QMouseEvent *e)
{
if (game_over) {
null_press = TRUE;
null_point = e->pos();
moving = 0;
return;
}
copy_press = FALSE;
null_press = FALSE;
/* ok, first work out if it is one of the bins that
got clicked */
if (e->x() > adjusted_panel_width) {
/* its a bin, but which bin */
int bin = (e->y() + 2) / (adjusted_board_height / 6);
if (bin > 5)
return; // missed everything
/* make new peg... set it moving */
moving_pos = e->pos();
moving = new Peg(canvas(), bin, current_go);
moving->setX(e->x() - (adjusted_peg_size >> 1));
moving->setY(e->y() - (adjusted_peg_size >> 1));
moving->setZ(5);
moving->show();
canvas()->update();
return;
}
QCanvasItemList l = canvas()->collisions(e->pos());
for (QCanvasItemList::Iterator it=l.begin(); it !=l.end(); ++it) {
if ( (*it)->rtti() == pegRTTI ) {
Peg *item = (Peg *)(*it);
if (!item->hit(e->pos()))
continue;
if (item->type() > 5) {
null_press = TRUE;
null_point = e->pos();
continue; /* not a color peg */
}
if (item->placed()) {
/* copy */
if(item->pegGo() == -1)
return;
if(item->pegGo() == current_go) {
copy_press = TRUE;
copy_peg = item;
}
moving = new Peg(canvas(),
item->type(), current_go);
moving->setX(e->x() - (adjusted_peg_size >> 1));
moving->setY(e->y() - (adjusted_peg_size >> 1));
moving->setZ(5);
moving->show();
moving_pos = QPoint(e->x(), e->y());
canvas()->update();
return;
}
moving = (Peg *)*it;
moving_pos = e->pos();
canvas()->update();
return;
}
}
null_press = TRUE;
null_point = e->pos();
moving = 0;
}
void MindBreakerBoard::contentsMouseMoveEvent(QMouseEvent* e)
{
if (moving ) {
moving->moveBy(e->pos().x() - moving_pos.x(),
e->pos().y() - moving_pos.y());
moving_pos = e->pos();
canvas()->update();
return;
}
}
void MindBreakerBoard::contentsMouseReleaseEvent(QMouseEvent* e)
{
/* time to put down the peg */
if(moving) {
if(copy_press) {
/* check if collided with original. if so, delete both */
copy_press = FALSE;
QCanvasItemList l = canvas()->collisions(e->pos());
for (QCanvasItemList::Iterator it=l.begin(); it !=l.end(); ++it) {
if (*it == copy_peg)
copy_press = TRUE;
}
if (copy_press) {
current_guess[copy_peg->pegPos()] = 6;
delete copy_peg;
delete moving;
copy_press = FALSE;
moving = 0;
copy_peg = 0;
canvas()->update();
return;
}
}
/* first work out if in y */
if (e->y() > (adjusted_board_height - (current_go * adjusted_panel_height))) {
delete moving;
moving = 0;
canvas()->update();
return;
}
if (e->y() < (adjusted_board_height - ((current_go + 1) * adjusted_panel_height))) {
delete moving;
moving = 0;
canvas()->update();
return;
}
/* ok, a valid go, but which peg */
int x_bar = adjusted_first_peg_x_diff - (adjusted_peg_size >> 1);
x_bar += adjusted_peg_spacing;
int pos = 0;
if (e->x() > x_bar)
pos = 1;
x_bar += adjusted_peg_spacing;
if (e->x() > x_bar)
pos = 2;
x_bar += adjusted_peg_spacing;
if (e->x() > x_bar)
pos = 3;
x_bar += adjusted_peg_spacing;
if (e->x() > x_bar) {
/* invalid x */
delete moving;
moving = 0;
canvas()->update();
return;
}
int x = adjusted_first_peg_x_diff + (pos * adjusted_peg_spacing);
int y = adjusted_board_height - ((current_go + 1) * adjusted_panel_height)
+ adjusted_first_peg_y_diff;
moving->setPegPos(pos);
moving->setX(x);
moving->setY(y);
moving->setZ(2);
/* remove all other pegs from this position */
QCanvasItemList l = canvas()->collisions(QPoint(x,y));
for (QCanvasItemList::Iterator it=l.begin(); it !=l.end(); ++it) {
if ( (*it)->rtti() == pegRTTI ) {
Peg *item = (Peg *)(*it);
if ((item != moving) && (item != current_highlight))
delete item;
}
}
current_guess[pos] = ((Peg *)moving)->type();
((Peg *)moving)->setPlaced(true);
canvas()->update();
return;
}
moving = 0;
null_point -= e->pos();
if(null_point.manhattanLength() < 6) {
if (game_over)
clear();
else
checkGuess();
}
}
void MindBreakerBoard::resizeEvent(QResizeEvent *e)
{
QCanvasView::resizeEvent(e);
fixSize();
}
/* Easter egg function... beat the clock */
void MindBreakerBoard::checkScores()
{
double games = total_games;
double turns = total_turns;
double g = games / 10.0;
Peg::eggLevel = 0;
double break_even = 5.0;
if (g < 1.0)
return;
double avg = turns / games;
g--;
while (break_even >= 0.0) {
if (avg >= (break_even + g))
return;
// score a peg.
break_even -= 1.0;
Peg::eggLevel = int(5.0 - break_even);
}
}
diff --git a/noncore/games/minesweep/main.cpp b/noncore/games/minesweep/main.cpp
index bd70f7c..e187be5 100644
--- a/noncore/games/minesweep/main.cpp
+++ b/noncore/games/minesweep/main.cpp
@@ -1,27 +1,26 @@
/**********************************************************************
** Copyright (C) 2000 Trolltech AS. All rights reserved.
**
** This file is part of Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include "minesweep.h"
-#include <qpe/qpeapplication.h>
#include <opie/oapplicationfactory.h>
OPIE_EXPORT_APP( OApplicationFactory<MineSweep> )
diff --git a/noncore/games/minesweep/minefield.cpp b/noncore/games/minesweep/minefield.cpp
index 1790110..72c05b0 100644
--- a/noncore/games/minesweep/minefield.cpp
+++ b/noncore/games/minesweep/minefield.cpp
@@ -1,751 +1,747 @@
/**********************************************************************
** Copyright (C) 2000-2002 Trolltech AS. All rights reserved.
**
** This file is part of the Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include "minefield.h"
#include <qtopia/config.h>
#include <qtopia/qpeapplication.h>
-#include <qpainter.h>
-#include <qdrawutil.h>
-#include <qpixmap.h>
-#include <qimage.h>
#include <qtimer.h>
#include <stdlib.h>
static const char *pix_flag[]={
"13 13 3 1",
"# c #000000",
"x c #ff0000",
". c None",
".............",
".............",
".....#xxxxxx.",
".....#xxxxxx.",
".....#xxxxxx.",
".....#xxxxxx.",
".....#.......",
".....#.......",
".....#.......",
".....#.......",
"...#####.....",
"..#######....",
"............."};
static const char *pix_mine[]={
"13 13 3 1",
"# c #000000",
". c None",
"a c #ffffff",
"......#......",
"......#......",
"..#.#####.#..",
"...#######...",
"..##aa#####..",
"..##aa#####..",
"#############",
"..#########..",
"..#########..",
"...#######...",
"..#.#####.#..",
"......#......",
"......#......"};
static const int maxGrid = 28;
static const int minGrid = 12;
class Mine : public Qt
{
public:
enum MineState {
Hidden = 0,
Empty,
Mined,
Flagged,
#ifdef MARK_UNSURE
Unsure,
#endif
Exploded,
Wrong
};
Mine( MineField* );
void paint( QPainter * p, const QColorGroup & cg, const QRect & cr );
QSize sizeHint() const { return QSize( maxGrid, maxGrid ); }
void activate( bool sure = TRUE );
void setHint( int );
void setState( MineState );
MineState state() const { return st; }
bool isMined() const { return mined; }
void setMined( bool m ) { mined = m; }
static void paletteChange();
private:
bool mined;
int hint;
MineState st;
MineField *field;
static QPixmap* knownField;
static QPixmap* unknownField;
static QPixmap* flag_pix;
static QPixmap* mine_pix;
};
QPixmap* Mine::knownField = 0;
QPixmap* Mine::unknownField = 0;
QPixmap* Mine::flag_pix = 0;
QPixmap* Mine::mine_pix = 0;
Mine::Mine( MineField *f )
{
mined = FALSE;
st = Hidden;
hint = 0;
field = f;
}
void Mine::activate( bool sure )
{
if ( !sure ) {
switch ( st ) {
case Hidden:
setState( Flagged );
break;
case Flagged:
#ifdef MARK_UNSURE
setState( Unsure );
break;
case Unsure:
#endif
setState( Hidden );
default:
break;
}
} else if ( st == Flagged ) {
return;
} else {
if ( mined ) {
setState( Exploded );
} else {
setState( Empty );
}
}
}
void Mine::setState( MineState s )
{
st = s;
}
void Mine::setHint( int h )
{
hint = h;
}
void Mine::paletteChange()
{
delete knownField;
knownField = 0;
delete unknownField;
unknownField = 0;
delete mine_pix;
mine_pix = 0;
delete flag_pix;
flag_pix = 0;
}
void Mine::paint( QPainter* p, const QColorGroup &cg, const QRect& cr )
{
int x = cr.x();
int y = cr.y();
if ( !knownField || knownField->width() != cr.width() ||
knownField->height() != cr.height() ) {
delete knownField;
knownField = new QPixmap( cr.width(), cr.height() );
QPainter pp( knownField );
QBrush br( cg.button().dark(115) );
qDrawWinButton( &pp, QRect( 0, 0, cr.width(), cr.height() ), cg, TRUE, &br );
}
const int pmmarg=cr.width()/5;
if ( !unknownField || unknownField->width() != cr.width() ||
unknownField->height() != cr.height() ) {
delete unknownField;
unknownField = new QPixmap( cr.width(), cr.height() );
QPainter pp( unknownField );
QBrush br( cg.button() );
qDrawWinButton( &pp, QRect( 0, 0, cr.width(), cr.height() ), cg, FALSE, &br );
}
if ( !flag_pix || flag_pix->width() != cr.width()-pmmarg*2 ||
flag_pix->height() != cr.height()-pmmarg*2 ) {
delete flag_pix;
flag_pix = new QPixmap( cr.width()-pmmarg*2, cr.height()-pmmarg*2 );
flag_pix->convertFromImage( QImage(pix_flag).smoothScale(cr.width()-pmmarg*2, cr.height()-pmmarg*2) );
}
if ( !mine_pix || mine_pix->width() != cr.width()-pmmarg*2 ||
mine_pix->height() != cr.height()-pmmarg*2 ) {
delete mine_pix;
mine_pix = new QPixmap( cr.width()-pmmarg*2, cr.height()-pmmarg*2 );
mine_pix->convertFromImage( QImage(pix_mine).smoothScale(cr.width()-pmmarg*2, cr.height()-pmmarg*2) );
}
p->save();
switch(st) {
case Hidden:
p->drawPixmap( x, y, *unknownField );
break;
case Empty:
p->drawPixmap( x, y, *knownField );
if ( hint > 0 ) {
switch( hint ) {
case 1:
p->setPen( blue );
break;
case 2:
p->setPen( green.dark() );
break;
case 3:
p->setPen( red );
break;
case 4:
p->setPen( darkYellow.dark() );
break;
case 5:
p->setPen( darkMagenta );
break;
case 6:
p->setPen( darkRed );
break;
default:
p->setPen( black );
break;
}
p->drawText( cr, AlignHCenter | AlignVCenter, QString::number( hint ) );
}
break;
case Mined:
p->drawPixmap( x, y, *knownField );
p->drawPixmap( x+pmmarg, y+pmmarg, *mine_pix );
break;
case Exploded:
p->drawPixmap( x, y, *knownField );
p->drawPixmap( x+pmmarg, y+pmmarg, *mine_pix );
p->setPen( red );
p->drawText( cr, AlignHCenter | AlignVCenter, "X" );
break;
case Flagged:
p->drawPixmap( x, y, *unknownField );
p->drawPixmap( x+pmmarg, y+pmmarg, *flag_pix );
break;
#ifdef MARK_UNSURE
case Unsure:
p->drawPixmap( x, y, *unknownField );
p->drawText( cr, AlignHCenter | AlignVCenter, "?" );
break;
#endif
case Wrong:
p->drawPixmap( x, y, *unknownField );
p->drawPixmap( x+pmmarg, y+pmmarg, *flag_pix );
p->setPen( red );
p->drawText( cr, AlignHCenter | AlignVCenter, "X" );
break;
}
p->restore();
}
/*
MineField implementation
*/
MineField::MineField( QWidget* parent, const char* name )
: QScrollView( parent, name )
{
viewport()->setBackgroundMode( NoBackground );
setState( GameOver );
setSizePolicy( QSizePolicy( QSizePolicy::Maximum, QSizePolicy::Maximum ) );
setFocusPolicy( QWidget::NoFocus );
holdTimer = new QTimer( this );
connect( holdTimer, SIGNAL( timeout() ), this, SLOT( held() ) );
flagAction = NoAction;
ignoreClick = FALSE;
currRow = currCol = -1;
minecount=0;
mineguess=0;
nonminecount=0;
cellSize = -1;
numRows = numCols = 0;
mines = NULL;
}
MineField::~MineField()
{
for ( int i = 0; i < numCols*numRows; i++ )
delete mines[i];
delete[] mines;
}
void MineField::setState( State st )
{
stat = st;
}
void MineField::setup( int level )
{
lev = level;
setState( Waiting );
//viewport()->setUpdatesEnabled( FALSE );
int i;
for ( i = 0; i < numCols*numRows; i++ )
delete mines[i];
delete[] mines;
switch( lev ) {
case 1:
numRows = 9 ;
numCols = 9 ;
minecount = 12;
break;
case 2:
numRows = 13;
numCols = 13;
minecount = 33;
break;
case 3:
numCols = 18;
numRows = 18;
minecount = 66 ;
break;
}
mines = new Mine* [numRows*numCols];
for ( i = 0; i < numCols*numRows; i++ )
mines[i] = new Mine( this );
nonminecount = numRows*numCols - minecount;
mineguess = minecount;
emit mineCount( mineguess );
Mine::paletteChange();
if ( availableRect.isValid() )
setCellSize(findCellSize());
// viewport()->setUpdatesEnabled( TRUE );
//viewport()->repaint( TRUE );
updateContents( 0, 0, numCols*cellSize, numRows*cellSize );
updateGeometry();
}
void MineField::drawContents( QPainter * p, int clipx, int clipy, int clipw, int cliph )
{
int c1 = clipx / cellSize;
int c2 = ( clipx + clipw - 1 ) / cellSize;
int r1 = clipy / cellSize;
int r2 = ( clipy + cliph - 1 ) / cellSize;
for ( int c = c1; c <= c2 ; c++ ) {
for ( int r = r1; r <= r2 ; r++ ) {
int x = c * cellSize;
int y = r * cellSize;
Mine *m = mine( r, c );
if ( m )
m->paint( p, colorGroup(), QRect(x, y, cellSize, cellSize ) );
}
}
}
// Chicken and egg problem: We need to know how big the parent is
// before we can decide how big to make the table.
void MineField::setAvailableRect( const QRect &r )
{
availableRect = r;
int newCellSize = findCellSize();
if ( newCellSize == cellSize ) {
setCellSize( cellSize );
} else {
viewport()->setUpdatesEnabled( FALSE );
setCellSize( newCellSize );
viewport()->setUpdatesEnabled( TRUE );
viewport()->repaint( TRUE );
}
}
int MineField::findCellSize()
{
int w = availableRect.width() - 2;
int h = availableRect.height() - 2;
int cellsize;
cellsize = QMIN( w/numCols, h/numRows );
cellsize = QMIN( QMAX( cellsize, minGrid ), maxGrid );
return cellsize;
}
void MineField::setCellSize( int cellsize )
{
int b = 2;
int w2 = cellsize*numCols;
int h2 = cellsize*numRows;
int w = QMIN( availableRect.width(), w2+b );
int h = QMIN( availableRect.height(), h2+b );
//
// Don't rely on the change in cellsize to force a resize,
// as it's possible to have the same size cells when going
// from a large play area to a small one.
//
resizeContents(w2, h2);
if ( availableRect.height() < h2 &&
availableRect.width() - w > style().scrollBarExtent().width() ) {
w += style().scrollBarExtent().width();
}
setGeometry( availableRect.x() + (availableRect.width()-w)/2,
availableRect.y() + (availableRect.height()-h)/2, w, h );
cellSize = cellsize;
}
void MineField::placeMines()
{
int mines = minecount;
while ( mines ) {
int col = int((double(rand()) / double(RAND_MAX)) * numCols);
int row = int((double(rand()) / double(RAND_MAX)) * numRows);
Mine* m = mine( row, col );
if ( m && !m->isMined() && m->state() == Mine::Hidden ) {
m->setMined( TRUE );
mines--;
}
}
}
void MineField::updateCell( int r, int c )
{
updateContents( c*cellSize, r*cellSize, cellSize, cellSize );
}
void MineField::contentsMousePressEvent( QMouseEvent* e )
{
int c = e->pos().x() / cellSize;
int r = e->pos().y() / cellSize;
if ( onBoard( r, c ) )
cellPressed( r, c );
else
currCol = currRow = -1;
}
void MineField::contentsMouseReleaseEvent( QMouseEvent* e )
{
int c = e->pos().x() / cellSize;
int r = e->pos().y() / cellSize;
if ( onBoard( r, c ) && c == currCol && r == currRow )
cellClicked( r, c );
if ( flagAction == FlagNext ) {
flagAction = NoAction;
}
}
/*
state == Waiting means no "hold"
*/
void MineField::cellPressed( int row, int col )
{
if ( state() == GameOver )
return;
currRow = row;
currCol = col;
if ( state() == Playing )
holdTimer->start( 150, TRUE );
}
void MineField::held()
{
flagAction = FlagNext;
updateMine( currRow, currCol );
ignoreClick = TRUE;
}
void MineField::keyPressEvent( QKeyEvent* e )
{
#if defined(Q_WS_QWS) || defined(_WS_QWS_)
flagAction = ( e->key() == Key_Up ) ? FlagOn : NoAction;
#else
flagAction = ( ( e->state() & ShiftButton ) == ShiftButton ) ? FlagOn : NoAction;
#endif
}
void MineField::keyReleaseEvent( QKeyEvent* )
{
flagAction = NoAction;
}
int MineField::getHint( int row, int col )
{
int hint = 0;
for ( int c = col-1; c <= col+1; c++ )
for ( int r = row-1; r <= row+1; r++ ) {
Mine* m = mine( r, c );
if ( m && m->isMined() )
hint++;
}
return hint;
}
void MineField::setHint( int row, int col )
{
Mine *m = mine( row, col );
if ( !m )
return;
int hint = getHint( row, col );
if ( !hint ) {
for ( int c = col-1; c <= col+1; c++ )
for ( int r = row-1; r <= row+1; r++ ) {
Mine* m = mine( r, c );
if ( m && m->state() == Mine::Hidden ) {
m->activate( TRUE );
nonminecount--;
setHint( r, c );
updateCell( r, c );
}
}
}
m->setHint( hint );
updateCell( row, col );
}
/*
Only place mines after first click, since it is pointless to
kill the player before the game has started.
*/
void MineField::cellClicked( int row, int col )
{
if ( state() == GameOver )
return;
if ( state() == Waiting ) {
Mine* m = mine( row, col );
if ( !m )
return;
m->setState( Mine::Empty );
nonminecount--;
placeMines();
setState( Playing );
emit gameStarted();
updateMine( row, col );
} else { // state() == Playing
holdTimer->stop();
if ( ignoreClick )
ignoreClick = FALSE;
else
updateMine( row, col );
}
}
void MineField::updateMine( int row, int col )
{
Mine* m = mine( row, col );
if ( !m )
return;
bool wasFlagged = m->state() == Mine::Flagged;
bool wasEmpty = m->state() == Mine::Empty;
m->activate( flagAction == NoAction );
if ( m->state() == Mine::Exploded ) {
emit gameOver( FALSE );
setState( GameOver );
return;
} else if ( m->state() == Mine::Empty ) {
setHint( row, col );
if ( !wasEmpty )
nonminecount--;
}
if ( flagAction != NoAction ) {
if ( m->state() == Mine::Flagged ) {
if (mineguess > 0) {
--mineguess;
emit mineCount( mineguess );
if ( m->isMined() )
--minecount;
} else {
m->setState(Mine::Hidden);
}
} else if ( wasFlagged ) {
++mineguess;
emit mineCount( mineguess );
if ( m->isMined() )
++minecount;
}
}
updateCell( row, col );
if ( !minecount && !mineguess || !nonminecount ) {
emit gameOver( TRUE );
setState( GameOver );
}
}
void MineField::showMines()
{
for ( int c = 0; c < numCols; c++ )
for ( int r = 0; r < numRows; r++ ) {
Mine* m = mine( r, c );
if ( !m )
continue;
if ( m->isMined() && m->state() == Mine::Hidden )
m->setState( Mine::Mined );
if ( !m->isMined() && m->state() == Mine::Flagged )
m->setState( Mine::Wrong );
updateCell( r, c );
}
}
void MineField::paletteChange( const QPalette &o )
{
Mine::paletteChange();
QScrollView::paletteChange( o );
}
void MineField::writeConfig(Config& cfg) const
{
cfg.setGroup("Field");
cfg.writeEntry("Level",lev);
QString grid="";
if ( stat == Playing ) {
for ( int x = 0; x < numCols; x++ )
for ( int y = 0; y < numRows; y++ ) {
char code='A'+(x*17+y*101)%21; // Reduce the urge to cheat
const Mine* m = mine( y, x );
int st = (int)m->state(); if ( m->isMined() ) st+=5;
grid += code + st;
}
}
cfg.writeEntry("Grid",grid);
}
void MineField::readConfig(Config& cfg)
{
cfg.setGroup("Field");
lev = cfg.readNumEntry("Level",1);
setup(lev);
flagAction = NoAction;
ignoreClick = FALSE;
currRow = currCol = 0;
QString grid = cfg.readEntry("Grid");
int x;
if ( !grid.isEmpty() ) {
int i=0;
minecount=0;
mineguess=0;
for ( x = 0; x < numCols; x++ ) {
for ( int y = 0; y < numRows; y++ ) {
char code='A'+(x*17+y*101)%21; // Reduce the urge to cheat
int st = (char)(QChar)grid[i++]-code;
Mine* m = mine( y, x );
if ( st >= 5 ) {
st-=5;
m->setMined(TRUE);
minecount++;
mineguess++;
}
m->setState((Mine::MineState)st);
switch ( m->state() ) {
case Mine::Flagged:
if (m->isMined())
minecount--;
mineguess--;
break;
case Mine::Empty:
--nonminecount;
break;
default:
break;
}
}
}
for ( x = 0; x < numCols; x++ ) {
for ( int y = 0; y < numRows; y++ ) {
Mine* m = mine( y, x );
if ( m->state() == Mine::Empty )
m->setHint(getHint(y,x));
}
}
}
setState( Playing );
emit mineCount( mineguess );
}
QSize MineField::sizeHint() const
{
if ( qApp->desktop()->width() >= 240 )
return QSize(200,200);
else
return QSize(160, 160);
}
diff --git a/noncore/games/minesweep/minesweep.cpp b/noncore/games/minesweep/minesweep.cpp
index d707dab..4a6a92c 100644
--- a/noncore/games/minesweep/minesweep.cpp
+++ b/noncore/games/minesweep/minesweep.cpp
@@ -1,413 +1,408 @@
/**********************************************************************
** Copyright (C) 2000-2002 Trolltech AS. All rights reserved.
**
** This file is part of the Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include "minesweep.h"
#include "minefield.h"
#include <qtopia/qpeapplication.h>
#include <qtopia/resource.h>
#include <qtopia/config.h>
#include <qtoolbar.h>
#include <qmenubar.h>
-#include <qpopupmenu.h>
#include <qpushbutton.h>
#include <qlcdnumber.h>
-#include <qmessagebox.h>
#include <qtimer.h>
-#include <qpalette.h>
-#include <qapplication.h>
-#include <qlayout.h>
#include <qlabel.h>
#include <stdlib.h>
#include <time.h>
static const char *pix_new[]={
"20 20 3 1",
" c None",
"# c #00FF00",
". c #000000",
" ",
" ...... ",
" ..######.. ",
" .##########. ",
" .############. ",
" .##############. ",
" .##############. ",
" .################. ",
" .################. ",
" .################. ",
" .################. ",
" .################. ",
" .################. ",
" .##############. ",
" .##############. ",
" .############. ",
" .##########. ",
" ..######.. ",
" ...... ",
" "};
/* XPM */
static const char * happy_xpm[] = {
"20 20 3 1",
" c None",
". c #ffff3f ",
"# c #000000",
" ",
" ###### ",
" ##......## ",
" #..........# ",
" #............# ",
" #..............# ",
" #..............# ",
" #....##....##....# ",
" #....##....##....# ",
" #................# ",
" #................# ",
" #................# ",
" #...#........#...# ",
" #.##........##.# ",
" #...########...# ",
" #...######...# ",
" #..........# ",
" ##......## ",
" ###### ",
" "};
/* XPM */
static const char * worried_xpm[] = {
"20 20 3 1",
" c None",
". c #ffff3f",
"# c #000000",
" ",
" ###### ",
" ##......## ",
" #..........# ",
" #............# ",
" #..............# ",
" #..............# ",
" #....##....##....# ",
" #....##....##....# ",
" #................# ",
" #................# ",
" #................# ",
" #................# ",
" #....######....# ",
" #..............# ",
" #............# ",
" #..........# ",
" ##......## ",
" ###### ",
" "};
/* XPM */
static const char * dead_xpm[] = {
"20 20 3 1",
" c None",
". c #ffff3f",
"# c #000000",
" ",
" ###### ",
" ##......## ",
" #..........# ",
" #............# ",
" #..............# ",
" #..#.#...#.#...# ",
" #....#.....#.....# ",
" #...#.#...#.#....# ",
" #................# ",
" #................# ",
" #................# ",
" #......####......# ",
" #....# #....# ",
" #...#......#...# ",
" #............# ",
" #..........# ",
" ##......## ",
" ###### ",
" "};
class ResultIndicator : private QLabel
{
public:
static void showResult( QWidget *ref, bool won );
private:
ResultIndicator( QWidget *parent, const char *name, WFlags f)
:QLabel( parent, name, f ) {}
void timerEvent( QTimerEvent *);
void center();
bool twoStage;
int timerId;
};
void ResultIndicator::showResult( QWidget *ref, bool won )
{
ResultIndicator *r = new ResultIndicator( ref, 0, WStyle_Customize | WStyle_Tool | WType_TopLevel );
r->setAlignment( AlignCenter );
r->setFrameStyle( Sunken|StyledPanel );
if ( won ) {
r->setText( MineSweep::tr("You won!") );
r->center();
r->show();
r->twoStage = FALSE;
r->timerId = r->startTimer(1500);
} else {
QPalette p( red );
r->setPalette( p );
r->setText( MineSweep::tr("You exploded!") );
r->resize( ref->size() );
r->move( ref->mapToGlobal(QPoint(0,0)) );
r->show();
r->twoStage = TRUE;
r->timerId =r->startTimer(200);
}
}
void ResultIndicator::center()
{
QWidget *w = parentWidget();
QPoint pp = w->mapToGlobal( QPoint(0,0) );
QSize s = sizeHint()*3;
s.setWidth( QMIN(s.width(), w->width()) );
pp = QPoint( pp.x() + w->width()/2 - s.width()/2,
pp.y() + w->height()/ 2 - s.height()/2 );
setGeometry( QRect(pp, s) );
}
void ResultIndicator::timerEvent( QTimerEvent *te )
{
if ( te->timerId() != timerId )
return;
killTimer( timerId );
if ( twoStage ) {
center();
twoStage = FALSE;
timerId = startTimer( 1000 );
} else {
delete this;
}
}
class MineFrame : public QFrame
{
public:
MineFrame( QWidget *parent, const char *name = 0 )
:QFrame( parent, name ), field(0) {}
void setField( MineField *f ) {
field = f;
setMinimumSize( field->sizeHint() );
}
protected:
void resizeEvent( QResizeEvent *e ) {
field->setAvailableRect( contentsRect());
QFrame::resizeEvent(e);
}
private:
MineField *field;
};
MineSweep::MineSweep( QWidget* parent, const char* name, WFlags f )
: QMainWindow( parent, name, f )
{
srand(::time(0));
setCaption( tr("Mine Hunt") );
QPEApplication::setInputMethodHint(this, QPEApplication::AlwaysOff );
setIcon( Resource::loadPixmap( "minesweep/MineHunt" ) );
QToolBar *toolBar = new QToolBar( this );
toolBar->setHorizontalStretchable( TRUE );
QMenuBar *menuBar = new QMenuBar( toolBar );
QPopupMenu *gameMenu = new QPopupMenu( this );
gameMenu->insertItem( tr("Beginner"), this, SLOT( beginner() ) );
gameMenu->insertItem( tr("Advanced"), this, SLOT( advanced() ) );
if (qApp->desktop()->width() >= 240) {
gameMenu->insertItem( tr("Expert"), this, SLOT( expert() ) );
}
menuBar->insertItem( tr("Game"), gameMenu );
guessLCD = new QLCDNumber( toolBar );
toolBar->setStretchableWidget( guessLCD );
QPalette lcdPal( red );
lcdPal.setColor( QColorGroup::Background, QApplication::palette().active().background() );
lcdPal.setColor( QColorGroup::Button, QApplication::palette().active().button() );
// guessLCD->setPalette( lcdPal );
guessLCD->setSegmentStyle( QLCDNumber::Flat );
guessLCD->setFrameStyle( QFrame::NoFrame );
guessLCD->setNumDigits( 2 );
guessLCD->setBackgroundMode( PaletteButton );
newGameButton = new QPushButton( toolBar );
newGameButton->setPixmap( QPixmap( pix_new ) );
newGameButton->setFocusPolicy(QWidget::NoFocus);
connect( newGameButton, SIGNAL(clicked()), this, SLOT(newGame()) );
timeLCD = new QLCDNumber( toolBar );
// timeLCD->setPalette( lcdPal );
timeLCD->setSegmentStyle( QLCDNumber::Flat );
timeLCD->setFrameStyle( QFrame::NoFrame );
timeLCD->setNumDigits( 5 ); // "mm:ss"
timeLCD->setBackgroundMode( PaletteButton );
setToolBarsMovable ( FALSE );
addToolBar( toolBar );
MineFrame *mainframe = new MineFrame( this );
mainframe->setFrameShape( QFrame::Box );
mainframe->setFrameShadow( QFrame::Raised );
mainframe->setLineWidth(2);
field = new MineField( mainframe );
mainframe->setField( field );
QFont fnt = field->font();
fnt.setBold( TRUE );
field->setFont( QFont( fnt ) );
field->setFocus();
setCentralWidget( mainframe );
connect( field, SIGNAL( gameOver(bool) ), this, SLOT( gameOver(bool) ) );
connect( field, SIGNAL( mineCount(int) ), this, SLOT( setCounter(int) ) );
connect( field, SIGNAL( gameStarted()), this, SLOT( startPlaying() ) );
timer = new QTimer( this );
connect( timer, SIGNAL( timeout() ), this, SLOT( updateTime() ) );
readConfig();
}
MineSweep::~MineSweep()
{
writeConfig();
}
void MineSweep::gameOver( bool won )
{
field->showMines();
if ( won ) {
newGameButton->setPixmap( QPixmap( happy_xpm ) );
} else {
newGameButton->setPixmap( QPixmap( dead_xpm ) );
}
ResultIndicator::showResult( this, won );
timer->stop();
}
void MineSweep::newGame()
{
newGame(field->level());
}
void MineSweep::newGame(int level)
{
timeLCD->display( "0:00" );
field->setup( level );
newGameButton->setPixmap( QPixmap( pix_new ) );
timer->stop();
}
void MineSweep::startPlaying()
{
newGameButton->setPixmap( QPixmap( worried_xpm ) );
starttime = QDateTime::currentDateTime();
timer->start( 1000 );
}
void MineSweep::beginner()
{
newGame(1);
}
void MineSweep::advanced()
{
newGame(2);
}
void MineSweep::expert()
{
newGame(3);
}
void MineSweep::setCounter( int c )
{
if ( !guessLCD )
return;
guessLCD->display( c );
}
void MineSweep::updateTime()
{
if ( !timeLCD )
return;
int s = starttime.secsTo(QDateTime::currentDateTime());
if ( s/60 > 99 )
timeLCD->display( "-----" );
else
timeLCD->display( QString().sprintf("%2d:%02d",s/60,s%60) );
}
void MineSweep::writeConfig() const
{
Config cfg("MineSweep");
cfg.setGroup("Panel");
cfg.writeEntry("Time",
timer->isActive() ? starttime.secsTo(QDateTime::currentDateTime()) : -1);
field->writeConfig(cfg);
}
void MineSweep::readConfig()
{
Config cfg("MineSweep");
field->readConfig(cfg);
cfg.setGroup("Panel");
int s = cfg.readNumEntry("Time",-1);
if ( s<0 ) {
newGame();
} else {
startPlaying();
starttime = QDateTime::currentDateTime().addSecs(-s);
updateTime();
}
}
diff --git a/noncore/games/oyatzee/oyatzee.cpp b/noncore/games/oyatzee/oyatzee.cpp
index 0bd22f6..86318db 100644
--- a/noncore/games/oyatzee/oyatzee.cpp
+++ b/noncore/games/oyatzee/oyatzee.cpp
@@ -1,693 +1,687 @@
#include "oyatzee.h"
#include <qmessagebox.h>
-#include <qapplication.h>
-#include <qdir.h>
-#include <qlabel.h>
#include <qpushbutton.h>
-#include <qtimer.h>
-#include <qvbox.h>
#include <qpainter.h>
#include <qlayout.h>
-#include <qpoint.h>
#include <stdlib.h>
OYatzee::OYatzee( QWidget *parent , const char *name, WFlags fl ) : QMainWindow( parent , name , fl )
{
QWidget *thing = new QWidget( this );
setCentralWidget( thing );
setCaption( tr( "OYatzee" ) );
setPlayerNumber( 4 );
setRoundsNumber( 1 );
lastPlayerFinished = false;
currentPlayer = 1;
ps.append( new Player( "Carsten" ) );
ps.append( new Player( "Julia" ) );
ps.append( new Player( "Christine" ) );
ps.append( new Player( "Stephan" ) );
QVBoxLayout *vbox = new QVBoxLayout( thing );
sb = new Scoreboard( ps, thing , "sb" );
connect( sb->pb , SIGNAL( item( int ) ), this , SLOT( slotEndRound( int ) ) );
dw = new DiceWidget( thing , "dw" );
dw->setMaximumHeight( this->height()/4 );
connect( dw->rollButton, SIGNAL( clicked() ), this , SLOT( slotRollDices() ) );
vbox->addWidget( sb );
vbox->addWidget( dw );
}
void OYatzee::slotEndRound( int item )
{
qDebug( "Der User hat Nummer %d ausgewählt" , item );
/*
* if the user clicked on Total, Bonus or Score and thus not on a
* selectable item return and do nothing
*/
if ( item == 7 || item == 8 || item == 16 ) return;
/*
* check if the user can really click on that item
*/
if ( posibilities.find( item ) == posibilities.end() ) return;
QValueListInt numbers;
Dice *d = dw->diceList.first();
for ( ; d != 0 ; d = dw->diceList.next() )
{
numbers.append( d->hasValue() );
}
int points = 0;
switch ( item )
{
case Ones:
points = getPoints( 1 , numbers );
break;
case Twos:
points = getPoints( 2 , numbers );
break;
case Threes:
points = getPoints( 3 , numbers );
break;
case Fours:
points = getPoints( 4 , numbers );
break;
case Fives:
points = getPoints( 5 , numbers );
break;
case Sixes:
points = getPoints( 6 , numbers );
break;
case ThreeOfAKind:
points = oakPoints;
break;
case FourOfAKind:
points = oakPoints;
break;
case FullHouse:
points = 25;
break;
case SStraight:
points = 30;
break;
case LStraight:
points = 40;
break;
case Yatzee:
points = 50;
break;
case Chance:
points = getPoints ( Chance , numbers );
}
sb->nextRB(currentPlayer-1)->updateMap( item , points );
nextPlayer();
qDebug( "Punkte: %d" , points );
}
void OYatzee::nextPlayer()
{
currentPlayer++;
if ( currentPlayer > numOfPlayers )
{
currentPlayer = 1;
}
ps.at(currentPlayer-1)->turn = 0;
}
int OYatzee::getPoints( const int num , QValueListInt l)
{
QValueListInt::Iterator it = l.begin();
int c = 0;
if ( num != Chance )
{
for ( ; it != l.end() ; ++it )
{
if ( *it == num )
c++;
}
return c * num;
}
else
{
for ( ; it != l.end() ; ++it )
{
c += *it;
}
return c;
}
}
OYatzee::~OYatzee()
{
}
void OYatzee::detectPosibilities()
{
posibilities.clear();
qDebug( "running detectPosibilities()" );
Dice *d = dw->diceList.first();
QValueListInt numbers;
for ( ; d != 0 ; d = dw->diceList.next() )
{
numbers.append( d->hasValue() );
}
//the 6 numbers
QValueListInt::Iterator it;
for ( int i = 1 ; i < 7 ; ++i ) // check for 1-->6
{
bool cont = false;
it = numbers.begin();
for ( ; it != numbers.end() ; ++it )
{
if ( cont )
continue;
if ( numbers.find( i ) != numbers.end() )
{
posibilities.append( i );
cont = true;
}
}
}
//3er, 4er, Yatzee
it = numbers.begin();
int count;
int temp;
int countFH = 0; //for the full-house-check
for ( int i = 1 ; i < 7 ; ++i ) // check for 1-->6 at least 3 times
{
count = 0;
temp = 0;
it = numbers.begin();
for ( ; it != numbers.end() ; ++it )
{
if ( *it == i )
{
count++;
temp++;
}
if ( temp == 2 )
countFH = temp;
}
if ( count >= 3 )
{
posibilities.append( 9 );
//now we check if it is a full house
if ( count == 3 && countFH == 2 ) //aka Full House
posibilities.append( 11 );
if ( count >= 4 )
posibilities.append( 10 );
if ( count == 5 ) //Yatzee
posibilities.append( 14 );
oakPoints = count * i;
}
}
//S-Straight
if ( numbers.find( 3 ) != numbers.end() && numbers.find( 4 ) != numbers.end() )
{
bool isLong = false;
bool isShort = true;
//L-Straight
if ( numbers.find( 2 ) != numbers.end() && numbers.find( 5 ) != numbers.end() )
{
isShort = true;
//12345 or 23456
if ( numbers.find( 1 ) != numbers.end() || numbers.find( 6) != numbers.end() )
isLong = true;
}
//1234
if ( numbers.find( 1 ) != numbers.end() && numbers.find( 2 ) != numbers.end() )
isShort = true;
//3456
if ( numbers.find( 5 ) != numbers.end() && numbers.find( 6 ) != numbers.end() )
isShort = true;
if ( isShort )
posibilities.append( 12 );
if ( isLong )
posibilities.append( 13 );
}
posibilities.append( 13 ); //Chance, well, this is allways possible
displayPossibilites();
}
void OYatzee::displayPossibilites()
{
//X for ( QValueListInt::Iterator it = posibilities.begin() ; it != posibilities.end(); ++it )
//X {
//X qDebug( QString::number( *it ) );
//X switch ( *it )
//X {
//X case Ones:
//X qDebug( "1er" );
//X break;
//X case Twos:
//X qDebug( "2er" );
//X break;
//X case Threes:
//X qDebug( "3er" );
//X break;
//X case Fours:
//X qDebug( "4er" );
//X break;
//X case Fives:
//X qDebug( "5er" );
//X break;
//X case Sixes:
//X qDebug( "6er" );
//X break;
//X case ThreeOfAKind:
//X qDebug( "3oaK" );
//X break;
//X case FourOfAKind:
//X qDebug( "4oaK" );
//X break;
//X case FullHouse:
//X qDebug( "Full House" );
//X break;
//X case SStraight:
//X qDebug( "Short S" );
//X break;
//X case LStraight:
//X qDebug( "Long S" );
//X break;
//X case Yatzee:
//X qDebug( "Yatzee!" );
//X break;
//X case Chance:
//X qDebug( "Chance" );
//X break;
//X }
//X }
sb->pb->setIntlist( posibilities );
sb->pb->update();
}
void OYatzee::startGame()
{
/*
* TODO
*/
}
void OYatzee::stopGame(){}
void OYatzee::setPlayerNumber( const int num )
{
numOfPlayers = num;
}
void OYatzee::setRoundsNumber( const int num )
{
numOfRounds = num;
}
void OYatzee::slotStartGame()
{
}
void OYatzee::slotRollDices()
{
qDebug( "Roll nummer: %d" , ps.at( currentPlayer-1 )->turn );
if ( ps.at( currentPlayer-1 )->turn == 3 )
{
QMessageBox::information( this,
"OYatzee",
tr( "Only three rolls per turn allowed." ) );
return;
}
Dice *d = dw->diceList.first();
for ( ; d != 0 ; d = dw->diceList.next() )
{
if ( !d->isSelected )
d->roll();
}
// qDebug( "Roll nummer (vorher): %d" , ps.at( currentPlayer-1 )->turn );
ps.at(currentPlayer-1)->turn++;
// qDebug( "Roll nummer (nachher): %d" , ps.at( currentPlayer-1 )->turn );
detectPosibilities();
}
/*
* Scoreboard
*/
Scoreboard::Scoreboard( playerList ps, QWidget *parent, const char *name ) : QWidget( parent , name )
{
ps_ = ps;
pb = new Possibilityboard( this , "pb" );
createResultboards( 4 );
QHBoxLayout *hbox = new QHBoxLayout( this );
hbox->addWidget( pb );
hbox->addSpacing( 25 );
Resultboard *r = rbList.first();
for ( ; r != 0 ; r = rbList.next() )
{
hbox->addWidget( r );
}
}
Resultboard* Scoreboard::nextRB( int currentPlayer )
{
Resultboard *b;
b = rbList.at( currentPlayer );
qDebug( "Anzahl: %d" , rbList.count() );
return b;
}
void Scoreboard::createResultboards(const int num)
{
Player *p = ps_.first();
for ( int i = 0 ; i < num ; ++i , p = ps_.next() )
{
QString n = p->playerName;
rbList.append( new Resultboard( n , this ) );
}
}
void Scoreboard::paintEvent( QPaintEvent * )
{
//X QPainter p;
//X p.begin( this );
//X
//X p.drawRect( 0,0, this->width() , this->height() );
}
/*
* Dice
*/
Dice::Dice( QWidget *parent , const char *name ) : QFrame( parent , name )
{
QTime t = QTime::currentTime(); // set random seed
srand(t.hour()*12+t.minute()*60+t.second()*60);
connect( this , SIGNAL( selected() ), this , SLOT( slotSelected() ) );
}
void Dice::slotSelected()
{
if ( isSelected )
isSelected = false;
else isSelected = true;
update();
}
const int Dice::hasValue() const
{
return Value;
}
void Dice::roll()
{
Value = rand()%6;
Value += 1;
update();
}
void Dice::mousePressEvent( QMouseEvent* /*e*/ )
{
emit selected();
}
void Dice::paintEvent( QPaintEvent * )
{
QPainter p;
p.begin( this );
p.drawRect( 0,0, this->width() , this->height() );
if ( isSelected )
p.drawRect( 20,20, 10,10 );
paintNumber( &p );
}
void Dice::paintNumber( QPainter *p )
{
p->setBrush( Qt::black );
int w = this->width();
int h = this->height();
int r = this->width();
r /= 10;
switch ( Value )
{
case 1:
p->drawEllipse( (int)( 0.5*w - r ) , (int)( 0.5*h - r ) , r , r ) ;
break;
case 2:
p->drawEllipse( (int)( 0.3*w - r ) , (int)( 0.3*h - r ) , r , r ) ;
p->drawEllipse( (int)( 0.7*w - r ) , (int)( 0.7*h - r ) , r , r ) ;
break;
case 3:
p->drawEllipse( (int)( 0.5*w - r ) , (int)( 0.5*h - r ) , r , r ) ;
p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.2*h - r ) , r , r ) ;
p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.8*h - r ) , r , r ) ;
break;
case 4:
p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.2*h - r ) , r , r ) ;
p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.8*h - r ) , r , r ) ;
p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.2*h - r ) , r , r ) ;
p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.8*h - r ) , r , r ) ;
break;
case 5:
p->drawEllipse( (int)( 0.5*w - r ) , (int)( 0.5*h - r ) , r , r ) ;
p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.2*h - r ) , r , r ) ;
p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.8*h - r ) , r , r ) ;
p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.2*h - r ) , r , r ) ;
p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.8*h - r ) , r , r ) ;
break;
case 6:
p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.2*h - r ) , r , r ) ;
p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.8*h - r ) , r , r ) ;
p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.2*h - r ) , r , r ) ;
p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.8*h - r ) , r , r ) ;
p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.5*h - r ) , r , r ) ;
p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.5*h - r ) , r , r ) ;
break;
}
}
/*
* DiceWidget
*/
DiceWidget::DiceWidget( QWidget *parent , const char *name ) : QWidget( parent , name )
{
rollButton = new QPushButton( tr( "Roll" ) , this ) ;
for ( int i = 0 ; i < 5 ; i++ )
{
//appending the 5 dices of the game
diceList.append( new Dice( this, "wuerfel" ) );
}
QHBoxLayout *hbox = new QHBoxLayout( this );
Dice *d = diceList.first();
for ( ; d != 0 ; d = diceList.next() )
{
hbox->addWidget( d );
}
hbox->addWidget( rollButton );
}
/*
* Player
*/
Player::Player( QString name )
{
playerName = name;
setupResultList();
turn = 0;
}
void Player::setupResultList()
{
for ( int i = 1 ; i < 14 ; ++i )
{
pResults.append( 0 );
}
}
/*
* TODO: muss noch genutzt werden
*/
void Player::updateTotalPoints( pointMap m )
{
pointMap::Iterator it = m.begin();
for ( ; it != m.end() ; ++it )
{
totalPoints += it.data();
}
}
void Player::setResults( const int cat , const int points )
{
QValueListInt::Iterator it = pResults.at( cat );
*it = points;
}
/*
* Board
*/
Board::Board( QWidget *parent , const char* name ) : QWidget ( parent , name )
{
}
void Board::mousePressEvent( QMouseEvent *e )
{
emit clicked( e->pos() );
}
/*
* Resultboard
*/
Resultboard::Resultboard( QString playerName , QWidget *parent , const char* name ) : Board ( parent , name )
{
pName = playerName;
}
void Resultboard::paintEvent( QPaintEvent* )
{
QPainter p;
p.begin( this );
const int cell_width = this->width();
const int cell_height = this->height()/17;
pointMap::Iterator it = pMap.begin();
for ( ; it != pMap.end() ; ++it )
{
int i = it.key();
qDebug( "ok: %d , %d" , i , it.data() );
p.drawText( 0, i*cell_height , cell_width , cell_height , Qt::AlignCenter , QString::number( it.data() ) );
}
p.drawText( 0,0,cell_width,cell_height, Qt::AlignCenter , pName ); //Playername
}
void Resultboard::updateMap( int item , int points )
{
pMap.insert( item , points );
update();
}
/*
* Possibilityboard
*/
Possibilityboard::Possibilityboard( QWidget *parent , const char* name ) : Board ( parent , name )
{
begriffe.append( "1er" );
begriffe.append( "2er" );
begriffe.append( "3er" );
begriffe.append( "4er" );
begriffe.append( "5er" );
begriffe.append( "6er" );
begriffe.append( "Total" );
begriffe.append( "Bonus" );
begriffe.append( "3oaK" );
begriffe.append( "4oaK" );
begriffe.append( "Full House" );
begriffe.append( "Short S" );
begriffe.append( "Long S" );
begriffe.append( "Yatzee!" );
begriffe.append( "Chance" );
begriffe.append( "Score" );
connect( this , SIGNAL( clicked( QPoint ) ), this , SLOT( slotClicked( QPoint ) ) );
}
void Possibilityboard::slotClicked( QPoint p)
{
emit item( p.y()/(this->height()/17) );
}
void Possibilityboard::paintEvent( QPaintEvent* )
{
QPainter p;
p.begin( this );
const int cell_width = this->width();
const int cell_height = this->height()/17;
p.setBrush( Qt::blue );
QValueListInt::Iterator listIt = list.begin();
for ( ; listIt != list.end() ; ++listIt )
{
p.drawRect( 0 , (*listIt) * cell_height , cell_width , cell_height );
}
p.setBrush( Qt::black );
p.setBrush( Qt::NoBrush );
QStringList::Iterator begriffeIt = begriffe.begin();
for ( int i = 1 ; i < 18 ; ++i )
{
p.drawText( 0 , i*cell_height , cell_width , cell_height , Qt::AlignCenter , *begriffeIt );
++begriffeIt;
}
}
void Possibilityboard::setIntlist( QValueListInt &l )
{
list = l;
}
diff --git a/noncore/games/parashoot/base.cpp b/noncore/games/parashoot/base.cpp
index cdf1dfa..5f3c79d 100644
--- a/noncore/games/parashoot/base.cpp
+++ b/noncore/games/parashoot/base.cpp
@@ -1,77 +1,75 @@
/**********************************************************************
** Copyright (C) 2000-2002 Trolltech AS. All rights reserved.
**
** This file is part of the Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include "codes.h"
#include "base.h"
-#include "man.h"
#include <qtopia/resource.h>
-#include <qregexp.h>
int damage;
Base::Base(QCanvas* canvas) :
QCanvasSprite(0, canvas),
kaboom("landmine"),
ohdear("crmble01")
{
basearray = new QCanvasPixmapArray();
QString b0 = Resource::findPixmap("parashoot/b0001");
b0.replace(QRegExp("0001"),"%1");
basearray->readPixmaps(b0, 4);
setSequence(basearray);
setFrame(0);
move(2, canvas->height()-50);
setZ(10);
show();
damage = 0;
}
void Base::damageBase()
{
damage++;
switch(damage) {
case 1: setFrame(1); ohdear.play(); break;
case 2: setFrame(2); ohdear.play(); break;
case 3: setFrame(3); kaboom.play(); break;
}
show();
}
bool Base::baseDestroyed()
{
return (damage >= 3);
}
Base::~Base()
{
}
int Base::rtti() const
{
return base_rtti;
}
void
Base::reposition(void)
{
move(2, canvas()->height()-50);
}
diff --git a/noncore/games/parashoot/cannon.cpp b/noncore/games/parashoot/cannon.cpp
index 5671351..330d850 100644
--- a/noncore/games/parashoot/cannon.cpp
+++ b/noncore/games/parashoot/cannon.cpp
@@ -1,150 +1,149 @@
/**********************************************************************
** Copyright (C) 2000-2002 Trolltech AS. All rights reserved.
**
** This file is part of the Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include <qtopia/resource.h>
-#include <qregexp.h>
#include "codes.h"
#include "cannon.h"
Cannon::Cannon(QCanvas* canvas) :
QCanvasSprite(0, canvas)
{
shotsfired=0;
index = 8;
cannonx = 0;
cannony = 0;
cannonarray = new QCanvasPixmapArray();
QString c0 = Resource::findPixmap("parashoot/can0001");
c0.replace(QRegExp("0001"),"%1");
cannonarray->readPixmaps(c0,17);
setSequence(cannonarray);
setFrame(index);
reposition();
movedir = NoDir;
moveDelay = 0;
setAnimated(TRUE);
show();
}
void Cannon::advance(int stage)
{
if ( stage == 1 && moveDelay-- == 0 ) {
if (movedir == Left) {
if (index > 0) {
setFrame(index-1);
index--;
}
}
if (movedir == Right) {
if (index < 16) {
setFrame(index+1);
index++;
}
}
moveDelay = 0;
}
}
void Cannon::pointCannon(Direction dir)
{
movedir = dir;
moveDelay = 0;
advance(1);
moveDelay = 1;
}
void Cannon::setCoords()
{
switch(index) {
case 0: cannonx = barrelxpos-29; cannony = barrelypos-8; break;
case 1: cannonx = barrelxpos-27; cannony = barrelypos-8; break;
case 2: cannonx = barrelxpos-25; cannony = barrelypos-6; break;
case 3: cannonx = barrelxpos-23; cannony = barrelypos-4; break;
case 4: cannonx = barrelxpos-21; cannony = barrelypos-2; break;
case 5: cannonx = barrelxpos-19; cannony = barrelypos; break;
case 6: cannonx = barrelxpos-15; cannony = barrelypos; break;
case 7: cannonx = barrelxpos-10; cannony = barrelypos; break;
case 8: cannonx = barrelxpos; cannony = barrelypos; break;
case 9: cannonx = barrelxpos+2; cannony = barrelypos; break;
case 10: cannonx = barrelxpos+6; cannony = barrelypos; break;
case 11: cannonx = barrelxpos+8; cannony = barrelypos; break;
case 12: cannonx = barrelxpos+12; cannony = barrelypos-2; break;
case 13: cannonx = barrelxpos+18; cannony = barrelypos-4; break;
case 14: cannonx = barrelxpos+22; cannony = barrelypos-6; break;
case 15: cannonx = barrelxpos+26; cannony = barrelypos-8; break;
case 16: cannonx = barrelxpos+28; cannony = barrelypos-8; break;
}
}
double Cannon::shootAngle()
{
switch(index) {
case 0: return 30.0;
case 1: return 37.5;
case 2: return 45.0;
case 3: return 52.5;
case 4: return 60.0;
case 5: return 67.5;
case 6: return 75.0;
case 7: return 82.5;
case 8: return 90.0;
case 9: return 97.5;
case 10: return 105.0;
case 11: return 112.5;
case 12: return 120.0;
case 13: return 127.5;
case 14: return 135.0;
case 15: return 142.5;
case 16: return 150.0;
}
return 0;
}
void Cannon::shoot()
{
setCoords();
Bullet* bullet = new Bullet(canvas(), shootAngle(), cannonx, cannony);
connect(bullet, SIGNAL(score(int)), this, SIGNAL(score(int)));
shotsfired++;
}
Cannon::~Cannon()
{
}
int Cannon::rtti() const
{
return cannon_rtti;
}
void Cannon::reposition(void)
{
move(canvas()->width()/2-20, canvas()->height()-32);
// co ords for barrel of cannon when upright
barrelypos = canvas()->height()-32;
barrelxpos = canvas()->width()/2;
setFrame(index);
setCoords();
}
diff --git a/noncore/games/parashoot/helicopter.cpp b/noncore/games/parashoot/helicopter.cpp
index 036b21e..7d91cd1 100644
--- a/noncore/games/parashoot/helicopter.cpp
+++ b/noncore/games/parashoot/helicopter.cpp
@@ -1,120 +1,119 @@
/**********************************************************************
** Copyright (C) 2000-2002 Trolltech AS. All rights reserved.
**
** This file is part of the Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include "helicopter.h"
#include "man.h"
#include "codes.h"
#include <qtopia/resource.h>
-#include <qregexp.h>
static QList<Helicopter> all;
Helicopter::Helicopter(QCanvas* canvas) :
QCanvasSprite(0, canvas),
chikachika("aland01")
{
all.append(this);
hits = 0;
QCanvasPixmapArray* helicopterarray = new QCanvasPixmapArray();
QString h0 = Resource::findPixmap("parashoot/helicopter0001");
h0.replace(QRegExp("0001"),"%1");
helicopterarray->readPixmaps(h0,4 );
setSequence(helicopterarray);
setAnimated(true);
move(canvas->width(), 5);
setVelocity(-2, 0);
chikachika.playLoop();
show();
}
Helicopter::~Helicopter()
{
all.remove(this);
}
int fr = 0;
void Helicopter::advance(int phase)
{
QCanvasSprite::advance(phase);
if (phase == 0) {
if (frame() == 3) {
delete this;
return;
}
if (hits >= 2) {
setFrame(3);
} else {
setFrame(fr%3);
fr++;
checkCollision();
}
}
}
void Helicopter::checkCollision()
{
if (x() == 6) {
setAnimated(false); //setVelocity(0, 0);
dropman();
}
if (x() < 0)
done();
}
void Helicopter::dropman()
{
(void)new Man(canvas(), 15, 25);
(void)new Man(canvas(), 35, 25);
takeOff();
}
void Helicopter::done()
{
hits++;
}
void Helicopter::takeOff()
{
setVelocity(-1, 0);
}
int Helicopter::rtti() const
{
return helicopter_rtti;
}
void Helicopter::silenceAll()
{
for (Helicopter* h = all.first(); h; h = all.next())
h->chikachika.stop();
}
void Helicopter::deleteAll()
{
Helicopter* h;
while ((h = all.first()))
delete h;
}
diff --git a/noncore/games/parashoot/interface.cpp b/noncore/games/parashoot/interface.cpp
index 948b92c..5c9b0ef 100644
--- a/noncore/games/parashoot/interface.cpp
+++ b/noncore/games/parashoot/interface.cpp
@@ -1,282 +1,278 @@
/**********************************************************************
** Copyright (C) 2000-2002 Trolltech AS. All rights reserved.
**
** This file is part of the Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include "interface.h"
#include "man.h"
#include <qtopia/qpeapplication.h>
#include <qtopia/resource.h>
-#include <qlabel.h>
-#include <qmessagebox.h>
-#include <qapplication.h>
-#include <qstyle.h>
#include <qtoolbar.h>
#include <qtoolbutton.h>
ParaShoot::ParaShoot(QWidget* parent, const char* name, WFlags f) :
QMainWindow(parent,name,f),
canvas( 232, 258 ),
cannon(NULL),
base(NULL),
gamestopped( true ),
waitover( false ),
fanfare("level_up"),
score(0)
{
QPEApplication::grabKeyboard();
QPEApplication::setInputMethodHint(this, QPEApplication::AlwaysOff );
updatespeed = 80;
canvas.setAdvancePeriod(80);
pb = new QCanvasView(&canvas, this);
pb->setFocus();
setToolBarsMovable( FALSE );
QToolBar* toolbar = new QToolBar(this);
toolbar->setHorizontalStretchable( TRUE );
setCaption( tr("ParaShoot") );
new QToolButton( Resource::loadIconSet("new"), tr("New Game"), 0,
this, SLOT(newGame()), toolbar, "New Game");
levelscore = new QLabel(toolbar);
levelscore->setBackgroundMode( PaletteButton );
levelscore->setAlignment( AlignRight | AlignVCenter | ExpandTabs );
toolbar->setStretchableWidget( levelscore );
showScore(0,0);
setCentralWidget(pb);
autoDropTimer = new QTimer(this);
connect (autoDropTimer, SIGNAL(timeout()), this, SLOT(play()) );
pauseTimer = new QTimer(this);
connect(pauseTimer, SIGNAL(timeout()), this, SLOT(wait()) );
setFocusPolicy(StrongFocus);
}
void ParaShoot::resizeEvent(QResizeEvent *)
{
QSize s = centralWidget()->size();
int fw = style().defaultFrameWidth();
canvas.resize( s.width() - fw - 2, s.height() - fw - 2);
QImage bgimage = Resource::loadImage("parashoot/sky");
QPixmap bgpixmap;
bgpixmap.convertFromImage(bgimage.smoothScale(canvas.width(),
canvas.height()), QPixmap::Auto);
canvas.setBackgroundPixmap(bgpixmap);
if (base) {
base->reposition();
}
if (cannon) {
cannon->reposition();
}
}
void ParaShoot::focusOutEvent (QFocusEvent *)
{
if (!gamestopped)
canvas.setAdvancePeriod(-1);
}
void ParaShoot::focusInEvent (QFocusEvent *)
{
if (!gamestopped)
canvas.setAdvancePeriod(updatespeed);
}
void ParaShoot::showScore( int score, int level )
{
levelscore->setText(tr(" Level: %1 Score: %2 ").arg(score).arg(level) );
}
void ParaShoot::newGame()
{
clear();
if (pauseTimer->isActive())
pauseTimer->stop();
clear();
Man::setManCount(0);
score = 0;
Bullet::setShotCount(0);
Bullet::setNobullets(0);
nomen = 2;
Bullet::setLimit(nomen);
level = 0;
updatespeed = 80;
showScore(0,0);
gamestopped = false;
Helicopter::deleteAll();
waitover = true;
base = new Base(&canvas);
cannon = new Cannon(&canvas);
connect( cannon, SIGNAL(score(int)), this, SLOT(increaseScore(int)));
autoDropTimer->start(100);
}
void ParaShoot::clear()
{
autoDropTimer->stop();
// QCanvasItem* item;
QCanvasItemList l = canvas.allItems();
for (QCanvasItemList::Iterator it=l.begin(); it!=l.end(); ++it) {
delete *it;
}
}
void ParaShoot::gameOver()
{
QCanvasItem* item;
QCanvasItemList l = canvas.allItems();
for (QCanvasItemList::Iterator it=l.begin(); it!=l.end(); ++it) {
item = *it;
if ((item->rtti()==1500) || (item->rtti()==1600) || item->rtti()==1900)
item->setAnimated(false);
}
autoDropTimer->stop();
Helicopter::silenceAll();
int shots = Bullet::getShotCount();
int shotsFired = cannon->shotsFired();
if ( shotsFired == 0 )
shotsFired = 1;
QCanvasText* gameover = new QCanvasText(
tr( " GAME OVER!\n"
" Your Score: %1\n"
" Parachuters Killed: %2\n"
" Accuracy: %3% " ).arg(score).arg(shots).arg(shots * 100 / shotsFired ),
&canvas);
gameover->setColor(red);
gameover->setFont( QFont("times", 16, QFont::Bold) );
gameover->move((canvas.width() - gameover->boundingRect().width()) / 2,
(canvas.height() - gameover->boundingRect().height()) / 2);
gameover->setZ(500);
gameover->show();
gamestopped = true;
waitover = false;
pauseTimer->start(3000);
}
void ParaShoot::wait()
{
waitover = true;
pauseTimer->stop();
}
void ParaShoot::play()
{
if (Man::getManCount() < nomen ) {
new Man(&canvas);
}
if (Base::baseDestroyed()) {
gameOver();
return;
}
}
void ParaShoot::increaseScore(int x)
{
score += x;
if ( score / 150 != (score-x) / 150 )
levelUp();
showScore(level,score);
}
void ParaShoot::levelUp()
{
level++;
int stage = level % 3;
switch(stage) {
case 0:
nomen++;
Bullet::setLimit(nomen);
fanfare.play();
break;
case 1:
new Helicopter(&canvas);
break;
case 2:
moveFaster();
fanfare.play();
break;
default: return;
}
}
void ParaShoot::moveFaster()
{
if (updatespeed > 50)
updatespeed = updatespeed-5;
else
updatespeed = updatespeed-3;
canvas.setAdvancePeriod(updatespeed);
}
void ParaShoot::keyPressEvent(QKeyEvent* event)
{
if (gamestopped) {
if (waitover)
newGame();
else
return;
} else {
switch(event->key()) {
case Key_Up:
case Key_F1:
case Key_F9:
case Key_Space:
if ( cannon )
cannon->shoot();
break;
case Key_Left:{
if (cannon )
cannon->pointCannon(Cannon::Left);
lastcannonkey=Key_Left;
break;
}
case Key_Right:{
if ( cannon )
cannon->pointCannon(Cannon::Right);
lastcannonkey=Key_Right;
break;
}
default:
return;
}
}
}
void ParaShoot::keyReleaseEvent(QKeyEvent* event)
{
if ( cannon && lastcannonkey == event->key() )
cannon->pointCannon(Cannon::NoDir);
}
diff --git a/noncore/games/parashoot/main.cpp b/noncore/games/parashoot/main.cpp
index ee36d26..40f809f 100644
--- a/noncore/games/parashoot/main.cpp
+++ b/noncore/games/parashoot/main.cpp
@@ -1,27 +1,26 @@
/**********************************************************************
** Copyright (C) 2000 Trolltech AS. All rights reserved.
**
** This file is part of Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include "interface.h"
-#include <qpe/qpeapplication.h>
#include <opie/oapplicationfactory.h>
OPIE_EXPORT_APP( OApplicationFactory<ParaShoot> )
diff --git a/noncore/games/parashoot/man.cpp b/noncore/games/parashoot/man.cpp
index 94807c2..0a151b0 100644
--- a/noncore/games/parashoot/man.cpp
+++ b/noncore/games/parashoot/man.cpp
@@ -1,191 +1,190 @@
/**********************************************************************
** Copyright (C) 2000-2002 Trolltech AS. All rights reserved.
**
** This file is part of the Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include "codes.h"
#include "man.h"
#include "base.h"
#include <qtopia/resource.h>
-#include <qregexp.h>
int mancount;
Man::Man(QCanvas* canvas) :
QCanvasSprite(0, canvas),
splat("lose") // No tr
{
manarray = new QCanvasPixmapArray();
QString m0 = Resource::findPixmap("parashoot/man0001");
m0.replace(QRegExp("0001"),"%1");
manarray->readPixmaps(m0, 7);
setSequence(manarray);
setAnimated(true);
mancount++;
dead = false;
start();
}
Man::Man(QCanvas* canvas, int x, int y) :
QCanvasSprite(0, canvas),
splat("bang") // No tr
{
manarray = new QCanvasPixmapArray();
QString m0 = Resource::findPixmap("parashoot/man0001");
m0.replace(QString("0001"),"%1");
manarray->readPixmaps(m0, 7);
setSequence(manarray);
move(x, y);
setFrame(5);
setZ(300);
show();
static bool first_time = TRUE;
if (first_time) {
first_time = FALSE;
QTime midnight(0, 0, 0);
srand(midnight.secsTo(QTime::currentTime()) );
}
int yfallspeed = 0;
yfallspeed = (rand() % 3) + 1;
setVelocity(0, yfallspeed);
mancount++;
dead = false;
}
int f = 0;
void Man::advance(int phase)
{
QCanvasSprite::advance(phase);
if (phase == 0) {
checkCollision();
if (dead) {
if (count < 10) {
setFrame(6);
setVelocity(0,0);
count++;
} else {
delete this;
return;
}
}
if (y() > canvas()->height()-43) {
setFrame(f%5);
f++;
move(x(), canvas()->height()-26);
setVelocity(-2, 0);
} else if (xVelocity() == -2) {
//
// There's been a resize event while this Man has
// been on the ground. Move the man back to the
// new ground location. This is not neat.
//
move(x(), canvas()->height()-26);
}
}
}
void Man::setInitialCoords()
{
static bool first_time = TRUE;
if (first_time) {
first_time = FALSE;
QTime midnight(0, 0, 0);
srand(midnight.secsTo(QTime::currentTime()) );
}
dx = rand() % (canvas()->width()-16);
dy = -43; //height of a man off the screen
}
//check if man has reached the base
void Man::checkCollision()
{
if ( (x() < 23) && (y() == canvas()->height()-26)) {
QCanvasItem* item;
QCanvasItemList l=collisions(FALSE);
for (QCanvasItemList::Iterator it=l.begin(); it!=l.end(); ++it) {
item = *it;
if ( (item->rtti()== 1800) && (item->collidesWith(this)) ) {
Base* base = (Base*) item;
base->damageBase();
start();
}
}
}
//
// resize events may cause Man objects to appear
// outside the screen. Get rid of them if this
// is the case.
//
if ((x() < 0) || (x() > canvas()->width())) {
delete this;
return;
}
}
void Man::start()
{
setInitialCoords();
move(dx, dy);
setFrame(5);
setZ(300);
show();
static bool first_time = TRUE;
if (first_time) {
first_time = FALSE;
QTime midnight(0, 0, 0);
srand(midnight.secsTo(QTime::currentTime()) );
}
int yfallspeed = 0;
yfallspeed = (rand() % 3) + 1;
setVelocity(0, yfallspeed);
}
void Man::done()
{
splat.play();
count = 0;
dead = true;
setFrame(6);
}
int Man::getManCount()
{
return mancount;
}
void Man::setManCount(int count)
{
mancount = count;
}
int Man::rtti() const
{
return man_rtti;
}
Man::~Man()
{
mancount--;
}
diff --git a/noncore/games/qasteroids/main.cpp b/noncore/games/qasteroids/main.cpp
index c762990..18a13eb 100644
--- a/noncore/games/qasteroids/main.cpp
+++ b/noncore/games/qasteroids/main.cpp
@@ -1,27 +1,26 @@
/**********************************************************************
** Copyright (C) 2000 Trolltech AS. All rights reserved.
**
** This file is part of Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include "toplevel.h"
-#include <qpe/qpeapplication.h>
#include <opie/oapplicationfactory.h>
OPIE_EXPORT_APP( OApplicationFactory<KAstTopLevel> )
diff --git a/noncore/games/qasteroids/toplevel.cpp b/noncore/games/qasteroids/toplevel.cpp
index c4fea89..9053d3d 100644
--- a/noncore/games/qasteroids/toplevel.cpp
+++ b/noncore/games/qasteroids/toplevel.cpp
@@ -1,535 +1,533 @@
/**********************************************************************
** Copyright (C) 2000 Trolltech AS. All rights reserved.
**
** This file is part of Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************//*
* KAsteroids - Copyright (c) Martin R. Jones 1997
*
* Part of the KDE project
*/
// --- toplevel.cpp ---
#include "toplevel.h"
#include "ledmeter.h"
#include <qpe/qpeapplication.h>
#include <qpe/resource.h>
-#include <qaccel.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qlcdnumber.h>
-#include <qpushbutton.h>
#include <sys/utsname.h>
#define SB_SCORE 1
#define SB_LEVEL 2
#define SB_SHIPS 3
struct SLevel
{
int nrocks;
double rockSpeed;
};
#define MAX_LEVELS 16
SLevel levels[MAX_LEVELS] =
{
{ 1, 0.4 },
{ 1, 0.6 },
{ 2, 0.5 },
{ 2, 0.7 },
{ 2, 0.8 },
{ 3, 0.6 },
{ 3, 0.7 },
{ 3, 0.8 },
{ 4, 0.6 },
{ 4, 0.7 },
{ 4, 0.8 },
{ 5, 0.7 },
{ 5, 0.8 },
{ 5, 0.9 },
{ 5, 1.0 }
};
const char *soundEvents[] =
{
"ShipDestroyed",
"RockDestroyed",
0
};
const char *soundDefaults[] =
{
"Explosion.wav",
"ploop.wav",
0
};
KAstTopLevel::KAstTopLevel( QWidget *parent, const char *_name, WFlags fl )
: QMainWindow( parent, _name, fl )
{
setCaption( tr("Asteroids") );
QPEApplication::grabKeyboard();
QWidget *border = new QWidget( this );
border->setBackgroundColor( black );
setCentralWidget( border );
QVBoxLayout *borderLayout = new QVBoxLayout( border );
QWidget *mainWin = new QWidget( border );
borderLayout->addWidget( mainWin, 2, AlignHCenter );
view = new KAsteroidsView( mainWin );
connect( view, SIGNAL( shipKilled() ), SLOT( slotShipKilled() ) );
connect( view, SIGNAL( rockHit(int) ), SLOT( slotRockHit(int) ) );
connect( view, SIGNAL( rocksRemoved() ), SLOT( slotRocksRemoved() ) );
connect( view, SIGNAL( updateVitals() ), SLOT( slotUpdateVitals() ) );
QVBoxLayout *vb = new QVBoxLayout( mainWin );
QHBoxLayout *hb = new QHBoxLayout;
QHBoxLayout *hbd = new QHBoxLayout;
vb->addLayout( hb );
QFont labelFont( "helvetica", 12 );
QColorGroup grp( darkGreen, black, QColor( 128, 128, 128 ),
QColor( 64, 64, 64 ), black, darkGreen, black );
QPalette pal( grp, grp, grp );
mainWin->setPalette( pal );
QLabel *label;
label = new QLabel( tr("Score"), mainWin );
label->setFont( labelFont );
label->setPalette( pal );
// label->setFixedWidth( label->sizeHint().width() );
hb->addWidget( label );
scoreLCD = new QLCDNumber( 5, mainWin );
scoreLCD->setFrameStyle( QFrame::NoFrame );
scoreLCD->setSegmentStyle( QLCDNumber::Flat );
scoreLCD->setFixedHeight( 16 );
scoreLCD->setPalette( pal );
hb->addWidget( scoreLCD );
hb->addStretch( 1 );
label = new QLabel( tr("Level"), mainWin );
label->setFont( labelFont );
label->setPalette( pal );
// label->setFixedWidth( label->sizeHint().width() );
hb->addWidget( label );
levelLCD = new QLCDNumber( 2, mainWin );
levelLCD->setFrameStyle( QFrame::NoFrame );
levelLCD->setSegmentStyle( QLCDNumber::Flat );
levelLCD->setFixedHeight( 16 );
levelLCD->setPalette( pal );
hb->addWidget( levelLCD );
hb->addStretch( 1 );
label = new QLabel( tr("Ships"), mainWin );
label->setFont( labelFont );
// label->setFixedWidth( label->sizeHint().width() );
label->setPalette( pal );
hb->addWidget( label );
shipsLCD = new QLCDNumber( 1, mainWin );
shipsLCD->setFrameStyle( QFrame::NoFrame );
shipsLCD->setSegmentStyle( QLCDNumber::Flat );
shipsLCD->setFixedHeight( 16 );
shipsLCD->setPalette( pal );
hb->addWidget( shipsLCD );
// hb->addStrut( 14 );
vb->addWidget( view, 10 );
// -- bottom layout:
vb->addLayout( hbd );
QFont smallFont( "helvetica", 12 );
hbd->addSpacing( 5 );
/*
label = new QLabel( tr( "T" ), mainWin );
label->setFont( smallFont );
label->setFixedWidth( label->sizeHint().width() );
label->setPalette( pal );
hbd->addWidget( label );
teleportsLCD = new QLCDNumber( 1, mainWin );
teleportsLCD->setFrameStyle( QFrame::NoFrame );
teleportsLCD->setSegmentStyle( QLCDNumber::Flat );
teleportsLCD->setPalette( pal );
teleportsLCD->setFixedHeight( 18 );
hbd->addWidget( teleportsLCD );
hbd->addSpacing( 10 );
*/
label = new QLabel( mainWin );
label->setPixmap( Resource::loadPixmap("qasteroids/powerups/brake.png") );
label->setFixedWidth( 16 );
label->setPalette( pal );
hbd->addWidget( label );
brakesLCD = new QLCDNumber( 1, mainWin );
brakesLCD->setFrameStyle( QFrame::NoFrame );
brakesLCD->setSegmentStyle( QLCDNumber::Flat );
brakesLCD->setPalette( pal );
brakesLCD->setFixedHeight( 16 );
hbd->addWidget( brakesLCD );
hbd->addSpacing( 5 );
label = new QLabel( mainWin );
label->setPixmap( Resource::loadPixmap("qasteroids/powerups/shield.png") );
label->setFixedWidth( 16 );
label->setPalette( pal );
hbd->addWidget( label );
shieldLCD = new QLCDNumber( 1, mainWin );
shieldLCD->setFrameStyle( QFrame::NoFrame );
shieldLCD->setSegmentStyle( QLCDNumber::Flat );
shieldLCD->setPalette( pal );
shieldLCD->setFixedHeight( 16 );
hbd->addWidget( shieldLCD );
hbd->addSpacing( 5 );
label = new QLabel( mainWin );
label->setPixmap( Resource::loadPixmap("qasteroids/powerups/shoot.png") );
label->setFixedWidth( 16 );
label->setPalette( pal );
hbd->addWidget( label );
shootLCD = new QLCDNumber( 1, mainWin );
shootLCD->setFrameStyle( QFrame::NoFrame );
shootLCD->setSegmentStyle( QLCDNumber::Flat );
shootLCD->setPalette( pal );
shootLCD->setFixedHeight( 16 );
hbd->addWidget( shootLCD );
hbd->addStretch( 1 );
label = new QLabel( tr( "Fuel" ), mainWin );
label->setFont( smallFont );
label->setFixedWidth( label->sizeHint().width() + 5 );
label->setPalette( pal );
hbd->addWidget( label );
powerMeter = new KALedMeter( mainWin );
powerMeter->setFrameStyle( QFrame::Box | QFrame::Plain );
powerMeter->setRange( MAX_POWER_LEVEL );
powerMeter->addColorRange( 10, darkRed );
powerMeter->addColorRange( 20, QColor(160, 96, 0) );
powerMeter->addColorRange( 70, darkGreen );
powerMeter->setCount( 15 );
powerMeter->setPalette( pal );
powerMeter->setFixedSize( 60, 12 );
hbd->addWidget( powerMeter );
shipsRemain = 3;
showHiscores = FALSE;
actions.insert( Qt::Key_Up, Thrust );
actions.insert( Qt::Key_Left, RotateLeft );
actions.insert( Qt::Key_Right, RotateRight );
actions.insert( Qt::Key_Enter, Shoot );
actions.insert( Qt::Key_Z, Teleport );
actions.insert( Qt::Key_Down, Brake );
actions.insert( Qt::Key_P, Pause );
struct utsname name; /* check for embedix kernel running on the zaurus, if
lineo change string, this break
*/
if (uname(&name) != -1) {
QString release=name.release;
if(release.find("embedix",0,TRUE) !=-1) {
actions.insert( Key_F12, Launch );
actions.insert( Key_F11, Shield );
actions.insert( Key_F9, NewGame );
} else {
// ipaq
actions.insert( Key_F12, Shoot );
actions.insert( Key_F11, Shield );
actions.insert( Key_F10, Launch );
actions.insert( Key_F9, NewGame );
}
}
// actions.insert( Qt::Key_S, Shield );
// actions.insert( Qt::Key_X, Brake );
// actions.insert( Qt::Key_L, Launch );
actions.insert( Qt::Key_Space, Shoot );
view->showText( tr( "Press Calendar to start playing" ), yellow );
setFocusPolicy( StrongFocus );
slotNewGame();
}
KAstTopLevel::~KAstTopLevel()
{
}
void KAstTopLevel::playSound( const char * )
{
}
void KAstTopLevel::keyPressEvent( QKeyEvent *event )
{
if ( event->isAutoRepeat() || !actions.contains( event->key() ) )
{
event->ignore();
return;
}
Action a = actions[ event->key() ];
switch ( a )
{
case RotateLeft:
view->rotateLeft( TRUE );
break;
case RotateRight:
view->rotateRight( TRUE );
break;
case Thrust:
view->thrust( TRUE );
break;
case Shoot:
view->shoot( TRUE );
break;
case Shield:
view->setShield( TRUE );
break;
case Teleport:
view->teleport( TRUE );
break;
case Brake:
view->brake( TRUE );
break;
default:
event->ignore();
return;
}
event->accept();
}
void KAstTopLevel::keyReleaseEvent( QKeyEvent *event )
{
if ( event->isAutoRepeat() || !actions.contains( event->key() ) )
{
event->ignore();
return;
}
Action a = actions[ event->key() ];
switch ( a )
{
case RotateLeft:
view->rotateLeft( FALSE );
break;
case RotateRight:
view->rotateRight( FALSE );
break;
case Thrust:
view->thrust( FALSE );
break;
case Shoot:
view->shoot( FALSE );
break;
case Brake:
view->brake( FALSE );
break;
case Shield:
view->setShield( FALSE );
break;
case Teleport:
view->teleport( FALSE );
break;
case Launch:
if ( waitShip )
{
view->newShip();
waitShip = FALSE;
view->hideText();
}
else
{
event->ignore();
return;
}
break;
case NewGame:
slotNewGame();
break;
/*
case Pause:
{
view->pause( TRUE );
QMessageBox::information( this,
tr("KAsteroids is paused"),
tr("Paused") );
view->pause( FALSE );
}
break;
*/
default:
event->ignore();
return;
}
event->accept();
}
void KAstTopLevel::showEvent( QShowEvent *e )
{
QMainWindow::showEvent( e );
view->pause( FALSE );
setFocus();
}
void KAstTopLevel::hideEvent( QHideEvent *e )
{
QMainWindow::hideEvent( e );
view->pause( TRUE );
}
void KAstTopLevel::focusInEvent( QFocusEvent * )
{
view->pause( FALSE );
setFocus();
}
void KAstTopLevel::focusOutEvent( QFocusEvent * )
{
view->pause( TRUE );
}
void KAstTopLevel::slotNewGame()
{
shipsRemain = 3;
score = 0;
scoreLCD->display( 0 );
level = 0;
levelLCD->display( level+1 );
shipsLCD->display( shipsRemain-1 );
view->newGame();
view->setRockSpeed( levels[0].rockSpeed );
view->addRocks( levels[0].nrocks );
view->newShip();
waitShip = FALSE;
view->hideText();
isPaused = FALSE;
}
void KAstTopLevel::slotShipKilled()
{
shipsRemain--;
shipsLCD->display( shipsRemain-1 );
playSound( "ShipDestroyed" );
if ( shipsRemain > 0 )
{
waitShip = TRUE;
view->showText( tr( "Ship Destroyed.\nPress Contacts/Home key."), yellow );
}
else
{
view->endGame();
doStats();
}
}
void KAstTopLevel::slotRockHit( int size )
{
switch ( size )
{
case 0:
score += 10;
break;
case 1:
score += 20;
break;
default:
score += 40;
}
playSound( "RockDestroyed" );
scoreLCD->display( score );
}
void KAstTopLevel::slotRocksRemoved()
{
level++;
if ( level >= MAX_LEVELS )
level = MAX_LEVELS - 1;
view->setRockSpeed( levels[level-1].rockSpeed );
view->addRocks( levels[level-1].nrocks );
levelLCD->display( level+1 );
}
void KAstTopLevel::doStats()
{
QString r( "0.00" );
if ( view->shots() )
r = QString::number( (double)view->hits() / view->shots() * 100.0,
'g', 2 );
view->showText( tr( "Game Over.\nPress Calendar for a new game." ), yellow, FALSE );
}
void KAstTopLevel::slotUpdateVitals()
{
brakesLCD->display( view->brakeCount() );
shieldLCD->display( view->shieldCount() );
shootLCD->display( view->shootCount() );
// teleportsLCD->display( view->teleportCount() );
powerMeter->setValue( view->power() );
}
diff --git a/noncore/games/qasteroids/view.cpp b/noncore/games/qasteroids/view.cpp
index 448a54a..352c63b 100644
--- a/noncore/games/qasteroids/view.cpp
+++ b/noncore/games/qasteroids/view.cpp
@@ -1,884 +1,881 @@
/**********************************************************************
** Copyright (C) 2000 Trolltech AS. All rights reserved.
**
** This file is part of Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************//*
* KAsteroids - Copyright (c) Martin R. Jones 1997
*
* Part of the KDE project
*/
#include "view.h"
#include <qpe/resource.h>
-#include <qapplication.h>
-#include <qkeycode.h>
-#include <qaccel.h>
#include <stdlib.h>
#include <math.h>
#define IMG_BACKGROUND "qasteroids/bg.png"
#define REFRESH_DELAY 33
#define SHIP_SPEED 0.3
#define MISSILE_SPEED 10.0
#define SHIP_STEPS 64
#define ROTATE_RATE 2
#define SHIELD_ON_COST 1
#define SHIELD_HIT_COST 30
#define BRAKE_ON_COST 4
#define MAX_ROCK_SPEED 2.5
#define MAX_POWERUP_SPEED 1.5
#define MAX_SHIP_SPEED 8
#define MAX_BRAKES 5
#define MAX_SHIELDS 5
#define MAX_FIREPOWER 5
#define TEXT_SPEED 4
#define PI_X_2 6.283185307
#ifndef M_PI
#define M_PI 3.141592654
#endif
struct
{
int id;
const char *path;
int frames;
}
kas_animations [] =
{
// { ID_ROCK_LARGE, "rock1/rock1\%1.png", 32 },
{ ID_ROCK_MEDIUM, "rock2/rock2\%1.png", 32 },
{ ID_ROCK_SMALL, "rock3/rock3\%1.png", 32 },
{ ID_SHIP, "ship/ship\%1.png", 32 },
{ ID_MISSILE, "missile/missile.png", 0 },
{ ID_BIT, "bits/bits\%1.png", 16 },
{ ID_EXHAUST, "exhaust/exhaust.png", 0 },
{ ID_ENERGY_POWERUP, "powerups/energy.png", 0 },
// { ID_TELEPORT_POWERUP, "powerups/teleport%1.png", 12 },
{ ID_BRAKE_POWERUP, "powerups/brake.png", 0 },
{ ID_SHIELD_POWERUP, "powerups/shield.png", 0 },
{ ID_SHOOT_POWERUP, "powerups/shoot.png", 0 },
{ ID_SHIELD, "shield/shield\%1.png", 6 },
{ 0, 0, 0 }
};
KAsteroidsView::KAsteroidsView( QWidget *parent, const char *name )
: QWidget( parent, name ),
field(200, 200),
view(&field,this)
{
view.setVScrollBarMode( QScrollView::AlwaysOff );
view.setHScrollBarMode( QScrollView::AlwaysOff );
rocks.setAutoDelete( TRUE );
missiles.setAutoDelete( TRUE );
bits.setAutoDelete( TRUE );
powerups.setAutoDelete( TRUE );
exhaust.setAutoDelete( TRUE );
QPixmap pm( Resource::loadPixmap(IMG_BACKGROUND) );
field.setBackgroundPixmap( pm );
textSprite = new QCanvasText( &field );
QFont font( "helvetica", 14 );
textSprite->setFont( font );
shield = 0;
shieldOn = FALSE;
refreshRate = REFRESH_DELAY;
readSprites();
shieldTimer = new QTimer( this );
connect( shieldTimer, SIGNAL(timeout()), this, SLOT(hideShield()) );
mTimerId = -1;
shipPower = MAX_POWER_LEVEL;
vitalsChanged = TRUE;
can_destroy_powerups = FALSE;
mPaused = TRUE;
}
// - - -
KAsteroidsView::~KAsteroidsView()
{
}
// - - -
void KAsteroidsView::reset()
{
rocks.clear();
missiles.clear();
bits.clear();
powerups.clear();
exhaust.clear();
shotsFired = 0;
shotsHit = 0;
rockSpeed = 1.0;
powerupSpeed = 1.0;
mFrameNum = 0;
mPaused = FALSE;
ship->hide();
shield->hide();
/*
if ( mTimerId >= 0 ) {
killTimer( mTimerId );
mTimerId = -1;
}
*/
}
// - --
void KAsteroidsView::newGame()
{
if ( shieldOn )
{
shield->hide();
shieldOn = FALSE;
}
reset();
if ( mTimerId < 0 )
mTimerId = startTimer( REFRESH_DELAY );
emit updateVitals();
}
// - - -
void KAsteroidsView::endGame()
{
}
void KAsteroidsView::pause( bool p )
{
if ( !mPaused && p ) {
if ( mTimerId >= 0 ) {
killTimer( mTimerId );
mTimerId = -1;
}
} else if ( mPaused && !p )
mTimerId = startTimer( REFRESH_DELAY );
mPaused = p;
}
// - - -
void KAsteroidsView::newShip()
{
ship->move( field.width()/2, field.height()/2, 0 );
shield->move( field.width()/2, field.height()/2, 0 );
ship->setVelocity( 0.0, 0.0 );
shipDx = 0;
shipDy = 0;
shipAngle = 0;
rotateL = FALSE;
rotateR = FALSE;
thrustShip = FALSE;
shootShip = FALSE;
brakeShip = FALSE;
teleportShip = FALSE;
shieldOn = TRUE;
shootDelay = 0;
shipPower = MAX_POWER_LEVEL;
rotateRate = ROTATE_RATE;
rotateSlow = 0;
mBrakeCount = 0;
mTeleportCount = 0;
mShootCount = 0;
ship->show();
shield->show();
mShieldCount = 1; // just in case the ship appears on a rock.
shieldTimer->start( 1000, TRUE );
}
void KAsteroidsView::setShield( bool s )
{
if ( shieldTimer->isActive() && !s ) {
shieldTimer->stop();
hideShield();
} else {
shieldOn = s && mShieldCount;
}
}
void KAsteroidsView::brake( bool b )
{
if ( mBrakeCount )
{
if ( brakeShip && !b )
{
rotateL = FALSE;
rotateR = FALSE;
thrustShip = FALSE;
rotateRate = ROTATE_RATE;
}
brakeShip = b;
}
}
// - - -
void KAsteroidsView::readSprites()
{
QString sprites_prefix = Resource::findPixmap( IMG_BACKGROUND );
int sep = sprites_prefix.findRev( "/" );
sprites_prefix.truncate( sep );
int i = 0;
while ( kas_animations[i].id )
{
animation.insert( kas_animations[i].id,
new QCanvasPixmapArray( sprites_prefix + "/" + kas_animations[i].path,
kas_animations[i].frames ) );
i++;
}
ship = new QCanvasSprite( animation[ID_SHIP], &field );
ship->hide();
shield = new KShield( animation[ID_SHIELD], &field );
shield->hide();
}
// - - -
void KAsteroidsView::addRocks( int num )
{
for ( int i = 0; i < num; i++ )
{
KRock *rock = new KRock( animation[ID_ROCK_MEDIUM], &field,
ID_ROCK_MEDIUM, randInt(2), randInt(2) ? -1 : 1 );
double dx = (2.0 - randDouble()*4.0) * rockSpeed;
double dy = (2.0 - randDouble()*4.0) * rockSpeed;
rock->setVelocity( dx, dy );
rock->setFrame( randInt( rock->frameCount() ) );
if ( dx > 0 )
{
if ( dy > 0 )
rock->move( 5, 5, 0 );
else
rock->move( 5, field.height() - 25, 0 );
}
else
{
if ( dy > 0 )
rock->move( field.width() - 25, 5, 0 );
else
rock->move( field.width() - 25, field.height() - 25, 0 );
}
rock->show( );
rocks.append( rock );
}
}
// - - -
void KAsteroidsView::showText( const QString &text, const QColor &color, bool scroll )
{
textSprite->setTextFlags( AlignLeft | AlignVCenter );
textSprite->setText( text );
textSprite->setColor( color );
if ( scroll ) {
textSprite->move( (field.width()-textSprite->boundingRect().width()) / 2,
-textSprite->boundingRect().height() );
textDy = TEXT_SPEED;
} else {
textSprite->move( (field.width()-textSprite->boundingRect().width()) / 2,
(field.height()-textSprite->boundingRect().height()) / 2 );
textDy = 0;
}
textSprite->show();
}
// - - -
void KAsteroidsView::hideText()
{
textDy = -TEXT_SPEED;
}
// - - -
void KAsteroidsView::resizeEvent(QResizeEvent* event)
{
QWidget::resizeEvent(event);
field.resize(width()-4, height()-4);
view.resize(width(),height());
}
// - - -
void KAsteroidsView::timerEvent( QTimerEvent * )
{
field.advance();
QCanvasSprite *rock;
// move rocks forward
for ( rock = rocks.first(); rock; rock = rocks.next() ) {
((KRock *)rock)->nextFrame();
wrapSprite( rock );
}
wrapSprite( ship );
// check for missile collision with rocks.
processMissiles();
// these are generated when a ship explodes
for ( KBit *bit = bits.first(); bit; bit = bits.next() )
{
if ( bit->expired() )
{
bits.removeRef( bit );
}
else
{
bit->growOlder();
bit->setFrame( ( bit->frame()+1 ) % bit->frameCount() );
}
}
for ( KExhaust *e = exhaust.first(); e; e = exhaust.next() )
exhaust.removeRef( e );
// move / rotate ship.
// check for collision with a rock.
processShip();
// move powerups and check for collision with player and missiles
processPowerups();
if ( textSprite->visible() )
{
if ( textDy < 0 &&
textSprite->boundingRect().y() <= -textSprite->boundingRect().height() ) {
textSprite->hide();
} else {
textSprite->moveBy( 0, textDy );
}
if ( textSprite->boundingRect().y() > (field.height()-textSprite->boundingRect().height())/2 )
textDy = 0;
}
if ( vitalsChanged && !(mFrameNum % 10) ) {
emit updateVitals();
vitalsChanged = FALSE;
}
mFrameNum++;
}
void KAsteroidsView::wrapSprite( QCanvasItem *s )
{
int x = int(s->x() + s->boundingRect().width() / 2);
int y = int(s->y() + s->boundingRect().height() / 2);
if ( x > field.width() )
s->move( s->x() - field.width(), s->y() );
else if ( x < 0 )
s->move( field.width() + s->x(), s->y() );
if ( y > field.height() )
s->move( s->x(), s->y() - field.height() );
else if ( y < 0 )
s->move( s->x(), field.height() + s->y() );
}
// - - -
void KAsteroidsView::rockHit( QCanvasItem *hit )
{
KPowerup *nPup = 0;
int rnd = static_cast<int>(randDouble()*30.0) % 30;
switch( rnd )
{
case 4:
case 5:
nPup = new KPowerup( animation[ID_ENERGY_POWERUP], &field,
ID_ENERGY_POWERUP );
break;
case 10:
// nPup = new KPowerup( animation[ID_TELEPORT_POWERUP], &field,
// ID_TELEPORT_POWERUP );
break;
case 15:
nPup = new KPowerup( animation[ID_BRAKE_POWERUP], &field,
ID_BRAKE_POWERUP );
break;
case 20:
nPup = new KPowerup( animation[ID_SHIELD_POWERUP], &field,
ID_SHIELD_POWERUP );
break;
case 24:
case 25:
nPup = new KPowerup( animation[ID_SHOOT_POWERUP], &field,
ID_SHOOT_POWERUP );
break;
}
if ( nPup )
{
double r = 0.5 - randDouble();
nPup->move( hit->x(), hit->y(), 0 );
nPup->setVelocity( hit->xVelocity() + r, hit->yVelocity() + r );
nPup->show( );
powerups.append( nPup );
}
if ( hit->rtti() == ID_ROCK_LARGE || hit->rtti() == ID_ROCK_MEDIUM )
{
// break into smaller rocks
double addx[4] = { 1.0, 1.0, -1.0, -1.0 };
double addy[4] = { -1.0, 1.0, -1.0, 1.0 };
double dx = hit->xVelocity();
double dy = hit->yVelocity();
double maxRockSpeed = MAX_ROCK_SPEED * rockSpeed;
if ( dx > maxRockSpeed )
dx = maxRockSpeed;
else if ( dx < -maxRockSpeed )
dx = -maxRockSpeed;
if ( dy > maxRockSpeed )
dy = maxRockSpeed;
else if ( dy < -maxRockSpeed )
dy = -maxRockSpeed;
QCanvasSprite *nrock;
for ( int i = 0; i < 4; i++ )
{
double r = rockSpeed/2 - randDouble()*rockSpeed;
if ( hit->rtti() == ID_ROCK_LARGE )
{
nrock = new KRock( animation[ID_ROCK_MEDIUM], &field,
ID_ROCK_MEDIUM, randInt(2), randInt(2) ? -1 : 1 );
emit rockHit( 0 );
}
else
{
nrock = new KRock( animation[ID_ROCK_SMALL], &field,
ID_ROCK_SMALL, randInt(2), randInt(2) ? -1 : 1 );
emit rockHit( 1 );
}
nrock->move( hit->x(), hit->y(), 0 );
nrock->setVelocity( dx+addx[i]*rockSpeed+r, dy+addy[i]*rockSpeed+r );
nrock->setFrame( randInt( nrock->frameCount() ) );
nrock->show( );
rocks.append( nrock );
}
}
else if ( hit->rtti() == ID_ROCK_SMALL )
emit rockHit( 2 );
rocks.removeRef( (QCanvasSprite *)hit );
if ( rocks.count() == 0 )
emit rocksRemoved();
}
void KAsteroidsView::reducePower( int val )
{
shipPower -= val;
if ( shipPower <= 0 )
{
shipPower = 0;
thrustShip = FALSE;
if ( shieldOn )
{
shieldOn = FALSE;
shield->hide();
}
}
vitalsChanged = TRUE;
}
void KAsteroidsView::addExhaust( double x, double y, double dx,
double dy, int count )
{
for ( int i = 0; i < count; i++ )
{
KExhaust *e = new KExhaust( animation[ID_EXHAUST], &field );
e->move( x + 2 - randDouble()*4, y + 2 - randDouble()*4 );
e->setVelocity( dx, dy );
e->show( );
exhaust.append( e );
}
}
void KAsteroidsView::processMissiles()
{
KMissile *missile;
// if a missile has hit a rock, remove missile and break rock into smaller
// rocks or remove completely.
QPtrListIterator<KMissile> it(missiles);
for ( ; it.current(); ++it )
{
missile = it.current();
missile->growOlder();
if ( missile->expired() )
{
missiles.removeRef( missile );
continue;
}
wrapSprite( missile );
QCanvasItemList hits = missile->collisions( TRUE );
QCanvasItemList::Iterator hit;
for ( hit = hits.begin(); hit != hits.end(); ++hit )
{
if ( (*hit)->rtti() >= ID_ROCK_LARGE &&
(*hit)->rtti() <= ID_ROCK_SMALL )
{
shotsHit++;
rockHit( *hit );
missiles.removeRef( missile );
break;
}
}
}
}
// - - -
void KAsteroidsView::processShip()
{
if ( ship->visible() )
{
if ( shieldOn )
{
shield->show();
reducePower( SHIELD_ON_COST );
static int sf = 0;
sf++;
if ( sf % 2 )
shield->setFrame( (shield->frame()+1) % shield->frameCount() );
shield->move( ship->x() - 5, ship->y() - 5 );
QCanvasItemList hits = shield->collisions( TRUE );
QCanvasItemList::Iterator it;
for ( it = hits.begin(); it != hits.end(); ++it )
{
if ( (*it)->rtti() >= ID_ROCK_LARGE &&
(*it)->rtti() <= ID_ROCK_SMALL )
{
int factor;
switch ( (*it)->rtti() )
{
case ID_ROCK_LARGE:
factor = 3;
break;
case ID_ROCK_MEDIUM:
factor = 2;
break;
default:
factor = 1;
}
if ( factor > mShieldCount )
{
// shield not strong enough
shieldOn = FALSE;
break;
}
rockHit( *it );
// the more shields we have the less costly
reducePower( factor * (SHIELD_HIT_COST - mShieldCount*2) );
}
}
}
if ( !shieldOn )
{
shield->hide();
QCanvasItemList hits = ship->collisions( TRUE );
QCanvasItemList::Iterator it;
for ( it = hits.begin(); it != hits.end(); ++it )
{
if ( (*it)->rtti() >= ID_ROCK_LARGE &&
(*it)->rtti() <= ID_ROCK_SMALL )
{
KBit *bit;
for ( int i = 0; i < 8; i++ )
{
bit = new KBit( animation[ID_BIT], &field );
bit->move( ship->x() + 5 - randDouble() * 10,
ship->y() + 5 - randDouble() * 10,
randInt(bit->frameCount()) );
bit->setVelocity( 1-randDouble()*2,
1-randDouble()*2 );
bit->setDeath( 60 + randInt(60) );
bit->show( );
bits.append( bit );
}
ship->hide();
shield->hide();
emit shipKilled();
break;
}
}
}
if ( rotateSlow )
rotateSlow--;
if ( rotateL )
{
shipAngle -= rotateSlow ? 1 : rotateRate;
if ( shipAngle < 0 )
shipAngle += SHIP_STEPS;
}
if ( rotateR )
{
shipAngle += rotateSlow ? 1 : rotateRate;
if ( shipAngle >= SHIP_STEPS )
shipAngle -= SHIP_STEPS;
}
double angle = shipAngle * PI_X_2 / SHIP_STEPS;
double cosangle = cos( angle );
double sinangle = sin( angle );
if ( brakeShip )
{
thrustShip = FALSE;
rotateL = FALSE;
rotateR = FALSE;
rotateRate = ROTATE_RATE;
if ( fabs(shipDx) < 2.5 && fabs(shipDy) < 2.5 )
{
shipDx = 0.0;
shipDy = 0.0;
ship->setVelocity( shipDx, shipDy );
brakeShip = FALSE;
}
else
{
double motionAngle = atan2( -shipDy, -shipDx );
if ( angle > M_PI )
angle -= PI_X_2;
double angleDiff = angle - motionAngle;
if ( angleDiff > M_PI )
angleDiff = PI_X_2 - angleDiff;
else if ( angleDiff < -M_PI )
angleDiff = PI_X_2 + angleDiff;
double fdiff = fabs( angleDiff );
if ( fdiff > 0.08 )
{
if ( angleDiff > 0 )
rotateL = TRUE;
else if ( angleDiff < 0 )
rotateR = TRUE;
if ( fdiff > 0.6 )
rotateRate = mBrakeCount + 1;
else if ( fdiff > 0.4 )
rotateRate = 2;
else
rotateRate = 1;
if ( rotateRate > 5 )
rotateRate = 5;
}
else if ( fabs(shipDx) > 1 || fabs(shipDy) > 1 )
{
thrustShip = TRUE;
// we'll make braking a bit faster
shipDx += cosangle/6 * (mBrakeCount - 1);
shipDy += sinangle/6 * (mBrakeCount - 1);
reducePower( BRAKE_ON_COST );
addExhaust( ship->x() + 10 - cosangle*11,
ship->y() + 10 - sinangle*11,
shipDx-cosangle, shipDy-sinangle,
mBrakeCount+1 );
}
}
}
if ( thrustShip )
{
// The ship has a terminal velocity, but trying to go faster
// still uses fuel (can go faster diagonally - don't care).
double thrustx = cosangle/8;
double thrusty = sinangle/8;
if ( fabs(shipDx + thrustx) < MAX_SHIP_SPEED )
shipDx += thrustx;
if ( fabs(shipDy + thrusty) < MAX_SHIP_SPEED )
shipDy += thrusty;
ship->setVelocity( shipDx, shipDy );
reducePower( 1 );
addExhaust( ship->x() + 10 - cosangle*10,
ship->y() + 10 - sinangle*10,
shipDx-cosangle, shipDy-sinangle, 3 );
}
ship->setFrame( shipAngle >> 1 );
if ( shootShip )
{
if ( !shootDelay && (int)missiles.count() < mShootCount + 2 )
{
KMissile *missile = new KMissile( animation[ID_MISSILE], &field );
missile->move( 11+ship->x()+cosangle*11,
11+ship->y()+sinangle*11, 0 );
missile->setVelocity( shipDx + cosangle*MISSILE_SPEED,
shipDy + sinangle*MISSILE_SPEED );
missile->show( );
missiles.append( missile );
shotsFired++;
reducePower( 1 );
shootDelay = 5;
}
if ( shootDelay )
shootDelay--;
}
if ( teleportShip )
{
int ra = rand() % 10;
if( ra == 0 )
ra += rand() % 20;
int xra = ra * 60 + ( (rand() % 20) * (rand() % 20) );
int yra = ra * 50 - ( (rand() % 20) * (rand() % 20) );
ship->move( xra, yra );
}
vitalsChanged = TRUE;
}
}
// - - -
void KAsteroidsView::processPowerups()
{
if ( !powerups.isEmpty() )
{
// if player gets the powerup remove it from the screen, if option
// "Can destroy powerups" is enabled and a missile hits the powerup
// destroy it
KPowerup *pup;
QPtrListIterator<KPowerup> it( powerups );
for( ; it.current(); ++it )
{
pup = it.current();
pup->growOlder();
if( pup->expired() )
{
powerups.removeRef( pup );
continue;
}
wrapSprite( pup );
QCanvasItemList hits = pup->collisions( TRUE );
QCanvasItemList::Iterator it;
for ( it = hits.begin(); it != hits.end(); ++it )
{
if ( (*it) == ship )
{
switch( pup->rtti() )
{
case ID_ENERGY_POWERUP:
shipPower += 150;
if ( shipPower > MAX_POWER_LEVEL )
shipPower = MAX_POWER_LEVEL;
break;
case ID_TELEPORT_POWERUP:
mTeleportCount++;
break;
case ID_BRAKE_POWERUP:
if ( mBrakeCount < MAX_BRAKES )
mBrakeCount++;
break;
case ID_SHIELD_POWERUP:
if ( mShieldCount < MAX_SHIELDS )
mShieldCount++;
break;
case ID_SHOOT_POWERUP:
if ( mShootCount < MAX_FIREPOWER )
mShootCount++;
break;
}
powerups.removeRef( pup );
vitalsChanged = TRUE;
}
else if ( (*it) == shield )
{
powerups.removeRef( pup );
}
else if ( (*it)->rtti() == ID_MISSILE )
{
if ( can_destroy_powerups )
{
powerups.removeRef( pup );
}
}
}
}
} // -- if( powerups.isEmpty() )
}
// - - -
void KAsteroidsView::hideShield()
{
shield->hide();
mShieldCount = 0;
shieldOn = FALSE;
}
double KAsteroidsView::randDouble()
{
int v = rand();
return (double)v / (double)RAND_MAX;
}
int KAsteroidsView::randInt( int range )
{
return rand() % range;
}
diff --git a/noncore/games/sfcave/helpwindow.cpp b/noncore/games/sfcave/helpwindow.cpp
index 544e237..8a5d034 100644
--- a/noncore/games/sfcave/helpwindow.cpp
+++ b/noncore/games/sfcave/helpwindow.cpp
@@ -1,81 +1,79 @@
/***************************************************************************
helpwindow.cpp - description
-------------------
begin : Sun Sep 8 2002
copyright : (C) 2002 by Andy Qua
email : andy.qua@blueyonder.co.uk
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
-#include <qwidget.h>
#include <qlayout.h>
-#include <qstring.h>
#include <qtextview.h>
#include <qpe/qpeapplication.h>
#include "helpwindow.h"
#define HELP_TEXT \
"<qt><h1>SFCave Help</h1><p> " \
"SFCave is a flying game for the Zaurus.<br><br> " \
"The aim is to stay alive for as long as possible and get the highest score " \
"you can.<br><br>" \
"There are three game types currently - SFCave, Gates, and Fly.<br>" \
"<b>SFCave</b> is a remake of the classic SFCave game - fly through the " \
"cavern avoiding all the blocks that just happen to be hanging in " \
"midair<br><br>" \
"<b>Gates</b> is similar to SFCave but instead you must fly through the " \
"without crashing.<br><br>" \
"<b>Fly</b> is somewhat different to SFCave and above. Instead, you have " \
"are flying in the open air above a scrolling landscape, and the aim is to " \
"hug the ground - the closer to the land you fly the more points " \
"scored.<br><br><br>" \
"Basic instruction - Press <b>Up</B> or <b>Down</b> on the circle pad to " \
"start a new game, press the middle of the pad to apply thrust (makes you " \
"go up), and release the pad to remove thrust and drop down.<br><br>" \
"Also, if playing the Fly game, you can press z to toggle the display " \
"of the scoring zones. This will display 4 red lines at varying heights " \
"above the landscape - if your ship falls into this zone, point are scored. " \
"The closer to the landscape you get the more points you get.<br><br>" \
"In addition, SFCave has replays - save and load too so you can show off to all " \
"your friends (or vice versa). Currently, this is in its infancy but will improve.<br>" \
"To use, once you have crashed, press 'r' to replay the last game.<br>" \
"To save the replay press 's'.<br>" \
"To load a saved replay press 'l' (after you've crashed at least once).<br><br>" \
"Replays are currently saved to your home directory in a file called sfcave.replay." \
"This file can be copied and given to others as long as it it put in their home directory.<br><br>" \
"Have lots of fun.<br>" \
"Andy" \
"</p></qt>"
HelpWindow::HelpWindow( QWidget *parent, const char *name, bool modal, WFlags flags )
: QDialog( parent, name, modal, flags )
{
// resize( 230, 280 );
setCaption( "Help for SFCave" );
QVBoxLayout *layout = new QVBoxLayout( this );
QString text = HELP_TEXT;;
QTextView *view = new QTextView( text, 0, this, "view" );
layout->insertSpacing( -1, 5 );
layout->insertWidget( -1, view );
layout->insertSpacing( -1, 5 );
QPEApplication::showDialog( this );
}
HelpWindow::~HelpWindow()
{
}
diff --git a/noncore/games/snake/interface.cpp b/noncore/games/snake/interface.cpp
index 2c60693..b5fb5bf 100644
--- a/noncore/games/snake/interface.cpp
+++ b/noncore/games/snake/interface.cpp
@@ -1,223 +1,219 @@
/**********************************************************************
** Copyright (C) 2000 Trolltech AS. All rights reserved.
**
** This file is part of Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include "interface.h"
#include <qpe/resource.h>
-#include <qpe/qpeapplication.h>
#include <qpe/qpetoolbar.h>
#include <qtoolbutton.h>
-#include <qstyle.h>
-#include <qapplication.h>
-#include <qmessagebox.h>
SnakeGame::SnakeGame(QWidget* parent, const char* name, WFlags f) :
QMainWindow(parent,name,f),
canvas(232, 258)
{
setCaption( tr("Snake") );
QPEApplication::setInputMethodHint(this, QPEApplication::AlwaysOff );
QPixmap bg = Resource::loadPixmap("snake/grass");
canvas.setBackgroundPixmap(bg);
canvas.setUpdatePeriod(100);
snake = 0;
cv = new QCanvasView(&canvas, this);
pauseTimer = new QTimer(this);
connect(pauseTimer, SIGNAL(timeout()), this, SLOT(wait()) );
setToolBarsMovable( FALSE );
QToolBar* toolbar = new QToolBar( this);
toolbar->setHorizontalStretchable( TRUE );
QPixmap newicon = Resource::loadPixmap("ksnake");
setIcon(newicon);
(void)new QToolButton(newicon, tr("New Game"), 0,
this, SLOT(newGame()), toolbar, "New Game");
scorelabel = new QLabel(toolbar);
showScore(0);
scorelabel->setBackgroundMode( PaletteButton );
scorelabel->setAlignment( AlignRight | AlignVCenter | ExpandTabs );
toolbar->setStretchableWidget( scorelabel );
setFocusPolicy(StrongFocus);
setCentralWidget(cv);
QTimer::singleShot( 16, this, SLOT(welcomescreen()) );
gamestopped = true;
waitover = true;
}
SnakeGame::~SnakeGame()
{
delete snake;
}
void SnakeGame::resizeEvent(QResizeEvent *)
{
QSize s = centralWidget()->size();
int fw = style().defaultFrameWidth();
canvas.resize( s.width() - fw - 2, s.height() - fw - 2);
}
void SnakeGame::welcomescreen()
{
QCanvasText* title = new QCanvasText(tr("SNAKE!"), &canvas);
title->setColor(yellow);
title->setFont( QFont("times", 18, QFont::Bold) );
int w = title->boundingRect().width();
title->move(canvas.width()/2 -w/2, canvas.height()/2-110);
title->show();
QCanvasPixmapArray* titlearray = new QCanvasPixmapArray(Resource::findPixmap("snake/title"));
QCanvasSprite* titlepic = new QCanvasSprite(titlearray, &canvas);
titlepic->move(canvas.width()/2 - 33, canvas.height()/2-85);
titlepic->show();
QCanvasText* instr = new QCanvasText(tr("Use the arrow keys to guide the\n"
"snake to eat the mouse. You must not\n"
"crash into the walls, edges or its tail."),
&canvas);
w = instr->boundingRect().width();
instr->move(canvas.width()/2-w/2, canvas.height()/2-20);
instr->setColor(white);
instr->show();
QCanvasText* cont = new QCanvasText(tr("Press any key to start"), &canvas);
w = cont->boundingRect().width();
cont->move(canvas.width()/2-w/2, canvas.height()-20);
cont->setColor(yellow);
cont->show();
}
void SnakeGame::newGame()
{
clear();
snake = new Snake(&canvas);
connect(snake, SIGNAL(dead()), this, SLOT(gameOver()) );
connect(snake, SIGNAL(targethit()), this, SLOT(levelUp()) );
connect(snake, SIGNAL(scorechanged()), this, SLOT(scoreInc()) );
connect(this, SIGNAL(moveFaster()), snake, SLOT(increaseSpeed()) );
last = 0;
targetamount = 1;
notargets = 1;
level = 1;
stage = 1;
showScore(0);
gamestopped = false;
waitover = true;
int y = canvas.height()-50;
(void)new Obstacle(&canvas, 32);
(void)new Obstacle(&canvas, y);
createTargets();
}
void SnakeGame::showScore(int score)
{
scorelabel->setText(tr(" Score : %1 ").arg(score) );
}
void SnakeGame::scoreInc()
{
showScore( snake->getScore() );
}
void SnakeGame::levelUp()
{
notargets--;
if (notargets == 0) {
stage++;
if (stage == 3) {
level++;
emit moveFaster();
targetamount++;
stage = 0;
}
createTargets();
}
}
void SnakeGame::createTargets()
{
for (int i = 0; i < targetamount; i++)
(void)new Target(&canvas);
notargets = targetamount;
}
void SnakeGame::clear()
{
delete snake;
snake = 0;
QCanvasItemList l = canvas.allItems();
for (QCanvasItemList::Iterator it=l.begin(); it!=l.end(); ++it) {
delete *it;
}
}
void SnakeGame::gameOver()
{
int score = snake->getScore();
QString scoreoutput="";
scoreoutput.setNum(score);
QCanvasText* gameover = new QCanvasText(tr("GAME OVER!\n Your Score: %1").arg( scoreoutput), &canvas);
gameover->setZ(100);
gameover->setColor(yellow);
gameover->setFont( QFont("times", 18, QFont::Bold) );
int w = gameover->boundingRect().width();
gameover->move(canvas.width()/2 -w/2, canvas.height()/2 -50);
gameover->show();
gamestopped = true;
waitover = false;
pauseTimer->start(1500);
}
void SnakeGame::wait()
{
waitover = true;
pauseTimer->stop();
QCanvasText* cont = new QCanvasText(tr("Press any key to begin a new game."),
&canvas);
cont->setZ(100);
cont->setColor(white);
int w = cont->boundingRect().width();
cont->move(canvas.width()/2 -w/2, canvas.height()/2);
cont->show();
}
void SnakeGame::keyPressEvent(QKeyEvent* event)
{
if (gamestopped) {
if (waitover)
newGame();
else
return;
}
else {
int newkey = event->key();
snake->go(newkey);
}
}
diff --git a/noncore/games/snake/main.cpp b/noncore/games/snake/main.cpp
index 77a2769..9a9b167 100644
--- a/noncore/games/snake/main.cpp
+++ b/noncore/games/snake/main.cpp
@@ -1,29 +1,28 @@
/**********************************************************************
** Copyright (C) 2000 Trolltech AS. All rights reserved.
**
** This file is part of Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include "interface.h"
-#include <qpe/qpeapplication.h>
#include <opie/oapplicationfactory.h>
OPIE_EXPORT_APP( OApplicationFactory<SnakeGame> )
diff --git a/noncore/games/snake/snake.cpp b/noncore/games/snake/snake.cpp
index 9f19841..8a683ab 100644
--- a/noncore/games/snake/snake.cpp
+++ b/noncore/games/snake/snake.cpp
@@ -1,246 +1,244 @@
/**********************************************************************
** Copyright (C) 2000 Trolltech AS. All rights reserved.
**
** This file is part of Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include "snake.h"
#include "target.h"
-#include "codes.h"
#include <qpe/resource.h>
-#include <qregexp.h>
static int Piecekey[4][4] = { {6, 0, 4, 3 }, {0, 6, 2, 1 }, { 1, 3, 5, 0 }, {2, 4, 0, 5 } };
Snake::Snake(QCanvas* c)
{
canvas = c;
score = 0;
snakelist.setAutoDelete(true);
autoMoveTimer = new QTimer(this);
connect( autoMoveTimer, SIGNAL(timeout()), this, SLOT(moveSnake()) );
createSnake();
}
void Snake::createSnake()
{
snakeparts = new QCanvasPixmapArray();
QString s0 = Resource::findPixmap("snake/s0001");
s0.replace(QRegExp("0001"),"%1");
snakeparts->readPixmaps(s0, 15);
grow = 0;
last = Key_Right;
QCanvasSprite* head = new QCanvasSprite(snakeparts, canvas );
head->setFrame(7);
snakelist.insert(0, head);
head->show();
head->move(34, 16);
QCanvasSprite* body = new QCanvasSprite(snakeparts, canvas );
body->setFrame(6);
snakelist.append( body );
body->show();
body->move(18, 16);
QCanvasSprite* end = new QCanvasSprite(snakeparts, canvas );
end->setFrame(11);
snakelist.append( end );
end->show();
end->move(2, 16);
currentdir = right;
speed = 250;
autoMoveTimer->start(speed);
moveSnake();
}
void Snake::increaseSpeed()
{
if (speed > 150)
speed = speed - 5;
autoMoveTimer->start(speed);
}
void Snake::go(int newkey)
{
// check key is a direction
if (!( (newkey == Key_Up) || (newkey == Key_Left) ||
(newkey == Key_Right) || (newkey == Key_Down) ))
return;
// check move is possible
if ( ((currentdir == left) && ((newkey == Key_Right) || (newkey == Key_Left)) ) ||
((currentdir == right) && ((newkey == Key_Left) || (newkey == Key_Right)) ) ||
((currentdir == up) && ((newkey == Key_Down) || (newkey == Key_Up)) ) ||
((currentdir == down) && ((newkey == Key_Up) || (newkey == Key_Down)) ) )
return;
else {
Snake::changeHead(newkey);
Snake::moveSnake();
}
}
void Snake::move(Direction dir)
{
autoMoveTimer->start(speed);
int x = 0;
int y = 0;
newdir = dir;
switch (dir) {
case right: x = 16; break;
case left: x = -16; break;
case down: y = 16; break;
case up: y = -16; break;
}
int index = lookUpPiece(currentdir, newdir);
QCanvasSprite* sprite = new QCanvasSprite(snakeparts, canvas );
sprite->setFrame(index);
snakelist.insert(1, sprite);
sprite->move(snakelist.first()->x(), snakelist.first()->y() );
snakelist.first()->moveBy(x, y);
if (grow <= 0)
changeTail();
else
grow--;
sprite->show();
currentdir = dir;
}
void Snake::changeTail()
{
snakelist.removeLast();
double lastx = snakelist.last()->x();
double prevx = snakelist.prev()->x();
int index = 0;
if ( prevx == lastx ) { //vertical
if ( snakelist.prev()->y() > snakelist.last()->y() )
index = 13;
else
index = 14;
} else { //horizontal
if (snakelist.prev()->x() > snakelist.last()->x() )
index = 11;
else
index = 12;
}
snakelist.last()->setFrame(index);
}
void Snake::changeHead(int lastkey)
{
int index = 0;
last = lastkey;
switch (last)
{
case Key_Up: index = 10; break;
case Key_Left: index = 8; break;
case Key_Right: index = 7; break;
case Key_Down: index = 9; break;
}
if (index) {
snakelist.first()->setFrame(index);
}
}
// returns an integer corresponding to a particular type of snake piece
int Snake::lookUpPiece(Direction currentdir, Direction newdir)
{
return Piecekey[currentdir][newdir];
}
void Snake::extendSnake()
{
grow++;
}
void Snake::moveSnake()
{
switch (last)
{
case Key_Up: move(up); break;
case Key_Left: move(left); break;
case Key_Right: move(right); break;
case Key_Down: move(down); break;
}
detectCrash();
}
void Snake::detectCrash()
{
QCanvasSprite* head = snakelist.first();
QCanvasItem* item;
QCanvasItemList l=head->collisions(FALSE);
for (QCanvasItemList::Iterator it=l.begin(); it!=l.end(); ++it) {
item = *it;
// check if snake hit target
if ( (item->rtti()== 1500 ) && (item->collidesWith(head)) ) {
Target* target = (Target*) item;
target->done();
emit targethit();
extendSnake();
setScore(5);
return;
}
// check if snake hit obstacles
if ( (item->rtti()==1600) && (item->collidesWith(head)) ) {
emit dead();
autoMoveTimer->stop();
return;
}
}
//check if snake hit itself
for (uint i = 3; i < snakelist.count(); i++) {
if (head->collidesWith(snakelist.at(i)) ) {
emit dead();
autoMoveTimer->stop();
return;
}
}
//check if snake hit edge
if ( (head->x() > canvas->width()-5) || (head->y() > canvas->height()-10)
|| (head->x() <2) || (head->y() <-5) ) {
emit dead();
autoMoveTimer->stop();
return;
}
}
void Snake::setScore(int amount)
{
score = score + amount;
emit scorechanged();
}
int Snake::getScore()
{
return score;
}
Snake::~Snake()
{
autoMoveTimer->stop();
}
diff --git a/noncore/games/solitaire/canvascard.cpp b/noncore/games/solitaire/canvascard.cpp
index 7c4a5ba..c36da6c 100644
--- a/noncore/games/solitaire/canvascard.cpp
+++ b/noncore/games/solitaire/canvascard.cpp
@@ -1,313 +1,308 @@
/**********************************************************************
** Copyright (C) 2000 Trolltech AS. All rights reserved.
**
** This file is part of Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
-#include "cardgame.h"
#include "canvascard.h"
#include <qpe/resource.h>
-#include <qpainter.h>
-#include <qimage.h>
-#include <qpaintdevice.h>
-#include <qbitmap.h>
#include <qgfx_qws.h> // Needed to get the device's width
#include <math.h>
#if defined( QT_QWS_CASSIOPEIA )
#define SLOW_HARDWARE
#endif
// Seems to be fast enough to me even without Transformations in the library
//#if defined( QT_NO_TRANSFORMATIONS ) && defined( QT_QWS_IPAQ )
//#define SLOW_HARDWARE
//#endif
QBitmap *Create180RotatedBitmap(QBitmap *srcBitmap)
{
#ifdef QT_NO_TRANSFORMATIONS
int w = srcBitmap->width();
int h = srcBitmap->height();
QBitmap *dstBitmap = new QBitmap( w, h );
// ### this is very poorly implemented and probably could be much faster
for (int i = 0; i < w; i++)
for (int j = 0; j < h; j++)
bitBlt( dstBitmap, i, j, srcBitmap, w - i - 1, h - j - 1, 1, 1 );
return dstBitmap;
#else
QWMatrix m;
m.rotate( 180.0 );
return new QBitmap( srcBitmap->xForm( m ) );
#endif
}
QPixmap *CreateScaledPixmap(QPixmap *srcPixmap, double scaleX, double scaleY)
{
#ifdef QT_NO_TRANSFORMATIONS
int w = srcPixmap->width();
int h = srcPixmap->height();
int newW = (int)(w * scaleX);
int newH = (int)(h * scaleY);
QPixmap *dstPixmap = new QPixmap( newW, newH );
// ### this is very poorly implemented and probably could be much faster
for (int i = 0; i < newW; i++) {
int srcX = w * i / newW;
if (newH == h) {
// Optimise for scaleing in the X-axis only
bitBlt( dstPixmap, i, 0, srcPixmap, srcX, 0, 1, h );
} else {
for (int j = 0; j < newH; j++) {
int srcY = h * j / newH;
bitBlt( dstPixmap, i, j, srcPixmap, srcX, srcY, 1, 1 );
}
}
}
return dstPixmap;
#else
QWMatrix s;
s.scale( scaleX, scaleY );
return new QPixmap( srcPixmap->xForm( s ) );
#endif
}
// Initialise static member variables to NULL
QPixmap *CanvasCard::cardsFaces = NULL;
QPixmap *CanvasCard::cardsBacks = NULL;
QBitmap *CanvasCard::cardsChars = NULL;
QBitmap *CanvasCard::cardsSuits = NULL;
QBitmap *CanvasCard::cardsCharsUpsideDown = NULL;
QBitmap *CanvasCard::cardsSuitsUpsideDown = NULL;
CanvasCard::CanvasCard( eValue v, eSuit s, bool f, QCanvas *canvas ) :
Card(v, s, f), QCanvasRectangle( 0, 0, 1, 1, canvas ), cardBack(1), scaleX(1.0), scaleY(1.0)
{
if ( !cardsFaces ) {
if ( qt_screen->deviceWidth() < 200 ) {
cardsFaces = new QPixmap( Resource::loadPixmap( "cards/card_face_small" ) );
cardsBacks = new QPixmap( Resource::loadPixmap( "cards/card_back0001_small" ) );
cardsChars = new QBitmap( Resource::loadBitmap( "cards/card_chars_small" ) );
cardsSuits = new QBitmap( Resource::loadBitmap( "cards/card_suits_small" ) );
} else {
cardsFaces = new QPixmap( Resource::loadPixmap( "cards/card_face" ) );
cardsBacks = new QPixmap( Resource::loadPixmap( "cards/card_back0001" ) );
cardsChars = new QBitmap( Resource::loadBitmap( "cards/card_chars" ) );
cardsSuits = new QBitmap( Resource::loadBitmap( "cards/card_suits" ) );
}
cardsCharsUpsideDown = Create180RotatedBitmap( cardsChars );
cardsSuitsUpsideDown = Create180RotatedBitmap( cardsSuits );
}
xOff = cardsFaces->width() / 2;
yOff = cardsFaces->height() / 2;
setSize( cardsFaces->width(), cardsFaces->height() );
setPen( NoPen );
flipping = FALSE;
}
void CanvasCard::setCardBack(int b)
{
if ( cardBack != b ) {
cardBack = b;
if ( cardsBacks )
delete cardsBacks;
if ( qt_screen->deviceWidth() < 200 ) {
switch (cardBack) {
case 0:
cardsBacks = new QPixmap( Resource::loadPixmap( "cards/card_back0001_small" ) ); break;
case 1:
cardsBacks = new QPixmap( Resource::loadPixmap( "cards/card_back0002_small" ) ); break;
case 2:
cardsBacks = new QPixmap( Resource::loadPixmap( "cards/card_back0003_small" ) ); break;
case 3:
cardsBacks = new QPixmap( Resource::loadPixmap( "cards/card_back0004_small" ) ); break;
case 4:
cardsBacks = new QPixmap( Resource::loadPixmap( "cards/card_back0005_small" ) ); break;
}
} else {
switch (cardBack) {
case 0:
cardsBacks = new QPixmap( Resource::loadPixmap( "cards/card_back0001" ) ); break;
case 1:
cardsBacks = new QPixmap( Resource::loadPixmap( "cards/card_back0002" ) ); break;
case 2:
cardsBacks = new QPixmap( Resource::loadPixmap( "cards/card_back0003" ) ); break;
case 3:
cardsBacks = new QPixmap( Resource::loadPixmap( "cards/card_back0004" ) ); break;
case 4:
cardsBacks = new QPixmap( Resource::loadPixmap( "cards/card_back0005" ) ); break;
}
}
if ( !isFacing() )
redraw();
}
}
void CanvasCard::draw(QPainter &painter)
{
int ix = (int)x(), iy = (int)y();
QPainter *p = &painter;
QPixmap *unscaledCard = NULL;
if ((scaleX <= 0.98) || (scaleY <= 0.98))
{
p = new QPainter();
unscaledCard = new QPixmap( cardsFaces->width(), cardsFaces->height() );
p->begin(unscaledCard);
ix = 0;
iy = 0;
}
if ( isFacing() ) {
/*
// Now add the joker and card backs to the list of pixmaps
QPixmap *CardsBack = new QPixmap( Resource::loadPixmap( "cards/card_joker.png" ) );
QPoint *newBackHotspot = new QPoint( 0, 0 );
pixmaps->append((const QPixmap *)CardsBack);
hotspots->append((const QPoint *)newBackHotspot);
*/
int w = cardsFaces->width(), h = cardsFaces->height();
// p->setBrush( NoBrush );
p->setBrush( QColor( 0xFF, 0xFF, 0xFF ) );
if ( isRed() == TRUE )
p->setPen( QColor( 0xFF, 0, 0 ) );
else
p->setPen( QColor( 0, 0, 0 ) );
if ( qt_screen->deviceWidth() < 200 ) {
p->drawPixmap( ix + 0, iy + 0, *cardsFaces );
p->drawPixmap( ix + 3, iy + 3, *cardsChars, 5*(getValue()-1), 0, 5, 6 );
p->drawPixmap( ix + 11, iy + 3, *cardsSuits, 5*(getSuit()-1), 0, 5, 6 );
p->drawPixmap( ix + w-3-5, iy + h-3-6, *cardsCharsUpsideDown, 5*(12-getValue()+1), 0, 5, 6 );
p->drawPixmap( ix + w-11-5, iy + h-3-6, *cardsSuitsUpsideDown, 5*(3-getSuit()+1), 0, 5, 6 );
} else {
p->drawPixmap( ix + 0, iy + 0, *cardsFaces );
p->drawPixmap( ix + 4, iy + 4, *cardsChars, 7*(getValue()-1), 0, 7, 7 );
p->drawPixmap( ix + 12, iy + 4, *cardsSuits, 7*(getSuit()-1), 0, 7, 8 );
p->drawPixmap( ix + w-4-7, iy + h-4-7, *cardsCharsUpsideDown, 7*(12-getValue()+1), 0, 7, 7 );
p->drawPixmap( ix + w-12-7, iy + h-5-7, *cardsSuitsUpsideDown, 7*(3-getSuit()+1), 0, 7, 8 );
}
} else {
p->drawPixmap( ix, iy, *cardsBacks );
}
if (p != &painter)
{
p->end();
QPixmap *scaledCard = CreateScaledPixmap( unscaledCard, scaleX, scaleY );
int xoff = scaledCard->width() / 2;
int yoff = scaledCard->height() / 2;
painter.drawPixmap( (int)x() + xOff - xoff, (int)y() + yOff - yoff, *scaledCard );
delete p;
delete unscaledCard;
delete scaledCard;
}
}
static const double flipLift = 1.5;
void CanvasCard::flipTo(int x2, int y2, int steps)
{
flipSteps = steps;
#ifdef SLOW_HARDWARE
move(x2,y2);
Card::flipTo(x2,y2,steps);
#else
int x1 = (int)x();
int y1 = (int)y();
double dx = x2 - x1;
double dy = y2 - y1;
flipping = TRUE;
destX = x2;
destY = y2;
animSteps = flipSteps;
setVelocity(dx/animSteps, dy/animSteps-flipLift);
setAnimated(TRUE);
#endif
}
void CanvasCard::advance(int stage)
{
if ( stage==1 ) {
if ( animSteps-- <= 0 ) {
scaleX = 1.0;
scaleY = 1.0;
flipping = FALSE;
setVelocity(0,0);
setAnimated(FALSE);
move(destX,destY); // exact
} else {
if ( flipping ) {
if ( animSteps > flipSteps / 2 ) {
// animSteps = flipSteps .. flipSteps/2 (flip up) -> 1..0
scaleX = ((double)animSteps/flipSteps-0.5)*2;
} else {
// animSteps = flipSteps/2 .. 0 (flip down) -> 0..1
scaleX = 1-((double)animSteps/flipSteps)*2;
}
if ( animSteps == flipSteps / 2-1 ) {
setYVelocity(yVelocity()+flipLift*2);
setFace( !isFacing() );
}
}
}
}
QCanvasRectangle::advance(stage);
}
void CanvasCard::animatedMove(int x2, int y2, int steps)
{
destX = x2;
destY = y2;
double x1 = x(), y1 = y(), dx = x2 - x1, dy = y2 - y1;
// Ensure a good speed
while ( fabs(dx/steps)+fabs(dy/steps) < 5.0 && steps > 4 )
steps--;
setAnimated(TRUE);
setVelocity(dx/steps, dy/steps);
animSteps = steps;
}
diff --git a/noncore/games/solitaire/canvascardgame.cpp b/noncore/games/solitaire/canvascardgame.cpp
index 9ae2a23..ed5748e 100644
--- a/noncore/games/solitaire/canvascardgame.cpp
+++ b/noncore/games/solitaire/canvascardgame.cpp
@@ -1,388 +1,380 @@
/**********************************************************************
** Copyright (C) 2000 Trolltech AS. All rights reserved.
**
** This file is part of Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
-#include "cardgame.h"
-#include "canvasshapes.h"
-#include "canvascard.h"
#include "canvascardgame.h"
-#include <qpe/resource.h>
-#include <qpe/config.h>
-#include <qmainwindow.h>
-#include <qmenubar.h>
-#include <qpainter.h>
#include <qgfx_qws.h>
#include <stdlib.h>
#include <limits.h>
#include <time.h>
#include <math.h>
extern int highestZ;
class CanvasCardPile : public QCanvasRectangle
{
public:
CanvasCardPile( CanvasCardGame *ccg, QCanvas *canvas ) : QCanvasRectangle( canvas ), parent( ccg ) {
pile = new QPixmap( 0, 0 );
pileHeight = 0;
firstCard = NULL;
}
void addCard( CanvasCard *card );
void advance(int stage);
void animatedMove() { animatedMove(savedX, savedY); }
void savePos(void) { savedX = (int)x(); savedY = (int)y(); }
void animatedMove(int x2, int y2, int steps = 7 );
protected:
virtual void draw( QPainter& p );
private:
CanvasCardGame *parent;
QPixmap *pile;
QImage tempImage32;
CanvasCard *firstCard;
int pileHeight;
int destX, destY;
int savedX, savedY;
int animSteps;
};
void CanvasCardPile::addCard( CanvasCard *card )
{
int offsetDown = ( qt_screen->deviceWidth() < 200 ) ? 9 : 13;
int cardHeight = ( qt_screen->deviceWidth() < 200 ) ? 27 : 36;
int cardWidth = ( qt_screen->deviceWidth() < 200 ) ? 20 : 23;
if ( !firstCard )
firstCard = card;
int height = cardHeight + pileHeight * offsetDown;
setSize( cardWidth, height );
pile->resize( cardWidth, height );
QPainter p( pile );
p.translate( -card->x(), -card->y() + pileHeight * offsetDown );
card->draw( p );
pileHeight++;
QImage tempImage;
tempImage = *pile;
tempImage32 = tempImage.convertDepth( 32 );
tempImage32.setAlphaBuffer( TRUE );
for ( int i = 0; i < tempImage32.width(); i++ )
for ( int j = 0; j < tempImage32.height(); j++ ) {
QRgb col = tempImage32.pixel( i, j );
int a = 255-j*220/tempImage32.height();
QRgb alpha = qRgba( qRed( col ), qGreen( col ), qBlue( col ), a );
tempImage32.setPixel( i, j, alpha );
}
QRgb alpha = qRgba( 0, 0, 0, 0 );
tempImage32.setPixel( 1, 0, alpha );
tempImage32.setPixel( 0, 0, alpha );
tempImage32.setPixel( 0, 1, alpha );
tempImage32.setPixel( cardWidth - 2, 0, alpha );
tempImage32.setPixel( cardWidth - 1, 0, alpha );
tempImage32.setPixel( cardWidth - 1, 1, alpha );
height--;
tempImage32.setPixel( 1, height, alpha );
tempImage32.setPixel( 0, height - 1, alpha );
tempImage32.setPixel( 0, height, alpha );
tempImage32.setPixel( cardWidth - 2, height, alpha );
tempImage32.setPixel( cardWidth - 1, height, alpha );
tempImage32.setPixel( cardWidth - 1, height - 1, alpha );
}
void CanvasCardPile::advance(int stage)
{
if ( stage==1 ) {
if ( animSteps-- <= 0 ) {
CanvasCard *item = firstCard;
while (item) {
item->show();
item = (CanvasCard *)item->getCardPile()->cardInfront(item);
}
setVelocity(0,0);
setAnimated(FALSE);
parent->cancelMoving();
hide();
move(destX,destY); // exact
}
}
QCanvasRectangle::advance(stage);
}
void CanvasCardPile::animatedMove(int x2, int y2, int steps )
{
destX = x2;
destY = y2;
double x1 = x(), y1 = y(), dx = x2 - x1, dy = y2 - y1;
// Ensure a good speed
while ( fabs(dx/steps)+fabs(dy/steps) < 5.0 && steps > 4 )
steps--;
setAnimated(TRUE);
setVelocity(dx/steps, dy/steps);
animSteps = steps;
}
void CanvasCardPile::draw( QPainter& p )
{
int ix = (int)x(), iy = (int)y();
p.drawImage( ix, iy, tempImage32 );
}
CanvasCardGame::~CanvasCardGame() {
// the deletion stuff should be fixed now and only deletes
// items created by this CardGame. I haven't verified there are zero
// memory leaks yet
if ( alphaCardPile )
delete alphaCardPile;
}
void CanvasCardGame::gameWon() {
srand(time(NULL));
QCanvasItemList list = canvas()->allItems();
QCanvasItemList::Iterator it = list.begin();
for (; it != list.end(); ++it) {
if ( (*it)->rtti() == canvasCardId ) {
// disperse the cards everywhere
int x = 300 - rand() % 1000;
int y = 300 + rand() % 200;
((CanvasCard *)*it)->animatedMove( x, y, 50 );
}
}
}
void CanvasCardGame::contentsMousePressEvent(QMouseEvent *e) {
if ( moving )
return;
QCanvasItemList l = canvas()->collisions( e->pos() );
for (QCanvasItemList::Iterator it = l.begin(); it != l.end(); ++it) {
if ( (*it)->rtti() == canvasCardId ) {
moving = (CanvasCard *)*it;
if ( moving->animated() )
return;
cardXOff = (int)(e->pos().x() - moving->x());
cardYOff = (int)(e->pos().y() - moving->y());
if ( !mousePressCard( moving, e->pos() ) ) {
CanvasCard *card = moving;
if ( alphaCardPile )
delete alphaCardPile;
alphaCardPile = new CanvasCardPile( this, canvas() );
alphaCardPile->move( card->x(), card->y() );
alphaCardPile->savePos();
alphaCardPile->show();
while (card) {
alphaCardPile->addCard( card );
card->hide();
card = (CanvasCard *)card->getCardPile()->cardInfront(card);
}
alphaCardPile->setZ( INT_MAX );
moved = TRUE;
} else {
if ( alphaCardPile )
alphaCardPile->hide();
}
return;
}
}
mousePress( e->pos() );
}
/*
//
// Should have some intelligent way to make double clicking on a
// card send it to the most appropriate pile
//
void CanvasCardGame::contentsMouseDoubleClickEvent(QMouseEvent *e) {
QCanvasItemList l = canvas()->collisions( e->pos() );
for (QCanvasItemList::Iterator it = l.begin(); it != l.end(); ++it) {
if ( (*it)->rtti() == canvasCardId ) {
CanvasCard *card = (CanvasCard *)*it;
if ( card->animated() )
return;
if ( card->getCardPile()->isAllowedToBeMoved(card) ) {
if (card->getCardPile()->cardInfront(card) == NULL) {
CardPile *pile = first();
if (pile && pile->isAllowedOnTop(card)) {
// move card to this pile
return;
}
}
}
}
}
}
*/
void CanvasCardGame::contentsMouseMoveEvent(QMouseEvent *e) {
QPoint p = e->pos();
if ( moving ) {
moved = TRUE;
if (moving->isFacing() != TRUE)
return;
int tx = (int)p.x() - cardXOff;
int ty = (int)p.y() - cardYOff;
if (snapOn == TRUE) {
CardPile *pile = closestPile( tx, ty, 50 );
if ( pile && pile->isAllowedOnTop( moving ) ) {
QPoint p = pile->getHypertheticalNextCardPos();
if ( alphaCardPile )
alphaCardPile->move( p.x(), p.y() );
return;
}
}
if ( alphaCardPile )
alphaCardPile->move( tx, ty );
}
}
void CanvasCardGame::contentsMouseReleaseEvent(QMouseEvent *e)
{
QPoint p = e->pos();
Q_UNUSED(p);
if ( moving ) {
CanvasCard *item = moving;
if ( item->animated() )
return;
if ( alphaCardPile )
if ( moved ) {
CardPile *pile = closestPile((int)alphaCardPile->x(), (int)alphaCardPile->y(), 30);
if (pile && pile->isAllowedOnTop(item)) {
CardPile *oldPile = item->getCardPile();
Card *c = NULL;
if ( oldPile != pile) {
while ( item ) {
item->show();
if ( oldPile ) {
c = oldPile->cardInfront(item);
oldPile->removeCard(item);
}
item->setCardPile(pile);
//item->move( pile->getCardPos(item) );
pile->addCardToTop(item);
QPoint p = pile->getCardPos(item);
item->setPos( p.x(), p.y(), highestZ );
highestZ++;
checkUnusable(); // added for freecell to move card to discard pile
if (item->getValue() == king && haveWeWon()) {
alphaCardPile->hide();
gameWon();
moving = NULL;
return;
}
if (oldPile) {
item = (CanvasCard *)c;
} else {
item = NULL;
}
}
alphaCardPile->hide();
moving = NULL;
return;
}
}
alphaCardPile->animatedMove();
}
}
moved = FALSE;
}
void CanvasCardGame::readPile( Config& cfg, CardPile *pile, QString name, int& highestZ )
{
cfg.setGroup( name );
int numberOfCards = cfg.readNumEntry("NumberOfCards", 0);
Card *card = NULL;
for ( int i = 0; i < numberOfCards; i++ ) {
QString cardStr;
cardStr.sprintf( "%i", i );
int val = cfg.readNumEntry( "Card" + cardStr );
bool facing = cfg.readBoolEntry( "CardFacing" + cardStr );
card = cards[ val ];
card->setFace(facing);
card->setCardPile(pile); // cam: setCardPile has to happen bevor addCardToTop
pile->addCardToTop(card); // due to a empty pointer if you use cardAddedToTop
QPoint p = pile->getCardPos( card );
card->setPos( p.x(), p.y(), highestZ );
card->showCard();
highestZ++;
}
}
diff --git a/noncore/games/solitaire/canvascardwindow.cpp b/noncore/games/solitaire/canvascardwindow.cpp
index c12344a..503bc92 100644
--- a/noncore/games/solitaire/canvascardwindow.cpp
+++ b/noncore/games/solitaire/canvascardwindow.cpp
@@ -1,315 +1,310 @@
/**********************************************************************
** Copyright (C) 2000 Trolltech AS. All rights reserved.
**
** This file is part of Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include "canvascardwindow.h"
-#include "patiencecardgame.h"
#include "freecellcardgame.h"
#include "chicanecardgame.h"
#include "harpcardgame.h"
#include "teeclubcardgame.h"
-#include <qpe/resource.h>
-#include <qmainwindow.h>
-#include <qpopupmenu.h>
-#include <qstyle.h>
CanvasCardWindow::CanvasCardWindow(QWidget* parent, const char* name, WFlags f) :
QMainWindow(parent, name, f), canvas(230, 260), snapOn(TRUE), cardBack(4), gameType(0),
cardGame(NULL)
{
setIcon( Resource::loadPixmap( "cards" ) );
setCaption(tr("Patience"));
// Create Playing Area for Games
if ( QPixmap::defaultDepth() < 12 ) {
// canvas.setBackgroundColor(QColor(0x51, 0x74, 0x6B));
// canvas.setBackgroundColor(QColor(0x20, 0xb0, 0x50));
canvas.setBackgroundColor(QColor(0x08, 0x98, 0x2D));
} else {
QPixmap bg;
bg.convertFromImage( Resource::loadImage( "table_pattern" ), ThresholdDither );
canvas.setBackgroundPixmap(bg);
}
#if defined( QT_QWS_CASSIOPEIA )
canvas.setAdvancePeriod(70);
#else
canvas.setAdvancePeriod(30);
#endif
#ifdef _PATIENCE_USE_ACCELS_
QMenuBar* menu = menuBar();
QPopupMenu* file = new QPopupMenu;
file->insertItem(tr("Patience"), this, SLOT(initPatience()), CTRL+Key_F);
file->insertItem(tr("Freecell"), this, SLOT(initFreecell()), CTRL+Key_F);
file->insertItem(tr("Chicane"), this, SLOT(initChicane()), CTRL+Key_F);
file->insertItem(tr("Harp"), this, SLOT(initHarp()), CTRL+Key_F);
file->insertItem(tr("Teeclub"), this, SLOT(initTeeclub()), CTRL+Key_F);
menu->insertItem(tr("&Game"), file);
menu->insertSeparator();
settings = new QPopupMenu;
settings->insertItem(tr("&Change card backs"), this, SLOT(changeCardBacks()), Key_F2);
snap_id = settings->insertItem(tr("&Snap to position"), this, SLOT(snapToggle()), Key_F3);
settings->setCheckable(TRUE);
menu->insertItem(tr("&Settings"),settings);
menu->insertSeparator();
QPopupMenu* help = new QPopupMenu;
help->insertItem(tr("&About"), this, SLOT(help()), Key_F1);
help->setItemChecked(dbf_id, TRUE);
menu->insertItem(tr("&Help"),help);
#else
QMenuBar* menu = menuBar();
QPopupMenu* file = new QPopupMenu;
file->insertItem(tr("Patience"), this, SLOT(initPatience()));
file->insertItem(tr("Freecell"), this, SLOT(initFreecell()));
file->insertItem(tr("Chicane"), this, SLOT(initChicane()));
file->insertItem(tr("Harp"), this, SLOT(initHarp()));
file->insertItem(tr("Teeclub"), this, SLOT(initTeeclub()));
menu->insertItem(tr("Play"), file);
menu->insertSeparator();
settings = new QPopupMenu;
settings->setCheckable(TRUE);
settings->insertItem(tr("Change card backs"), this, SLOT(changeCardBacks()));
snap_id = settings->insertItem(tr("Snap to position"), this, SLOT(snapToggle()));
QString m;
drawId = settings->insertItem(tr("Turn one card"), this, SLOT(drawnToggle()));
menu->insertItem(tr("Settings"),settings);
settings->setCheckable(TRUE);
#endif
menu->show();
Config cfg( "Patience" );
cfg.setGroup( "GlobalSettings" );
snapOn = cfg.readBoolEntry( "SnapOn", TRUE);
settings->setItemChecked(snap_id, snapOn);
gameType = cfg.readNumEntry( "GameType", -1 );
drawThree = cfg.readBoolEntry( "DrawThree", FALSE);
if ( gameType == 0 ) {
cardGame = new PatienceCardGame( &canvas, snapOn, this );
cardGame->setNumberToDraw(drawThree ? 3 : 1);
setCaption(tr("Patience"));
setCentralWidget(cardGame);
cardGame->readConfig( cfg );
setCardBacks();
} else if ( gameType == 1 ) {
cardGame = new FreecellCardGame( &canvas, snapOn, this );
setCaption(tr("Freecell"));
setCentralWidget(cardGame);
//cardGame->newGame(); // Until we know how to handle reading freecell config
cardGame->readConfig( cfg );
setCardBacks();
} else if ( gameType == 2 ) {
cardGame = new ChicaneCardGame( &canvas, snapOn, this );
cardGame->setNumberToDraw(1);
setCaption(tr("Chicane"));
setCentralWidget(cardGame);
cardGame->readConfig( cfg );
setCardBacks();
} else if ( gameType == 3 ) {
cardGame = new HarpCardGame( &canvas, snapOn, this );
cardGame->setNumberToDraw(1);
setCaption(tr("Harp"));
setCentralWidget(cardGame);
cardGame->readConfig( cfg );
setCardBacks();
} else if ( gameType == 4 ) {
cardGame = new TeeclubCardGame( &canvas, snapOn, this );
cardGame->setNumberToDraw(1);
setCaption(tr("Teeclub"));
setCentralWidget(cardGame);
cardGame->readConfig( cfg );
setCardBacks();
} else {
// Probably there isn't a config file or it is broken
// Start a new game
initPatience();
}
updateDraw();
}
CanvasCardWindow::~CanvasCardWindow()
{
if (cardGame) {
Config cfg("Patience");
cfg.setGroup( "GlobalSettings" );
cfg.writeEntry( "GameType", gameType );
cfg.writeEntry( "SnapOn", snapOn );
cfg.writeEntry( "DrawThree", drawThree);
cfg.write();
cardGame->writeConfig( cfg );
delete cardGame;
}
}
void CanvasCardWindow::resizeEvent(QResizeEvent *)
{
QSize s = centralWidget()->size();
int fw = style().defaultFrameWidth();
canvas.resize( s.width() - fw - 2, s.height() - fw - 2);
}
void CanvasCardWindow::initPatience()
{
// Create New Game
if ( cardGame )
delete cardGame;
cardGame = new PatienceCardGame( &canvas, snapOn, this );
cardGame->setNumberToDraw(drawThree ? 3 : 1);
gameType = 0;
setCaption(tr("Patience"));
setCentralWidget(cardGame);
cardGame->newGame();
setCardBacks();
updateDraw();
}
void CanvasCardWindow::initFreecell()
{
// Create New Game
if ( cardGame ) {
delete cardGame;
}
cardGame = new FreecellCardGame( &canvas, snapOn, this );
gameType = 1;
setCaption(tr("Freecell"));
setCentralWidget(cardGame);
cardGame->newGame();
setCardBacks();
}
void CanvasCardWindow::initChicane()
{
// Create New Game
if ( cardGame ) {
delete cardGame;
}
cardGame = new ChicaneCardGame( &canvas, snapOn, this );
cardGame->setNumberToDraw(1);
gameType = 2;
setCaption(tr("Chicane"));
setCentralWidget(cardGame);
cardGame->newGame();
setCardBacks();
}
void CanvasCardWindow::initHarp()
{
// Create New Game
if ( cardGame ) {
delete cardGame;
}
cardGame = new HarpCardGame( &canvas, snapOn, this );
cardGame->setNumberToDraw(1);
gameType = 3;
setCaption(tr("Harp"));
setCentralWidget(cardGame);
cardGame->newGame();
setCardBacks();
}
void CanvasCardWindow::initTeeclub()
{
// Create New Game
if ( cardGame ) {
delete cardGame;
}
cardGame = new TeeclubCardGame( &canvas, snapOn, this );
cardGame->setNumberToDraw(1);
gameType = 4;
setCaption(tr("Teeclub"));
setCentralWidget(cardGame);
cardGame->newGame();
setCardBacks();
}
void CanvasCardWindow::snapToggle()
{
snapOn = !snapOn;
settings->setItemChecked(snap_id, snapOn);
cardGame->toggleSnap();
}
void CanvasCardWindow::drawnToggle()
{
drawThree=!drawThree;
Config cfg( "Patience" );
cfg.setGroup( "GlobalSettings" );
cardGame->toggleCardsDrawn();
updateDraw();
cfg.writeEntry( "DrawThree", drawThree);
cfg.write();
}
void CanvasCardWindow::updateDraw() {
if(cardGame->cardsDrawn() == 3){
settings->changeItem(drawId, tr("Turn one card"));
} else {
settings->changeItem(drawId, tr("Turn three cards"));
}
}
void CanvasCardWindow::setCardBacks()
{
QCanvasItemList l = canvas.allItems();
for (QCanvasItemList::Iterator it = l.begin(); it != l.end(); ++it) {
if ( (*it)->rtti() == canvasCardId )
((CanvasCard *)(*it))->setCardBack( cardBack );
}
}
void CanvasCardWindow::changeCardBacks()
{
cardBack++;
if (cardBack == 5)
cardBack = 0;
setCardBacks();
}
diff --git a/noncore/games/solitaire/canvasshapes.cpp b/noncore/games/solitaire/canvasshapes.cpp
index 6ccd4a4..011958d 100644
--- a/noncore/games/solitaire/canvasshapes.cpp
+++ b/noncore/games/solitaire/canvasshapes.cpp
@@ -1,114 +1,112 @@
/**********************************************************************
** Copyright (C) 2000 Trolltech AS. All rights reserved.
**
** This file is part of Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
-#include <qpainter.h>
-#include <qcanvas.h>
#include <qgfx_qws.h>
#include "canvasshapes.h"
CanvasRoundRect::CanvasRoundRect(int x, int y, QCanvas *canvas) :
QCanvasRectangle( x, y, ( qt_screen->deviceWidth() < 200 ) ? 20 : 23, ( qt_screen->deviceWidth() < 200 ) ? 27 : 36, canvas)
{
setZ(0);
show();
}
void CanvasRoundRect::redraw()
{
hide();
show();
}
void CanvasRoundRect::drawShape(QPainter &p)
{
if ( qt_screen->deviceWidth() < 200 )
p.drawRoundRect( (int)x() + 1, (int)y() + 1, 18, 25);
else
p.drawRoundRect( (int)x(), (int)y(), 23, 36);
}
CanvasCircleOrCross::CanvasCircleOrCross(int x, int y, QCanvas *canvas) :
QCanvasRectangle( x, y, 21, 21, canvas), circleShape(TRUE)
{
show();
}
void CanvasCircleOrCross::redraw()
{
hide();
show();
}
void CanvasCircleOrCross::setCircle()
{
circleShape = TRUE;
redraw();
}
void CanvasCircleOrCross::setCross()
{
circleShape = FALSE;
redraw();
}
void CanvasCircleOrCross::drawShape(QPainter &p)
{
if ( qt_screen->deviceWidth() < 200 ) {
int x1 = (int)x(), y1 = (int)y();
// Green circle
if (circleShape == TRUE) {
p.setPen( QPen( QColor(0x10, 0xE0, 0x10), 1 ) );
p.drawEllipse( x1 - 1, y1 - 1, 17, 17);
p.drawEllipse( x1 - 1, y1 - 0, 17, 15);
p.drawEllipse( x1 + 0, y1 + 0, 15, 15);
p.drawEllipse( x1 + 1, y1 + 0, 13, 15);
p.drawEllipse( x1 + 1, y1 + 1, 13, 13);
// Red cross
} else {
p.setPen( QPen( QColor(0xE0, 0x10, 0x10), 4 ) );
p.drawLine( x1, y1, x1 + 14, y1 + 14);
p.drawLine( x1 + 14, y1, x1, y1 + 14);
}
} else {
int x1 = (int)x(), y1 = (int)y();
// Green circle
if (circleShape == TRUE) {
p.setPen( QPen( QColor(0x10, 0xE0, 0x10), 1 ) );
p.drawEllipse( x1 - 1, y1 - 1, 21, 21);
p.drawEllipse( x1 - 1, y1 - 0, 21, 19);
p.drawEllipse( x1 + 0, y1 + 0, 19, 19);
p.drawEllipse( x1 + 1, y1 + 0, 17, 19);
p.drawEllipse( x1 + 1, y1 + 1, 17, 17);
// Red cross
} else {
p.setPen( QPen( QColor(0xE0, 0x10, 0x10), 5 ) );
p.drawLine( x1, y1, x1 + 20, y1 + 20);
p.drawLine( x1 + 20, y1, x1, y1 + 20);
}
}
}
diff --git a/noncore/games/solitaire/card.cpp b/noncore/games/solitaire/card.cpp
index 609e280..52e38ac 100644
--- a/noncore/games/solitaire/card.cpp
+++ b/noncore/games/solitaire/card.cpp
@@ -1,53 +1,50 @@
/**********************************************************************
** Copyright (C) 2000 Trolltech AS. All rights reserved.
**
** This file is part of Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include "card.h"
-#include <qpe/config.h>
-#include <qpoint.h>
-#include <qlist.h>
/*
Card( eValue v, eSuit s, bool f ) :
val(v), suit(s), faceUp(f), showing(FALSE), ix(0), iy(0), iz(0), cardPile(NULL) { }
virtual ~Card() { }
eValue getValue() { return val; }
eSuit getSuit() { return suit; }
CardPile *getCardPile() { return cardPile; }
bool isFacing() { return faceUp; }
bool isShowing() { return showing; }
bool isRed() { return ((suit == diamonds) || (suit == hearts)); }
int getX(void) { return ix; }
int getY(void) { return iy; }
int getZ(void) { return iz; }
void setCardPile(CardPile *p) { cardPile = p; }
void setFace(bool f) { faceUp = f; }
void flip(void) { flipTo(getX(), getY()); }
virtual void setPos(int x, int y, int z) { ix = x; iy = y; iz = z; }
virtual void move(int x, int y) { ix = x; iy = y; }
virtual void move(QPoint p) { ix = p.x(); iy = p.y(); }
virtual void flipTo(int x, int y, int steps = 8) { ix = x; iy = y; faceUp = !faceUp; redraw(); Q_UNUSED(steps); }
virtual void showCard(void) { showing = TRUE; }
virtual void hideCard(void) { showing = FALSE; }
virtual void redraw(void) { }
*/
diff --git a/noncore/games/solitaire/cardpile.cpp b/noncore/games/solitaire/cardpile.cpp
index aace2e2..1d572be 100644
--- a/noncore/games/solitaire/cardpile.cpp
+++ b/noncore/games/solitaire/cardpile.cpp
@@ -1,115 +1,113 @@
/**********************************************************************
** Copyright (C) 2000 Trolltech AS. All rights reserved.
**
** This file is part of Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include "cardpile.h"
#include "card.h"
#include <qpe/config.h>
-#include <qpoint.h>
-#include <qlist.h>
CardPile::CardPile(int x, int y) : pileX(x), pileY(y), dealing(FALSE), PileResize(FALSE) {
pileWidth = 0;
pileHeight = 0;
pileNextX = pileX;
pileNextY = pileY;
pileCenterX = x + pileWidth / 2;
pileCenterY = y + pileHeight / 2;
pileRadius = (pileWidth > pileHeight) ? pileWidth : pileHeight;
pileOffsetDown = 13;
}
int CardPile::distanceFromPile(int x, int y) {
return (pileCenterX-x)*(pileCenterX-x)+(pileCenterY-y)*(pileCenterY-y);
}
int CardPile::distanceFromNextPos(int x, int y) {
return (pileNextX-x)*(pileNextX-x)+(pileNextY-y)*(pileNextY-y);
}
Card *CardPile::cardInfront(Card *c) {
CardPile *p = c->getCardPile();
if (p) {
p->at(p->find(c));
return p->next();
} else {
return NULL;
}
}
bool CardPile::kingOnTop() {
Card *top = cardOnTop();
return top && top->getValue() == king;
}
bool CardPile::addCardToTop(Card *c) {
if (dealing || isAllowedOnTop(c)) {
append((const Card *)c);
cardAddedToTop(c);
return TRUE;
}
return FALSE;
}
bool CardPile::addCardToBottom(Card *c) {
if (dealing || isAllowedOnBottom(c)) {
prepend((const Card *)c);
cardAddedToBottom(c);
return TRUE;
}
return FALSE;
}
bool CardPile::removeCard(Card *c) {
if (dealing || isAllowedToBeMoved(c)) {
take(find(c));
cardRemoved(c);
return TRUE;
}
return FALSE;
}
void CardPile::writeConfig( Config& cfg, QString name ) {
int numberOfCards = 0;
cfg.setGroup( name );
Card *card = cardOnBottom();
while ( card ) {
QString cardStr;
cardStr.sprintf( "%i", numberOfCards );
int val = (int)card->getValue()-1 + ((int)card->getSuit()-1)*13 + (int)card->getDeckNumber()*52;
cfg.writeEntry( "Card" + cardStr, val );
cfg.writeEntry( "CardFacing" + cardStr, card->isFacing() );
card = cardInfront( card );
numberOfCards++;
}
cfg.writeEntry("NumberOfCards", numberOfCards);
}
diff --git a/noncore/games/solitaire/chicanecardgame.cpp b/noncore/games/solitaire/chicanecardgame.cpp
index 6729a94..6c607b9 100644
--- a/noncore/games/solitaire/chicanecardgame.cpp
+++ b/noncore/games/solitaire/chicanecardgame.cpp
@@ -1,177 +1,176 @@
/**********************************************************************
** Copyright (C) 2000 Trolltech AS. All rights reserved.
**
** This file is part of Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**
** created on base of patiencecardgame by cam (C.A.Mader) 2002
** Rules for this game:
** use 2 decks = 104 cards
** deal 8 rows with 3 hidden cards and one open card
** append red to black and vice versa
** each card can be layed on a free place
** deal 8 cards at once
**
**********************************************************************/
-#include <qgfx_qws.h>
#include "chicanecardgame.h"
extern int highestZ;
ChicaneCardGame::ChicaneCardGame(QCanvas *c, bool snap, QWidget *parent) : CanvasCardGame(*c, snap, parent, 2) // Use 2 Decks
{
highestZ = 0;
for (int i = 0; i < 8; i++) {
discardPiles[i] = new ChicaneDiscardPile( 27 + i * 26, 10, canvas() );
addCardPile(discardPiles[i]);
}
for (int i = 0; i < 8; i++) {
workingPiles[i] = new ChicaneWorkingPile( 27 + i * 26, 50, canvas() );
addCardPile(workingPiles[i]);
}
faceDownDealingPile = new ChicaneFaceDownDeck( 2, 10, canvas() );
}
void ChicaneCardGame::deal(void)
{
highestZ = 1;
int t = 0;
beginDealing();
for (int i = 0; i < 8; i++) {
for (int k = 0; k < 4; k++, t++) {
Card *card = cards[t];
workingPiles[i]->addCardToTop(card);
card->setCardPile( workingPiles[i] );
card->setPos( 0, 0, highestZ );
card->setFace(k==3);
card->move( workingPiles[i]->getCardPos( card ) );
card->showCard();
highestZ++;
}
}
for ( ; t < getNumberOfCards(); t++) {
Card *card = cards[t];
faceDownDealingPile->addCardToTop(card);
card->setCardPile( faceDownDealingPile );
QPoint p = faceDownDealingPile->getCardPos( card );
card->setPos( p.x(), p.y(), highestZ );
card->showCard();
highestZ++;
}
endDealing();
}
void ChicaneCardGame::readConfig( Config& cfg )
{
cfg.setGroup("GameState");
// Create Cards, but don't shuffle or deal them yet
createDeck();
// Move the cards to their piles (deal them to their previous places)
beginDealing();
highestZ = 1;
for (int i = 0; i < 8; i++) {
QString pile;
pile.sprintf( "ChicaneDiscardPile%i", i );
readPile( cfg, discardPiles[i], pile, highestZ );
}
for (int i = 0; i < 8; i++) {
QString pile;
pile.sprintf( "ChicaneWorkingPile%i", i );
readPile( cfg, workingPiles[i], pile, highestZ );
}
readPile( cfg, faceDownDealingPile, "ChicaneFaceDownDealingPile", highestZ );
highestZ++;
endDealing();
}
void ChicaneCardGame::writeConfig( Config& cfg )
{
cfg.setGroup("GameState");
for ( int i = 0; i < 8; i++ ) {
QString pile;
pile.sprintf( "ChicaneDiscardPile%i", i );
discardPiles[i]->writeConfig( cfg, pile );
}
for ( int i = 0; i < 8; i++ ) {
QString pile;
pile.sprintf( "ChicaneWorkingPile%i", i );
workingPiles[i]->writeConfig( cfg, pile );
}
faceDownDealingPile->writeConfig( cfg, "ChicaneFaceDownDealingPile" );
}
bool ChicaneCardGame::mousePressCard( Card *card, QPoint p )
{
Q_UNUSED(p);
CanvasCard *item = (CanvasCard *)card;
if (item->isFacing() != TRUE) {
// From facedown stack
if ((item->x() == 2) && ((int)item->y() == 10)) { // Deal a row of 8 cards
// Move 8 cards, one to each workingPile
beginDealing();
for (int i=0; i<8 && faceDownDealingPile->cardOnTop(); i++) {
CanvasCard *card = (CanvasCard *)faceDownDealingPile->cardOnTop();
card->setZ(highestZ);
highestZ++;
faceDownDealingPile->removeCard(card);
workingPiles[i]->addCardToTop(card);
card->setCardPile( workingPiles[i] );
card->setFace(FALSE);
QPoint p = workingPiles[i]->getCardPos(card);
card->flipTo( p.x(), p.y() );
}
endDealing();
}
moving = NULL;
moved = FALSE;
return TRUE;
} else if ( !card->getCardPile()->isAllowedToBeMoved(card) ) { // Don't allow unclean columns to be moved
moving = NULL;
return TRUE;
}
return FALSE;
}
void ChicaneCardGame::mousePress(QPoint p)
{
Q_UNUSED(p);
}
diff --git a/noncore/games/solitaire/freecellcardgame.cpp b/noncore/games/solitaire/freecellcardgame.cpp
index aeb32fc..d474f4e 100644
--- a/noncore/games/solitaire/freecellcardgame.cpp
+++ b/noncore/games/solitaire/freecellcardgame.cpp
@@ -1,225 +1,224 @@
/**********************************************************************
** Copyright (C) 2000 Trolltech AS. All rights reserved.
**
** This file is part of Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
-#include <qgfx_qws.h>
#include "freecellcardgame.h"
extern int highestZ;
int numberOfFreeCells = 4;
FreecellCardGame::FreecellCardGame(QCanvas *c, bool snap, QWidget *parent) : CanvasCardGame(*c, snap, parent)
{
numberOfFreeCells = 4;
highestZ = 0;
int spaceBetweenPiles = ( qt_screen->deviceWidth() < 200 ) ? 21 : 28;
int xOrigin = ( qt_screen->deviceWidth() < 200 ) ? 0 : 5;
int spacing = ( qt_screen->deviceWidth() < 200 ) ? 0 : 0;
for (int i = 0; i < 4; i++) {
freecellPiles[i] = new FreecellFreecellPile( xOrigin + i * spaceBetweenPiles, 10, canvas() );
addCardPile(freecellPiles[i]);
}
for (int i = 0; i < 4; i++) {
discardPiles[i] = new FreecellDiscardPile( xOrigin + spacing + 6 + (i + 4) * spaceBetweenPiles, 10, canvas() );
addCardPile(discardPiles[i]);
}
for (int i = 0; i < 8; i++) {
workingPiles[i] = new FreecellWorkingPile( xOrigin + spacing + 2 + i * spaceBetweenPiles, 50, canvas() );
addCardPile(workingPiles[i]);
}
}
void FreecellCardGame::deal(void)
{
highestZ = 1;
beginDealing();
for (int i = 0; i < 52; i++) {
Card *card = cards[i];
card->setFace( TRUE );
card->setPos( 0, 0, highestZ );
card->setCardPile( workingPiles[i%8] );
workingPiles[i%8]->addCardToTop( card );
card->move( workingPiles[i%8]->getCardPos( card ) );
card->showCard();
highestZ++;
}
endDealing();
}
// checks if smaller card with different color, that could be put on top on the
// card, is present in working or freecell pile
bool FreecellCardGame::checkNeeded(Card *card)
{
if (card->getValue() > 2){
int i;
Card *c;
for (i=0;i<4;i++){
c = freecellPiles[i]->cardOnBottom();
if (c != NULL){
if (card->isRed()!= c->isRed() && card->getValue()== c->getValue()+1){
return (false);
}
}
}
for (i=0;i<8;i++){
c=workingPiles[i]->cardOnBottom();
while (c!=NULL){
if (card->isRed() != c->isRed() && card->getValue() == c->getValue()+1) {
return (false);
}
c=workingPiles[i]->cardInfront(c);
}
}
}
return(true);
}
// added to move cards, on which no card can be moved, to discard pile
void FreecellCardGame::checkUnusable()
{
int i,j;
// printf("void FreecellCardGame::checkUnusable()\n");
Card *top_one;
for (i=0;i < 8;i++)
{
top_one = workingPiles[i]->cardOnTop();
if (top_one != NULL)
{
j = 0;
while ((j < 4))
{
if (discardPiles[j]->isAllowedOnTop(top_one)){
if (checkNeeded(top_one)){
top_one->setCardPile(discardPiles[j]);
workingPiles[i]->removeCard(top_one);
// printf("k %d f work%d to disk%d on %d\n ",top_one->getValue(),i+1,j+1,highestZ);
discardPiles[j]->addCardToTop(top_one);
top_one->setPos(discardPiles[j]->getX(),discardPiles[j]->getY(),highestZ);
highestZ++;
j = 4;
checkUnusable();
}
}
j++;
}
}
}
for (i=0;i<4;i++){
top_one = freecellPiles[i]->cardOnTop();
if (top_one != NULL)
{
j = 0;
while ((j < 4))
{
if (discardPiles[j]->isAllowedOnTop(top_one)){
if (checkNeeded(top_one)){
top_one->setCardPile(discardPiles[j]);
freecellPiles[i]->removeCard(top_one);
// printf("k %d f work%d to disk%d on %d\n ",top_one->getValue(),i+1,j+1,highestZ);
discardPiles[j]->addCardToTop(top_one);
top_one->setPos(discardPiles[j]->getX(),discardPiles[j]->getY(),highestZ);
highestZ++;
j = 4;
checkUnusable();
}
}
j++;
}
}
}
}
bool FreecellCardGame::mousePressCard( Card *c, QPoint p )
{
Q_UNUSED(p);
if ( !c->getCardPile()->isAllowedToBeMoved(c) ) {
moving = NULL;
return TRUE;
}
return FALSE;
}
void FreecellCardGame::readConfig( Config& cfg )
{
cfg.setGroup("GameState");
// Create Cards, but don't shuffle or deal them yet
createDeck();
// Move the cards to their piles (deal them to their previous places)
beginDealing();
highestZ = 1;
for (int k = 0; k < 4; k++) {
QString pile;
pile.sprintf( "FreeCellPile%i", k );
readPile( cfg, freecellPiles[k], pile, highestZ );
}
for (int k = 0; k < 4; k++) {
QString pile;
pile.sprintf( "DiscardPile%i", k );
readPile( cfg, discardPiles[k], pile, highestZ );
}
for (int k = 0; k < 8; k++) {
QString pile;
pile.sprintf( "WorkingPile%i", k );
readPile( cfg, workingPiles[k], pile, highestZ );
}
highestZ++;
endDealing();
}
void FreecellCardGame::writeConfig( Config& cfg )
{
cfg.setGroup("GameState");
for ( int i = 0; i < 4; i++ ) {
QString pile;
pile.sprintf( "FreeCellPile%i", i );
freecellPiles[i]->writeConfig( cfg, pile );
}
for ( int i = 0; i < 4; i++ ) {
QString pile;
pile.sprintf( "DiscardPile%i", i );
discardPiles[i]->writeConfig( cfg, pile );
}
for ( int i = 0; i < 8; i++ ) {
QString pile;
pile.sprintf( "WorkingPile%i", i );
workingPiles[i]->writeConfig( cfg, pile );
}
}
diff --git a/noncore/games/solitaire/harpcardgame.cpp b/noncore/games/solitaire/harpcardgame.cpp
index 0711622..d13d73b 100644
--- a/noncore/games/solitaire/harpcardgame.cpp
+++ b/noncore/games/solitaire/harpcardgame.cpp
@@ -1,179 +1,178 @@
/**********************************************************************
** Copyright (C) 2000 Trolltech AS. All rights reserved.
**
** This file is part of Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**
** created on base of patiencecardgame by cam (C.A.Mader) 2002
** Rules for this game:
** use 2 decks = 104 cards
** deal 8 rows with one open card in the first place
** one hidden and one open in the second place and so on
** append red to black and vice versa
** each card can be layed on a free place
** deal 8 cards at once
**
**
**********************************************************************/
-#include <qgfx_qws.h>
#include "harpcardgame.h"
extern int highestZ;
HarpCardGame::HarpCardGame(QCanvas *c, bool snap, QWidget *parent) : CanvasCardGame(*c, snap, parent, 2) // Use 2 Decks
{
highestZ = 0;
for (int i = 0; i < 8; i++) {
discardPiles[i] = new HarpDiscardPile( 27 + i * 26, 10, canvas() );
addCardPile(discardPiles[i]);
}
for (int i = 0; i < 8; i++) {
workingPiles[i] = new HarpWorkingPile( 27 + i * 26, 50, canvas() );
addCardPile(workingPiles[i]);
}
faceDownDealingPile = new HarpFaceDownDeck( 2, 10, canvas() );
}
void HarpCardGame::deal(void)
{
highestZ = 1;
int t = 0;
beginDealing();
for (int i = 0; i < 8; i++) {
for (int k = 0; k < i+1; k++, t++) {
Card *card = cards[t];
workingPiles[i]->addCardToTop(card);
card->setCardPile( workingPiles[i] );
card->setPos( 0, 0, highestZ );
card->setFace(k==i);
card->move( workingPiles[i]->getCardPos( card ) );
card->showCard();
highestZ++;
}
}
for ( ; t < getNumberOfCards(); t++) {
Card *card = cards[t];
faceDownDealingPile->addCardToTop(card);
card->setCardPile( faceDownDealingPile );
QPoint p = faceDownDealingPile->getCardPos( card );
card->setPos( p.x(), p.y(), highestZ );
card->showCard();
highestZ++;
}
endDealing();
}
void HarpCardGame::readConfig( Config& cfg )
{
cfg.setGroup("GameState");
// Create Cards, but don't shuffle or deal them yet
createDeck();
// Move the cards to their piles (deal them to their previous places)
beginDealing();
highestZ = 1;
for (int i = 0; i < 8; i++) {
QString pile;
pile.sprintf( "HarpDiscardPile%i", i );
readPile( cfg, discardPiles[i], pile, highestZ );
}
for (int i = 0; i < 8; i++) {
QString pile;
pile.sprintf( "HarpWorkingPile%i", i );
readPile( cfg, workingPiles[i], pile, highestZ );
}
readPile( cfg, faceDownDealingPile, "HarpFaceDownDealingPile", highestZ );
highestZ++;
endDealing();
}
void HarpCardGame::writeConfig( Config& cfg )
{
cfg.setGroup("GameState");
for ( int i = 0; i < 8; i++ ) {
QString pile;
pile.sprintf( "HarpDiscardPile%i", i );
discardPiles[i]->writeConfig( cfg, pile );
}
for ( int i = 0; i < 8; i++ ) {
QString pile;
pile.sprintf( "HarpWorkingPile%i", i );
workingPiles[i]->writeConfig( cfg, pile );
}
faceDownDealingPile->writeConfig( cfg, "HarpFaceDownDealingPile" );
}
bool HarpCardGame::mousePressCard( Card *card, QPoint p )
{
Q_UNUSED(p);
CanvasCard *item = (CanvasCard *)card;
if (item->isFacing() != TRUE) {
// From facedown stack
if ((item->x() == 2) && ((int)item->y() == 10)) { // Deal a row of 8 cards
// Move 8 cards, one to each workingPile
beginDealing();
for (int i=0; i<8 && faceDownDealingPile->cardOnTop(); i++) {
CanvasCard *card = (CanvasCard *)faceDownDealingPile->cardOnTop();
card->setZ(highestZ);
highestZ++;
faceDownDealingPile->removeCard(card);
workingPiles[i]->addCardToTop(card);
card->setCardPile( workingPiles[i] );
card->setFace(FALSE);
QPoint p = workingPiles[i]->getCardPos(card);
card->flipTo( p.x(), p.y() );
}
endDealing();
}
moving = NULL;
moved = FALSE;
return TRUE;
} else if ( !card->getCardPile()->isAllowedToBeMoved(card) ) { // Don't allow unclean columns to be moved
moving = NULL;
return TRUE;
}
return FALSE;
}
void HarpCardGame::mousePress(QPoint p)
{
Q_UNUSED(p);
}
diff --git a/noncore/games/solitaire/main.cpp b/noncore/games/solitaire/main.cpp
index bd3cf8b..9301171 100644
--- a/noncore/games/solitaire/main.cpp
+++ b/noncore/games/solitaire/main.cpp
@@ -1,26 +1,25 @@
/**********************************************************************
** Copyright (C) 2000 Trolltech AS. All rights reserved.
**
** This file is part of Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include "canvascardwindow.h"
-#include <qpe/qpeapplication.h>
#include <opie/oapplicationfactory.h>
OPIE_EXPORT_APP( OApplicationFactory<CanvasCardWindow> ) \ No newline at end of file
diff --git a/noncore/games/solitaire/patiencecardgame.cpp b/noncore/games/solitaire/patiencecardgame.cpp
index 96a599c..756577a 100644
--- a/noncore/games/solitaire/patiencecardgame.cpp
+++ b/noncore/games/solitaire/patiencecardgame.cpp
@@ -1,280 +1,279 @@
/**********************************************************************
** Copyright (C) 2000 Trolltech AS. All rights reserved.
**
** This file is part of Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
-#include <qgfx_qws.h>
#include "patiencecardgame.h"
int highestZ = 0;
PatienceCardGame::PatienceCardGame(QCanvas *c, bool snap, QWidget *parent) : CanvasCardGame(*c, snap, parent)
{
numberOfTimesThroughDeck = 0;
highestZ = 0;
if ( qt_screen->deviceWidth() < 200 )
{
circleCross = new CanvasCircleOrCross( 7, 16, canvas() );
rectangle = new CanvasRoundRect( 30, 10, canvas() );
for (int i = 0; i < 4; i++)
{
discardPiles[i] = new PatienceDiscardPile( 78 + i * 23, 10, canvas() );
addCardPile(discardPiles[i]);
}
for (int i = 0; i < 7; i++)
{
workingPiles[i] = new PatienceWorkingPile( 5 + i * 23, 50, canvas() );
addCardPile(workingPiles[i]);
}
faceDownDealingPile = new PatienceFaceDownDeck( 5, 10, canvas() );
faceUpDealingPile = new PatienceFaceUpDeck( 30, 10, canvas() );
}
else
{
circleCross = new CanvasCircleOrCross( 7, 18, canvas() );
rectangle = new CanvasRoundRect( 35, 10, canvas() );
for (int i = 0; i < 4; i++)
{
discardPiles[i] = new PatienceDiscardPile( 110 + i * 30, 10, canvas() );
addCardPile(discardPiles[i]);
}
for (int i = 0; i < 7; i++)
{
workingPiles[i] = new PatienceWorkingPile( 10 + i * 30, 50, canvas() );
addCardPile(workingPiles[i]);
}
faceDownDealingPile = new PatienceFaceDownDeck( 5, 10, canvas() );
faceUpDealingPile = new PatienceFaceUpDeck( 35, 10, canvas() );
}
}
PatienceCardGame::~PatienceCardGame()
{
delete circleCross;
delete rectangle;
delete faceDownDealingPile;
delete faceUpDealingPile;
}
void PatienceCardGame::deal(void)
{
highestZ = 1;
int t = 0;
beginDealing();
for (int i = 0; i < 7; i++)
{
cards[t]->setFace(TRUE);
for (int k = i; k < 7; k++, t++)
{
Card *card = cards[t];
workingPiles[k]->addCardToTop(card);
card->setCardPile( workingPiles[k] );
QPoint p = workingPiles[k]->getCardPos( card );
card->setPos( p.x(), p.y(), highestZ );
card->showCard();
highestZ++;
}
}
for ( ; t < 52; t++)
{
Card *card = cards[t];
faceDownDealingPile->addCardToTop(card);
card->setCardPile( faceDownDealingPile );
QPoint p = faceDownDealingPile->getCardPos( card );
card->setPos( p.x(), p.y(), highestZ );
card->showCard();
highestZ++;
}
endDealing();
}
void PatienceCardGame::readConfig( Config& cfg )
{
cfg.setGroup("GameState");
// Do we have a config file to read in?
if ( !cfg.hasKey("numberOfTimesThroughDeck") )
{
// if not, create a new game
newGame();
return;
}
// We have a config file, lets read it in and use it
// Create Cards, but don't shuffle or deal them yet
createDeck();
// How many times through the deck have we been
numberOfTimesThroughDeck = cfg.readNumEntry("numberOfTimesThroughDeck");
// restore state to the circle/cross under the dealing pile
if ( canTurnOverDeck() )
circleCross->setCircle();
else
circleCross->setCross();
// Move the cards to their piles (deal them to their previous places)
beginDealing();
highestZ = 1;
for (int k = 0; k < 7; k++)
{
QString pile;
pile.sprintf( "WorkingPile%i", k );
readPile( cfg, workingPiles[k], pile, highestZ );
}
for (int k = 0; k < 4; k++)
{
QString pile;
pile.sprintf( "DiscardPile%i", k );
readPile( cfg, discardPiles[k], pile, highestZ );
}
readPile( cfg, faceDownDealingPile, "FaceDownDealingPile", highestZ );
readPile( cfg, faceUpDealingPile, "FaceUpDealingPile", highestZ );
highestZ++;
endDealing();
}
void PatienceCardGame::writeConfig( Config& cfg )
{
cfg.setGroup("GameState");
cfg.writeEntry("numberOfTimesThroughDeck", numberOfTimesThroughDeck);
for ( int i = 0; i < 7; i++ )
{
QString pile;
pile.sprintf( "WorkingPile%i", i );
workingPiles[i]->writeConfig( cfg, pile );
}
for ( int i = 0; i < 4; i++ )
{
QString pile;
pile.sprintf( "DiscardPile%i", i );
discardPiles[i]->writeConfig( cfg, pile );
}
faceDownDealingPile->writeConfig( cfg, "FaceDownDealingPile" );
faceUpDealingPile->writeConfig( cfg, "FaceUpDealingPile" );
}
bool PatienceCardGame::mousePressCard( Card *card, QPoint p )
{
Q_UNUSED(p);
CanvasCard *item = (CanvasCard *)card;
if (item->isFacing() != TRUE)
{
// From facedown stack
if ((item->x() == 5) && ((int)item->y() == 10))
{
item->setZ(highestZ);
highestZ++;
// Added Code
faceDownDealingPile->removeCard(item);
faceUpDealingPile->addCardToTop(item);
item->setCardPile( faceUpDealingPile );
if ( qt_screen->deviceWidth() < 200 )
item->flipTo( 30, (int)item->y() );
else
item->flipTo( 35, (int)item->y() );
}
else return FALSE; // <- was missing, caused facedown card to react
// to clicking, which is wrong
moving = NULL;
moved = FALSE;
// move two other cards if we flip three at a time
int flipped = 1;
QCanvasItemList l = canvas()->collisions( p );
for (QCanvasItemList::Iterator it = l.begin(); (it != l.end()) && (flipped != cardsDrawn()); ++it)
{
if ( (*it)->rtti() == canvasCardId )
{
CanvasCard *item = (CanvasCard *)*it;
if (item->animated())
continue;
item->setZ(highestZ);
highestZ++;
flipped++;
// Added Code
faceDownDealingPile->removeCard(item);
faceUpDealingPile->addCardToTop(item);
item->setCardPile( faceUpDealingPile );
if ( qt_screen->deviceWidth() < 200 )
item->flipTo( 30, (int)item->y(), 8 * flipped );
else
item->flipTo( 35, (int)item->y(), 8 * flipped );
}
}
return TRUE;
}
return FALSE;
}
void PatienceCardGame::mousePress(QPoint p)
{
if ( canTurnOverDeck() &&
(p.x() > 5) && (p.x() < 28) &&
(p.y() > 10) && (p.y() < 46) )
{
beginDealing();
Card *card = faceUpDealingPile->cardOnTop();
while ( card )
{
card->setPos( 5, 10, highestZ );
card->setFace( FALSE );
faceUpDealingPile->removeCard( card );
faceDownDealingPile->addCardToTop( card );
card->setCardPile( faceDownDealingPile );
card = faceUpDealingPile->cardOnTop();
highestZ++;
}
endDealing();
throughDeck();
moved = TRUE;
}
}
diff --git a/noncore/games/solitaire/teeclubcardgame.cpp b/noncore/games/solitaire/teeclubcardgame.cpp
index 0941e0d..b1af757 100644
--- a/noncore/games/solitaire/teeclubcardgame.cpp
+++ b/noncore/games/solitaire/teeclubcardgame.cpp
@@ -1,202 +1,201 @@
/**********************************************************************
** Copyright (C) 2000 Trolltech AS. All rights reserved.
**
** This file is part of Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**
** created on base of patiencecardgame by cam (C.A.Mader) 2002
** Rules for this game:
** use 2 decks = 104 cards
** deal 9 rows with 5 open cards each
** append one card to each other card which is one step higher
** move only columns of cards which are equal in suit
** each card can be layed on a free place
** deal 1 card at once on the first pile
**
**
**********************************************************************/
-#include <qgfx_qws.h>
#include "teeclubcardgame.h"
extern int highestZ;
TeeclubCardGame::TeeclubCardGame(QCanvas *c, bool snap, QWidget *parent) : CanvasCardGame(*c, snap, parent, 2) // Use 2 Decks
{
highestZ = 0;
for (int i = 0; i < 8; i++) {
discardPiles[i] = new TeeclubDiscardPile( 27 + i * 26, 10, canvas() );
addCardPile(discardPiles[i]);
}
for (int i = 0; i < 9; i++) {
workingPiles[i] = new TeeclubWorkingPile( 2 + i * 26, 50, canvas() );
addCardPile(workingPiles[i]);
}
faceDownDealingPile = new TeeclubFaceDownDeck( 2, 10, canvas() );
}
void TeeclubCardGame::deal(void)
{
highestZ = 1;
int t = 0;
beginDealing();
for (int i = 0; i < 9; i++) {
workingPiles[i]->setOffsetDown(13);
workingPiles[i]->beginPileResize();
for (int k = 0; k < 5; k++, t++) {
Card *card = cards[t];
workingPiles[i]->addCardToTop(card);
card->setCardPile( workingPiles[i] );
card->setPos( 0, 0, highestZ );
card->setFace(TRUE);
card->move( workingPiles[i]->getCardPos( card ) );
card->showCard();
highestZ++;
}
}
for ( ; t < getNumberOfCards(); t++) {
Card *card = cards[t];
faceDownDealingPile->addCardToTop(card);
card->setCardPile( faceDownDealingPile );
QPoint p = faceDownDealingPile->getCardPos( card );
card->setPos( p.x(), p.y(), highestZ );
card->showCard();
highestZ++;
}
endDealing();
}
void TeeclubCardGame::resizePiles()
{
beginDealing();
for (int i = 0; i < 9; i++) {
while ((workingPiles[i]->getCardPos(NULL).y() > 230) && (workingPiles[i]->getOffsetDown()>1)) {
// resize the pile
workingPiles[i]->setOffsetDown(workingPiles[i]->getOffsetDown()-1);
Card *card = workingPiles[i]->cardOnBottom();
int p=0;
while (card != NULL) {
card->setPos( 0, 0, p++ );
card->move( workingPiles[i]->getCardPos( card ) );
card = workingPiles[i]->cardInfront(card);
}
}
}
endDealing();
}
void TeeclubCardGame::readConfig( Config& cfg )
{
cfg.setGroup("GameState");
// Create Cards, but don't shuffle or deal them yet
createDeck();
// Move the cards to their piles (deal them to their previous places)
beginDealing();
highestZ = 1;
for (int i = 0; i < 8; i++) {
QString pile;
pile.sprintf( "TeeclubDiscardPile%i", i );
readPile( cfg, discardPiles[i], pile, highestZ );
}
for (int i = 0; i < 9; i++) {
workingPiles[i]->endPileResize();
QString pile;
pile.sprintf( "TeeclubWorkingPile%i", i );
readPile( cfg, workingPiles[i], pile, highestZ );
workingPiles[i]->beginPileResize();
}
readPile( cfg, faceDownDealingPile, "TeeclubFaceDownDealingPile", highestZ );
highestZ++;
endDealing();
resizePiles();
}
void TeeclubCardGame::writeConfig( Config& cfg )
{
cfg.setGroup("GameState");
for ( int i = 0; i < 8; i++ ) {
QString pile;
pile.sprintf( "TeeclubDiscardPile%i", i );
discardPiles[i]->writeConfig( cfg, pile );
}
for ( int i = 0; i < 9; i++ ) {
QString pile;
pile.sprintf( "TeeclubWorkingPile%i", i );
workingPiles[i]->writeConfig( cfg, pile );
}
faceDownDealingPile->writeConfig( cfg, "TeeclubFaceDownDealingPile" );
}
bool TeeclubCardGame::mousePressCard( Card *card, QPoint p )
{
Q_UNUSED(p);
CanvasCard *item = (CanvasCard *)card;
if (item->isFacing() != TRUE) {
// From facedown stack
if ((item->x() == 2) && ((int)item->y() == 10)) { // Deal 1 card
// Move 8 cards, one to each workingPile
beginDealing();
CanvasCard *card = (CanvasCard *)faceDownDealingPile->cardOnTop();
card->setZ(highestZ);
highestZ++;
faceDownDealingPile->removeCard(card);
workingPiles[0]->addCardToTop(card);
card->setCardPile( workingPiles[0] );
card->setFace(FALSE);
QPoint p = workingPiles[0]->getCardPos(card);
card->flipTo( p.x(), p.y() );
endDealing();
}
moving = NULL;
moved = FALSE;
return TRUE;
} else if ( !card->getCardPile()->isAllowedToBeMoved(card) ) { // Don't allow unclean columns to be moved
moving = NULL;
return TRUE;
}
return FALSE;
}
void TeeclubCardGame::mousePress(QPoint p)
{
Q_UNUSED(p);
}
diff --git a/noncore/games/tetrix/main.cpp b/noncore/games/tetrix/main.cpp
index fcf4b33..bf1242f 100644
--- a/noncore/games/tetrix/main.cpp
+++ b/noncore/games/tetrix/main.cpp
@@ -1,28 +1,27 @@
/**********************************************************************
** Copyright (C) 2000 Trolltech AS. All rights reserved.
**
** This file is part of Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include "qtetrix.h"
-#include <qpe/qpeapplication.h>
#include <opie/oapplicationfactory.h>
OPIE_EXPORT_APP( OApplicationFactory<QTetrix> )
diff --git a/noncore/games/tetrix/ohighscoredlg.cpp b/noncore/games/tetrix/ohighscoredlg.cpp
index 7581f51..8d8079e 100644
--- a/noncore/games/tetrix/ohighscoredlg.cpp
+++ b/noncore/games/tetrix/ohighscoredlg.cpp
@@ -1,200 +1,199 @@
/***************************************************************************
begin : January 2003
copyright : ( C ) 2003 by Carsten Niehaus
email : cniehaus@handhelds.org
**************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* ( at your option ) any later version. *
* *
**************************************************************************/
#include <qdialog.h>
-#include <qpe/config.h>
#include <qlayout.h>
-#include <qpe/config.h>
#include <qpe/qpeapplication.h>
+#include <qpe/config.h>
#include <qstring.h>
#include <qhbox.h>
#include <qvbox.h>
#include <qlabel.h>
#include <qlistview.h>
#include <qlineedit.h>
#include "ohighscoredlg.h"
OHighscore::OHighscore( int score , int playerLevel )
{
pLevel = playerLevel;
getList();
checkIfItIsANewhighscore( score );
}
OHighscore::~OHighscore()
{
std::list<t_playerData*>::iterator deleteIterator = playerData.begin();
for ( ; deleteIterator != playerData.end() ; deleteIterator++ )
{
delete ( *deleteIterator );
}
}
void OHighscore::getList()
{
Config cfg ( "tetrix" );
cfg.setGroup( QString::number( 1 ) );
lowest = cfg.readNumEntry( "Points" );
playerData.clear();
int rest = 1; //for the filling up later
for ( int i = 1 ; i < 11 ; i++ )
{
if ( cfg.hasGroup( QString::number( i ) ) )
{
cfg.setGroup( QString::number( i ) );
int temp = cfg.readNumEntry( "Points" );
t_playerData *pPlayerData = new t_playerData;
pPlayerData->sName = cfg.readEntry( "Name" );
pPlayerData->points = temp;
pPlayerData->level = cfg.readNumEntry( "Level" );
playerData.push_back( pPlayerData );
if ( (temp < lowest) ) lowest = temp;
rest++;
}
}
//now I fill up the rest of the list
if ( rest < 11 ) //only go in this loop if there are less than
//10 highscoreentries
{
lowest = 0;
for ( ; rest < 11 ; rest++ )
{
t_playerData *pPlayerData = new t_playerData;
pPlayerData->sName = tr( "empty");
pPlayerData->points = 0;
pPlayerData->level = 0;
playerData.push_back( pPlayerData );
}
}
}
void OHighscore::checkIfItIsANewhighscore( int points)
{
if ( points > lowest )
isNewhighscore = true;
else
isNewhighscore = false;
}
void OHighscore::insertData( QString name , int punkte , int playerLevel )
{
Config cfg ( "tetrix" );
int entryNumber = 1;
std::list<t_playerData*>::iterator insertIterator = playerData.begin();
while ( insertIterator != playerData.end() )
{
if ( punkte > ( *insertIterator )->points )
{
t_playerData* temp = new t_playerData;
temp->sName = name;
temp->points = punkte;
temp->level = playerLevel;
playerData.insert( insertIterator , temp );
//now we have to delete the last entry
insertIterator = playerData.end();
insertIterator--;
//X delete *insertIterator; //memleak?
playerData.erase( insertIterator );
/////////////////////////////////////////
//this block just rewrites the highscore
insertIterator = playerData.begin();
while ( insertIterator != playerData.end() )
{
cfg.setGroup( QString::number( entryNumber ) );
cfg.writeEntry( "Name" , ( *insertIterator )->sName );
cfg.writeEntry( "Points" , ( *insertIterator )->points );
cfg.writeEntry( "Level" , ( *insertIterator )->level );
entryNumber++;
insertIterator++;
}
////////////////////////////////////////
return;
}
insertIterator++;
}
}
QString OHighscore::getName()
{
QString name;
QDialog *d = new QDialog ( this, 0, true );
d->setCaption( tr( "Enter your name!" ));
QLineEdit *ed = new QLineEdit ( d );
( new QVBoxLayout ( d, 3, 3 ))->addWidget ( ed );
ed->setFocus ( );
if ( d->exec() == QDialog::Accepted ) {
name = ed->text();
}
//delete d;
return name;
}
OHighscoreDialog::OHighscoreDialog(OHighscore *highscore, QWidget *parent, const char *name, bool modal) : QDialog(parent, name, modal)
{
hs_ = highscore;
setCaption( tr( "Highscores" ) );
vbox_layout = new QVBoxLayout( this, 4 , 4 );
list = new QListView( this );
list->setSorting( -1 );
list->addColumn( tr( "#" ));
list->addColumn( tr( "Name" ));
list->addColumn( tr( "Points" ));
list->addColumn( tr( "Level" ));
createHighscoreListView();
vbox_layout->addWidget( list );
QPEApplication::showDialog( this );
}
void OHighscoreDialog::createHighscoreListView()
{
int pos = 10;
int points_ = 0;
int level_ = 0;
std::list<t_playerData*>::reverse_iterator iListe = hs_->playerData.rbegin();
for ( ; iListe != hs_->playerData.rend() ; ++iListe )
{
QListViewItem *item = new QListViewItem( list );
item->setText( 0 , QString::number( pos ) ); //number
item->setText( 1 , ( *iListe )->sName ); //name
if ( ( *iListe )->points == -1 )
points_ = 0;
else points_ = ( *iListe )->points;
if ( ( *iListe )->level == -1 )
level_ = 0;
else level_ = ( *iListe )->level;
item->setText( 2 , QString::number( points_ ) ); //points
item->setText( 3 , QString::number( level_ ) ); //level
pos--;
}
}
diff --git a/noncore/games/tetrix/qtetrix.cpp b/noncore/games/tetrix/qtetrix.cpp
index 6d29c3f..20cf1a7 100644
--- a/noncore/games/tetrix/qtetrix.cpp
+++ b/noncore/games/tetrix/qtetrix.cpp
@@ -1,177 +1,174 @@
/**********************************************************************
** Copyright (C) 2000 Trolltech AS. All rights reserved.
**
** This file is part of Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include "qtetrix.h"
#include <qpe/resource.h>
-#include <qpe/config.h>
-#include <qapplication.h>
#include <qlabel.h>
#include <qdatetime.h>
#include <qlayout.h>
-#include <qstring.h>
#include "ohighscoredlg.h"
void drawTetrixButton( QPainter *p, int x, int y, int w, int h,
const QColor *color )
{
QColor fc;
if ( color ) {
QPointArray a;
a.setPoints( 3, x,y+h-1, x,y, x+w-1,y );
p->setPen( color->light() );
p->drawPolyline( a );
a.setPoints( 3, x+1,y+h-1, x+w-1,y+h-1, x+w-1,y+1 );
p->setPen( color->dark() );
p->drawPolyline( a );
x++;
y++;
w -= 2;
h -= 2;
fc = *color;
}
else
fc = p->backgroundColor();
p->fillRect( x, y, w, h, fc );
}
ShowNextPiece::ShowNextPiece( QWidget *parent, const char *name )
: QFrame( parent, name )
{
setFrameStyle( QFrame::Panel | QFrame::Sunken );
xOffset = -1; // -1 until first resizeEvent.
}
void ShowNextPiece::resizeEvent( QResizeEvent *e )
{
QSize sz = e->size();
blockWidth = (sz.width() - 3)/5;
blockHeight = (sz.height() - 3)/6;
xOffset = (sz.width() - 3)/5;
yOffset = (sz.height() - 3)/6;
}
void ShowNextPiece::paintEvent( QPaintEvent * )
{
QPainter p( this );
drawFrame( &p );
p.end(); // explicit end() so any slots can paint too
emit update();
}
void ShowNextPiece::drawNextSquare(int x, int y,QColor *color)
{
if (xOffset == -1) // Before first resizeEvent?
return;
QPainter paint;
paint.begin(this);
drawTetrixButton( &paint, xOffset+x*blockWidth, yOffset+y*blockHeight,
blockWidth, blockHeight, color );
paint.end();
}
QTetrix::QTetrix( QWidget *parent, const char *name, WFlags f )
: QMainWindow( parent, name, f )
{
setIcon( Resource::loadPixmap( "tetrix_icon" ) );
setCaption( tr("Tetrix" ) );
QTime t = QTime::currentTime();
TetrixPiece::setRandomSeed( (((double)t.hour())+t.minute()+t.second())/
(24+60+60) );
QWidget *gameArea = new QWidget( this );
setCentralWidget( gameArea );
QGridLayout *gl = new QGridLayout( gameArea, 5, 3, 8 );
QLabel *l;
l = new QLabel( tr("Next"), gameArea );
gl->addWidget( l, 0, 0 );
showNext = new ShowNextPiece(gameArea);
showNext->setBackgroundColor(QColor(0,0,0));
gl->addWidget( showNext, 0, 1 );
l = new QLabel( tr("Score"), gameArea );
gl->addWidget( l, 1, 0 );
showScore = new QLabel(gameArea);
gl->addWidget( showScore, 1, 1 );
l = new QLabel( tr("Level"), gameArea );
gl->addWidget( l, 2, 0 );
showLevel = new QLabel(gameArea);
gl->addWidget( showLevel, 2, 1 );
l = new QLabel( tr("Removed"), gameArea );
gl->addWidget( l, 3, 0 );
showLines = new QLabel(gameArea);
gl->addWidget( showLines, 3, 1 );
board = new QTetrixBoard(gameArea);
board->setBackgroundColor(QColor(0,0,0));
board->setFixedWidth( 124 );
gl->addMultiCellWidget( board, 0, 4, 2, 2 );
gl->addColSpacing( 2, 100 );
gl->addColSpacing( 1, 35 );
gl->addRowSpacing( 0, 35 );
QPushButton *pb = new QPushButton( tr("Start"), gameArea );
pb->setFocusPolicy( NoFocus );
connect( pb, SIGNAL( clicked() ), board, SLOT( start() ) );
gl->addMultiCellWidget( pb, 4, 4, 0, 1 );
connect( board, SIGNAL(gameOverSignal()), SLOT(gameOver()) );
connect( board, SIGNAL(drawNextSquareSignal(int,int,QColor*)), showNext,
SLOT(drawNextSquare(int,int,QColor*)) );
connect( showNext, SIGNAL(update()), board, SLOT(updateNext()) );
connect( board, SIGNAL(updateScoreSignal(int)), showScore,
SLOT(setNum(int)) );
connect( board, SIGNAL(updateLevelSignal(int)), showLevel,
SLOT(setNum(int)));
connect( board, SIGNAL(updateRemovedSignal(int)), showLines,
SLOT(setNum(int)));
showScore->setNum( 0 );
showLevel->setNum( 0 );
showLines->setNum( 0 );
board->revealNextPiece(TRUE);
board->setFocusPolicy( StrongFocus );
}
void QTetrix::gameOver()
{
OHighscore *hs = new OHighscore( showScore->text().toInt() , showLevel->text().toInt() );
if ( hs->isNewhighscore )
hs->insertData( hs->getName(), showScore->text().toInt() , showLevel->text().toInt() );
OHighscoreDialog hscdlg( hs, this, "OHighscoreDialog", true );
hscdlg.exec();
}
void QTetrix::quit()
{
close();
}
diff --git a/noncore/games/tetrix/qtetrixb.cpp b/noncore/games/tetrix/qtetrixb.cpp
index 521f171..3c179df 100644
--- a/noncore/games/tetrix/qtetrixb.cpp
+++ b/noncore/games/tetrix/qtetrixb.cpp
@@ -1,251 +1,249 @@
/**********************************************************************
** Copyright (C) 2000 Trolltech AS. All rights reserved.
**
** This file is part of Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include "qtetrixb.h"
#include "qtetrix.h"
#include <qtimer.h>
-#include <qkeycode.h>
-#include <qpainter.h>
const int waitAfterLineTime = 500;
QTetrixBoard::QTetrixBoard( QWidget *p, const char *name )
: QFrame( p, name )
{
setFrameStyle( QFrame::Panel | QFrame::Sunken );
paint = 0;
timer = new QTimer(this);
connect( timer, SIGNAL(timeout()), SLOT(timeout()) );
colors[0].setRgb(200,100,100);
colors[1].setRgb(100,200,100);
colors[2].setRgb(100,100,200);
colors[3].setRgb(200,200,100);
colors[4].setRgb(200,100,200);
colors[5].setRgb(100,200,200);
colors[6].setRgb(218,170, 0);
xOffset = -1; // -1 until a resizeEvent is received.
blockWidth = 20;
yOffset = 30;
blockHeight = 20;
noGame = TRUE;
isPaused = FALSE;
waitingAfterLine = FALSE;
updateTimeoutTime(); // Sets timeoutTime
}
void QTetrixBoard::startGame(int gameType,int fillRandomLines)
{
if ( isPaused )
return; // ignore if game is paused
noGame = FALSE;
GenericTetrix::startGame( gameType, fillRandomLines );
// Note that the timer is started by updateLevel!
}
void QTetrixBoard::pause()
{
if ( noGame ) // game not active
return;
isPaused = !isPaused;
if ( isPaused ) {
timer->stop();
hideBoard();
}
else
timer->start(timeoutTime);
update();
}
void QTetrixBoard::drawSquare(int x,int y,int value)
{
if (xOffset == -1) // Before first resizeEvent?
return;
const int X = xOffset + x*blockWidth;
const int Y = yOffset + (y - 1)*blockHeight;
bool localPainter = paint == 0;
QPainter *p;
if ( localPainter )
p = new QPainter( this );
else
p = paint;
drawTetrixButton( p, X, Y, blockWidth, blockHeight,
value == 0 ? 0 : &colors[value-1] );
/*
if ( value != 0 ) {
QColor tc, bc;
tc = colors[value-1].light();
bc = colors[value-1].dark();
p->drawShadePanel( X, Y, blockWidth, blockHeight,
tc, bc, 1, colors[value-1], TRUE );
}
else
p->fillRect( X, Y, blockWidth, blockHeight, backgroundColor() );
*/
if ( localPainter )
delete p;
}
void QTetrixBoard::drawNextSquare( int x, int y, int value )
{
if ( value == 0 )
emit drawNextSquareSignal (x, y, 0 );
else
emit drawNextSquareSignal( x, y, &colors[value-1] );
}
void QTetrixBoard::updateRemoved( int noOfLines )
{
if ( noOfLines > 0 ) {
timer->stop();
timer->start( waitAfterLineTime );
waitingAfterLine = TRUE;
}
emit updateRemovedSignal( noOfLines );
}
void QTetrixBoard::updateScore( int newScore )
{
emit updateScoreSignal( newScore );
}
void QTetrixBoard::updateLevel( int newLevel )
{
timer->stop();
updateTimeoutTime();
timer->start( timeoutTime );
emit updateLevelSignal( newLevel );
}
void QTetrixBoard::pieceDropped(int)
{
if ( waitingAfterLine ) // give player a break if a line has been removed
return;
newPiece();
}
void QTetrixBoard::gameOver()
{
timer->stop();
noGame = TRUE;
emit gameOverSignal();
}
void QTetrixBoard::timeout()
{
if ( waitingAfterLine ) {
timer->stop();
waitingAfterLine = FALSE;
newPiece();
timer->start( timeoutTime );
} else {
oneLineDown();
}
}
void QTetrixBoard::drawContents( QPainter *p )
{
const char *text = "Press \"Pause\"";
QRect r = contentsRect();
paint = p; // set widget painter
if ( isPaused ) {
p->drawText( r, AlignCenter | AlignVCenter, text );
return;
}
int x1,y1,x2,y2;
x1 = (r.left() - xOffset) / blockWidth;
if (x1 < 0)
x1 = 0;
if (x1 >= boardWidth())
x1 = boardWidth() - 1;
x2 = (r.right() - xOffset) / blockWidth;
if (x2 < 0)
x2 = 0;
if (x2 >= boardWidth())
x2 = boardWidth() - 1;
y1 = (r.top() - yOffset) / blockHeight;
if (y1 < 0)
y1 = 0;
if (y1 >= boardHeight())
y1 = boardHeight() - 1;
y2 = (r.bottom() - yOffset) / blockHeight;
if (y2 < 0)
y2 = 0;
if (y2 >= boardHeight())
y2 = boardHeight() - 1;
updateBoard( x1, y1, x2, y2, TRUE );
paint = 0; // reset widget painter
return;
}
void QTetrixBoard::resizeEvent(QResizeEvent *e)
{
QSize sz = e->size();
blockWidth = (sz.width() - 2)/10;
blockHeight = (sz.height() - 2)/22;
xOffset = 1;
//yOffset = 1;
yOffset = (sz.height() - 2) - (blockHeight *22);
}
void QTetrixBoard::keyPressEvent( QKeyEvent *e )
{
if ( noGame || isPaused || waitingAfterLine )
return;
switch( e->key() ) {
case Key_Left :
moveLeft();
break;
case Key_Right :
moveRight();
break;
case Key_Down :
// rotateRight();
dropDown();
break;
case Key_Up :
rotateLeft();
break;
case Key_Space :
dropDown();
break;
case Key_D :
oneLineDown();
break;
default:
return;
}
e->accept();
}
void QTetrixBoard::updateTimeoutTime()
{
timeoutTime = 1000/(1 + getLevel());
}
diff --git a/noncore/games/tictac/main.cpp b/noncore/games/tictac/main.cpp
index cfff683..9aafe4c 100644
--- a/noncore/games/tictac/main.cpp
+++ b/noncore/games/tictac/main.cpp
@@ -1,13 +1,12 @@
/****************************************************************************
** Copyright (C) 1992-2000 Trolltech AS. All rights reserved.
**
** This file is part of an example program for Qt. This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/
-#include <qpe/qpeapplication.h>
#include <opie/oapplicationfactory.h>
#include "tictac.h"
OPIE_EXPORT_APP( OApplicationFactory<TicTacToe> )
diff --git a/noncore/games/tictac/tictac.cpp b/noncore/games/tictac/tictac.cpp
index 9de3b58..12ce35f 100644
--- a/noncore/games/tictac/tictac.cpp
+++ b/noncore/games/tictac/tictac.cpp
@@ -1,382 +1,378 @@
/****************************************************************************
** tictac.cpp,v 1.3.8.1 2003/08/29 06:50:40 harlekin Exp
**
** Copyright (C) 1992-2000 Trolltech AS. All rights reserved.
**
** This file is part of an example program for Qt. This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/
#include "tictac.h"
#include <qpe/qpeapplication.h>
-#include <qpainter.h>
#include <qdrawutil.h>
#include <qcombobox.h>
-#include <qcheckbox.h>
#include <qlabel.h>
#include <qlayout.h>
#include <stdlib.h> // rand() function
-#include <qdatetime.h> // seed for rand()
-#include <qstringlist.h> //needed for proper internationalization
//***************************************************************************
//* TicTacButton member functions
//***************************************************************************
// --------------------------------------------------------------------------
// Creates a TicTacButton
//
TicTacButton::TicTacButton( QWidget *parent ) : QPushButton( parent )
{
t = Blank; // initial type
}
// --------------------------------------------------------------------------
// Paints TicTacButton
//
void TicTacButton::drawButtonLabel( QPainter *p )
{
QRect r = rect();
p->setPen( QPen( white,2 ) ); // set fat pen
if ( t == Circle ) {
p->drawEllipse( r.left()+4, r.top()+4, r.width()-8, r.height()-8 );
} else if ( t == Cross ) { // draw cross
p->drawLine( r.topLeft() +QPoint(4,4), r.bottomRight()-QPoint(4,4));
p->drawLine( r.bottomLeft()+QPoint(4,-4),r.topRight() -QPoint(4,-4));
}
}
//***************************************************************************
//* TicTacGameBoard member functions
//***************************************************************************
// --------------------------------------------------------------------------
// Creates a game board with N x N buttons and connects the "clicked()"
// signal of all buttons to the "buttonClicked()" slot.
//
TicTacGameBoard::TicTacGameBoard( int n, QWidget *parent, const char *name )
: QWidget( parent, name )
{
QPEApplication::showWidget( this );
st = Init; // initial state
nBoard = n;
n *= n; // make square
comp_starts = FALSE; // human starts
buttons = new TicTacButtons(n); // create real buttons
btArray = new TicTacArray(n); // create button model
QGridLayout * grid = new QGridLayout( this, 3, 3, 4 );
QPalette p( blue );
for ( int i=0; i<n; i++ ) { // create and connect buttons
TicTacButton *ttb = new TicTacButton( this );
ttb->setPalette( p );
ttb->setEnabled( FALSE );
connect( ttb, SIGNAL(clicked()), SLOT(buttonClicked()) );
grid->addWidget( ttb, i%3, i/3 );
buttons->insert( i, ttb );
btArray->at(i) = TicTacButton::Blank; // initial button type
}
QTime t = QTime::currentTime(); // set random seed
srand( t.hour()*12+t.minute()*60+t.second()*60 );
}
TicTacGameBoard::~TicTacGameBoard()
{
delete buttons;
delete btArray;
}
// --------------------------------------------------------------------------
// TicTacGameBoard::computerStarts( bool v )
//
// Computer starts if v=TRUE. The human starts by default.
//
void TicTacGameBoard::computerStarts( bool v )
{
comp_starts = v;
}
// --------------------------------------------------------------------------
// TicTacGameBoard::newGame()
//
// Clears the game board and prepares for a new game
//
void TicTacGameBoard::newGame()
{
st = HumansTurn;
for ( int i=0; i<nBoard*nBoard; i++ )
btArray->at(i) = TicTacButton::Blank;
if ( comp_starts )
computerMove();
else
updateButtons();
}
// --------------------------------------------------------------------------
// TicTacGameBoard::buttonClicked() - SLOT
//
// This slot is activated when a TicTacButton emits the signal "clicked()",
// i.e. the user has clicked on a TicTacButton.
//
void TicTacGameBoard::buttonClicked()
{
if ( st != HumansTurn ) // not ready
return;
int i = buttons->findRef( (TicTacButton*)sender() );
TicTacButton *b = buttons->at(i); // get piece that was pressed
if ( b->type() == TicTacButton::Blank ) { // empty piece?
btArray->at(i) = TicTacButton::Circle;
updateButtons();
if ( checkBoard( btArray ) == 0 ) // not a winning move?
computerMove();
int s = checkBoard( btArray );
if ( s ) { // any winners yet?
st = s == TicTacButton::Circle ? HumanWon : ComputerWon;
emit finished();
}
}
}
// --------------------------------------------------------------------------
// TicTacGameBoard::updateButtons()
//
// Updates all buttons that have changed state
//
void TicTacGameBoard::updateButtons()
{
for ( int i=0; i<nBoard*nBoard; i++ ) {
if ( buttons->at(i)->type() != btArray->at(i) )
buttons->at(i)->setType( (TicTacButton::Type)btArray->at(i) );
buttons->at(i)->setEnabled( buttons->at(i)->type() ==
TicTacButton::Blank );
}
}
// --------------------------------------------------------------------------
// TicTacGameBoard::checkBoard()
//
// Checks if one of the players won the game, works for any board size.
//
// Returns:
// - TicTacButton::Cross if the player with X buttons won
// - TicTacButton::Circle if the player with O buttons won
// - Zero (0) if there is no winner yet
//
int TicTacGameBoard::checkBoard( TicTacArray *a )
{
int t = 0;
int row, col;
bool won = FALSE;
for ( row=0; row<nBoard && !won; row++ ) { // check horizontal
t = a->at(row*nBoard);
if ( t == TicTacButton::Blank )
continue;
col = 1;
while ( col<nBoard && a->at(row*nBoard+col) == t )
col++;
if ( col == nBoard )
won = TRUE;
}
for ( col=0; col<nBoard && !won; col++ ) { // check vertical
t = a->at(col);
if ( t == TicTacButton::Blank )
continue;
row = 1;
while ( row<nBoard && a->at(row*nBoard+col) == t )
row++;
if ( row == nBoard )
won = TRUE;
}
if ( !won ) { // check diagonal top left
t = a->at(0); // to bottom right
if ( t != TicTacButton::Blank ) {
int i = 1;
while ( i<nBoard && a->at(i*nBoard+i) == t )
i++;
if ( i == nBoard )
won = TRUE;
}
}
if ( !won ) { // check diagonal bottom left
int j = nBoard-1; // to top right
int i = 0;
t = a->at(i+j*nBoard);
if ( t != TicTacButton::Blank ) {
i++; j--;
while ( i<nBoard && a->at(i+j*nBoard) == t ) {
i++; j--;
}
if ( i == nBoard )
won = TRUE;
}
}
if ( !won ) // no winner
t = 0;
return t;
}
// --------------------------------------------------------------------------
// TicTacGameBoard::computerMove()
//
// Puts a piece on the game board. Very, very simple.
//
void TicTacGameBoard::computerMove()
{
int numButtons = nBoard*nBoard;
int *altv = new int[numButtons]; // buttons alternatives
int altc = 0;
int stopHuman = -1;
TicTacArray a = btArray->copy();
int i;
for ( i=0; i<numButtons; i++ ) { // try all positions
if ( a[i] != TicTacButton::Blank ) // already a piece there
continue;
a[i] = TicTacButton::Cross; // test if computer wins
if ( checkBoard(&a) == a[i] ) { // computer will win
st = ComputerWon;
stopHuman = -1;
break;
}
a[i] = TicTacButton::Circle; // test if human wins
if ( checkBoard(&a) == a[i] ) { // oops...
stopHuman = i; // remember position
a[i] = TicTacButton::Blank; // restore button
continue; // computer still might win
}
a[i] = TicTacButton::Blank; // restore button
altv[altc++] = i; // remember alternative
}
if ( stopHuman >= 0 ) // must stop human from winning
a[stopHuman] = TicTacButton::Cross;
else if ( i == numButtons ) { // tried all alternatives
if ( altc > 0 ) // set random piece
a[altv[rand()%(altc--)]] = TicTacButton::Cross;
if ( altc == 0 ) { // no more blanks
st = NobodyWon;
emit finished();
}
}
*btArray = a; // update model
updateButtons(); // update buttons
delete[] altv;
}
//***************************************************************************
//* TicTacToe member functions
//***************************************************************************
// --------------------------------------------------------------------------
// Creates a game widget with a game board and two push buttons, and connects
// signals of child widgets to slots.
//
TicTacToe::TicTacToe( QWidget *parent, const char *name, WFlags fl )
: QWidget( parent, name, fl )
{
QVBoxLayout * l = new QVBoxLayout( this, 6 );
// Create a message label
boardSize = 3;
message = new QLabel( this );
message->setFrameStyle( QFrame::WinPanel | QFrame::Sunken );
message->setAlignment( AlignCenter );
l->addWidget( message );
// Create the game board and connect the signal finished() to this
// gameOver() slot
board = new TicTacGameBoard( boardSize, this );
connect( board, SIGNAL(finished()), SLOT(gameOver()) );
l->addWidget( board );
// Create a horizontal frame line
QFrame *line = new QFrame( this );
line->setFrameStyle( QFrame::HLine | QFrame::Sunken );
l->addWidget( line );
// Create the combo box for deciding who should start, and
// connect its clicked() signals to the buttonClicked() slot
whoStarts = new QComboBox( this );
whoStarts->insertItem( tr( "Computer starts" ) );
whoStarts->insertItem( tr( "Human starts" ) );
l->addWidget( whoStarts );
// Create the push buttons and connect their clicked() signals
// to this right slots.
newGame = new QPushButton( tr( "Play!" ), this );
connect( newGame, SIGNAL(clicked()), SLOT(newGameClicked()) );
quit = new QPushButton( tr( "Quit" ), this );
connect( quit, SIGNAL(clicked()), qApp, SLOT(quit()) );
QHBoxLayout * b = new QHBoxLayout;
l->addLayout( b );
b->addWidget( newGame );
b->addWidget( quit );
QPEApplication::showWidget( this );
newState();
}
// --------------------------------------------------------------------------
// TicTacToe::newGameClicked() - SLOT
//
// This slot is activated when the new game button is clicked.
//
void TicTacToe::newGameClicked()
{
board->computerStarts( whoStarts->currentItem() == 0 );
board->newGame();
newState();
}
// --------------------------------------------------------------------------
// TicTacToe::gameOver() - SLOT
//
// This slot is activated when the TicTacGameBoard emits the signal
// "finished()", i.e. when a player has won or when it is a draw.
//
void TicTacToe::gameOver()
{
newState(); // update text box
}
// --------------------------------------------------------------------------
// Updates the message to reflect a new state.
//
void TicTacToe::newState()
{
QStringList msg;
msg << tr( "Click Play to start")
<< tr("Make your move")
<< tr("You won!")
<< tr("Computer won!")
<< tr("It's a draw");
message->setText( msg[board->state()] );
return;
}
diff --git a/noncore/games/wordgame/main.cpp b/noncore/games/wordgame/main.cpp
index f32acff..eb3e2f2 100644
--- a/noncore/games/wordgame/main.cpp
+++ b/noncore/games/wordgame/main.cpp
@@ -1,28 +1,27 @@
/**********************************************************************
** Copyright (C) 2000 Trolltech AS. All rights reserved.
**
** This file is part of Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include "wordgame.h"
-#include <qpe/qpeapplication.h>
#include <opie/oapplicationfactory.h>
OPIE_EXPORT_APP( OApplicationFactory<WordGame> )
diff --git a/noncore/games/wordgame/wordgame.cpp b/noncore/games/wordgame/wordgame.cpp
index c01551d..43a54f8 100644
--- a/noncore/games/wordgame/wordgame.cpp
+++ b/noncore/games/wordgame/wordgame.cpp
@@ -1,1519 +1,1510 @@
/**********************************************************************
** Copyright (C) 2000 Trolltech AS. All rights reserved.
**
** This file is part of Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include "wordgame.h"
-#include <qpe/applnk.h>
#include <qpe/global.h>
-#include <qpe/filemanager.h>
#include <qpe/resource.h>
#include <qpe/config.h>
#include <qapplication.h>
#include <qmessagebox.h>
#include <qcombobox.h>
-#include <qdatetime.h>
-#include <qfileinfo.h>
-#include <qfile.h>
#include <qdir.h>
-#include <qiconset.h>
-#include <qlabel.h>
#include <qlineedit.h>
#include <qpushbutton.h>
#include <qtextstream.h>
#include <qtimer.h>
#include <qpe/qpetoolbar.h>
#include <qtoolbutton.h>
#include <qvbox.h>
#include <qwidgetstack.h>
-#include <qpainter.h>
#include <qlayout.h>
-#include <qregexp.h>
#include <stdlib.h>
#include <unistd.h>
#include <pwd.h>
#include <sys/types.h>
enum RuleEffects {
Multiplier=15,
MultiplyAll=64,
Start=128
};
static int tile_smallw = 16;
static int tile_smallh = 16;
static int tile_bigw = 22;
static int tile_bigh = 22;
static int tile_stweak = -2;
static int tile_btweak = -1;
static const int rack_tiles=7;
const char* sampleWGR=
"wordgame_shapes\n"
"15 15\n"
"400001040100004\n"
"030000000000030\n"
"002002000200200\n"
"000300020003000\n"
"000020000020000\n"
"102001000100201\n"
"000000202000000\n"
"400200050002004\n"
"000000202000000\n"
"102001000100201\n"
"000020000020000\n"
"000300020003000\n"
"002002000200200\n"
"030000000000030\n"
"400001040100004\n"
"1 2 3 66 67 194 100 0\n"
"1 j 8\n"
"1 q 7\n"
"1 x 6\n"
"1 z 6\n"
"1 w 4\n"
"1 k 4\n"
"1 v 3\n"
"1 f 3\n"
"2 y 3\n"
"2 h 2\n"
"2 b 2\n"
"2 m 2\n"
"3 p 2\n"
"3 g 2\n"
"3 u 2\n"
"4 d 2\n"
"4 c 2\n"
"5 l 1\n"
"5 o 1\n"
"7 t 1\n"
"7 n 1\n"
"7 a 1\n"
"7 r 1\n"
"8 s 1\n"
"8 i 1\n"
"11 e 1\n"
"0\n";
WordGame::WordGame( QWidget* parent, const char* name, WFlags fl ) :
QMainWindow(parent, name, fl)
{
if ( qApp->desktop()->width() < 240 ) {
tile_smallw = 10;
tile_smallh = 10;
tile_bigw = 16;
tile_bigh = 16;
tile_stweak = 0;
tile_btweak = 0;
}
setIcon( Resource::loadPixmap( "wordgame/WordGame.png" ) );
setCaption( tr("Word Game") );
setToolBarsMovable( FALSE );
vbox = new QVBox(this);
setCentralWidget(vbox);
toolbar = new QToolBar(this);
addToolBar(toolbar, Bottom);
reset = new QToolButton(Resource::loadPixmap("back"), tr("Back"), "", this, SLOT(resetTurn()), toolbar);
done = new QToolButton(Resource::loadPixmap("done"), tr("Done"), "", this, SLOT(endTurn()), toolbar);
scoreinfo = new ScoreInfo(toolbar);
scoreinfo->setFont(QFont("Helvetica",10));
new QToolButton(Resource::loadPixmap("finish"), tr("Close"), "", this, SLOT(endGame()), toolbar);
toolbar->setStretchableWidget(scoreinfo);
cpu = 0;
board = 0;
bag = 0;
racks = 0;
aiheart = new QTimer(this);
connect(aiheart, SIGNAL(timeout()), this, SLOT(think()));
readConfig();
}
WordGame::~WordGame()
{
writeConfig();
}
void WordGame::writeConfig()
{
Config cfg("WordGame");
cfg.setGroup("Game");
cfg.writeEntry("NameList",namelist,';');
cfg.writeEntry("CurrentPlayer",gameover ? 0 : player+1);
if ( !gameover ) {
cfg.writeEntry("Rules",rules);
bag->writeConfig(cfg);
board->writeConfig(cfg);
scoreinfo->writeConfig(cfg);
}
for (int p=0; p<nplayers; p++) {
cfg.setGroup("Player"+QString::number(p+1));
if ( gameover ) cfg.clearGroup(); else rack(p)->writeConfig(cfg);
}
}
void WordGame::readConfig()
{
Config cfg("WordGame");
cfg.setGroup("Game");
int currentplayer = cfg.readNumEntry("CurrentPlayer",0);
QStringList pnames = cfg.readListEntry("NameList",';');
if ( currentplayer ) {
gameover = FALSE;
rules = cfg.readEntry("Rules");
if ( rules.find("x-wordgamerules") >= 0 ) {
// rules files moved
rules = "Sample.rules";
}
if ( loadRules(rules) ) {
startGame(pnames);
bag->readConfig(cfg);
board->readConfig(cfg);
scoreinfo->readConfig(cfg);
for (int p=0; p<nplayers; p++) {
cfg.setGroup("Player"+QString::number(p+1));
rack(p)->readConfig(cfg);
}
player=currentplayer-1;
readyRack(player);
return;
}
}
// fall-back
openGameSelector(pnames);
}
void WordGame::openGameSelector(const QStringList& initnames)
{
toolbar->hide();
gameover = FALSE;
delete board;
board = 0;
delete racks;
racks = 0;
delete cpu;
cpu = 0;
newgame = new NewGame(vbox);
//Rules rules(this);
//connect(game.editrules, SIGNAL(clicked()), &rules, SLOT(editRules()));
//connect(&rules, SIGNAL(rulesChanged()), &game, SLOT(updateRuleSets()));
struct passwd* n = getpwuid(getuid());
QString playername = n ? n->pw_name : "";
if ( playername.isEmpty() ) {
playername = "Player";
}
newgame->player0->changeItem(playername,0);
newgame->player1->setCurrentItem(1);
newgame->updateRuleSets();
newgame->show();
connect(newgame->buttonOk, SIGNAL(clicked()), this, SLOT(startGame()));
}
void WordGame::startGame()
{
rules = newgame->ruleslist[newgame->rules->currentItem()];
if ( loadRules(rules) ) {
QStringList names;
names.append(newgame->player0->currentText());
names.append(newgame->player1->currentText());
names.append(newgame->player2->currentText());
names.append(newgame->player3->currentText());
names.append(newgame->player4->currentText());
names.append(newgame->player5->currentText());
delete newgame;
startGame(names);
} else {
// error...
delete newgame;
close();
}
}
void WordGame::startGame(const QStringList& playerlist)
{
toolbar->show();
racks = new QWidgetStack(vbox);
racks->setFixedHeight(TileItem::bigHeight()+2);
namelist.clear();
nplayers=0;
for (QStringList::ConstIterator it=playerlist.begin(); it!=playerlist.end(); ++it)
addPlayer(*it);
scoreinfo->init(namelist);
if ( nplayers ) {
player=0;
readyRack(player);
}
board->show();
racks->show();
}
bool WordGame::loadRules(const QString &name)
{
QString filename = Global::applicationFileName( "wordgame", name );
QFile file( filename );
if ( !file.open( IO_ReadOnly ) )
return FALSE;
QTextStream ts( &file );
QString title = name;
title.truncate( title.length() - 6 );
//setCaption( title );
QString shapepixmap;
ts >> shapepixmap;
int htiles,vtiles;
ts >> htiles >> vtiles;
if ( htiles < 3 || vtiles < 3 )
return FALSE;
QString rule_shapes;
for (int i=0; i<vtiles; i++) {
QString line;
ts >> line;
rule_shapes += line;
}
static int rule_effects[12];
int re=0,e;
ts >> e;
while ( e && re < 10 ) {
rule_effects[re] = e;
if ( re++ < 10 ) ts >> e;
}
QImage shim = Resource::loadImage("wordgame/wordgame_shapes");
shim = shim.smoothScale((re-1)*TileItem::smallWidth(),TileItem::smallHeight());
QPixmap bgshapes;
bgshapes.convertFromImage(shim);
rule_effects[re++] = 100; // default bonus
board = new Board(bgshapes, htiles, vtiles, vbox);
board->setRules(rule_shapes, rule_effects);
connect(board, SIGNAL(temporaryScore(int)), scoreinfo, SLOT(showTemporaryScore(int)));
bag = new Bag;
int count;
ts >> count;
while ( count ) {
QString text;
int value;
ts >> text >> value;
if ( text == "_" )
text = "";
Tile t(text, value);
for (int n=count; n--; )
bag->add(t);
ts >> count;
}
return TRUE;
}
NewGame::NewGame(QWidget* parent) :
NewGameBase(parent)
{
}
void NewGame::updateRuleSets()
{
rules->clear();
QString rulesDir = Global::applicationFileName( "wordgame", "" );
QDir dir( rulesDir, "*.rules" );
ruleslist = dir.entryList();
if ( ruleslist.isEmpty() ) {
// Provide a sample
QFile file( rulesDir + "Sample.rules" );
if ( file.open( IO_WriteOnly ) ) {
file.writeBlock( sampleWGR, strlen(sampleWGR) );
file.close();
updateRuleSets();
}
return;
}
int newest=0;
int newest_age=INT_MAX;
QDateTime now = QDateTime::currentDateTime();
QStringList::Iterator it;
for ( it = ruleslist.begin(); it != ruleslist.end(); ++it ) {
QFileInfo fi((*it));
int age = fi.lastModified().secsTo(now);
QString name = *it;
name.truncate( name.length()-6 ); // remove extension
rules->insertItem( name );
if ( age < newest_age ) {
newest_age = age;
newest = rules->count()-1;
}
}
rules->setCurrentItem(newest);
}
Rules::Rules(QWidget* parent) :
RulesBase(parent,0,TRUE)
{
}
void Rules::editRules()
{
if ( exec() ) {
// ### create a new set of rules
emit rulesChanged();
}
}
void Rules::deleteRuleSet()
{
// ### delete existing rule set
emit rulesChanged();
}
void WordGame::addPlayer(const QString& name)
{
if ( !name.isEmpty() ) {
int colon = name.find(':');
int cpu = (colon >=0 && name.left(2) == "AI") ? name.mid(2,1).toInt() : 0;
addPlayer(name,cpu);
}
}
void WordGame::addPlayer(const QString& name, int cpu)
{
Rack* r = new Rack(rack_tiles,racks);
r->setPlayerName(name);
r->setComputerization(cpu);
racks->addWidget(r, nplayers);
refillRack(nplayers);
namelist.append(name);
++nplayers;
}
void WordGame::nextPlayer()
{
if ( !refillRack(player) ) {
endGame();
} else {
player = (player+1)%nplayers;
scoreinfo->setBoldOne(player);
readyRack(player);
}
}
bool WordGame::mayEndGame()
{
int out=-1;
int i;
for (i=0; i<nplayers; i++)
if ( !rack(i)->count() )
out = i;
if ( out<0 ) {
if ( QMessageBox::warning(this,tr("End game"),
tr("Do you want to end the game early?"),
tr("Yes"), tr("No") )!=0 )
{
return FALSE;
}
}
return TRUE;
}
void WordGame::endGame()
{
if ( gameover ) {
close();
return;
}
if ( !mayEndGame() )
return;
int out=-1;
int totalleft=0;
int i;
for (i=0; i<nplayers; i++) {
Rack* r = rack(i);
int c = r->count();
if ( c ) {
int lose=0;
for ( int j=0; j<c; j++ )
lose += r->tileRef(j)->value();
totalleft += lose;
scoreinfo->addScore(i,-lose);
} else {
out = i;
}
}
int highest=0;
int winner=0;
for (i=0; i<nplayers; i++) {
int s = scoreinfo->playerScore(i);
if ( s > highest ) {
highest = s;
winner = i;
}
}
if ( out >= 0 )
scoreinfo->addScore(out,totalleft);
scoreinfo->setBoldOne(winner);
gameover = TRUE;
done->setEnabled(TRUE);
reset->setEnabled(FALSE);
}
void WordGame::endTurn()
{
if ( gameover ) {
openGameSelector(namelist);
} else {
if ( board->checkTurn() ) {
if ( board->turnScore() >= 0 ) {
scoreinfo->addScore(player,board->turnScore());
board->finalizeTurn();
} else {
QApplication::beep();
}
nextPlayer();
}
}
}
void WordGame::resetTurn()
{
board->resetRack();
}
void WordGame::passTurn()
{
// ######## trade?
nextPlayer();
}
bool WordGame::refillRack(int i)
{
Rack* r = rack(i);
while ( !bag->isEmpty() && !r->isFull() ) {
r->addTile(bag->takeRandom());
}
return r->count() != 0;
}
void WordGame::readyRack(int i)
{
Rack* r = rack(i);
racks->raiseWidget(i);
board->setCurrentRack(r);
done->setEnabled( !r->computerized() );
reset->setEnabled( !r->computerized() );
if ( r->computerized() ) {
cpu = new ComputerPlayer(board, r);
aiheart->start(0);
}
}
Rack* WordGame::rack(int i) const
{
return (Rack*)racks->widget(i);
}
void WordGame::think()
{
if ( !cpu->step() ) {
delete cpu;
cpu = 0;
aiheart->stop();
if ( board->turnScore() < 0 )
passTurn();
else
endTurn();
}
}
ComputerPlayer::ComputerPlayer(Board* b, Rack* r) :
board(b), rack(r), best(new const Tile*[rack_tiles]),
best_blankvalues(new Tile[rack_tiles])
{
best_score = -1;
across=FALSE;
dict=0;
}
ComputerPlayer::~ComputerPlayer()
{
delete [] best;
delete [] best_blankvalues;
}
bool ComputerPlayer::step()
{
const QDawg::Node* root = dict ? Global::dawg("WordGame").root()
: Global::fixedDawg().root();
QPoint d = across ? QPoint(1,0) : QPoint(0,1);
const Tile* tiles[99]; // ### max board size
uchar nletter[4095]; // QDawg only handles 0..4095
memset(nletter,0,4096);
for (int i=0; i<rack->count(); i++) {
const Tile* r = rack->tileRef(i);
if ( r->isBlank() )
nletter[0]++;
else
nletter[r->text()[0].unicode()]++;
}
Tile blankvalues[99]; // ### max blanks
findBest(current, d, root, 0, nletter, tiles, 0, blankvalues, 0);
if ( ++current.rx() == board->xTiles() ) {
current.rx() = 0;
if ( ++current.ry() == board->yTiles() ) {
if ( across ) {
if ( dict == 1 ) {
if ( best_score >= 0 ) {
rack->arrangeTiles(best,best_n);
rack->setBlanks(best_blankvalues);
board->scoreTurn(best_start, best_n, best_dir);
board->showTurn();
}
return FALSE;
}
dict++;
across = FALSE;
current = QPoint(0,0);
} else {
across = TRUE;
current = QPoint(0,0);
}
}
}
return TRUE;
}
void ComputerPlayer::findBest(QPoint at, const QPoint& d, const QDawg::Node* node, ulong used, uchar* nletter, const Tile** tiles, int n, Tile* blankvalues, int blused)
{
if ( !node )
return;
QChar l = node->letter();
const Tile* cur = board->tile(at);
if ( cur ) {
if ( cur->text()[0] == l ) {
bool nextok = board->contains(at+d);
if ( node->isWord() && n && (!nextok || !board->tile(at+d)) )
noteChoice(tiles,n,d,blankvalues,blused);
if ( nextok )
findBest(at+d, d, node->jump(), used, nletter, tiles, n, blankvalues, blused);
// #### text()[1]...
}
} else {
if ( nletter[l.unicode()] || nletter[0] ) {
int rc = rack->count();
ulong msk = 1;
for ( int x=0; x<rc; x++ ) {
if ( !(used&msk) ) {
const Tile* t = rack->tileRef(x);
if ( t->isBlank() || t->text() == l ) { // #### multi-char value()s
bool nextok = board->contains(at+d);
tiles[n++] = t;
if ( t->isBlank() )
blankvalues[blused++] = Tile(l,0);
if ( node->isWord() && (!nextok || !board->tile(at+d)) )
noteChoice(tiles,n,d,blankvalues,blused);
used |= msk; // mark
nletter[t->text()[0].unicode()]--;
if ( nextok )
findBest(at+d, d, node->jump(), used, nletter, tiles, n, blankvalues, blused);
n--;
nletter[t->text()[0].unicode()]++;
if ( t->isBlank() ) {
// keep looking
blused--;
used &= ~msk; // unmark
} else {
break;
}
}
}
msk <<= 1;
}
}
// #### text()[1]...
}
findBest(at, d, node->next(), used, nletter, tiles, n, blankvalues, blused);
}
void ComputerPlayer::noteChoice(const Tile** tiles, int n, const QPoint& d, const Tile* blankvalues, int blused)
{
int s = board->score(current, tiles, n, blankvalues, d, TRUE, 0);
/*
if (s>0 || current==QPoint(5,1)){
QString st;
for ( int i=0; i<n; i++ )
st += tiles[i]->text();
qDebug("%d,%d: %s (%d) for %d",current.x(),current.y(),st.latin1(),n,s);
}
*/
if ( s > best_score ) {
int i;
for ( i=0; i<n; i++ )
best[i] = tiles[i];
for ( i=0; i<blused; i++ )
best_blankvalues[i] = blankvalues[i];
best_n = n;
best_blused = blused;
best_score = s;
best_dir = d;
best_start = current;
}
}
int TileItem::smallWidth()
{
return tile_smallw;
}
int TileItem::smallHeight()
{
return tile_smallh;
}
int TileItem::bigWidth()
{
return tile_bigw;
}
int TileItem::bigHeight()
{
return tile_bigh;
}
void TileItem::setState( State state )
{
hide();
s = state;
show(); // ### use update() in Qt 3.0
}
void TileItem::setTile(const Tile& tile)
{
hide();
t = tile;
show(); // ### use update() in Qt 3.0
}
void TileItem::setBig(bool b)
{
big = b;
}
void TileItem::drawShape(QPainter& p)
{
static QFont *value_font=0;
static QFont *big_font=0;
static QFont *small_font=0;
if ( !value_font ) {
value_font = new QFont("helvetica",8);
if ( TileItem::bigWidth() < 20 ) {
big_font = new QFont("helvetica",12);
small_font = new QFont("helvetica",8);
} else {
big_font = new QFont("smoothtimes",17);
small_font = new QFont("smoothtimes",10);
}
}
QRect area(x(),y(),width(),height());
p.setBrush(s == Floating ? yellow/*lightGray*/ : white);
p.drawRect(area);
if ( big ) {
p.setFont(*value_font);
QString n = QString::number(t.value());
int w = p.fontMetrics().width('1');
int h = p.fontMetrics().height();
w *= n.length();
QRect valuearea(x()+width()-w-1,y()+height()-h,w,h);
p.drawText(valuearea,AlignCenter,n);
p.setFont(*big_font);
area = QRect(x(),y()+tile_btweak,width()-4,height()-1);
} else {
p.setFont(*small_font);
area = QRect(x()+1+tile_stweak,y()+1,width(),height()-3);
}
if ( t.value() == 0 )
p.setPen(darkGray);
p.drawText(area,AlignCenter,t.text().upper());
}
Board::Board(QPixmap bgshapes, int w, int h, QWidget* parent) :
QCanvasView(new QCanvas(bgshapes,w,h, TileItem::smallWidth(), TileItem::smallHeight()),
parent)
{
setFixedSize(w*TileItem::smallWidth(),h*TileItem::smallHeight());
grid = new TileItem*[w*h];
memset(grid,0,w*h*sizeof(TileItem*));
setFrameStyle(0);
setHScrollBarMode(AlwaysOff);
setVScrollBarMode(AlwaysOff);
current_rack = 0;
shown_n = 0;
}
Board::~Board()
{
delete canvas();
}
QSize Board::sizeHint() const
{
return QSize(canvas()->width(),canvas()->height());
}
void Board::writeConfig(Config& cfg)
{
QStringList t;
int n=canvas()->tilesHorizontally()*canvas()->tilesVertically();
for (int i=0; i<n; i++)
t.append( grid[i] ? grid[i]->tile().key() : QString(".") );
cfg.writeEntry("Board",t,';');
}
void Board::readConfig(Config& cfg)
{
clear();
QStringList t = cfg.readListEntry("Board",';');
int i=0;
int h=canvas()->tilesHorizontally();
for (QStringList::ConstIterator it=t.begin(); it!=t.end(); ++it) {
if ( *it != "." ) {
QPoint p(i%h,i/h);
setTile(p,Tile(*it));
}
i++;
}
canvas()->update();
}
void Board::clear()
{
int n=canvas()->tilesHorizontally()*canvas()->tilesVertically();
for (int i=0; i<n; i++) {
delete grid[i];
grid[i]=0;
}
}
void Board::setCurrentRack(Rack* r)
{
turn_score = -1;
current_rack = r;
}
void Board::resetRack()
{
unshowTurn();
canvas()->update();
}
void Board::contentsMousePressEvent(QMouseEvent* e)
{
dragstart = e->pos();
}
void Board::contentsMouseMoveEvent(QMouseEvent* e)
{
if ( current_rack && !current_rack->computerized() ) {
QPoint d = e->pos() - dragstart;
if ( d.x() <= 0 && d.y() <= 0 ) {
// None
resetRack();
} else {
int n;
QPoint start=boardPos(dragstart);
QPoint end=boardPos(e->pos());
QPoint diff=end-start;
QPoint dir;
if ( d.x() > d.y() ) {
n = diff.x()+1;
dir = QPoint(1,0);
} else {
n = diff.y()+1;
dir = QPoint(0,1);
}
unshowTurn();
// Subtract existing tiles from n
QPoint t = start;
for ( int i=n; i--; ) {
if ( contains(t) && tile(t) )
n--;
t += dir;
}
// Move start back to real start
while (contains(start-dir) && tile(start-dir))
start -= dir;
scoreTurn(start, n, dir);
showTurn();
}
}
}
void Board::finalizeTurn()
{
int i=0;
QPoint at = shown_at;
while ( i<shown_n && contains(at) ) {
if ( item(at) && item(at)->state() == TileItem::Floating ) {
current_rack->remove(item(at)->tile());
setTileState(at,TileItem::Firm);
i++;
}
at += shown_step;
}
canvas()->update();
}
void Board::unshowTurn()
{
int i=0;
QPoint at = shown_at;
while ( i<shown_n && i<current_rack->count() && contains(at) ) {
if ( item(at) && item(at)->state() == TileItem::Floating ) {
unsetTile(at);
i++;
}
at += shown_step;
}
}
void Board::showTurn()
{
unshowTurn();
QPoint at = shown_at;
int i=0;
while ( i<shown_n && i<current_rack->count() && contains(at) ) {
if ( !tile(at) ) {
Tile t = current_rack->tile(i);
setTile(at,t);
setTileState(at,TileItem::Floating);
i++;
}
at += shown_step;
}
canvas()->update();
}
int Board::bonussedValue(const QPoint& at, int base, int& all_mult) const
{
int rule = rule_shape[idx(at)]-'0';
int effect = rule_effect[rule];
int mult = effect&Multiplier;
if ( effect & MultiplyAll ) {
all_mult *= mult;
return base;
} else {
return base * mult;
}
}
bool Board::isStart(const QPoint& at) const
{
int rule = rule_shape[idx(at)]-'0';
int effect = rule_effect[rule];
return effect&Start;
}
bool Board::checkTurn()
{
if ( current_rack->computerized() )
return TRUE; // computer doesn't cheat, and has already set blanks.
QPoint at = shown_at;
int n = shown_n;
QPoint d = shown_step;
const Tile* tiles[99];
Tile blankvalues[99];
if ( n > current_rack->count() )
n = current_rack->count();
QDialog check(this,0,TRUE);
(new QVBoxLayout(&check))->setAutoAdd(TRUE);
QHBox mw(&check);
new QLabel(tr("Blanks: "),&mw);
int bl=0;
QLineEdit* le[99];
for (int i=0; i<n; i++) {
tiles[i] = current_rack->tileRef(i);
if ( tiles[i]->isBlank() ) {
QLineEdit *l = new QLineEdit(&mw);
le[bl++] = l;
l->setMaxLength(1);
l->setFixedSize(l->minimumSizeHint());
}
}
QHBox btns(&check);
connect(new QPushButton(tr("OK"),&btns), SIGNAL(clicked()), &check, SLOT(accept()));
connect(new QPushButton(tr("Cancel"),&btns), SIGNAL(clicked()), &check, SLOT(reject()));
if ( bl ) {
retry:
if ( !check.exec() ) {
unshowTurn();
canvas()->update();
return FALSE;
}
for (int b=0; b<bl; b++) {
QString v = le[b]->text();
blankvalues[b]=Tile(v,0);
if ( v.length() != 1 )
goto retry;
}
}
QStringList words;
unshowTurn();
turn_score = score(at,tiles,n,blankvalues,d,FALSE,&words);
showTurn();
QStringList to_add;
for (QStringList::Iterator it=words.begin(); it!=words.end(); ++it) {
if ( !Global::fixedDawg().contains(*it)
&& !Global::dawg("WordGame").contains(*it) ) {
switch (QMessageBox::warning(this, tr("Unknown word"),
tr("<p>The word \"%1\" is not in the dictionary.").arg(*it),
tr("Add"), tr("Ignore"), tr("Cancel")))
{
case 0:
// ####### add to wordgame dictionary
to_add.append(*it);
break;
case 1:
break;
case 2:
unshowTurn();
canvas()->update();
return FALSE;
}
}
}
if ( to_add.count() )
Global::addWords("WordGame",to_add);
return TRUE;
}
void Board::scoreTurn(const QPoint& at, int n, const QPoint& d)
{
unshowTurn();
shown_at = at;
shown_n = n;
shown_step = d;
const Tile* tiles[99];
if ( n > current_rack->count() )
n = current_rack->count();
for (int i=0; i<n; i++)
tiles[i] = current_rack->tileRef(i);
turn_score = score(at,tiles,n,0,d,FALSE,0);
emit temporaryScore(turn_score);
}
int Board::score(QPoint at, const Tile** tiles, int n, const Tile* blankvalue, const QPoint& d, bool checkdict, QStringList* words) const
{
int total=0;
int totalsidetotal=0;
// words gets filled with words made
// mainword==0 ->
// Checks side words, but not main word
// -1 means words not in dict, or illegally positioned (eg. not connected)
// text is assumed to fit on board.
if ( words ) *words=QStringList();
QPoint otherd(d.y(), d.x());
int all_mult = 1;
int bl=0;
bool connected = FALSE;
QString mainword="";
if ( contains(at-d) && tile(at-d) ) {
return -1; // preceeding tiles
}
const Tile* t;
for (int i=0; contains(at) && ((t=tile(at)) || i<n); ) {
if ( t ) {
if ( checkdict || words ) mainword += t->text();
total += t->value();
connected = TRUE;
} else {
QString sideword;
QString tt;
if ( tiles[i]->isBlank() ) {
if ( blankvalue )
tt = blankvalue[bl++].text();
} else {
tt = tiles[i]->text();
}
sideword=tt;
if ( checkdict || words ) mainword += tt;
int side_mult = 1;
int tilevalue = bonussedValue(at,tiles[i]->value(),side_mult);
all_mult *= side_mult;
if ( !connected && isStart(at) )
connected = TRUE;
total += tilevalue;
int sidetotal = tilevalue;
{
QPoint side = at-otherd;
while ( contains(side) && (t=tile(side)) ) {
sidetotal += t->value();
sideword.prepend(t->text());
side -= otherd;
}
}
{
QPoint side = at+otherd;
while ( contains(side) && (t=tile(side)) ) {
sidetotal += t->value();
sideword.append(t->text());
side += otherd;
}
}
if ( sideword.length() > 1 ) {
if ( words )
words->append(sideword);
if ( checkdict && !Global::fixedDawg().contains(sideword)
&& !Global::dawg("WordGame").contains(sideword) )
return -1;
totalsidetotal += sidetotal * side_mult;
connected = TRUE;
}
i++;
}
at += d;
}
if ( words )
words->append(mainword);
if ( checkdict && !Global::fixedDawg().contains(mainword)
&& !Global::dawg("WordGame").contains(mainword) )
return -1;
if ( n == rack_tiles )
totalsidetotal += rack_tiles_bonus;
return connected ? totalsidetotal + total * all_mult : -1;
}
QPoint Board::boardPos(const QPoint& p) const
{
return QPoint(p.x()/canvas()->tileWidth(), p.y()/canvas()->tileHeight());
}
void Board::contentsMouseReleaseEvent(QMouseEvent*)
{
if ( current_rack ) {
}
}
void Board::setRules(const QString& shapes, const int* effects)
{
rule_shape=shapes; rule_effect=effects;
int i=0;
int maxre=0;
for (int y=0; y<yTiles(); y++) {
for (int x=0; x<xTiles(); x++) {
int re = shapes[i++]-'0';
if ( re > maxre ) maxre = re;
canvas()->setTile(x,y,re);
}
}
rack_tiles_bonus=effects[maxre+1];
}
void Board::unsetTile(const QPoint& p)
{
delete item(p);
grid[idx(p)] = 0;
}
void Board::setTile(const QPoint& p, const Tile& t)
{
TileItem* it=item(p);
if ( !it ) {
it = grid[idx(p)] = new TileItem(t,FALSE,canvas());
it->move(p.x()*canvas()->tileWidth(), p.y()*canvas()->tileHeight());
it->show();
} else {
it->setTile(t);
}
}
Rack::Rack(int ntiles, QWidget* parent) : QCanvasView(
new QCanvas(ntiles*TileItem::bigWidth(),TileItem::bigHeight()),
parent),
item(ntiles)
{
setLineWidth(1);
setFixedHeight(sizeHint().height());
n = 0;
for (int i=0; i<ntiles; i++)
item[i]=0;
setHScrollBarMode(AlwaysOff);
setVScrollBarMode(AlwaysOff);
canvas()->setBackgroundColor(gray);
dragging = 0;
}
Rack::~Rack()
{
clear();
delete canvas();
}
QSize Rack::sizeHint() const
{
return QSize(-1,TileItem::bigHeight()+2);
}
void Rack::clear()
{
for (int i=0; i<n; i++)
delete item[i];
n=0;
}
void Rack::writeConfig(Config& cfg)
{
QStringList l;
for (int i=0; i<n; i++)
l.append(tile(i).key());
cfg.writeEntry("Tiles",l,';');
}
void Rack::readConfig(Config& cfg)
{
clear();
int x=0;
QStringList l = cfg.readListEntry("Tiles",';');
for (QStringList::ConstIterator it=l.begin(); it!=l.end(); ++it) {
TileItem *i = new TileItem(Tile(*it),TRUE,canvas());
i->move(x++,0);
i->show();
item[n++] = i;
}
layoutTiles();
}
static int cmp_tileitem(const void *a, const void *b)
{
const TileItem* ia = *(TileItem**)a;
const TileItem* ib = *(TileItem**)b;
return int(ia->x() - ib->x());
}
void Rack::layoutTiles()
{
int w = TileItem::bigWidth()+2;
if ( dragging ) dragging->moveBy(dragging_adj,0);
qsort(item.data(), n, sizeof(TileItem*), cmp_tileitem);
if ( dragging ) dragging->moveBy(-dragging_adj,0);
for (int i=0; i<n ;i++)
if ( item[i] == dragging ) {
item[i]->setZ(1);
} else {
item[i]->move(i*w, 0);
item[i]->setZ(0);
}
canvas()->update();
}
void Rack::setBlanks(const Tile* bv)
{
for (int j=0; j<n; j++) {
Tile tt = item[j]->tile();
if ( tt.isBlank() ) {
tt.setText(bv->text());
item[j]->setTile(tt);
bv++;
}
}
}
bool Rack::arrangeTiles(const Tile** s, int sn)
{
bool could = TRUE;
for (int j=0; j<n; j++) {
Tile tt = item[j]->tile();
int f=-1;
for (int i=0; i<sn && f<0; i++) {
if (s[i] && *s[i] == tt ) {
s[i]=0;
f=i;
}
}
if ( f >= 0 ) {
item[j]->move(f-999,0);
} else {
could = FALSE;
}
}
layoutTiles();
return could;
}
void Rack::addTile(const Tile& t)
{
TileItem *i = new TileItem(t,TRUE,canvas());
i->show();
item[n++] = i;
layoutTiles();
}
void Rack::remove(Tile t)
{
for (int i=0; i<n ;i++)
if ( item[i]->tile() == t ) {
remove(i);
return;
}
}
void Rack::remove(int i)
{
delete item[i];
n--;
for (;i<n;i++)
item[i]=item[i+1];
layoutTiles();
}
void Rack::resizeEvent(QResizeEvent* e)
{
canvas()->resize(width()-frameWidth()*2,height()-frameWidth()*2);
QCanvasView::resizeEvent(e);
}
void Rack::contentsMousePressEvent(QMouseEvent* e)
{
if ( computerized() )
return;
QCanvasItemList list = canvas()->collisions(e->pos());
if (list.count()) {
dragging = list.first();
dragstart = e->pos()-QPoint(int(dragging->x()),int(dragging->y()));
} else {
dragging = 0;
}
}
void Rack::contentsMouseMoveEvent(QMouseEvent* e)
{
if ( computerized() )
return;
//int w = TileItem::bigWidth()+2;
if ( dragging ) {
dragging_adj = TileItem::bigWidth()/2;
if ( dragging->x() > e->x()-dragstart.x() )
dragging_adj = -dragging_adj;
dragging->move(e->x()-dragstart.x(),0);
layoutTiles();
}
}
void Rack::contentsMouseReleaseEvent(QMouseEvent* e)
{
if ( computerized() )
return;
if ( dragging ) {
dragging=0;
layoutTiles();
}
}
Tile::Tile(const QString& key)
{
int a=key.find('@');
txt = key.left(a);
val = key.mid(a+1).toInt();
blank = txt.isEmpty();
}
QString Tile::key() const
{
return txt+"@"+QString::number(val);
}
Bag::Bag()
{
tiles.setAutoDelete(TRUE);
}
void Bag::writeConfig(Config& cfg)
{
QStringList t;
for (QListIterator<Tile> it(tiles); it; ++it)
t.append((*it)->key());
cfg.writeEntry("Tiles",t,';');
}
void Bag::readConfig(Config& cfg)
{
tiles.clear();
QStringList t = cfg.readListEntry("Tiles",';');
for (QStringList::ConstIterator it=t.begin(); it!=t.end(); ++it )
add(Tile(*it));
}
void Bag::add(const Tile& t)
{
tiles.append(new Tile(t));
}
Tile Bag::takeRandom()
{
Tile* rp = tiles.take(random()%tiles.count());
Tile r=*rp;
return r;
}
ScoreInfo::ScoreInfo( QWidget* parent, const char* name, WFlags fl ) :
QLabel("<P>",parent,name,fl)
{
score=0;
msgtimer = new QTimer(this);
connect(msgtimer, SIGNAL(timeout()), this, SLOT(showScores()));
setBackgroundMode( PaletteButton );
}
ScoreInfo::~ScoreInfo()
{
if ( score ) delete [] score;
}
void ScoreInfo::writeConfig(Config& cfg)
{
QStringList l;
for (int i=0; i<(int)names.count(); i++)
l.append(QString::number(score[i]));
cfg.writeEntry("Scores",l,';');
}
void ScoreInfo::readConfig(Config& cfg)
{
QStringList l = cfg.readListEntry("Scores",';');
int i=0;
for (QStringList::ConstIterator it=l.begin(); it!=l.end(); ++it )
score[i++]=(*it).toInt();
showScores();
}
QSize ScoreInfo::sizeHint() const
{
return QSize(QLabel::sizeHint().width(),fontMetrics().height());
}
void ScoreInfo::init(const QStringList& namelist)
{
names = namelist;
if ( score ) delete [] score;
score = new int[names.count()];
memset(score,0,sizeof(int)*names.count());
boldone = -1;
showScores();
}
void ScoreInfo::addScore(int player, int change)
{
score[player] += change;
showScores();
}
void ScoreInfo::setBoldOne(int b)
{
boldone=b;
showScores();
}
void ScoreInfo::showScores()
{
QString r="<p>";
int i=0;
//int spl=(names.count()+1)/2; // 2 lines
for (QStringList::ConstIterator it=names.begin(); it!=names.end(); ) {
if ( i==boldone ) r += "<b>";
QString n = *it;
n.replace(QRegExp(":.*"),"");
r += n;
r += ":";
r += QString::number(score[i]);
if ( i==boldone ) r += "</b>";
++i;
++it;
if ( it != names.end() )
r += " ";
}
setText(r);
}
void ScoreInfo::showTemporaryScore(int amount)
{
if ( amount < 0 )
setText(tr("<P>Invalid move"));
else
setText(tr("<P>Score: ")+QString::number(amount));
msgtimer->start(3000,TRUE);
}
diff --git a/noncore/games/zlines/ballpainter.cpp b/noncore/games/zlines/ballpainter.cpp
index c2b34e1..622ec29 100644
--- a/noncore/games/zlines/ballpainter.cpp
+++ b/noncore/games/zlines/ballpainter.cpp
@@ -1,135 +1,132 @@
/***************************************************************************
ballpainter.cpp - description
-------------------
begin : Fri May 19 2000
copyright : (C) 2000 by Roman Merzlyakov
email : roman@sbrf.barrt.ru
copyright : (C) 2000 by Roman Razilov
email : Roman.Razilov@gmx.de
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include <qpe/resource.h>
-#include <qapplication.h>
#include "ballpainter.h"
//#include "shotcounter.h"
#include <qpainter.h>
-#include "linesboard.h"
//#include <qcolor.h>
-#include <qjpegio.h>
#define PIXSIZE 21
int colorLinesArr[NCOLORS] =
{0x0000ff, 0x00ff00, 0xff0000, 0x00ffff, 0xff00ff, 0xffff00, 0x005080};
// 0x00bbggrr
// red , green , blue , yellow , violet , cyan , brown
BallPainter::BallPainter()
: QObject()
{
createPixmap();
}
BallPainter::~BallPainter()
{
}
QPixmap* BallPainter::pixmap( enum Pixmaps pix )
{
QString name;
switch(pix) {
case Field:
name = QString::fromLatin1("zlines/field");
break;
case Balls:
name = QString::fromLatin1("zlines/balls");
break;
case Fire:
name = QString::fromLatin1("zlines/fire");
break;
}
return new QPixmap(Resource::loadPixmap(name) );
}
void BallPainter::createPixmap()
{
// warning( kapp->kde_datadir() +"/klines/data/balls.bmp");
backgroundPix = pixmap(Field);
QPixmap *balls = pixmap(Balls);
QPixmap *fire = pixmap(Fire);
if (balls->isNull() ||backgroundPix->isNull() || fire->isNull() )
fatal("Cannot open data files.\nHave you correctly installed klines?");
warning("Pixsize %i", PIXSIZE);
for(int c=0; c<NCOLORS; c++)
{
for(int t=0; t<PIXTIME + FIREBALLS + BOOMBALLS + 1 ; t++)
{
imgCash[c][t] = new QPixmap(CELLSIZE, CELLSIZE);
QPainter p(imgCash[c][t]);
p.drawPixmap(0,0,(*backgroundPix),0,0,CELLSIZE,CELLSIZE);
p.drawPixmap(1,1,(*balls),t*PIXSIZE,c*PIXSIZE,PIXSIZE,PIXSIZE);
}
for(int t=0; t < FIREPIX ; t++)
{
firePix[t] = new QPixmap(CELLSIZE, CELLSIZE);
QPainter p(firePix[t]);
p.drawPixmap(0,0,(*backgroundPix),0,0,CELLSIZE,CELLSIZE);
p.drawPixmap(1,1,(*fire),t*PIXSIZE,0,PIXSIZE,PIXSIZE);
}
}
delete balls;
delete fire;
}
QPixmap* BallPainter::GetBall(int color, int animstep, int panim)
{
// return backgroundPix;
if( (color<0) || (color>=NCOLORS) || (animstep<0) || color == NOBALL )
{
// warning("BallPainter::Background");
return backgroundPix;
}
if ( panim == ANIM_JUMP )
{
if ( ( animstep < 0 ) || ( animstep >= PIXTIME ) )
return backgroundPix;
else
return imgCash[color][animstep];
}
else if ( panim == ANIM_BURN )
{
if ( animstep < FIREBALLS )
return imgCash[color][animstep + PIXTIME + BOOMBALLS + 1];
else if ( animstep < FIREBALLS + FIREPIX )
return firePix[animstep - FIREBALLS];
}
else if ( panim == ANIM_BORN )
{
if ( animstep < BOOMBALLS )
return imgCash[color][animstep + PIXTIME];
else
return imgCash[color][NORMALBALL];
}
// rest is not imlemented yet
return imgCash[color][NORMALBALL];
}
diff --git a/noncore/games/zlines/field.cpp b/noncore/games/zlines/field.cpp
index 2a87739..0adf4ac 100644
--- a/noncore/games/zlines/field.cpp
+++ b/noncore/games/zlines/field.cpp
@@ -1,132 +1,131 @@
/***************************************************************************
field.cpp - description
-------------------
begin : Fri May 19 2000
copyright : (C) 2000 by Roman Merzlyakov
email : roman@sbrf.barrt.ru
copyright : (C) 2000 by Roman Razilov
email : Roman.Razilov@gmx.de
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include <stdlib.h>
-#include "cfg.h"
#include "field.h"
Field::Field(QWidget* parent, const char* name)
: QWidget( parent, name )
{
clearField();
}
Field::~Field()
{
}
void Field::clearField()
{
for(int y=0; y<NUMCELLSH; y++)
for(int x=0; x<NUMCELLSW; x++)
field[y][x].clear();
}
void Field::clearAnim()
{
for(int y=0; y<NUMCELLSH; y++)
for(int x=0; x<NUMCELLSW; x++)
field[y][x].setAnim( ANIM_NO );
}
int Field::deleteAnimatedBalls()
{
int deleted = 0;
for(int y=0; y<NUMCELLSH; y++)
for(int x=0; x<NUMCELLSW; x++)
{
if ( field[y][x].getAnim() != ANIM_NO )
{
deleted++;
field[y][x].clear();
}
}
return deleted;
}
bool Field::checkBounds(int x, int y)
{
return (x>=0) && (x<NUMCELLSW) && (y>=0) && (y<NUMCELLSH);
}
void Field::putBall(int x, int y, int color)
{
if( checkBounds(x,y) )
field[y][x].setColor(color);
}
/*
void Field::putBall(int x, int y, char color)
{
if( checkBounds(x,y) ){
field[y][x].setColor(color);
erase5Balls();
repaint(FALSE);
}
}*/
void Field::moveBall(int xa, int ya, int xb, int yb)
{
if( checkBounds(xa,ya) && checkBounds(xb,yb) &&
field[yb][xb].isFree() && ( xa != xb || ya != yb) ) {
field[yb][xb].moveBall(field[ya][xa]);
}
}
int Field::getBall(int x, int y)
{
if( checkBounds(x,y) )
return field[y][x].getColor();
else
return NOBALL;
}
int Field::getAnim(int x, int y)
{
if( checkBounds(x,y) )
return field[y][x].getAnim();
else
return NOBALL;
}
void Field::setAnim(int x, int y, int anim)
{
if( checkBounds(x,y) )
field[y][x].setAnim( anim );
}
void Field::removeBall(int x, int y )
{
if( checkBounds(x,y) ) field[y][x].clear();
}
int Field::freeSpace()
{
int s = 0;
for(int y=0; y<NUMCELLSH; y++)
for(int x=0; x<NUMCELLSW; x++)
if(field[y][x].isFree()) s++;
return s;
}
void Field::saveUndo()
{
void clearAnim();
for(int y=0; y<NUMCELLSH; y++)
for(int x=0; x<NUMCELLSW; x++)
field_undo[y][x] = field[y][x];
}
void Field::restoreUndo()
{
for(int y=0; y<NUMCELLSH; y++)
for(int x=0; x<NUMCELLSW; x++)
field[y][x] = field_undo[y][x];
}
diff --git a/noncore/games/zlines/klines.cpp b/noncore/games/zlines/klines.cpp
index 02ff0db..76c94e2 100644
--- a/noncore/games/zlines/klines.cpp
+++ b/noncore/games/zlines/klines.cpp
@@ -1,214 +1,205 @@
/***************************************************************************
klines.cpp - description
-------------------
begin : Fri May 19 2000
copyright : (C) 2000 by Roman Merzlyakov
email : roman@sbrf.barrt.ru
copyright : (C) 2000 by Roman Razilov
email : Roman.Razilov@gmx.de
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
/* changes
21.05.2000 Roman Razilov Menu game/Next
*/
//
// The implementation of the KLines widget
//
-#include <qkeycode.h>
-#include <qlabel.h>
-#include <qpushbutton.h>
-#include <qtooltip.h>
-#include <qstring.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <qapplication.h>
-#include <qmenubar.h>
-#include <qpopupmenu.h>
-#include "cfg.h"
-#include <qstatusbar.h>
#include "klines.h"
/*
Creates the KLines widget and sets saved options (if any).
*/
KLines::KLines(QWidget *par, const char* n, WFlags fl) : QMainWindow(par,n,fl)
{
time_t t;
time(&t);
srand((unsigned int)t + getpid());
setCaption(QString("ZLines"));
mwidget = new MainWidget(this);
setCentralWidget( mwidget );
lsb = mwidget->GetLsb();
lPrompt = mwidget->GetPrompt();
menu = menuBar();
game = new QPopupMenu;
edit = new QPopupMenu;
game->insertItem(tr("&New game"), this, SLOT(stopGame()), CTRL+Key_N );
game->insertSeparator();
game->insertItem(tr("Ne&xt"), this, SLOT(makeTurn()), Key_N );
game->insertSeparator();
idMenuPrompt = game->insertItem( tr("&Show next"), this, SLOT(switchPrompt()), CTRL+Key_P );
game->setCheckable(true);
game->setItemChecked(idMenuPrompt, lPrompt->getState());
game->insertSeparator();
game->insertItem(tr("&Quit"), qApp, SLOT(quit()), CTRL+Key_Q );
idMenuUndo = edit->insertItem(tr("Und&o"), this, SLOT(undo()), CTRL+Key_Z );
menu->insertItem( tr("&Game"), game );
menu->insertItem( tr("&Edit"), edit );
menu->show();
score = 0;
prev_score = 0;
mwidget->setMessage(tr("Points: 0"));
startGame();
}
/*
Saves the options and destroys the KLines widget.
*/
KLines::~KLines()
{
}
/*
Resize event of the KLines widget.
*/
void KLines::resizeEvent( QResizeEvent *e )
{
QMainWindow::resizeEvent(e);
}
void KLines::setMinSize()
{
// setMinimumSize( gr->wHint(), gr->hHint() + menu->height() + stat->height() +
// tool->height() );
}
void KLines::startGame()
{
score = 0;
prev_score = 0;
bUndo=TRUE;
lsb->clearField();
generateRandomBalls();
placeBalls();
generateRandomBalls();
edit->setItemEnabled(idMenuUndo, FALSE );
updateStat();
}
void KLines::stopGame()
{
debug("Klines::stopGame");
endGame();
}
void KLines::searchBallsLine()
{
}
void KLines::generateRandomBalls()
{
for( int i = 0 ; i < BALLSDROP ; i++ )
{
nextBalls_undo[i] = nextBalls[i];
nextBalls[i] = bUndo ?
rand() % NCOLORS:
nextBalls_redo[i];
}
lPrompt->SetBalls(nextBalls);
}
void KLines::placeBalls()
{
lsb->placeBalls(nextBalls);
debug("exit from placeBalls");
}
void KLines::undo()
{
debug("Undo");
if (!bUndo)
return;
for( int i = 0 ; i < BALLSDROP ; i++ )
{
nextBalls_redo[i] = nextBalls[i];
nextBalls[i] = nextBalls_undo[i];
}
lPrompt->SetBalls(nextBalls);
lsb->undo();
switchUndo(FALSE);
}
void KLines::makeTurn()
{
placeBalls();
generateRandomBalls();
switchUndo(TRUE);
}
void KLines::addScore(int ballsErased)
{ if(ballsErased >= 5){
score += 2*ballsErased*ballsErased - 20*ballsErased + 60 ;
if( !lPrompt->getState() ) score+= 1;
updateStat();
};
}
void KLines::updateStat()
{
mwidget->setMessage(tr(" Score: %1 ").arg(score));
}
void KLines::endGame()
{
startGame();
}
void KLines::switchPrompt()
{
lPrompt->setPrompt(!lPrompt->getState());
game->setItemChecked(idMenuPrompt, lPrompt->getState());
}
void KLines::switchUndo(bool bu)
{
bUndo = bu;
edit->setItemEnabled(idMenuUndo, bUndo );
}
void KLines::help()
{
// KApplication::getKApplication()->invokeHTMLHelp("", "");
}
diff --git a/noncore/games/zlines/linesboard.cpp b/noncore/games/zlines/linesboard.cpp
index 0965b2c..1e59aeb 100644
--- a/noncore/games/zlines/linesboard.cpp
+++ b/noncore/games/zlines/linesboard.cpp
@@ -1,591 +1,588 @@
/***************************************************************************
linesboard.cpp - description
-------------------
begin : Fri May 19 2000
copyright : (C) 2000 by Roman Merzlyakov
email : roman@sbrf.barrt.ru
copyright : (C) 2000 by Roman Razilov
email : Roman.Razilov@gmx.de
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include <qpainter.h>
-#include <qpixmap.h>
-#include <qcolor.h>
-#include <qkeycode.h>
#include <stdlib.h>
#include "linesboard.h"
/*
Constructs a LinesBoard widget.
*/
LinesBoard::LinesBoard( BallPainter * abPainter, QWidget* parent, const char* name )
: Field( parent, name )
{
anim = ANIM_NO;
// waypos = 0;
// waylen = 0;
// jumpingRow = -1;
// jumpingCol = -1;
painting = 0;
way = new Waypoints[NUMCELLSW*NUMCELLSH];
bPainter = abPainter;
setFocusPolicy( NoFocus );
setBackgroundColor( gray );
setMouseTracking( FALSE );
setFixedSize(wHint(), hHint());
timer = new QTimer(this);
connect( timer, SIGNAL(timeout()), SLOT(timerSlot()) );
timer->start( TIMERCLOCK, FALSE );
}
/*
Destructor: deallocates memory for contents
*/
LinesBoard::~LinesBoard()
{
// debug("stop");
timer->stop();
delete timer;
delete []way;
}
void LinesBoard::placeBalls(int pnextBalls[BALLSDROP])
{
debug("LinesBoard::placeBalls( )");
for(int i=0; i < BALLSDROP; i++){
nextBalls[i] = pnextBalls[i];
}
nextBallToPlace = 0;
placeBall();
debug("LinesBoard::placeBalls End ");
}
void LinesBoard::placeBall( )
{
int color = nextBalls[nextBallToPlace];
debug("LinesBoard::placeBall( ) color=%i, nextBallToPlace = %i", color, nextBallToPlace);
char* xx = (char*)malloc( sizeof(char)*NUMCELLSW*NUMCELLSH );
char* yy = (char*)malloc( sizeof(char)*NUMCELLSW*NUMCELLSH );
// int nb=3;
// if( freeSpace() < 3) nb = freeSpace();
int empty=0;
for(int y=0; y<NUMCELLSH; y++)
for(int x=0; x<NUMCELLSW; x++)
if( getBall(x,y) == NOBALL )
{
xx[empty] = x;
yy[empty] = y;
empty++;
};
// debug("empty = %i",empty);
if ( empty > 0)
{
int pos = rand()%empty;
putBall( xx[pos], yy[pos], color );
clearAnim();
setAnim( xx[pos], yy[pos], ANIM_BORN );
nextBallToPlace++;
AnimStart(ANIM_BORN);
free(xx);
free(yy);
}
else
{
free(xx);
free(yy);
emit endGame();
}
debug("LinesBoard::placeBall END");
}
/*id LinesBoard::doAfterBalls() {
erase5Balls();
repaint(FALSE);
}
*/
/*
Sets the size of the table
*/
int LinesBoard::width() { return CELLSIZE * NUMCELLSW; }
int LinesBoard::height() { return CELLSIZE * NUMCELLSH; }
int LinesBoard::wHint() { return width(); }
int LinesBoard::hHint() { return height(); }
void LinesBoard::paintEvent( QPaintEvent* )
{
// debug("LinesBoard::paintEvent ");
QPixmap pixmap(width(), height());
QPainter paint(&pixmap, this);
for( int y=0; y < NUMCELLSH; y++ ){
for( int x=0; x < NUMCELLSW; x++ ){
if( getBall(x,y) == NOBALL )
{
// debug("draw empty %i %i", x, y );
paint.drawPixmap(x*CELLSIZE, y*CELLSIZE, *(bPainter->GetBackgroundPix()) );
}
else
{
// debug("draw empty %i %i %c", x, y, getBall(x,y) );
paint.drawPixmap(x*CELLSIZE, y*CELLSIZE,
*(bPainter->GetBall(getBall(x,y),animstep,getAnim(x,y))));
}
}
}
bitBlt(this, 0,0, &pixmap, 0,0, width(), height(), CopyROP);
}
/*
Handles mouse press events for the LinesBoard widget.
*/
void LinesBoard::mousePressEvent( QMouseEvent* e )
{
debug("LinesBoard::mousePressEvent START");
int curRow = e->y() / CELLSIZE;
int curCol = e->x() / CELLSIZE;
//debug
debug("Mouse pressed: curRow=%i, curCol=%i", curRow, curCol);
//check range
if (!checkBounds( curCol, curRow ) )
return;
// if( running || anim != ANIM_NO ) return;
if(anim != ANIM_JUMP && anim != ANIM_NO) return;
if ( anim == ANIM_JUMP )
{
if ( getBall(curCol,curRow) == NOBALL )
{
if(existPath(jumpingCol, jumpingRow, curCol, curRow))
{
saveUndo();
AnimStart(ANIM_RUN);
}
}
else
AnimJump(curCol,curRow);
}
else
AnimJump(curCol,curRow);
debug("LinesBoard::mousePressEvent END");
}
void LinesBoard::AnimJump(int x, int y ) {
debug("LinesBoard::AnimJump( %i,%i)", x,y );
if ( getBall(x,y) != NOBALL )
if (!( anim == ANIM_JUMP && jumpingCol == x && jumpingRow == y ))
if ( AnimEnd() )
{
clearAnim();
setAnim(x,y,ANIM_JUMP);
jumpingCol = x;
jumpingRow = y;
AnimStart(ANIM_JUMP);
}
debug("LinesBoard::AnimJump END");
}
void LinesBoard::AnimStart(int panim) {
debug("LinesBoard::AnimStart( %i )", panim);
if (anim != ANIM_NO)
AnimEnd();
animstep = 0;
animdelaystart = 1;
switch(panim) {
case ANIM_NO:
break;
case ANIM_BORN:
debug("LinesBoard::AnimStart( ANIM_BORN )");
animdelaystart=1;
animmax = BOOMBALLS;
break;
case ANIM_JUMP:
direction = -1;
animstep = 4;
animmax = PIXTIME -1;
break;
case ANIM_RUN:
animdelaystart=3;
// do first step on next timer;
animdelaycount = 0;
// animmax already set
break;
case ANIM_BURN:
animdelaystart=1;
animmax = FIREBALLS + FIREPIX - 1;
break;
default:
;
}
anim = panim;
animdelaycount = animdelaystart;
debug("LinesBoard::AnimStart END");
}
int LinesBoard::AnimEnd( )
{
debug("LinesBoard::AnimEnd( %i )",anim );
if (anim == ANIM_NO ) return true;
int oldanim = anim;
anim = ANIM_NO;
if (oldanim == ANIM_RUN) {
if (animstep != animmax) {
moveBall(way[animstep].x,way[animstep].y,way[animmax].x,way[animmax].y);
}
if ( erase5Balls() == 0 ) {
// debug("end turn");
emit endTurn();
debug("LinesBoard::AnimEnd END true 1");
return true;
}
else
debug("LinesBoard::AnimEnd END false 2");
return false;
} else if ( oldanim == ANIM_BURN )
{
emit eraseLine( deleteAnimatedBalls() );
repaint(FALSE);
if ( nextBallToPlace < BALLSDROP )
{
placeBall();
// continue with born
debug("LinesBoard::AnimEnd END false 3");
return false;
}
else
{
// emit endTurn();
debug("LinesBoard::AnimEnd END true 4");
return true;
}
} else if ( oldanim == ANIM_BORN )
{
if ( erase5Balls() == 0 )
{
if ( freeSpace() > 0)
{
if ( nextBallToPlace < BALLSDROP )
{
placeBall();
debug("LinesBoard::AnimEnd END false 5");
return false;
}
else
{
debug("LinesBoard::AnimEnd END true 6");
return true;
}
}
else
{
debug("emit endGame");
emit endGame();
debug("LinesBoard::AnimEnd END false 7");
return false;
}
}
else
{
// wait for user input
debug("LinesBoard::AnimEnd END true 8");
return true;
}
}
else
{
debug("LinesBoard::AnimEnd END true");
return true;
}
return true;
}
void LinesBoard::AnimNext() {
if ( anim != ANIM_NO )
{
debug("LinesBoard::AnimNext( ) anim %i animstep %i",anim,animstep);
if ( anim == ANIM_JUMP ) {
if ( (direction > 0 && animstep == animmax) || ( direction < 0 && animstep == 0))
direction = -direction;
animstep += direction;
repaint(FALSE);
} else {
if ( animstep >= animmax )
AnimEnd();
else {
animdelaycount--;
if (animdelaycount <= 0) {
debug("LinesBoard::AnimNext step %i", animstep);
if ( anim == ANIM_RUN )
moveBall(way[animstep].x,way[animstep].y,way[animstep+1].x,way[animstep+1].y);
animstep++;
animdelaycount = animdelaystart;
repaint( FALSE );
}
}
}
debug("LinesBoard::AnimNext END");
}
}
int LinesBoard::getAnim( int x, int y )
{
// debug("LinesBoard::getAnim( %i,%i )",x,y);
return (( Field::getAnim(x,y) != ANIM_NO )? anim : ANIM_NO);
}
void LinesBoard::timerSlot()
{
// debug("LinesBoard::Timer() anim = %i",anim );
AnimNext();
}
int LinesBoard::erase5Balls()
{
//debug
debug("LinesBoard::erase5Balls()");
int nb=5; // minimum balls for erasure
bool bit_erase[NUMCELLSH][NUMCELLSW]; //bool array for balls, that must be erased
for(int y=0; y<NUMCELLSH; y++)
for(int x=0; x<NUMCELLSW; x++)
bit_erase[y][x] = false;
int color,newcolor;
int count;
//for horisontal
//debug("entering to horiz");
for(int y=0; y<NUMCELLSH; y++) {
count = 1;
color = NOBALL;
for(int x=0; x<NUMCELLSW; x++){
if ( (newcolor = getBall(x,y)) == color) {
if ( color != NOBALL) {
count++;
if ( count >= nb )
if ( count == nb )
for (int i = 0; i < nb; i++)
bit_erase[y][x-i] = true;
else bit_erase[y][x] = true;
}
} else {
color = newcolor;
count = 1;
}
}
}
//for vertical
//debug("entering to vert");
for(int x=0; x<NUMCELLSW; x++) {
count = 0;
color = NOBALL;
for(int y=0; y<NUMCELLSH; y++){
if ( (newcolor = getBall(x,y)) == color) {
if ( color != NOBALL) {
count++;
if ( count >= nb )
if ( count == nb )
for (int i = 0; i < nb; i++)
bit_erase[y-i][x] = true;
else bit_erase[y][x] = true;
}
} else {
color = newcolor;
count = 1;
}
}
}
// debug("entering to diag1");
//for left-down to rigth-up diagonal
for ( int xs = NUMCELLSW-1,ys = NUMCELLSH-nb; xs >= nb-1; ) {
count = 0;
color = NOBALL;
for ( int x = xs, y = ys; x >= 0 && y < NUMCELLSH; x--, y++ ) {
if ( (newcolor = getBall(x,y)) == color) {
if ( color != NOBALL) {
count++;
if ( count >= nb )
if ( count == nb )
for (int i = 0; i < nb; i++)
bit_erase[y-i][x+i] = true;
else bit_erase[y][x] = true;
}
} else {
color = newcolor;
count = 1;
}
}
if ( ys > 0 ) ys--; else xs--;
}
//debug("entering to diag2");
//for left-up to rigth-down diagonal
for ( int xs = 0,ys = NUMCELLSH-nb; xs <= NUMCELLSW-nb; )
{
count = 0;
color = NOBALL;
for ( int x = xs, y = ys; x < NUMCELLSW && y < NUMCELLSH; x++, y++ )
{
if ( (newcolor = getBall(x,y)) == color)
{
if ( color != NOBALL)
{
count++;
if ( count >= nb )
if ( count == nb )
for (int i = 0; i < nb; i++)
bit_erase[y-i][x-i] = true;
else
bit_erase[y][x] = true;
}
}
else
{
color = newcolor;
count = 1;
}
}
if ( ys > 0 ) ys--; else xs++;
}
//remove all lines balls, that more than nb
int cb=0;
for(int y=0; y < NUMCELLSH; y++)
for(int x=0; x < NUMCELLSW; x++)
{
if (bit_erase[y][x])
{
setAnim(x,y,ANIM_YES);
cb++;
}
else
{
setAnim(x,y,ANIM_NO);
}
}
//debug
debug("LinesBoard::erase5Balls marked %i balls", cb);
if ( cb > 0 )
{
AnimStart(ANIM_BURN);
//emit eraseLine(cb);
}
//debug
debug("LinesBoard::erase5Balls END");
return cb;
}
#define GO_EMPTY 4
#define GO_A 5
#define GO_B 6
#define GO_BALL 7
bool LinesBoard::existPath(int bx, int by, int ax, int ay)
{
debug("LinesBoard::existPath( %i, %i, %i, %i )", bx, by, ax, ay);
int dx[4]={1,-1, 0, 0};
int dy[4]={0, 0, 1,-1};
// debug("path %i %i %i %i",bx,by,ax,ay);
if (getBall(ax,ay) != NOBALL)
return false;
char pf[NUMCELLSH][NUMCELLSW];
for(int y=0; y<NUMCELLSH; y++)
for(int x=0; x<NUMCELLSW; x++)
pf[y][x] = (getBall(x,y) == NOBALL) ? GO_EMPTY:GO_BALL;
Waypoints lastchanged[2][NUMCELLSH*NUMCELLSW];
int lastChangedCount[2];
int currentchanged = 0;
int nextchanged = 1;
lastchanged[currentchanged][0].x = ax;
lastchanged[currentchanged][0].y = ay;
lastChangedCount[currentchanged] = 1;
pf[ay][ax]=GO_A;
pf[by][bx]=GO_B;
// int expanded;
bool B_reached = false;
do
{
lastChangedCount[nextchanged] = 0;
for(int dir=0; dir<4; dir++)
{
for ( int i = 0 ; i < lastChangedCount[currentchanged]; i++ )
{
int nx = lastchanged[currentchanged][i].x + dx[dir];
int ny = lastchanged[currentchanged][i].y + dy[dir];
if( (nx>=0) && (nx<NUMCELLSW) && (ny>=0) && (ny<NUMCELLSH) )
{
if( pf[ny][nx]==GO_EMPTY ||( nx==bx && ny==by ))
{
pf[ny][nx] = dir;
lastchanged[nextchanged][lastChangedCount[nextchanged]].x = nx;
lastchanged[nextchanged][lastChangedCount[nextchanged]].y = ny;
lastChangedCount[nextchanged]++;
};
if( (nx==bx) && (ny==by) )
{
B_reached = true;
break;
}
}
}
}
nextchanged = nextchanged ^ 1;
currentchanged = nextchanged ^ 1;
// debug("currentchanged %i lastChangedCount[currentchanged] %i",
// currentchanged,lastChangedCount[currentchanged]);
} while(!B_reached && lastChangedCount[currentchanged] != 0);
//debug("B_reached %i ", B_reached );
if (B_reached) {
AnimStart( ANIM_BLOCK);
animmax = 0;
// waypos = 0;
int x, y,dir;
for( x = bx, y = by,dir; (dir = pf[y][x]) != GO_A;x -=dx[dir],y -= dy[dir]) {
way[animmax].x = x;
way[animmax].y = y;
//debug("%i %i %i %i",dir,waylen,x,y);
animmax++;
}
way[animmax].x = x;
way[animmax].y = y;
}
debug("LinesBoard::existPath END %s", B_reached?"true":"false" );
return B_reached;
}
void LinesBoard::undo()
{
AnimEnd();
restoreUndo();
repaint( FALSE );
}
diff --git a/noncore/games/zlines/main.cpp b/noncore/games/zlines/main.cpp
index ff41f95..238e7d3 100644
--- a/noncore/games/zlines/main.cpp
+++ b/noncore/games/zlines/main.cpp
@@ -1,30 +1,29 @@
/***************************************************************************
main.cpp - description
-------------------
begin : Fri May 19 2000
copyright : (C) 2000 by Roman Merzlyakov
email : roman@sbrf.barrt.ru
copyright : (C) 2000 by Roman Razilov
email : Roman.Razilov@gmx.de
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
/*
* Roman Razilov 2000-05-19 debug dummmy
* Roman Razilov 2000-05-21 qimgio
*/
-#include <qglobal.h>
#include <opie/oapplicationfactory.h>
#include "klines.h"
OPIE_EXPORT_APP( OApplicationFactory<KLines> )
diff --git a/noncore/games/zlines/mwidget.cpp b/noncore/games/zlines/mwidget.cpp
index 6641fa2..211d3d3 100644
--- a/noncore/games/zlines/mwidget.cpp
+++ b/noncore/games/zlines/mwidget.cpp
@@ -1,84 +1,83 @@
/***************************************************************************
mwidget.cpp - description
-------------------
begin : Fri May 19 2000
copyright : (C) 2000 by Roman Merzlyakov
email : roman@sbrf.barrt.ru
copyright : (C) 2000 by Roman Razilov
email : Roman.Razilov@gmx.de
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "mwidget.h"
#include <qlayout.h>
-#include "ballpainter.h"
#include <qhbox.h>
#include <qlabel.h>
MainWidget::MainWidget( QWidget* parent, const char* name )
: QFrame( parent, name )
{
BallPainter *bPainter = new BallPainter();
QGridLayout *Form1Layout = new QGridLayout( this );
Form1Layout->setSpacing( 4 );
Form1Layout->setMargin( 4 );
QSpacerItem* spacer = new QSpacerItem( 20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum );
Form1Layout->addItem( spacer, 0, 0 );
lsb = new LinesBoard(bPainter, this);
Form1Layout->addWidget( lsb, 0, 1 );
QSpacerItem* spacer_2 = new QSpacerItem( 20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum );
Form1Layout->addItem( spacer_2, 0, 2 );
QHBox *bottom=new QHBox(this);
mPoints=new QLabel(bottom);
bottom->setStretchFactor(mPoints, 2);
lPrompt = new LinesPrompt(bPainter, bottom);
Form1Layout->addWidget( bottom, 1, 1 );
QSpacerItem* spacer_3 = new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding );
Form1Layout->addItem( spacer_3, 2, 1 );
connect(lsb, SIGNAL(endTurn()), parent, SLOT(makeTurn()));
connect(lsb, SIGNAL(eraseLine(int)), parent, SLOT(addScore(int)));
connect(lsb, SIGNAL(endGame()), parent, SLOT(stopGame()));
connect(lPrompt, SIGNAL(PromptPressed()), parent, SLOT(switchPrompt()));
}
void MainWidget::setMessage(const QString &message)
{
mPoints->setText(message);
}
/*
Destructor: deallocates memory for contents
*/
MainWidget::~MainWidget()
{
}
LinesBoard * MainWidget::GetLsb()
{
return lsb;
}
LinesPrompt * MainWidget::GetPrompt()
{
return lPrompt;
}
diff --git a/noncore/games/zsame/StoneWidget.cpp b/noncore/games/zsame/StoneWidget.cpp
index 49fa1a4..646fc9c 100644
--- a/noncore/games/zsame/StoneWidget.cpp
+++ b/noncore/games/zsame/StoneWidget.cpp
@@ -1,350 +1,345 @@
/*
* ksame 0.4 - simple Game
* Copyright (C) 1997,1998 Marcus Kreutzberger
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*/
#include <stdio.h>
#include <stdlib.h>
-#include <qpainter.h>
-#include <qpixmap.h>
-#include <qbitmap.h>
-#include <qimage.h>
-#include <qcursor.h>
#include <qpe/resource.h>
#include <time.h>
#include <assert.h>
#include "StoneWidget.h"
struct StoneSlice {
QPixmap stone;
};
StoneWidget::StoneWidget( QWidget *parent, int x, int y )
: QWidget(parent,"StoneWidget"), stonefield(x,y)
{
// setBackgroundPixmap(QPixmap(locate("wallpaper", "Time-For-Lunch-2.jpg")));
// QPixmap stonemap(locate("appdata", "stones.png"));
QPixmap stonemap = Resource::loadPixmap("zsame/stones" );
assert(!stonemap.isNull());
slice=0;
maxslices=30;
maxcolors=4;
sizex=x;
sizey=y;
stone_width=stonemap.width()/(maxslices+1);
stone_height=stonemap.height()/maxcolors;
map = new StoneSlice*[maxcolors];
QBitmap mask;
for (int c = 0; c < maxcolors; c++) {
map[c] = new StoneSlice[maxslices];
for (int s = 0; s < maxslices; s++) {
map[c][s].stone.resize(stone_width, stone_height);
assert(!map[c][s].stone.isNull());
bitBlt(&map[c][s].stone, 0, 0,
&stonemap, stone_width * s,
c*stone_height,
stone_width,stone_height,CopyROP,false);
QImage im = map[c][s].stone.convertToImage();
mask = im.createHeuristicMask();
map[c][s].stone.setMask(mask);
}
}
field_height=stone_height*sizey;
field_width=stone_width*sizex;
setMouseTracking(true);
// QColor c(115,115,115);
// setBackgroundColor(c);
// emit s_sizechanged();
startTimer( 100 );
history.setAutoDelete(true);
}
StoneWidget::~StoneWidget() {
for (int c = 0; c < maxcolors; c++) {
delete [] map[c];
}
delete [] map;
setMouseTracking(false);
killTimers();
}
unsigned int
StoneWidget::board() {
return stonefield.getBoard();
}
int
StoneWidget::score() {
return stonefield.getScore();
}
int
StoneWidget::marked() {
return stonefield.getMarked();
}
QSize
StoneWidget::size() {
return QSize(sizex,sizey);
}
int
StoneWidget::colors() {
return stonefield.getColors();
}
QSize
StoneWidget::sizeHint () const {
return QSize(field_width,field_height);
}
void
StoneWidget::newGame(unsigned int board,int colors) {
stonefield.newGame(board,colors);
history.clear();
modified= false;
emit s_newgame();
emit s_colors(stonefield.getColors());
emit s_board(stonefield.getBoard());
}
void
StoneWidget::reset() {
stonefield.reset();
history.clear();
emit s_newgame();
}
void
StoneWidget::unmark() {
stonefield.unmark();
emit s_marked(0);
}
bool StoneWidget::undoPossible() const {
if (stonefield.isGameover()) return false;
return stonefield.undoPossible();
}
int
StoneWidget::undo(int count) {
if (stonefield.isGameover()) return 0;
int ret_val=stonefield.undo(count);
QPoint p=mapFromGlobal(cursor().pos());
int x=p.x();
int y=p.y();
if (x<0||y<0||x>=field_width||y>=field_height) {
emit s_score(stonefield.getMarked());
return ret_val;
}
int marked=stonefield.mark(x/stone_width,y/stone_height);
emit s_marked(marked);
slice=0;
emit s_score(stonefield.getScore());
modified= (stonefield.getScore()>0);
return ret_val;
}
bool StoneWidget::isGameover() {
return stonefield.isGameover();
}
bool StoneWidget::hasBonus() {
return stonefield.gotBonus(); // don't ask me why the names differ... ;-| [hlm]
}
bool StoneWidget::isOriginalBoard() {
return !modified;
}
void StoneWidget::readProperties(Config *) {
/* Q_ASSERT(conf);
history.clear();
if (!conf->hasKey("Board")||
!conf->hasKey("Colors")||
!conf->hasKey("Stones")) {
return;
}
newGame(conf->readNumEntry("Board"),conf->readNumEntry("Colors"));
QStrList list;
conf->readListEntry("Stones",list);
for (const char *item=list.first();item;item=list.next()) {
int x=-1,y=-1;
if (sscanf(item,"%02X%02X",&x,&y)!=2) break;
history.append(new QPoint(x,y));
stonefield.remove(x,y);
}
*/
}
void
StoneWidget::saveProperties(Config *) {
/*
Q_ASSERT(conf);
QStrList list(true);
QString tmp;
for (QPoint *item=history.first();item;item=history.next()) {
tmp.sprintf("%02X%02X",item->x(),item->y());
list.append(tmp.ascii());
}
conf->writeEntry("Stones",list);
conf->writeEntry("Board",stonefield.getBoard());
conf->writeEntry("Colors",stonefield.getColors());
*/
}
void
StoneWidget::timerEvent( QTimerEvent * ) {
QPoint p=mapFromGlobal(cursor().pos());
int x=p.x();
int y=p.y();
if (x<0||y<0||x>=field_width||y>=field_height)
stonefield.unmark();
slice=(slice+1)%maxslices;
paintEvent(0);
}
void
StoneWidget::paintEvent( QPaintEvent *e ) {
Stone *stone=stonefield.getField();
for (int y=0;y<sizey;y++) {
int cy = y * stone_height;
for (int x=0;x<sizex;x++) {
int cx = stone_width * x;
bool redraw=stone->marked||stone->changed;
if (!redraw&&e) {
QRect r(cx,cy,stone_width,stone_height);
redraw=r.intersects(e->rect());
}
if (redraw) {
stone->changed=false;
if (stone->color) {
int tslice = stone->marked?slice:0;
bitBlt(this,cx,cy,
&map[stone->color-1][tslice].stone,
0, 0,
stone_width,stone_height,CopyROP,FALSE);
} else {
erase(cx, cy, stone_width, stone_height);
}
}
stone++; // naechster Stein.
}
}
}
void
StoneWidget::mousePressEvent ( QMouseEvent *e) {
if (stonefield.isGameover()) return;
int x=e->pos().x();
int y=e->pos().y();
if (x<0||y<0||x>=field_width||y>=field_height) return;
int sx=x/stone_width;
int sy=y/stone_height;
int mar =stonefield.mark(sx, sy);
if ( mar != -1 ) {
myMoveEvent(e);
return;
}
if (stonefield.remove(sx, sy)) {
history.append(new QPoint(sx, sy));
emit s_remove(sx, sy);
stonefield.mark(sx,sy);
emit s_marked(stonefield.getMarked());
modified= true;
emit s_score(stonefield.getScore());
if (stonefield.isGameover()) emit s_gameover();
}
}
void
StoneWidget::myMoveEvent ( QMouseEvent *e)
{
return;
if (stonefield.isGameover()) {
stonefield.unmark();
emit s_marked(0);
return;
}
int x=e->pos().x();
int y=e->pos().y();
if (x<0||y<0||x>=field_width||y>=field_height) return;
int marked=stonefield.mark(x/stone_width,y/stone_height);
if (marked>=0) {
emit s_marked(marked);
slice=0;
}
}
diff --git a/noncore/games/zsame/ZSameWidget.cpp b/noncore/games/zsame/ZSameWidget.cpp
index 5001b55..45a877f 100644
--- a/noncore/games/zsame/ZSameWidget.cpp
+++ b/noncore/games/zsame/ZSameWidget.cpp
@@ -1,250 +1,243 @@
/* Yo Emacs, this is -*- C++ -*- */
/*
* ksame 0.4 - simple Game
* Copyright (C) 1997,1998 Marcus Kreutzberger
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*/
#include <stdio.h>
-#include <qwidget.h>
-#include <qpushbutton.h>
-#include <qpixmap.h>
-#include <qvbox.h>
-#include <qpopupmenu.h>
#include <qtoolbar.h>
#include <qmenubar.h>
#include <qapplication.h>
#include <qaction.h>
#include <qmessagebox.h>
#include <qpe/resource.h>
#include <opie/oapplicationfactory.h>
#include <kapplication.h>
#include "ZSameWidget.h"
-#include "StoneWidget.h"
-#include "version.h"
static int default_colors=3;
#define i18n tr
OPIE_EXPORT_APP( OApplicationFactory<ZSameWidget> )
ZSameWidget::ZSameWidget( QWidget* parent, const char* name, WFlags fl )
: QMainWindow( parent, name, fl )
{
setCaption(tr("ZSame"));
setToolBarsMovable( false );
QToolBar* con = new QToolBar( this );
con->setHorizontalStretchable( true );
QMenuBar* mb = new QMenuBar( con );
QToolBar* tb = new QToolBar( this );
QPopupMenu* fileMenu = new QPopupMenu( this );
QAction* a = new QAction(tr("New Game"), Resource::loadIconSet("new") ,
QString::null, 0, this, "new_icon");
a->addTo( fileMenu );
a->addTo( tb );
connect(a, SIGNAL(activated()), this, SLOT(m_new()));
a = new QAction(tr("Restart This Board"), Resource::loadIconSet("redo"),
QString::null, 0, this, "restart_board" );
a->addTo( fileMenu );
connect( a, SIGNAL(activated()), this, SLOT(m_restart()));
restart = a;
a = new QAction( tr("Undo"), Resource::loadIconSet("undo"),
QString::null, 0, this, "undo_action" );
a->addTo( fileMenu );
a->addTo( tb );
connect( a, SIGNAL(activated()), this, SLOT(m_undo()));
a = new QAction(tr("Quit"), Resource::loadIconSet("quit_icon"),
QString::null, 0, this, "quit_action");
a->addTo( fileMenu );
a->addTo( tb );
connect(a, SIGNAL(activated()), this, SLOT(m_quit()));
mb->insertItem(tr("Game" ), fileMenu );
int foo[2];
desktop_widget(foo);
stone = new StoneWidget(this,foo[0],foo[1]);
connect( stone, SIGNAL(s_gameover()), this, SLOT(gameover()));
connect( stone, SIGNAL(s_colors(int)), this, SLOT(setColors(int)));
connect( stone, SIGNAL(s_board(int)), this, SLOT(setBoard(int)));
connect( stone, SIGNAL(s_marked(int)), this, SLOT(setMarked(int)));
connect( stone, SIGNAL(s_score(int)), this, SLOT(setScore(int)));
connect( stone, SIGNAL(s_remove(int,int)), this, SLOT(stonesRemoved(int,int)));
connect(stone, SIGNAL(s_sizechanged()), this, SLOT(sizeChanged()));
sizeChanged();
setCentralWidget(stone);
setScore(0);
}
ZSameWidget::~ZSameWidget() {
}
void ZSameWidget::readProperties(Config *conf) {
/*
Q_ASSERT(conf);
stone->readProperties(conf);
*/
}
void ZSameWidget::saveProperties(Config *conf) {
/*
Q_ASSERT(conf);
stone->saveProperties(conf);
conf->sync();
*/
}
void ZSameWidget::sizeChanged() {
// stone->setFixedSize(stone->sizeHint());
}
void ZSameWidget::newGame(unsigned int board,int colors) {
while (board>=1000000) board-=1000000;
// kdDebug() << "newgame board " << board << " colors " << colors << endl;
stone->newGame(board,colors);
setScore(0);
}
bool ZSameWidget::confirmAbort() {
return stone->isGameover() ||
stone->isOriginalBoard() ||
(QMessageBox::warning(this, i18n("Resign"), i18n("<qt>Do you want to resign?</qt>"),
QMessageBox::Yes,
QMessageBox::No|QMessageBox::Default|QMessageBox::Escape, 0) == QMessageBox::Yes );
}
void ZSameWidget::m_new() {
if (confirmAbort())
newGame(_random(),default_colors);
}
void ZSameWidget::m_restart() {
if (confirmAbort())
newGame(stone->board(),default_colors);
}
void ZSameWidget::m_load() {
// kdDebug() << "menu load not supported" << endl;
}
void ZSameWidget::m_save() {
// kdDebug() << "menu save not supported" << endl;
}
void ZSameWidget::m_undo() {
// Q_ASSERT(stone);
stone->undo();
}
void ZSameWidget::m_showhs() {
/* Q_ASSERT(stone);
stone->unmark();
KScoreDialog d(KScoreDialog::Name | KScoreDialog::Score, this);
d.addField(Board, i18n("Board"), "Board");
d.exec();
*/
}
void ZSameWidget::m_quit() {
// Q_ASSERT(stone);
stone->unmark();
qApp->quit();
// delete this;
}
void ZSameWidget::m_tglboard() {
// kdDebug() << "toggled" << endl;
}
void ZSameWidget::setColors(int colors) {
// status->changeItem(i18n("%1 Colors").arg(colors),1);
}
void ZSameWidget::setBoard(int board) {
// status->changeItem(i18n("Board: %1").arg(board, 6), 2);
}
void ZSameWidget::setMarked(int m) {
// status->changeItem(i18n("Marked: %1").arg(m, 6),3);
}
void ZSameWidget::stonesRemoved(int,int) {
// KNotifyClient::event("stones removed",
// i18n("%1 stones removed.").arg(stone->marked()));
}
void ZSameWidget::setScore(int score) {
// status->changeItem(i18n("Score: %1").arg(score, 6),4);
// undo->setEnabled(stone->undoPossible());
// restart->setEnabled(!stone->isOriginalBoard());
}
void ZSameWidget::gameover() {
// kdDebug() << "GameOver" << endl;
if (stone->hasBonus()) {
QMessageBox::information(this,i18n("Game won"),
i18n("<qt>You even removed the last stone, great job! "
"This gave you a score of %1 in total.</qt>").arg(stone->score()));
} else {
QMessageBox::information(this,i18n("Game over"),
i18n("<qt>There are no more removeable stones. "
"You got a score of %1 in total.</qt>").arg(stone->score()));
}
stone->unmark();
}
void ZSameWidget::desktop_widget(int *f)const{
QWidget* wid = QApplication::desktop();
/* width > height landscape mode */
if ( wid->width() > wid->height() ) {
f[0]=15;
f[1]=9;
}
/* normal */
else{
f[0]=12;
f[1]=13;
}
}