summaryrefslogtreecommitdiff
Side-by-side diff
Diffstat (more/less context) (ignore whitespace changes)
-rw-r--r--noncore/games/backgammon/backgammon.cpp34
-rw-r--r--noncore/games/fifteen/fifteen.cpp16
-rw-r--r--noncore/games/mindbreaker/config.in2
-rw-r--r--noncore/games/mindbreaker/mindbreaker.cpp15
-rw-r--r--noncore/games/mindbreaker/opie-mindbreaker.control2
-rw-r--r--noncore/games/minesweep/minesweep.cpp5
-rw-r--r--noncore/games/parashoot/base.cpp5
-rw-r--r--noncore/games/parashoot/bullet.cpp5
-rw-r--r--noncore/games/parashoot/cannon.cpp5
-rw-r--r--noncore/games/parashoot/helicopter.cpp4
-rw-r--r--noncore/games/parashoot/interface.cpp10
-rw-r--r--noncore/games/parashoot/man.cpp7
-rw-r--r--noncore/games/solitaire/canvascard.cpp51
-rw-r--r--noncore/games/solitaire/canvascardgame.h1
-rw-r--r--noncore/games/solitaire/canvascardwindow.cpp7
-rw-r--r--noncore/games/tetrix/qtetrix.cpp4
-rw-r--r--noncore/games/wordgame/wordgame.cpp22
-rw-r--r--noncore/games/zlines/ballpainter.cpp4
18 files changed, 97 insertions, 102 deletions
diff --git a/noncore/games/backgammon/backgammon.cpp b/noncore/games/backgammon/backgammon.cpp
index c286a36..31835f8 100644
--- a/noncore/games/backgammon/backgammon.cpp
+++ b/noncore/games/backgammon/backgammon.cpp
@@ -1,975 +1,975 @@
#include "backgammon.h"
#include "aidialog.h"
#include "filedialog.h"
#include "playerdialog.h"
#include "rulesdialog.h"
#include "themedialog.h"
/* OPIE */
#include <opie2/odebug.h>
+#include <opie2/oresource.h>
#include <qpe/qpeapplication.h>
#include <qpe/config.h>
-#include <qpe/resource.h>
using namespace Opie::Core;
/* QT */
#include <qfile.h>
#include <qlayout.h>
#include <qmessagebox.h>
#include <qtimer.h>
#include <qmenubar.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" ) );
+ setIcon( Opie::Core::OResource::loadPixmap( "backgammon" ) );
//general counter varaible
int a=0;
//the game engine
move=new MoveEngine();
//load the default theme
Config conf("backgammon");
if(!conf.isValid())
{
odebug << "config file does not exist" << oendl;
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())
{
odebug << "theme file does not exist" << oendl;
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_all(Opie::Core::OResource::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_all(Opie::Core::OResource::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));
+ QImage dicebgA_all(Opie::Core::OResource::loadImage("backgammon/dice/"+diceA_name));
diceA1=new CanvasImageItem*[7];
diceA2=new CanvasImageItem*[7];
- QImage dicebgB_all(Resource::loadImage("backgammon/dice/"+diceB_name));
+ QImage dicebgB_all(Opie::Core::OResource::loadImage("backgammon/dice/"+diceB_name));
diceB1=new CanvasImageItem*[7];
diceB2=new CanvasImageItem*[7];
- QImage oddsbg_all=(Resource::loadImage("backgammon/odds/"+odds_name));
+ QImage oddsbg_all=(Opie::Core::OResource::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));
+ QImage boardbg(Opie::Core::OResource::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));
+ QImage tablebg(Opie::Core::OResource::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"));
+ QImage nomovebg(Opie::Core::OResource::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));
+ QImage boardbg(Opie::Core::OResource::loadImage("backgammon/boards/"+board_name));
board->setImage(boardbg);
- QImage tablebg(Resource::loadImage("backgammon/table/"+table_name));
+ QImage tablebg(Opie::Core::OResource::loadImage("backgammon/table/"+table_name));
table->setImage(tablebg);
- QImage piece_1_all(Resource::loadImage("backgammon/pieces/"+piecesA_name));
+ QImage piece_1_all(Opie::Core::OResource::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_all(Opie::Core::OResource::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));
+ QImage dicebgA_all(Opie::Core::OResource::loadImage("backgammon/dice/"+diceA_name));
+ QImage dicebgB_all(Opie::Core::OResource::loadImage("backgammon/dice/"+diceB_name));
+ QImage oddsbg_all=(Opie::Core::OResource::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/fifteen/fifteen.cpp b/noncore/games/fifteen/fifteen.cpp
index bb57ee1..c41c0a4 100644
--- a/noncore/games/fifteen/fifteen.cpp
+++ b/noncore/games/fifteen/fifteen.cpp
@@ -1,558 +1,550 @@
/**********************************************************************
** 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 "fifteenconfigdialog.h"
#include <opie2/ofileselector.h>
+#include <opie2/oresource.h>
-#include <qtopia/resource.h>
#include <qtopia/config.h>
#include <qtopia/qpeapplication.h>
#include <qvbox.h>
#include <qaction.h>
#include <qpainter.h>
#include <qmessagebox.h>
#include <qtoolbar.h>
#include <qmenubar.h>
#include <qimage.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 );
+ menubar->insertItem( tr( "Game" ), game );
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" ),
+ QAction *a = new QAction( tr( "Randomize" ), Opie::Core::OResource::loadPixmap( "new", Opie::Core::OResource::SmallIcon ),
QString::null, 0, this, 0 );
connect( a, SIGNAL( activated() ), table, SLOT( slotRandomize() ) );
a->addTo( game );
a->addTo( toolbar );
- a = new QAction( tr("Configure"), Resource::loadPixmap( "SettingsIcon" ),
+ a = new QAction( tr("Configure"), Opie::Core::OResource::loadPixmap( "SettingsIcon", Opie::Core::OResource::SmallIcon ),
QString::null, 0, this, 0 );
connect( a, SIGNAL( activated()), table, SLOT( slotConfigure()) );
a->addTo( game );
-
- /* 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 );
}
///////////////
/////// Pieces table Implementation
///////
PiecesTable::PiecesTable(QWidget* parent, const char* name )
: QTableView(parent, name), _menu(0), _randomized(false),
_dialog( 0l )
{
// setup table view
setFrameStyle(StyledPanel | Sunken);
setBackgroundMode(NoBackground);
setMouseTracking(true);
setNumRows(4);
setNumCols(4);
// init arrays
readConfig();
initColors();
}
PiecesTable::~PiecesTable()
{
writeConfig();
clear();
}
void PiecesTable::writeConfig()
{
Config cfg("Fifteen");
cfg.setGroup("Game");
QStringList map;
int items = numRows()*numCols();
for (int i = 0; i < items; i++)
map.append( QString::number( _map[i] ) );
cfg.writeEntry("Map", map, '-');
cfg.writeEntry("Randomized", _randomized );
cfg.writeEntry("Image", _image );
cfg.writeEntry("Rows", numRows() );
cfg.writeEntry("Cols", numCols() );
}
void PiecesTable::readConfig()
{
Config cfg("Fifteen");
cfg.setGroup("Game");
QStringList map = cfg.readListEntry("Map", '-');
_randomized = cfg.readBoolEntry( "Randomized", FALSE );
_image = cfg.readEntry( "Image", QString::null );
int rows = cfg.readNumEntry( "Rows", 4 );
int cols = cfg.readNumEntry( "Cols", 4 );
uint items= rows*cols;
setNumRows( rows );
setNumCols( cols );
initMap();
/* if we've more items than 'stones' don't restore the state */
if ( items > map.count() )
return;
uint i = 0;
for ( QStringList::Iterator it = map.begin(); it != map.end(); ++it ) {
_map[i] = (*it).toInt();
i++;
if ( i > items ) break;
}
}
void PiecesTable::clear() {
/* clean up and resize */
for (uint i = 0; i < _pixmap.count(); ++i )
delete _pixmap[i];
_pixmap.resize( numRows()*numCols() );
}
/*
* Let us pre-render the tiles. Either we've a Custom Image as
* background or we use the drawRect to fill the background and
* last we put the number on it
*/
void PiecesTable::slotCustomImage( const QString& _str ) {
QString str = _str;
/* couldn't load image fall back to plain tiles*/
QImage img = QImage(str);
QPixmap pix;
if(img.isNull())
str = QString::null;
else{
img = img.smoothScale( width(),height() );
pix.convertFromImage( img );
}
/* initialize base point */
uint image=0;
/* clear the old tiles */
clear();
/* used variables */
int cols = numCols();
int rows = numRows();
int cellW = cellWidth();
int cellH = cellHeight();
int x2 = cellW-1;
int y2 = cellH-1;
bool empty = str.isEmpty();
double bw = empty ? 0.9 : 0.98;
int x_offset = cellW - int(cellW * bw); // 10% should be enough
int y_offset = cellH - int(cellH * bw);
/* border polygon calculation*/
initPolygon(cellW, cellH, x_offset, y_offset );
/* avoid crashes with isNull() pixmap later */
if ( cellW == 0 || cellH == 0 ) {
_pixmap.resize( 0 );
return;
}
/* make it bold and bigger */
QFont f = font();
f.setPixelSize(18);
f.setBold( TRUE );
/* for every tile */
for(int row = 0; row < rows; ++row ) {
for(int col= 0; col < cols; ++col) {
QPixmap *pip = new QPixmap(cellW, cellH );
QPainter *p = new QPainter(pip );
p->setFont( f );
/* draw the tradional tile or a part of the pixmap*/
if(empty) {
p->setBrush(_colors[image]);
p->setPen(NoPen);
p->drawRect(0,0,cellW,cellH);
}else
p->drawPixmap(0, 0, pix,col*cellW, row*cellH, cellW, cellH );
// draw borders
if (height() > 40) {
p->setBrush(_colors[image].light(130));
p->drawPolygon(light_border);
p->setBrush(_colors[image].dark(130));
p->drawPolygon(dark_border);
}
// draw number
p->setPen(black);
p->drawText(0, 0, x2, y2, AlignHCenter | AlignVCenter, QString::number(image+1));
delete p;
_pixmap[image++] = pip;
}
}
_image = str;
}
/*
* Calculate 3d-effect borders
*/
void PiecesTable::initPolygon(int cell_w, int cell_h, int x_offset, int y_offset ) {
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::paintCell(QPainter *p, int row, int col)
{
int w = cellWidth();
int h = cellHeight();
uint pos = col+row*numCols();
/* sanity check. setNumRows()/setNumCols() calls repaint() directly */
if ( pos >= _map.count() ) {
p->drawRect(0, 0, w, h);
return;
}
int number = _map[col + row * numCols()] + 1;
// draw cell background
if(number == numCols()*numRows() ) {
p->setBrush(colorGroup().background());
p->setPen(NoPen);
p->drawRect(0, 0, w, h);
return;
}
/* no tiles then contentRect() is not visible or too small anyway */
if( _pixmap.count() == 0 )
return;
p->drawPixmap(0, 0, *(_pixmap[(number-1 )]) );
}
void PiecesTable::resizeEvent(QResizeEvent *e)
{
/*
* null if we faked it after the config dialog ran to
* regenerate everything
*/
if ( e )
QTableView::resizeEvent(e);
setCellWidth(contentsRect().width()/ numCols());
setCellHeight(contentsRect().height() / numRows());
/* update the image and calculate border*/
slotCustomImage( _image );
}
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 ,255 - (70 * r)%255, 150);
}
void PiecesTable::initMap()
{
int items = numCols()*numRows();
_map.resize( items );
for ( int i = 0; i < items; i++)
_map[i] = i;
_randomized = false;
}
void PiecesTable::randomizeMap()
{
initMap();
_randomized = true;
// find the free position
int cols = numCols();
int rows = numRows();
int pos = _map.find( cols*rows -1 );
int move = 0;
while ( move < 333 ) {
int frow = pos / cols;
int fcol = pos - frow * cols;
// find click position
int row = rand()%rows;
int col = rand()%cols;
// sanity check
if ( row < 0 || row >= rows ) continue;
if ( col < 0 || col >= cols ) 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 * cols] = _map[ c-1 + row *cols];
}
}
else if (col > fcol) {
for(int c = fcol; c < col; c++) {
_map[c + row * cols] = _map[ c+1 + row *cols];
}
}
}
// cols match -> shift pieces
else if (col == fcol) {
if (row < frow) {
for(int r = frow; r > row; r--) {
_map[col + r * cols] = _map[ col + (r-1) *cols];
}
}
else if (row > frow) {
for(int r = frow; r < row; r++) {
_map[col + r * cols] = _map[ col + (r+1) *cols];
}
}
}
// move free cell to click position
_map[pos=(col + row * cols)] = rows*cols-1;
}
repaint();
}
void PiecesTable::checkwin()
{
if(!_randomized) return;
int items=numCols()*numRows();
int i;
for (i = 0; i < items; i++)
if(i != _map[i])
break;
if (i == items) {
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
int cols = numCols();
int rows = numRows();
int item = cols*rows -1;
// find the free position
int pos = _map.find(item);
if(pos < 0) return;
int frow = pos / cols;
int fcol = pos - frow * cols;
// find click position
int row = findRow(e->y());
int col = findCol(e->x());
// sanity check
if (row < 0 || row >= rows) return;
if (col < 0 || col >= cols) 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 * cols] = _map[ c-1 + row *cols];
updateCell(row, c, false);
}
}
else if (col > fcol) {
for(int c = fcol; c < col; c++) {
_map[c + row * cols] = _map[ c+1 + row *cols];
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 * cols] = _map[ col + (r-1) *cols];
updateCell(r, col, false);
}
}
else if (row > frow) {
for(int r = frow; r < row; r++) {
_map[col + r * cols] = _map[ col + (r+1) *cols];
updateCell(r, col, false);
}
}
}
// move free cell to click position
_map[col + row * cols] = item;
updateCell(row, col, false);
// check if the player wins with this move
checkwin();
}
}
void PiecesTable::slotConfigure() {
if ( !_dialog )
_dialog = new FifteenConfigDialog(this, "Fifteen Configure Dialog", true );
_dialog->setImageSrc( _image );
_dialog->setGameboard( numRows(), numCols() );
if ( QPEApplication::execDialog(_dialog) == QDialog::Accepted ) {
/*
* update the board grid and reinit the game if changed
* First set new columns so the update will regenerate the
* tiles with slotCustomImage
*/
_image = _dialog->imageSrc();
if (numRows() != _dialog->rows() ||
numCols() != _dialog->columns() ) {
setNumCols(_dialog->columns());
setNumRows(_dialog->rows());
slotReset();
}
resizeEvent( 0l );
update();
}
}
diff --git a/noncore/games/mindbreaker/config.in b/noncore/games/mindbreaker/config.in
index b97a9e8..e3c0812 100644
--- a/noncore/games/mindbreaker/config.in
+++ b/noncore/games/mindbreaker/config.in
@@ -1,4 +1,4 @@
config MINDBREAKER
boolean "opie-mindbreaker (crack the coloured code)"
default "y"
- depends ( LIBQPE || LIBQPE-X11 )
+ depends ( LIBQPE || LIBQPE-X11 ) && LIBOPIE2CORE
diff --git a/noncore/games/mindbreaker/mindbreaker.cpp b/noncore/games/mindbreaker/mindbreaker.cpp
index 1f554d2..aa4afd7 100644
--- a/noncore/games/mindbreaker/mindbreaker.cpp
+++ b/noncore/games/mindbreaker/mindbreaker.cpp
@@ -1,953 +1,954 @@
/**********************************************************************
** 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 <opie2/oresource.h>
+
#include <qtopia/config.h>
#include <qtopia/qpeapplication.h>
#include <qtoolbar.h>
#include <qtoolbutton.h>
#include <qmessagebox.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;
// odebug << "Adjusted width " << adjusted_board_width << " height " << adjusted_board_height << "" << oendl;
}
/* 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");
+ QImage pegs = Opie::Core::OResource::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");
+ QImage image = Opie::Core::OResource::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");
+ QToolButton *btn = new QToolButton( Opie::Core::OResource::loadPixmap("new", Opie::Core::OResource::SmallIcon), tr("New Game"), 0,
+ board, SLOT(clear()), tb, "NewGame");
+ btn->setUsesBigPixmap( qApp->desktop()->size().width() > 330 );
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");
+ QImage image = Opie::Core::OResource::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/mindbreaker/opie-mindbreaker.control b/noncore/games/mindbreaker/opie-mindbreaker.control
index 5b342da..d3826fd 100644
--- a/noncore/games/mindbreaker/opie-mindbreaker.control
+++ b/noncore/games/mindbreaker/opie-mindbreaker.control
@@ -1,10 +1,10 @@
Package: opie-mindbreaker
Files: plugins/application/libmindbreaker.so* bin/mindbreaker apps/Games/mindbreaker.desktop pics/mindbreaker
Priority: optional
Section: opie/games
Maintainer: Martin Imobersteg <imm@gmx.ch>
Architecture: arm
-Depends: task-opie-minimal
+Depends: task-opie-minimal, libopiecore2
Description: Game: crack the coloured code
A game for the Opie environment.
Version: $QPE_VERSION$EXTRAVERSION
diff --git a/noncore/games/minesweep/minesweep.cpp b/noncore/games/minesweep/minesweep.cpp
index c14609d..18449ff 100644
--- a/noncore/games/minesweep/minesweep.cpp
+++ b/noncore/games/minesweep/minesweep.cpp
@@ -1,408 +1,409 @@
/**********************************************************************
** 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 <opie2/oresource.h>
+
#include <qtopia/qpeapplication.h>
-#include <qtopia/resource.h>
#include <qtopia/config.h>
#include <qtoolbar.h>
#include <qmenubar.h>
#include <qpushbutton.h>
#include <qlcdnumber.h>
#include <qtimer.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 Sweep") );
QPEApplication::setInputMethodHint(this, QPEApplication::AlwaysOff );
- setIcon( Resource::loadPixmap( "minesweep/MineSweep" ) );
+ setIcon( Opie::Core::OResource::loadPixmap( "minesweep/MineSweep" ) );
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/parashoot/base.cpp b/noncore/games/parashoot/base.cpp
index 5f3c79d..f232536 100644
--- a/noncore/games/parashoot/base.cpp
+++ b/noncore/games/parashoot/base.cpp
@@ -1,75 +1,74 @@
/**********************************************************************
** 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 <qtopia/resource.h>
-
+#include <opie2/oresource.h>
int damage;
Base::Base(QCanvas* canvas) :
QCanvasSprite(0, canvas),
kaboom("landmine"),
ohdear("crmble01")
{
basearray = new QCanvasPixmapArray();
- QString b0 = Resource::findPixmap("parashoot/b0001");
+ QString b0 = Opie::Core::OResource::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/bullet.cpp b/noncore/games/parashoot/bullet.cpp
index 584f564..1f02251 100644
--- a/noncore/games/parashoot/bullet.cpp
+++ b/noncore/games/parashoot/bullet.cpp
@@ -1,142 +1,143 @@
/**********************************************************************
** 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 "codes.h"
#include "bullet.h"
#include "man.h"
#include "helicopter.h"
-#include <qpe/resource.h>
+#include <opie2/oresource.h>
+
#include <qpe/qmath.h>
int limit;
int shotcount;
int nobullets;
Bullet::Bullet(QCanvas* canvas, double angle, int cannonx, int cannony) :
QCanvasSprite(0, canvas),
bang("collide01")
{
- QCanvasPixmapArray* bulletarray = new QCanvasPixmapArray(Resource::findPixmap("parashoot/bullet"));
+ QCanvasPixmapArray* bulletarray = new QCanvasPixmapArray(Opie::Core::OResource::findPixmap("parashoot/bullet"));
setSequence(bulletarray);
if (nobullets < limit) {
nobullets++;
move(cannonx, cannony);
dy = 0;
dx = 0;
show();
setXY(angle);
setVelocity(-dx, -dy);
bang.play();
} else
return;
}
void Bullet::setXY(double angle)
{
double ang = angle;
if ( (y() < 0) || (x() < 0) || (y() > canvas()->height()) ||
(x() > canvas()->width()) )
delete this;
else {
double radians = 0;
radians = ang * 3.14159265/180;
dx = (qCos(radians)) *7;
dy = (qSin(radians)) *7;
}
}
void Bullet::setLimit(int amount)
{
limit = amount;
}
void Bullet::setNobullets(int amount)
{
nobullets = amount;
}
void Bullet::checkCollision()
{
QCanvasItem* item;
QCanvasItemList l=collisions(FALSE);
for (QCanvasItemList::Iterator it=l.begin(); it!=l.end(); ++it) {
item = *it;
if ( (item->rtti()== 1500) && (item->collidesWith(this)) ) {
Man* deadman = (Man*)item;
if (deadman->frame() != 5) return;
deadman->done();
emit score(10);
setShotCount(shotcount+1);
setAnimated(false);
nobullets--;
delete this;
return;
}
else if ( (item->rtti()==1900) && (item->collidesWith(this)) ) {
Helicopter* deadchopper = (Helicopter*) item;
deadchopper->done();
emit score(50);
setAnimated(false);
nobullets--;
delete this;
return;
}
}
//check shot is not out of bounds
if ( (y() < 0) || (x() < 0) ||
(y() > canvas()->height()) ||
( x() > canvas()->width())) {
setAnimated(false);
nobullets--;
delete this;
return;
}
}
void Bullet::advance(int phase)
{
QCanvasSprite::advance(phase);
if (phase == 0)
checkCollision();
}
int Bullet::getShotCount()
{
return shotcount;
}
void Bullet::setShotCount(int amount)
{
shotcount = amount;
}
Bullet::~Bullet()
{
}
int Bullet::rtti() const
{
return bullet_rtti;
}
diff --git a/noncore/games/parashoot/cannon.cpp b/noncore/games/parashoot/cannon.cpp
index 330d850..2f4c353 100644
--- a/noncore/games/parashoot/cannon.cpp
+++ b/noncore/games/parashoot/cannon.cpp
@@ -1,149 +1,148 @@
/**********************************************************************
** 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 <opie2/oresource.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");
+ QString c0 = Opie::Core::OResource::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 7d91cd1..42adc34 100644
--- a/noncore/games/parashoot/helicopter.cpp
+++ b/noncore/games/parashoot/helicopter.cpp
@@ -1,119 +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 <opie2/oresource.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");
+ QString h0 = Opie::Core::OResource::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 5c9b0ef..8ec7032 100644
--- a/noncore/games/parashoot/interface.cpp
+++ b/noncore/games/parashoot/interface.cpp
@@ -1,278 +1,280 @@
/**********************************************************************
** 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 <opie2/oresource.h>
+
#include <qtopia/qpeapplication.h>
-#include <qtopia/resource.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");
+ QToolButton *btn = new QToolButton( Opie::Core::OResource::loadPixmap("new", Opie::Core::OResource::SmallIcon),
+ tr("New Game"), 0, this, SLOT(newGame()), toolbar, "New Game");
+ btn->setUsesBigPixmap( qApp->desktop()->size().width() > 330 );
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");
+ QImage bgimage = Opie::Core::OResource::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/man.cpp b/noncore/games/parashoot/man.cpp
index 0a151b0..080615e 100644
--- a/noncore/games/parashoot/man.cpp
+++ b/noncore/games/parashoot/man.cpp
@@ -1,190 +1,189 @@
/**********************************************************************
** 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 <opie2/oresource.h>
int mancount;
Man::Man(QCanvas* canvas) :
QCanvasSprite(0, canvas),
splat("lose") // No tr
{
manarray = new QCanvasPixmapArray();
- QString m0 = Resource::findPixmap("parashoot/man0001");
+ QString m0 = Opie::Core::OResource::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");
+ QString m0 = Opie::Core::OResource::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/solitaire/canvascard.cpp b/noncore/games/solitaire/canvascard.cpp
index c36da6c..cd298ef 100644
--- a/noncore/games/solitaire/canvascard.cpp
+++ b/noncore/games/solitaire/canvascard.cpp
@@ -1,308 +1,303 @@
/**********************************************************************
** 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 "canvascard.h"
-#include <qpe/resource.h>
+#include <opie2/oresource.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" ) );
+ cardsFaces = new QPixmap( Opie::Core::OResource::loadPixmap( "cards/card_face_small" ) );
+ cardsBacks = new QPixmap( Opie::Core::OResource::loadPixmap( "cards/card_back0001_small" ) );
+ cardsChars = new QBitmap();
+ *cardsChars = Opie::Core::OResource::loadPixmap( "cards/card_chars_small" );
+ cardsSuits = new QBitmap();
+ *cardsSuits = Opie::Core::OResource::loadPixmap( "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" ) );
+ cardsFaces = new QPixmap( Opie::Core::OResource::loadPixmap( "cards/card_face" ) );
+ cardsBacks = new QPixmap( Opie::Core::OResource::loadPixmap( "cards/card_back0001" ) );
+ cardsChars = new QBitmap();
+ *cardsChars = Opie::Core::OResource::loadPixmap( "cards/card_chars" );
+ cardsSuits = new QBitmap();
+ *cardsSuits = Opie::Core::OResource::loadPixmap( "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;
+ cardsBacks = new QPixmap( Opie::Core::OResource::loadPixmap( "cards/card_back0001_small" ) ); break;
case 1:
- cardsBacks = new QPixmap( Resource::loadPixmap( "cards/card_back0002_small" ) ); break;
+ cardsBacks = new QPixmap( Opie::Core::OResource::loadPixmap( "cards/card_back0002_small" ) ); break;
case 2:
- cardsBacks = new QPixmap( Resource::loadPixmap( "cards/card_back0003_small" ) ); break;
+ cardsBacks = new QPixmap( Opie::Core::OResource::loadPixmap( "cards/card_back0003_small" ) ); break;
case 3:
- cardsBacks = new QPixmap( Resource::loadPixmap( "cards/card_back0004_small" ) ); break;
+ cardsBacks = new QPixmap( Opie::Core::OResource::loadPixmap( "cards/card_back0004_small" ) ); break;
case 4:
- cardsBacks = new QPixmap( Resource::loadPixmap( "cards/card_back0005_small" ) ); break;
+ cardsBacks = new QPixmap( Opie::Core::OResource::loadPixmap( "cards/card_back0005_small" ) ); break;
}
} else {
switch (cardBack) {
case 0:
- cardsBacks = new QPixmap( Resource::loadPixmap( "cards/card_back0001" ) ); break;
+ cardsBacks = new QPixmap( Opie::Core::OResource::loadPixmap( "cards/card_back0001" ) ); break;
case 1:
- cardsBacks = new QPixmap( Resource::loadPixmap( "cards/card_back0002" ) ); break;
+ cardsBacks = new QPixmap( Opie::Core::OResource::loadPixmap( "cards/card_back0002" ) ); break;
case 2:
- cardsBacks = new QPixmap( Resource::loadPixmap( "cards/card_back0003" ) ); break;
+ cardsBacks = new QPixmap( Opie::Core::OResource::loadPixmap( "cards/card_back0003" ) ); break;
case 3:
- cardsBacks = new QPixmap( Resource::loadPixmap( "cards/card_back0004" ) ); break;
+ cardsBacks = new QPixmap( Opie::Core::OResource::loadPixmap( "cards/card_back0004" ) ); break;
case 4:
- cardsBacks = new QPixmap( Resource::loadPixmap( "cards/card_back0005" ) ); break;
+ cardsBacks = new QPixmap( Opie::Core::OResource::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.h b/noncore/games/solitaire/canvascardgame.h
index b93cfbf..c559a90 100644
--- a/noncore/games/solitaire/canvascardgame.h
+++ b/noncore/games/solitaire/canvascardgame.h
@@ -1,97 +1,96 @@
/**********************************************************************
** 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.
**
**********************************************************************/
#ifndef CANVAS_CARD_GAME_H
#define CANVAS_CARD_GAME_H
#include "cardgame.h"
#include "canvasshapes.h"
#include "canvascard.h"
-#include <qpe/resource.h>
#include <qpe/config.h>
#include <qmainwindow.h>
#include <qmenubar.h>
#include <qpainter.h>
#include <stdlib.h>
#include <time.h>
class CanvasCardPile;
class CanvasCardGame : public QCanvasView, public CardGame
{
public:
CanvasCardGame(QCanvas &c, bool snap, QWidget *parent = 0, int numOfDecks = 1, const char *name = 0, WFlags f = 0) :
QCanvasView( &c, parent, name, f ),
CardGame(0,numOfDecks),
moved(FALSE),
moving(NULL),
alphaCardPile( NULL ),
cardXOff(0), cardYOff(0),
snapOn(snap),
numberToDraw(1) { }
virtual ~CanvasCardGame();
virtual Card *newCard( eValue v, eSuit s, bool f ) {
return new CanvasCard( v, s, f, canvas() );
}
virtual void readConfig( Config& cfg ) { Q_UNUSED( cfg ); }
virtual void writeConfig( Config& cfg ) { Q_UNUSED( cfg ); }
virtual void gameWon();
virtual bool haveWeWon() { return FALSE; }
virtual bool mousePressCard(Card *card, QPoint p) { Q_UNUSED(card); Q_UNUSED(p); return FALSE; }
virtual void mouseReleaseCard(Card *card, QPoint p) { Q_UNUSED(card); Q_UNUSED(p); }
void cancelMoving() { moving = NULL; }
void toggleSnap() { snapOn = (snapOn == TRUE) ? FALSE : TRUE; }
void toggleCardsDrawn() { numberToDraw = (numberToDraw == 1) ? 3 : 1; }
int cardsDrawn() { return numberToDraw; }
void setNumberToDraw(int numToDraw) { this->numberToDraw = numToDraw; }
void readPile( Config& cfg, CardPile *pile, QString name, int& highestZ );
protected:
void contentsMousePressEvent(QMouseEvent *e);
void contentsMouseReleaseEvent(QMouseEvent *e);
void contentsMouseMoveEvent(QMouseEvent *e);
virtual void checkUnusable() { } //added for freecell
protected:
// Mouse event state variables
bool moved;
CanvasCard *moving;
CanvasCardPile *alphaCardPile;
int cardXOff, cardYOff;
private:
bool snapOn;
int numberToDraw;
};
#endif
diff --git a/noncore/games/solitaire/canvascardwindow.cpp b/noncore/games/solitaire/canvascardwindow.cpp
index 503bc92..956c5bd 100644
--- a/noncore/games/solitaire/canvascardwindow.cpp
+++ b/noncore/games/solitaire/canvascardwindow.cpp
@@ -1,310 +1,309 @@
/**********************************************************************
** 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 "freecellcardgame.h"
#include "chicanecardgame.h"
#include "harpcardgame.h"
#include "teeclubcardgame.h"
-
-
+#include <opie2/oresource.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" ) );
+ setIcon( Opie::Core::OResource::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 );
+ bg.convertFromImage( Opie::Core::OResource::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/tetrix/qtetrix.cpp b/noncore/games/tetrix/qtetrix.cpp
index a6a5f34..d949176 100644
--- a/noncore/games/tetrix/qtetrix.cpp
+++ b/noncore/games/tetrix/qtetrix.cpp
@@ -1,208 +1,208 @@
/**********************************************************************
** 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 <opie2/oresource.h>
#include <qlabel.h>
#include <qdatetime.h>
#include <qlayout.h>
#include <qtimer.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" ) );
+ setIcon( Opie::Core::OResource::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 );
gl->setColStretch( 1, 5 );
gl->setColStretch( 2, 10 );
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));
gl->addMultiCellWidget( board, 0, 4, 2, 2 );
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*)), this,
SLOT(setNext(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 );
QTimer::singleShot( -1, this, SLOT(setup()) );
}
void QTetrix::setup()
{
resizeEvent( 0x0 );
}
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();
}
void QTetrix::setNext( int x, int y, QColor *color )
{
resizeEvent( 0x0 );
showNext->drawNextSquare( x, y, color );
}
void QTetrix::resizeEvent( QResizeEvent * )
{
// Set size of board
int widthFactor = board->QFrame::width() / board->boardWidth();
if ( widthFactor < 1 )
widthFactor = 1;
int heightFactor = board->QFrame::height() / board->boardHeight();
if ( heightFactor < 1 )
heightFactor = 1;
widthFactor > heightFactor ? board->resize( heightFactor * board->boardWidth() + 2,
heightFactor * board->boardHeight() + 2 )
: board->resize( widthFactor * board->boardWidth() + 2,
widthFactor * board->boardHeight() + 2 );
// Set size of preview widget
widthFactor = showNext->width() / 5;
if ( widthFactor < 1 )
widthFactor = 1;
heightFactor = showNext->height() / 6;
if ( heightFactor < 1 )
heightFactor = 1;
widthFactor > heightFactor ? showNext->resize( heightFactor * 5 + 2, heightFactor * 6 + 2 )
: showNext->resize( widthFactor * 5 + 2, widthFactor * 6 + 2 );
}
diff --git a/noncore/games/wordgame/wordgame.cpp b/noncore/games/wordgame/wordgame.cpp
index 47d6725..52e2be2 100644
--- a/noncore/games/wordgame/wordgame.cpp
+++ b/noncore/games/wordgame/wordgame.cpp
@@ -1,1510 +1,1518 @@
/**********************************************************************
** 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 <opie2/oresource.h>
+
#include <qpe/global.h>
-#include <qpe/resource.h>
#include <qpe/config.h>
#include <qapplication.h>
#include <qmessagebox.h>
#include <qcombobox.h>
#include <qdir.h>
#include <qlineedit.h>
#include <qpushbutton.h>
#include <qtextstream.h>
#include <qtimer.h>
#include <qtoolbar.h>
#include <qtoolbutton.h>
#include <qvbox.h>
#include <qwidgetstack.h>
#include <qlayout.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" ) );
+ setIcon( Opie::Core::OResource::loadPixmap( "wordgame/WordGame" ) );
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);
+ bool useBigIcon = qApp->desktop()->size().width() > 330;
+ reset = new QToolButton(Opie::Core::OResource::loadPixmap("back", Opie::Core::OResource::SmallIcon),
+ tr("Back"), "", this, SLOT(resetTurn()), toolbar);
+ reset->setUsesBigPixmap( useBigIcon );
+ done = new QToolButton(Opie::Core::OResource::loadPixmap("done", Opie::Core::OResource::SmallIcon),
+ tr("Done"), "", this, SLOT(endTurn()), toolbar);
+ done->setUsesBigPixmap( useBigIcon );
scoreinfo = new ScoreInfo(toolbar);
scoreinfo->setFont(QFont("Helvetica",10));
- new QToolButton(Resource::loadPixmap("finish"), tr("Close"), "", this, SLOT(endGame()), toolbar);
+ QToolButton *btn = new QToolButton(Opie::Core::OResource::loadPixmap("finish", Opie::Core::OResource::SmallIcon),
+ tr("Close"), "", this, SLOT(endGame()), toolbar);
+ btn->setUsesBigPixmap( useBigIcon );
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");
+ QImage shim = Opie::Core::OResource::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();
odebug << "" << current.x() << "," << current.y() << ": " << st.latin1() << " (" << n << ") for " << s << "" << oendl;
}
*/
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)
+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 622ec29..e7596c4 100644
--- a/noncore/games/zlines/ballpainter.cpp
+++ b/noncore/games/zlines/ballpainter.cpp
@@ -1,132 +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 <opie2/oresource.h>
#include "ballpainter.h"
//#include "shotcounter.h"
#include <qpainter.h>
//#include <qcolor.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) );
+ return new QPixmap(Opie::Core::OResource::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];
}