Ejemplo n.º 1
0
void Board::drawConnection(int timeout)
{
	if(connection.empty())
		return;

	// lighten the fields
	updateField(connection.front().x, connection.front().y);
	updateField(connection.back().x, connection.back().y);

	QPainter p;
	p.begin(this);
	p.setPen(QPen(QColor("red"), tiles.lineWidth()));

	// Path.size() will always be >= 2
	Path::const_iterator pathEnd = connection.end();
	Path::const_iterator pt1 = connection.begin();
	Path::const_iterator pt2 = pt1;
	++pt2;
	while(pt2 != pathEnd)
	{
		p.drawLine( midCoord(pt1->x, pt1->y), midCoord(pt2->x, pt2->y) );
		++pt1;
		++pt2;
	}

	p.flush();
	p.end();

	QTimer::singleShot(timeout, this, SLOT(undrawConnection()));
}
Ejemplo n.º 2
0
void Board::drawArrow(int x1, int y1, int x2, int y2) {
  if(trying)
    return;

  // find out number of array
  int num = 0;
  while(num < 4 && history[num].x != -2)
    num++;

  // lighten the fields
  // remember mark_x,mark_y
  int mx = mark_x, my = mark_y;
  mark_x = x1; mark_y = y1;
  updateField(x1, y1);
  mark_x = x2; mark_y = y2;
  updateField(x2, y2);

  // restore the mark
  mark_x = mx;
  mark_y = my;

  QPainter p;
  p.begin(this);
  p.setPen(QPen(QColor("red"), 6));
  num = 0;
  while(num < 3 && history[num+1].x != -2) {
    p.drawLine(midCoord(history[num].x, history[num].y),
	       midCoord(history[num+1].x, history[num+1].y));
    num++;    
  }
  p.flush();
  p.end();

  QTimer::singleShot(getDelay(), this, SLOT(undrawArrow()));
}
Ejemplo n.º 3
0
void Board::gravity(int col, bool update)
{
	if(gravity_flag)
	{
		int rptr = y_tiles()-1, wptr = y_tiles()-1;
		while(rptr >= 0)
		{
			if(getField(col, wptr) != EMPTY)
			{
				rptr--;
				wptr--;
			}
			else
			{
				if(getField(col, rptr) != EMPTY)
				{
					setField(col, wptr, getField(col, rptr));
					setField(col, rptr, EMPTY);
					if(update)
					{
						updateField(col, rptr);
						updateField(col, wptr);
					}
					wptr--;
					rptr--;
				}
				else
					rptr--;
			}
		}
	}
}
Ejemplo n.º 4
0
void Board::marked(int x, int y) {
  // make sure that the last arrow is correctly undrawn
  undrawArrow();

  if(getField(x, y) == EMPTY)
    return;
  
  if(x == mark_x && y == mark_y) {
    // unmark the piece
    mark_x = -1;
    mark_y = -1;
    updateField(x, y);
    return;
  }

  if(mark_x == -1) {
    mark_x = x;
    mark_y = y;
    updateField(x, y);
    return;
  } else {
    int fld1 = getField(mark_x, mark_y);
    int fld2 = getField(x, y);
    
    // both field same?
    if(fld1 != fld2) {
      emit markError();
      return;
    }
    
    // trace    
    if(findPath(mark_x, mark_y, x, y)) {
      emit madeMove(mark_x, mark_y, x, y);
      drawArrow(mark_x, mark_y, x, y);
      setField(mark_x, mark_y, EMPTY);
      setField(x, y, EMPTY);
      mark_x = -1;
      mark_y = -1;

      int dummyx;
      History dummyh[4];

      // game is over?      
      if(!getHint_I(dummyx,dummyx,dummyx,dummyx,dummyh)) {
	time_for_game = (int)time((time_t)NULL) - starttime;
	emit endOfGame();
      }
      
    } else {
      clearHistory();
      emit markError();
    }
  }
}
Ejemplo n.º 5
0
void Board::marked(int x, int y)
{
	// make sure that the previous connection is correctly undrawn
	undrawConnection();

	if(getField(x, y) == EMPTY)
		return;

	if(x == mark_x && y == mark_y)
	{
		// unmark the piece
		mark_x = -1;
		mark_y = -1;
		updateField(x, y, false);
		return;
	}

	if(mark_x == -1)
	{
		mark_x = x;
		mark_y = y;
		updateField(x, y, false);
		return;
	}

	int fld1 = getField(mark_x, mark_y);
	int fld2 = getField(x, y);

	// both field same?
	if(fld1 != fld2)
		return;

	// trace
	if(findPath(mark_x, mark_y, x, y, connection))
	{
		madeMove(mark_x, mark_y, x, y);
		drawConnection(getDelay());
		setField(mark_x, mark_y, EMPTY);
		setField(x, y, EMPTY);
		grav_col_1 = x;
		grav_col_2 = mark_x;
		mark_x = -1;
		mark_y = -1;

		// game is over?
		// Must delay until after tiles fall to make this test
		// See undrawConnection GP.
	}
	else
	{
		connection.clear();
	}
}
Ejemplo n.º 6
0
void Board::redo() {
  if(canRedo()) {
    undrawArrow();
    Move *m = _redo.take(0);
    setField(m->x1, m->y1, EMPTY);
    setField(m->x2, m->y2, EMPTY);
    updateField(m->x1, m->y1);
    updateField(m->x2, m->y2);
    _undo.append(m);
    emit changed();
  }
}
Ejemplo n.º 7
0
void Board::undo() {
  if(canUndo()) {
    undrawArrow();
    Move *m = _undo.take(_undo.count() - 1);
    setField(m->x1, m->y1, m->tile);
    setField(m->x2, m->y2, m->tile);
    updateField(m->x1, m->y1);
    updateField(m->x2, m->y2);
    _redo.insert(0, m);
    emit changed();
  }
}
Ejemplo n.º 8
0
void Board::undrawConnection()
{
	if(grav_col_1 != -1 || grav_col_2 != -1)
	{
		gravity(grav_col_1, true);
		gravity(grav_col_2, true);
		grav_col_1 = -1;
		grav_col_2 = -1;
	}

	// is already undrawn?
	if(connection.empty())
		return;

	// Redraw all affected fields

	Path oldConnection = connection;
	connection.clear();

	// Path.size() will always be >= 2
	Path::const_iterator pathEnd = oldConnection.end();
	Path::const_iterator pt1 = oldConnection.begin();
	Path::const_iterator pt2 = pt1;
	++pt2;
	while(pt2 != pathEnd)
	{
		if(pt1->y == pt2->y)
		{
			for(int i = std::min(pt1->x, pt2->x); i <= std::max(pt1->x, pt2->x); i++)
				updateField(i, pt1->y);
		}
		else
		{
			for(int i = std::min(pt1->y, pt2->y); i <= std::max(pt1->y, pt2->y); i++)
				updateField(pt1->x, i);
		}
		++pt1;
		++pt2;
	}

	Path dummyPath;
	// game is over?
	if(!getHint_I(dummyPath))
	{
		time_for_game = (int)difftime( time((time_t)0), starttime);
		emit endOfGame();
	}
}
Ejemplo n.º 9
0
/*********** File **************/
FileConfigControl::FileConfigControl( vlc_object_t *_p_this,
                                          module_config_t *_p_item,
                                          QWidget *_parent, QGridLayout *l,
                                          int &line ) :
                           VStringConfigControl( _p_this, _p_item, _parent )
{
    label = new QLabel( qtr(p_item->psz_text) );
    text = new QLineEdit( qfu(p_item->value.psz) );
    browse = new QPushButton( qtr( "Browse..." ) );
    QHBoxLayout *textAndButton = new QHBoxLayout();
    textAndButton->setMargin( 0 );
    textAndButton->addWidget( text, 2 );
    textAndButton->addWidget( browse, 0 );

    BUTTONACT( browse, updateField() );

    finish();

    if( !l )
    {
        QHBoxLayout *layout = new QHBoxLayout();
        layout->addWidget( label, 0 );
        layout->insertSpacing( 1, 10 );
        layout->addLayout( textAndButton, LAST_COLUMN );
        widget->setLayout( layout );
    }
    else
    {
        l->addWidget( label, line, 0 );
        l->setColumnMinimumWidth( 1, 10 );
        l->addLayout( textAndButton, line, LAST_COLUMN );
    }
}
Ejemplo n.º 10
0
void Board::redo()
{
	if(canRedo())
	{
		clearHighlight();
		undrawConnection();
		Move* m = _redo.take(0);
		setField(m->x1, m->y1, EMPTY);
		setField(m->x2, m->y2, EMPTY);
		updateField(m->x1, m->y1);
		updateField(m->x2, m->y2);
		gravity(m->x1, true);
		gravity(m->x2, true);
		_undo.append(m);
		emit changed();
	}
}
Ejemplo n.º 11
0
void Board::mousePressEvent(QMouseEvent *e) {
    // calculate position
    int pos_x = (e->pos().x() - XBORDER <0)?-1:
                              (e->pos().x() - XBORDER) / pm_tile[0]->width();
    int pos_y = (e->pos().y() - YBORDER <0)?-1:
                              (e->pos().y() - YBORDER) / pm_tile[0]->height();

    // Mark tile
    if(e->button() == LeftButton) {
      if(highlighted_tile != -1) {
	int oldmarkx = mark_x;
	int oldmarky = mark_y;
	
	mark_x=-1; mark_y=-1;
	for(int i = 0; i < x_tiles(); i++)
	  for(int j = 0; j < y_tiles(); j++){
	    if( highlighted_tile == getField(i, j))
	      updateField(i, j);	      
	  }
	mark_x = oldmarkx; 
	mark_y = oldmarky;   // no tile selected
	highlighted_tile = -1;
      }
      
      if(pos_x >= 0 && pos_x < x_tiles() && pos_y >= 0 && pos_y < y_tiles())
	emit fieldClicked(pos_x, pos_y);  
    }

    // Assist by lighting all tiles of same type
    if(e->button() == RightButton) {
      int field = getField(pos_x,pos_y);
      highlighted_tile = field;
      
      for(int i = 0; i < x_tiles(); i++)
	for(int j = 0; j < y_tiles(); j++){
	  if( field == getField(i, j)){
	    mark_x=i; mark_y=j;
	  }
	  else{
	    mark_x=-1; mark_y=-1;
	  }
	  updateField(i, j);
	}
      mark_x=-1; mark_y=-1;   // no tile selected
    }
}
Ejemplo n.º 12
0
void tetris::run(){
	initDrawField();
	init();
	updateField();

	while(loop()){
		pSensors->m_reset->toggle();
	}
}
Ejemplo n.º 13
0
void  vectorField::update(ofPoint pt, ofPoint vel, float scale,  float w, float h)
{
    if( vel.x == 0 && vel.y == 0 )
    {
        lastx = pt.x*scale;
        lasty = pt.y*scale;
    }

    float tempVel =  5 * sqrt(vel.x * vel.x + vel.y * vel.y);
    updateField(pt.x*scale, pt.y*scale, tempVel,  w,  h);
}
Ejemplo n.º 14
0
void Board::undo()
{
	if(canUndo())
	{
		clearHighlight();
		undrawConnection();
		Move* m = _undo.last();
		_undo.take();
		if(gravityFlag())
		{
			int y;

			// When both tiles reside in the same column, the order of undo is
			// significant (we must undo the lower tile first).
			if(m->x1 == m->x2 && m->y1 < m->y2)
			{
				std::swap(m->x1, m->x2);
				std::swap(m->y1, m->y2);
			}

			for(y = 0; y < m->y1; y++)
			{
				setField(m->x1, y, getField(m->x1, y+1));
				updateField(m->x1, y);
			}

			for(y = 0; y < m->y2; y++)
			{
				setField(m->x2, y, getField(m->x2, y+1));
				updateField(m->x2, y);
			}
		}

		setField(m->x1, m->y1, m->tile);
		setField(m->x2, m->y2, m->tile);
		updateField(m->x1, m->y1);
		updateField(m->x2, m->y2);
		_redo.prepend(m);
		emit changed();
	}
}
Ejemplo n.º 15
0
/*********** File **************/
FileConfigControl::FileConfigControl( vlc_object_t *_p_this,
                                      module_config_t *_p_item, QWidget *p ) :
                           VStringConfigControl( _p_this, _p_item )
{
    label = new QLabel( qtr(p_item->psz_text), p );
    text = new QLineEdit( qfu(p_item->value.psz), p );
    browse = new QPushButton( qtr( "Browse..." ), p );

    BUTTONACT( browse, updateField() );

    finish();
}
Ejemplo n.º 16
0
/**
 * @brief updateColumn From pCname of pFile, replace pToCompare with newData
 * @param newData
 * @param pToCompare
 * @param pFile
 * @param pCName
 */
