破烂石头 说的 在MFC中典型的实现方法 ^_^
QT按钮数组我实现过,小封装下就可以狠优雅的实现了
pegsell.h
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#ifndef PEGCELL_H
#define PEGCELL_H
#include <QWidget>
class QGridLayout;
class QToolButton;
class PegCell :public QWidget
{
Q_OBJECT
public:
PegCell(QWidget *parent=0);
void setXY(int x,int y);
void setState(int s);
int getState();
signals:
void clicked(int x,int y);
public slots:
void onClicked();
void stateChanged();
private:
int posx,posy,state;
QToolButton *peg;
QGridLayout *lay;
};
#endif
pegsell.cpp
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#include <QtGui>
#include "pegcell.h"
PegCell::PegCell(QWidget *parent):QWidget(parent)
{
peg=new QToolButton;
lay=new QGridLayout;
state=1;
stateChanged();
lay->addWidget(peg);
setLayout(lay);
connect(peg, SIGNAL(clicked()), this, SLOT(onClicked()));
}
void PegCell::setXY(int x,int y)
{
posx=x;
posy=y;
}
void PegCell::setState(int s)
{
state=s;
stateChanged();
}
int PegCell::getState()
{
return state;
}
void PegCell::stateChanged()
{
QSize iconSize(40, 40);
if(state==1)
{
peg->setIcon(QIcon(QPixmap(":/images/purple_down.png")
.scaled(34, 34)));
peg->setIconSize(iconSize);
}
else if(state==2)
{
peg->setIcon(QIcon(QPixmap(":/images/orange_up.png")
.scaled(34, 34)));
peg->setIconSize(iconSize);
}
else
{
peg->setIcon(QIcon(QPixmap(":/images/empty.png")
.scaled(34, 34)));
peg->setIconSize(iconSize);
}
}
void PegCell::onClicked()
{
emit clicked(posx,posy);
}
创建
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
for(i=0;i<n;++i)
{
for (j=0;j<n;++j)
{
pegCell[j].setXY(i,j);
connect(&pegCell[j],SIGNAL(clicked(int,int)),
this,SLOT(onClicked(int,int)));
if(i<height||i>=width+height)
if(j<height||j>=width+height)
continue;
gridLayout->addWidget(&pegCell[j],i+1,j+1);
}
}
使用
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void PegField::onClicked(int x,int y)
{
if(!playing)
{
if(pegCell[x][y].getState()==0)
pegCell[x][y].setState(1);
else
pegCell[x][y].setState(0);
}
else
{
if(fromx==-1)
{
switch(pegCell[x][y].getState())
{
case 0:return;
case 2:{
pegCell[x][y].setState(1);
fromx=-1;
break;
}
case 1:
pegCell[x][y].setState(2);
fromx=x;
fromy=y;
}
}
else
{
if(pegCell[x][y].getState()==2)
{
pegCell[x][y].setState(1);
fromx=-1;
}
else if(pegCell[x][y].getState()==1)
{
pegCell[fromx][fromy].setState(1);
fromx=x;
fromy=y;
pegCell[x][y].setState(2);
}
else
{
if(x!=fromx&&y!=fromy)
{
pegCell[fromx][fromy].setState(1);
fromx=-1;
return ;
}
if(x-fromx==2||fromx-x==2||y-fromy==2||fromy-y==2)
{
if(pegCell[(fromx+x)/2][(fromy+y)/2].getState()==1)
{
pegCell[(fromx+x)/2][(fromy+y)/2].setState(0);
pegCell[fromx][fromy].setState(0);
pegCell[x][y].setState(1);
judge();
}
else
pegCell[fromx][fromy].setState(1);
fromx=-1;
}
else
{
pegCell[fromx][fromy].setState(1);
fromx=-1;
}
}
}
}
}