bool writefile::updateColumn(string newData,string pToCompare, string pFile, string pCName){

    int currSeek = file.tellg();
    int sizeToColumn;
    int cSize;
    string standardDir;
    bool bowl = true;

    //Relative route + the name of the file
    if ( !(file.is_open()) ){
        string fileH = pFile;
        standardDir = createNewFile(fileH.c_str());
        file.open(standardDir.c_str());
    }

    if ( !(file.is_open()) ){
        cout << "NED " + pFile << endl;
        bowl = false;
    }

    int Column = getColumnNumber(&standardDir , &pCName );
    int regQty = getRegisterQuantity();
    string currentData = K->EMPTY_STRING;

    for (int rowCounter = K->ONE_BYTE ; rowCounter <= regQty ; rowCounter++){

        //Move the seek to the column and register.
        placeSeekOn( &rowCounter , &Column, &sizeToColumn, &cSize);

        //Build the string of the old data
        for (int i = 0 ; i < cSize ; i++){
            char temp = file.get();
            if (temp == '*'){
                break;
            }else{
                currentData.push_back(temp);
            }
        }
        //Compare data.
        if (currentData == pToCompare){
            updateField(newData, pFile , rowCounter , Column);
        }else{
            currentData = K->EMPTY_STRING;
        }
    }

    file.seekg(currSeek);
    if (file.is_open()){
        file.close();
    }
    return bowl;
}
Ejemplo n.º 17
0
void Board::clearHighlight()
{
	if(highlighted_tile != -1)
	{
		int old_highlight = highlighted_tile;
		highlighted_tile = -1;

		for(int i = 0; i < x_tiles(); i++)
			for(int j = 0; j < y_tiles(); j++)
				if(old_highlight == getField(i, j))
					updateField(i, j, false);
	}
}
Ejemplo n.º 18
0
void SvgView::updateField(QDomNode &e, QString tag, QString value)
{
    if ( e.nodeType() == QDomNode::TextNode)
    {
        if (e.nodeValue() == tag)
            e.setNodeValue(value);
    }
    else
    {
        for(QDomNode n = e.firstChild(); !n.isNull(); n = n.nextSibling())
            updateField(n, tag, value);
    }
}
Ejemplo n.º 19
0
FileConfigControl::FileConfigControl( vlc_object_t *_p_this,
                                   module_config_t *_p_item,
                                   QLabel *_label, QLineEdit *_text,
                                   QPushButton *_button ):
                           VStringConfigControl( _p_this, _p_item )
{
    browse = _button;
    text = _text;
    label = _label;

    BUTTONACT( browse, updateField() );

    finish( );
}
Ejemplo n.º 20
0
int DirectoryConfigControl::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = FileConfigControl::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0: updateField(); break;
        default: ;
        }
        _id -= 1;
    }
    return _id;
}
Ejemplo n.º 21
0
void Board::undrawArrow() {
  if(trying)
    return;

  // is already undrawn?
  if(history[0].x == -2)
    return;

  // redraw all affected fields
  int num = 0;
  while(num < 3 && history[num+1].x != -2) {
    if(history[num].y == history[num+1].y)
      for(int i = MIN(history[num].x, history[num+1].x); 
	  i <= MAX(history[num].x, history[num+1].x); i++)
	updateField(i, history[num].y);
    else 
      for(int i = MIN(history[num].y, history[num+1].y); 
	  i <= MAX(history[num].y, history[num+1].y); i++)
	updateField(history[num].x, i);
    num++;
  }

  clearHistory();
}
Ejemplo n.º 22
0
bool BattleField::setFieldHit(int position, bool hit)
{
    FieldData* fieldData = getFieldData(position);
    if(fieldData)
    {
        // Check if field is already tried
        if(fieldData->isTried())
            return false;

        // Set information on the field
        fieldData->setIsHit(hit);
        fieldData->setIsTried(true);

        if(hit)
        {
            // Visualize a hit
            fieldData->setColor("#00ff00");

            // Check if ship is sunken
            QList<FieldData*> shipFields = _fieldsById[fieldData->shipId()];
            bool shipSunken = true;
            foreach(FieldData* field, shipFields)
            {
                shipSunken = field->isHit();
                if(!shipSunken)
                    break;
            }

            // If ship is sunken emit a signal with the new number of ships
            if(shipSunken)
            {
                _numberOfShips--;
                emit numberOfShipsChanged(_numberOfShips);
                foreach(FieldData* field, shipFields)
                {
                    field->setHideImage(false);
                    updateField(field->modelPosition());
                }
            }
        }
Ejemplo n.º 23
0
static void updateGamePlaying(void)
{
#ifdef DEBUG
    if (dbgRecvChar == 'a') initTrialField();
    if (dbgRecvChar == 'l') norm = 0;
    if (dbgRecvChar == 'q') field[cursorY][cursorX].chain = CHAIN_MAX;
#endif
    if (vanishFlashFrames > 0) vanishFlashFrames--;
    if (blinkFrameFrames > 0) blinkFrameFrames--;
    if (blinkChainFrames > 0) blinkChainFrames--;
    if (blinkLevelFrames > 0) blinkLevelFrames--;
    handleDPad();
    updateField();
    moveCursor();
    if (gameMode == GAME_MODE_ENDLESS) {
        if (level < LEVEL_MAX && norm <= 0) {
            setLevel(level + 1);
            arduboy.playScore2(soundLevelUp, 2);
        }
    } else if (gameMode == GAME_MODE_LIMITED) {
        if (isTimeToBlinkFrame()) {
            arduboy.playScore2(soundTimeToBlink, 2);
            blinkFrameFrames = BLINK_FRAME_FRAMES_MAX;
        }
    }
    gameFrames++;
    record.playFrames++;
    blinkFlg = !blinkFlg;
    if (isGameOver()) {
        state = STATE_OVER;
        writeRecord();
        blinkFlg = false;
        overAnimFrames = OVER_ANIM_FRAMES_MAX;
        dprintln(F("Game over"));
    } else if (arduboy.buttonDown(A_BUTTON)) {
        setupMenu();
    }
    isInvalid = true;
}
Ejemplo n.º 24
0
Archivo: ime.c Proyecto: AmesianX/wine
static HIMCC updateResultStr(HIMCC old, LPWSTR resultstr, DWORD len)
{
    /* we need to make sure the ResultStr and ResultClause fields are all
     * set and correct */
    int needed_size;
    HIMCC   rc;
    LPBYTE newdata = NULL;
    LPBYTE olddata = NULL;
    LPCOMPOSITIONSTRING new_one;
    LPCOMPOSITIONSTRING lpcs = NULL;
    INT current_offset = 0;

    TRACE("%s, %i\n",debugstr_wn(resultstr,len),len);

    if (old == NULL && resultstr == NULL && len == 0)
        return NULL;

    if (resultstr == NULL && len != 0)
    {
        ERR("resultstr is NULL however we have a len!  Please report\n");
        len = 0;
    }

    if (old != NULL)
    {
        olddata = ImmLockIMCC(old);
        lpcs = (LPCOMPOSITIONSTRING)olddata;
    }

    needed_size = sizeof(COMPOSITIONSTRING) + len * sizeof(WCHAR) +
                  sizeof(DWORD) * 2;

    if (lpcs != NULL)
    {
        needed_size += lpcs->dwCompReadAttrLen;
        needed_size += lpcs->dwCompReadClauseLen;
        needed_size += lpcs->dwCompReadStrLen * sizeof(DWORD);
        needed_size += lpcs->dwCompAttrLen;
        needed_size += lpcs->dwCompClauseLen;
        needed_size += lpcs->dwCompStrLen * sizeof(DWORD);
        needed_size += lpcs->dwResultReadClauseLen;
        needed_size += lpcs->dwResultReadStrLen * sizeof(DWORD);
        needed_size += lpcs->dwPrivateSize;
    }
    rc = ImmCreateIMCC(needed_size);
    newdata = ImmLockIMCC(rc);
    new_one = (LPCOMPOSITIONSTRING)newdata;

    new_one->dwSize = needed_size;
    current_offset = sizeof(COMPOSITIONSTRING);
    if (lpcs != NULL)
    {
        current_offset = updateField(lpcs->dwCompReadAttrLen,
                                     lpcs->dwCompReadAttrOffset,
                                     current_offset, newdata, olddata,
                                     &new_one->dwCompReadAttrLen,
                                     &new_one->dwCompReadAttrOffset, FALSE);

        current_offset = updateField(lpcs->dwCompReadClauseLen,
                                     lpcs->dwCompReadClauseOffset,
                                     current_offset, newdata, olddata,
                                     &new_one->dwCompReadClauseLen,
                                     &new_one->dwCompReadClauseOffset, FALSE);

        current_offset = updateField(lpcs->dwCompReadStrLen,
                                     lpcs->dwCompReadStrOffset,
                                     current_offset, newdata, olddata,
                                     &new_one->dwCompReadStrLen,
                                     &new_one->dwCompReadStrOffset, TRUE);

        current_offset = updateField(lpcs->dwCompAttrLen,
                                     lpcs->dwCompAttrOffset,
                                     current_offset, newdata, olddata,
                                     &new_one->dwCompAttrLen,
                                     &new_one->dwCompAttrOffset, FALSE);

        current_offset = updateField(lpcs->dwCompClauseLen,
                                     lpcs->dwCompClauseOffset,
                                     current_offset, newdata, olddata,
                                     &new_one->dwCompClauseLen,
                                     &new_one->dwCompClauseOffset, FALSE);

        current_offset = updateField(lpcs->dwCompStrLen,
                                     lpcs->dwCompStrOffset,
                                     current_offset, newdata, olddata,
                                     &new_one->dwCompStrLen,
                                     &new_one->dwCompStrOffset, TRUE);

        new_one->dwCursorPos = lpcs->dwCursorPos;
        new_one->dwDeltaStart = 0;

        current_offset = updateField(lpcs->dwResultReadClauseLen,
                                     lpcs->dwResultReadClauseOffset,
                                     current_offset, newdata, olddata,
                                     &new_one->dwResultReadClauseLen,
                                     &new_one->dwResultReadClauseOffset, FALSE);

        current_offset = updateField(lpcs->dwResultReadStrLen,
                                     lpcs->dwResultReadStrOffset,
                                     current_offset, newdata, olddata,
                                     &new_one->dwResultReadStrLen,
                                     &new_one->dwResultReadStrOffset, TRUE);

        /* new ResultClause , ResultStr */

        current_offset = updateField(lpcs->dwPrivateSize,
                                     lpcs->dwPrivateOffset,
                                     current_offset, newdata, olddata,
                                     &new_one->dwPrivateSize,
                                     &new_one->dwPrivateOffset, FALSE);
    }

    /* set new data */
    /* ResultClause */
    if (len > 0)
    {
        new_one->dwResultClauseLen = sizeof(DWORD) * 2;
        new_one->dwResultClauseOffset = current_offset;
        *(DWORD*)(&newdata[current_offset]) = 0;
        current_offset += sizeof(DWORD);
        *(DWORD*)(&newdata[current_offset]) = len;
        current_offset += sizeof(DWORD);
    }

    /* ResultStr */
    new_one->dwResultStrLen = len;
    if (len > 0)
    {
        new_one->dwResultStrOffset = current_offset;
        memcpy(&newdata[current_offset],resultstr,len*sizeof(WCHAR));
    }
    ImmUnlockIMCC(rc);
    if (lpcs)
        ImmUnlockIMCC(old);

    return rc;
}
Ejemplo n.º 25
0
void tetris::check_stack(){
	bool stacked=false;
	bool stop_me=false;

	for(int y=0;y<3 && !stop_me;y++){
		for(int x=0;x<3 && !stop_me;x++){
			if(active_element[x][y] && (area[active_y+y+1] & (1 << (COLS-active_x-x)))){
				stacked=true;
			}
			if(active_element[x][y] && (active_y+y==(LINES-1))){
				stacked=true;
			}
			if(stacked){
				//show_grid_on_serial();
				/////////////// copy element to grid ///////////////////
				for(int copy_x=0;copy_x<3;copy_x++){
					for(int copy_y=0;copy_y<3;copy_y++){
						if(active_element[copy_x][copy_y]){
							// area[13]=area[15-2+0]
							// area[14]=area[15-2+1]
							// area[15]=area[15-2+2]
							area[active_y+copy_y] |= (1<<(COLS-active_x-copy_x));
						};
						active_element[copy_x][copy_y]=false;
					};
				};


				// check if any line is completed
				for(int line=0;line<LINES;line++){
					if(area[line]==8190){
						// blinken lassen
						pOLED->filled_rect(12,line*4,12*4,4,0);
						_delay_ms(125);
						pOLED->filled_rect(12,line*4,12*4,4,6);
						_delay_ms(125);
						pOLED->filled_rect(12,line*4,12*4,4,0);
						_delay_ms(125);
						pOLED->filled_rect(12,line*4,12*4,4,6);
						// felder verschieben
						for(int upper_line=line;upper_line>0;upper_line--){
							area[upper_line]=area[upper_line-1];
							// alle linien drüber neu zeichnen
							for(int copy_x=0;copy_x<COLS;copy_x++){
								unsigned char color=0x00;
								if(area[upper_line] & (1<<(COLS-copy_x))){
									color=0x06;
								}
								pOLED->filled_rect(12+copy_x*4,upper_line*4,4,4,color);
							}
						}
						// letzte feld löschen
						area[0]=0b0000000000000000;
						pOLED->filled_rect(12,0,48,4,0);

						// lines hochzählen
						lines++;
						// level schwerer machen :D
						if(lines%10==0){
							time_between_steps=4*time_between_steps/5;
							// 1000
							// 800
							// 640
							// 512
							// 409
							// 327
							// 261
							// 208
							// 166
							// 132
							// 105
							// 084
							// 067
							// 053
						}
						char temp[3];
						sprintf(temp,"%2i",int(floor(lines/10)));
						pOLED->string(pSpeedo->default_font,temp,19,6,0,15,0);
						sprintf(temp,"%2i",lines);
						pOLED->string(pSpeedo->default_font,temp,19,7,0,15,0);
					}
				}

				if(area[0]!=0){
					you_loose=true;
				}

				updateField();

				//show_grid_on_serial();
				new_element();
				stop_me=true;
			};
		}
	}
};
Ejemplo n.º 26
0
bool tetris::loop(){
	char c=0x00;
	int state=0;
	while(Serial.available()>0){
		_delay_ms(5);
		if(state==0){
			//pOLED->string(0,"0",0,0);

			if(Serial.read()==MESSAGE_START){	state=1;	} else {	state=0;	}
		} else if(state==1){
			//pOLED->string(0,"1",0,0);

			if(Serial.read()==0x01){	state=2;	} else {	state=0;	}
		} else if(state==2){
			//pOLED->string(0,"2",0,0);

			if(Serial.read()==0x00){	state=3;	} else {	state=0;	}
		} else if(state==3){
			//pOLED->string(0,"3",0,0);

			if(Serial.read()==0x01){	state=4;	} else {	state=0;	}
		} else if(state==4){
			//pOLED->string(0,"4",0,0);

			if(Serial.read()==TOKEN){	state=5;	} else {	state=0;	}
		} else if(state==5){
			//pOLED->string(0,"5",0,0);
			char d=Serial.read();

			if(d==CMD_GO_LEFT){
				//pOLED->string(0,"6",0,0);
				c=1;
				state=6;
			} else if(d==CMD_GO_RIGHT){
				//pOLED->string(0,"6",0,0);
				c=2;
				state=6;
			} else if(d==CMD_GO_UP){
				//pOLED->string(0,"6",0,0);
				c=3;
				state=6;
			} else if(d==CMD_GO_DOWN){
				//pOLED->string(0,"6",0,0);
				c=4;
				state=6;
			} else {	state=0; c=0;	}
		} else if(state==6){
			//pOLED->string(0,"7",0,0);

			state=0;
			Serial.flush();
			break;
		}
		// left
		// right
		// up
		// down
	};

	// check if you are stil in the race
	if(you_loose){
		// Nope, you loose show the box once
		if(pSpeedo->disp_zeile_bak[0]!=123){
			// show a animation depending on line count
			int ani=1; // simpsons
			if(lines>50){
				ani=4; // JTM
			} else if(lines>30){
				ani=5;
			}
			// 1sec geben damit der user realisiert
			// dann sicher sein das er keine taste
			// mehr drückt
			_delay_ms(1000);
			while(Serial.available()>0 || 	!(PINJ & (1<<menu_button_links)) || !(PINJ & (1<<menu_button_rechts)) || !(PINJ & (1<<menu_button_oben)) ||	!(PINJ & (1<<menu_button_unten)) ){
					Serial.flush();
				_delay_ms(50);
			}
			pOLED->animation(ani);
			initDrawField(); // draw the field again, to show the line and level counter

			// make sure to draw this box only once
			pSpeedo->disp_zeile_bak[0]=123;
			// draw box
			pOLED->highlight_bar(8,8,104,48);
			pOLED->string_P(pSpeedo->default_font,PSTR("You loose"),5,2,15,0,0);
			pOLED->string_P(pSpeedo->default_font,PSTR("L Quit"),5,4,15,0,0);
			char temp[2];
			sprintf(temp,"%c",126);
			pOLED->string(pSpeedo->default_font,temp,5,4,15,0,0);
			pOLED->string_P(pSpeedo->default_font,PSTR("R Retry"),5,5,15,0,0);
			sprintf(temp,"%c",127);
			pOLED->string(pSpeedo->default_font,temp,5,5,15,0,0);
			// way at least one second to prevent unnoticed button push
			_delay_ms(1000);
			// if you loose and the box has been drawn, way on key down
		} else {
			if(c==1 || !(PINJ & (1<<menu_button_links))){
				_delay_ms(MIN_SIDE_PUSH_TIME);
				return false;
			} else if (c==2 || !(PINJ & (1<<menu_button_rechts))){
				_delay_ms(MIN_SIDE_PUSH_TIME);
				pOLED->clear_screen();
				// ja das ist ungeschickt, init leert uns die line variable, drawfield malt das hin, das problem ist nur
				// das wir mit drawfield die in init gezeichneten "next" übermalen .. also einfach 2x init .. is ja wurst
				init();
				initDrawField();
				init();
				updateField();
			};
		}
		// nope you haven't lost by now .. go on
	} else {
		////////////////// if there is a button pushed, //////////////////
		if(!(PINJ & (1<<menu_button_links))){
			c=1;
			_delay_ms(MIN_SIDE_PUSH_TIME);
		} else if(!(PINJ & (1<<menu_button_oben))){
			c=3;
			_delay_ms(MIN_TURN_PUSH_TIME);
		} else if(!(PINJ & (1<<menu_button_unten))){
			c=4;
			_delay_ms(MIN_DOWN_PUSH_TIME);
		} else if(!(PINJ & (1<<menu_button_rechts))){
			c=2;
			_delay_ms(MIN_SIDE_PUSH_TIME);
		}

		// now lets see if any action is required
		////////////////// rotate element //////////////////
		if(c==3){
			// element drehen
			bool copy[3][3];
			copy[0][0]=active_element[0][2];	//	00	10	20  		02	01	00
			copy[1][0]=active_element[0][1];	//  01	11	21   ==>	12	11	10
			copy[2][0]=active_element[0][0];	//	02	12	22			22	21	20
			copy[0][1]=active_element[1][2];
			copy[1][1]=active_element[1][1];
			copy[2][1]=active_element[1][0];
			copy[0][2]=active_element[2][2];
			copy[1][2]=active_element[2][1];
			copy[2][2]=active_element[2][0];

			// check if a rotation would result in a collision
			bool rotate_possible=true;
			bool check_running=true;

			for(int y=0;y<3 && check_running;y++){
				for(int x=0;x<3 && check_running;x++){
					// check if in the rotated figure the px is in use
					if(copy[x][y]){
						// if so, check if it is already in use by the area
						if(area[active_y+y] & 1<<(COLS-active_x-x)){
							// if so, rotation is impossible
							rotate_possible=false;
							check_running=false;
						};
					};
				};
			};

			// if rotation is possible, move the content from copy -> active_element
			if(rotate_possible){
				for(int x=0;x<3;x++){
					for(int y=0;y<3;y++){
						active_element[x][y]=copy[x][y];
					}
				};
				// element drehen
				updateField();
			}

			////////////////// move element down //////////////////
		} else if(c==4){
			if(pSpeedo->disp_zeile_bak[1]!=111){
				active_y++;
			};
			updateField();
			check_stack();
			last_update=millis();

			////////////////// move element left //////////////////
		} else if(c==1){
			// find out the leftmost positions
			short most_left[3];
			for(int y=0;y<3;y++){
				most_left[y]=-1;

				for(int x=0;x<3;x++){
					if(active_element[x][y]){
						most_left[y]=x;
						break;
					}
				}
			}

			// check collisions
			if(!((most_left[0]!=-1 && (area[active_y+0] & (1<<(COLS-active_x+1-most_left[0])))) ||
					(most_left[1]!=-1 && (area[active_y+1] & (1<<(COLS-active_x+1-most_left[1])))) ||
					(most_left[2]!=-1 && (area[active_y+2] & (1<<(COLS-active_x+1-most_left[2])))))){
				active_x--;
			};

			if(active_x<0){
				active_x=0;
				if(!active_element[0][0] && !active_element[0][1] && !active_element[0][2]){
					// 1. reihe inhalt der 0. reihe
					active_element[0][0]=active_element[1][0];
					active_element[0][1]=active_element[1][1];
					active_element[0][2]=active_element[1][2];
					// 2.reihe mit dem inhalt der 1. reihe
					active_element[1][0]=active_element[2][0];
					active_element[1][1]=active_element[2][1];
					active_element[1][2]=active_element[2][2];
					// 0. Reihe nullen
					active_element[2][0]=false;
					active_element[2][1]=false;
					active_element[2][2]=false;
				}
			};
			updateField();

			////////////////// move element right //////////////////
		} else if(c==2){
			// find out the leftmost positions
			short most_right[3];
			for(int y=0;y<3;y++){
				most_right[y]=-1;

				for(int x=2;x>=0;x--){
					if(active_element[x][y]){
						most_right[y]=x;
						break;
					}
				}
			}

			// check collisions
			if(!((most_right[0]!=-1 && (area[active_y+0] & (1<<(COLS-active_x-1-most_right[0])))) ||
					(most_right[1]!=-1 && (area[active_y+1] & (1<<(COLS-active_x-1-most_right[1])))) ||
					(most_right[2]!=-1 && (area[active_y+2] & (1<<(COLS-active_x-1-most_right[2])))))){
				active_x++;
			};

			if(active_x>9){
				active_x=9;
				// wenn wir eigentlich ganz nach rechts wollten, dann versuch dochmal
				// den inhalt weiter nach rechts zu schieben
				if(!active_element[2][0] && !active_element[2][1] && !active_element[2][2]){
					// 2.reihe mit dem inhalt der 1. reihe
					active_element[2][0]=active_element[1][0];
					active_element[2][1]=active_element[1][1];
					active_element[2][2]=active_element[1][2];
					// 1. reihe inhalt der 0. reihe
					active_element[1][0]=active_element[0][0];
					active_element[1][1]=active_element[0][1];
					active_element[1][2]=active_element[0][2];
					// 0. Reihe nullen
					active_element[0][0]=false;
					active_element[0][1]=false;
					active_element[0][2]=false;
				}
			}

			updateField();
		}
		////////////////// auto move down //////////////////
		// einen tiefer setzen nach ablauf von zeit
		if(last_update+time_between_steps<millis()){
			check_stack(); // erst checken, dann verschieben
			active_y++;
			updateField();
			last_update=millis();
			// 100ms nach dem automatisch runtersetzen checken obs kollisionen gibt
		};
	};

	return true;
};
Ejemplo n.º 27
0
void SvgView::loadPlan(vlePlan *plan)
{
    qWarning() << "SvgView::loadPlan";

    if ( mTplHeader.isNull() )
    {
        // ToDo : improve error handling
        qWarning() << "SvgView::loadPlan() Template error";
        return;
    }

    // Compute the height of a group
    if (mTplHeader.hasAttribute("height"))
        mGroupHeight = mTplHeader.attribute("height").toDouble();
    else
        mGroupHeight = 100;

    // Compute size of the whole plan
    int planHeight = mGroupHeight * (1 + plan->countGroups());
    int planWidth  = (mMaxWidth * mZoomLevel);

    // Create SVG document
    QDomDocument planSVG("xml");
    // Create root element
    QDomElement e = planSVG.createElement("svg");
    e.setAttribute("width",   QString(planWidth));
    e.setAttribute("height",  QString(planHeight));
    e.setAttribute("viewBox", QString("0 0 %1 %2").arg(planWidth).arg(planHeight));
    e.setAttribute("version", "1.1");

    QDate dateStart = plan->dateStart();
    QDate dateEnd   = plan->dateEnd();
    int nbDays = dateStart.daysTo(dateEnd);

    // In the plan duration is more than 1500 days
    if (nbDays > mMaxWidth)
    {
        // Update "pixel-per-day" to avoid very large picture
        qreal widgetSize = mMaxWidth;
        mPixelPerDay = (widgetSize / nbDays);
    }

    if (plan != mPlan)
    {
    qWarning() << "Plan period is from" << dateStart.toString("dd/MM/yyyy")
            << "to" << dateEnd.toString("dd/MM/yyyy")
            << "(" << nbDays<< "days)"
            << "[" << mPixelPerDay << "pixel per day]";
    }

    // First insert the time rule
    QDomElement timeGrp = mTplHeader.cloneNode().toElement();
    updateField(timeGrp, "{{name}}", "");
    updatePos  (timeGrp, 0, 0);
    updateAttr (timeGrp, "header_background", "width", QString::number(planWidth));
    float yLen = (mPixelPerDay * 365 * mZoomLevel);
    // Show Weeks
    if (yLen > 2000)
    {
        QDate r;
        if (dateStart.daysInMonth() == 1)
            r.setDate(dateStart.year(), dateStart.month(), dateStart.day());
        else
            r.setDate(dateStart.year(), dateStart.month() + 1, 1);
        while (r < dateEnd)
        {
            QDomElement newTimeStep = mTplTime.cloneNode().toElement();
            if (yLen < 5000)
                updateField(newTimeStep, "{{name}}", r.toString("dd/MM") );
            else
                updateField(newTimeStep, "{{name}}", r.toString("dd/MM/yy") );
            updateAttr (newTimeStep, "step_block", "width", QString::number(4));

            int offset = dateStart.daysTo(r);
            int aPos = (offset * mPixelPerDay * mZoomLevel);
            updatePos(newTimeStep, aPos, 0);
            timeGrp.appendChild(newTimeStep);
            r = r.addDays(7);
        }
    }
    // Show month
    else if (yLen > 500)
    {
        QDate r;
        if (dateStart.daysInMonth() == 1)
            r.setDate(dateStart.year(), dateStart.month(), dateStart.day());
        else
            r.setDate(dateStart.year(), dateStart.month() + 1, 1);
        while (r < dateEnd)
        {
            QDomElement newTimeStep = mTplTime.cloneNode().toElement();
            if (yLen < 1000)
                updateField(newTimeStep, "{{name}}", r.toString("MMM") );
            else
                updateField(newTimeStep, "{{name}}", r.toString("MMM yy") );
            updateAttr (newTimeStep, "step_block", "width", QString::number(4));

            int offset = dateStart.daysTo(r);
            int aPos = (offset * mPixelPerDay * mZoomLevel);
            updatePos(newTimeStep, aPos, 0);
            timeGrp.appendChild(newTimeStep);
            r = r.addMonths(1);
        }
    }
    // Show Year
    else
    {
        QDate r;
        if (dateStart.dayOfYear() == 1)
            r.setDate(dateStart.year(), dateStart.month(), dateStart.day());
        else
            r.setDate(dateStart.year() + 1, 1, 1);
        while (r < dateEnd)
        {
            QDomElement newTimeStep = mTplTime.cloneNode().toElement();
            updateField(newTimeStep, "{{name}}", QString::number(r.year()) );
            updateAttr (newTimeStep, "step_block", "width", QString::number(4));

            int offset = dateStart.daysTo(r);
            int aPos = (offset * mPixelPerDay * mZoomLevel);
            updatePos(newTimeStep, aPos, 0);
            timeGrp.appendChild(newTimeStep);
            r = r.addYears(1);
        }
    }
    e.appendChild(timeGrp);

    // Insert all the known groups
    for (int i=0; i < plan->countGroups(); i++)
    {
        vlePlanGroup *planGroup = plan->getGroup(i);
        vlePlanActivity *prevActivity = 0;
        int prevLen = 0;
        int prevOffset = 0;

        // Create a new Group
        QDomElement newGrp = mTplHeader.cloneNode().toElement();
        updateField(newGrp, "{{name}}", planGroup->getName());
        updatePos  (newGrp, 0, ((i + 1) * mGroupHeight));
        updateAttr (newGrp, "header_background", "width", QString::number(planWidth));

        for (int j = 0; j < planGroup->count(); j++)
        {
            vlePlanActivity *planActivity = planGroup->getActivity(j);

            QDate actStart = planActivity->dateStart();
            QDate actEnd   = planActivity->dateEnd();

            qreal actLength = (mPixelPerDay * actStart.daysTo(actEnd) * mZoomLevel);
            if (actLength < 1)
                actLength = 1;

            QDomElement newAct = mTplTask.cloneNode().toElement();
            updateField(newAct, "{{name}}", planActivity->getName());
            updateAttr (newAct, "activity_block", "width", QString::number(actLength));

            QString cfgColor("#00edda");
            QString activityClass = planActivity->getClass();
            if ( ! activityClass.isEmpty() )
            {
                QString cfg = getConfig("color", activityClass);
                if ( ! cfg.isEmpty() )
                    cfgColor = cfg;
            }
            QString fillStyle = QString(";fill:%1").arg(cfgColor);
            updateAttr (newAct, "activity_block", "style", fillStyle, false);

            int date = dateStart.daysTo(planActivity->dateStart());
            int aPos = (date * mPixelPerDay * mZoomLevel);

            if (prevActivity)
            {
                if (prevLen > aPos)
                {
                    if (prevOffset < 40)
                        prevOffset += 15;
                    updateAttr(newAct, "activity_name", "y", QString::number(prevOffset));
                }
                else
                    prevOffset = 15;
            }

            updatePos(newAct, aPos, 0);
            newGrp.appendChild(newAct);

            prevActivity = planActivity;
            prevLen = aPos + (planActivity->getName().size() * 8);
        }

        e.appendChild(newGrp);
    }
    planSVG.appendChild( e );

    QByteArray data;
    QTextStream stream(&data);
    planSVG.save(stream, QDomNode::EncodingFromTextStream);

#ifdef PLAN_OUT
    QFile File("planOut.svg");
    File.open( QIODevice::WriteOnly );
    QTextStream TextStream(&File);
    planSVG.save(TextStream, 0);
    File.close();
    mFilename = "planOut.svg";
#else
    mFilename.clear();
#endif

    mPlan = plan;

    QXmlStreamReader xData(data);
    mSvgRenderer->load(&xData);
    refresh();
}
Ejemplo n.º 28
0
//al apretar el boton reset, vuelve a cargar los parametros del modulo seleccionado.
void ParameterDialog::on_resetButton_clicked(){
    updateField(ui->currentList->currentItem()->text());
}
Ejemplo n.º 29
0
ParameterDialog::ParameterDialog(VideoAnalysis *i_va, QWidget *parent) : QDialog(parent), va(i_va), ui(new Ui::ParameterDialog){
    ui->setupUi(this);
    QObject::connect(ui->currentList,SIGNAL(currentTextChanged(QString)),this,SLOT(updateField(QString)));
}
Ejemplo n.º 30
0
void Board::mousePressEvent(QMouseEvent *e)
{
	// Calculate field position
	int pos_x = (e->pos().x() - xOffset()) / tiles.tileWidth();
	int pos_y = (e->pos().y() - yOffset()) / tiles.tileHeight();

	if(e->pos().x() < xOffset() || e->pos().y() < yOffset() ||
		pos_x >= x_tiles() || pos_y >= y_tiles())
	{
		pos_x = -1;
		pos_y = -1;
	}

	// Mark tile
	if(e->button() == LeftButton)
	{
		clearHighlight();

		if(pos_x != -1)
			marked(pos_x, pos_y);
	}

	// Assist by highlighting all tiles of same type
	if(e->button() == RightButton)
	{
		int clicked_tile = getField(pos_x, pos_y);

		// Clear marked tile
		if(mark_x != -1 && getField(mark_x, mark_y) != clicked_tile)
		{
			// We need to set mark_x and mark_y to -1 before calling
			// updateField() to ensure the tile is redrawn as unmarked.
			int oldmarkx = mark_x;
			int oldmarky = mark_y;
			mark_x = -1;
			mark_y = -1;
			updateField(oldmarkx, oldmarky, false);
		}
		else
		{
			mark_x = -1;
			mark_y = -1;
		}

		// Perform highlighting
		if(clicked_tile != highlighted_tile)
		{
			int old_highlighted = highlighted_tile;
			highlighted_tile = clicked_tile;
			for(int i = 0; i < x_tiles(); i++)
			{
				for(int j = 0; j < y_tiles(); j++)
				{
					const int field_tile = getField(i, j);
					if(field_tile != EMPTY)
					{
						if(field_tile == old_highlighted)
							updateField(i, j, false);
						else if(field_tile == clicked_tile)
							updateField(i, j, false);
					}
				}
			}
		}
	}
}