Ejemplo n.º 1
0
//---------------------------------------------------------------
//--- rFile Constructors
//---------------------------------------------------------------
rFile::rFile(void)
{
	init();
	typeSize = 0;
	dataLen = 0;
	clearPath();
	clearName();
}
void drawUnits(UnitListHeader * units, Path * thePath, int makeHit) {
    int i = 0;
    int healthColour = 0;
    int drawColour = 0;
    Unit * curUnit;
    int y = 0;
    int x = 0;
    int maxHealth = 0;

    clearPath();
    for(i = 0; i < units->size; i++) {
        curUnit = moveTo(i,units);
        switch(curUnit->unitType) {
            case unit1:
                maxHealth = unit1Health;
                break;
            case unit2:
                maxHealth = unit2Health;
                break;
            case unit3:
                maxHealth = unit3Health;
                break;
            case unit4:
                maxHealth = unit4Health;
                break;
            case unit5:
                maxHealth = unit5Health;
                break;
            default:
                endwin();
                exit(1);
                break;
        }

        healthColour = curUnit->health;
        if (healthColour < (int)(maxHealth / 3)) {
            drawColour = 4;
        } else if (healthColour < (int)(maxHealth * 2 / 3)) {
            drawColour = 1;
        } else {
            drawColour = 3;
        }
        if (makeHit == 1 && curUnit->isHit == 1) {
            drawColour = 1;
            curUnit->isHit = 0;
        }

        if (curUnit->pathLocation > 0 && curUnit->pathLocation < thePath->size) {
            refresh();
            y = thePath->coords[curUnit->pathLocation].y+3;
            x = thePath->coords[curUnit->pathLocation].x+10;

            attron(COLOR_PAIR(drawColour));
            mvaddch(y, x, curUnit->unitType | A_ALTCHARSET);
            attroff(COLOR_PAIR(drawColour));
        }
    }
}
Ejemplo n.º 3
0
void AIPlayer::onRemove()
{
#ifdef TORQUE_NAVIGATION_ENABLED
   clearPath();
   clearCover();
   clearFollow();
#endif
   Parent::onRemove();
}
Ejemplo n.º 4
0
/**
 * Stops movement for this AI
 */
void AIPlayer::stopMove()
{
   mMoveState = ModeStop;
#ifdef TORQUE_NAVIGATION_ENABLED
   clearPath();
   clearCover();
   clearFollow();
#endif
}
Ejemplo n.º 5
0
bool AIPlayer::setPathDestination(const Point3F &pos)
{
   // Pathfinding only happens on the server.
   if(!isServerObject())
      return false;

   if(!getNavMesh())
      updateNavMesh();
   // If we can't find a mesh, just move regularly.
   if(!getNavMesh())
   {
      //setMoveDestination(pos);
      throwCallback("onPathFailed");
      return false;
   }

   // Create a new path.
   NavPath *path = new NavPath();

   path->mMesh = getNavMesh();
   path->mFrom = getPosition();
   path->mTo = pos;
   path->mFromSet = path->mToSet = true;
   path->mAlwaysRender = true;
   path->mLinkTypes = mLinkTypes;
   path->mXray = true;
   // Paths plan automatically upon being registered.
   if(!path->registerObject())
   {
      delete path;
      return false;
   }

   if(path->success())
   {
      // Clear any current path we might have.
      clearPath();
      clearCover();
      clearFollow();
      // Store new path.
      mPathData.path = path;
      mPathData.owned = true;
      // Skip node 0, which we are currently standing on.
      moveToNode(1);
      throwCallback("onPathSuccess");
      return true;
   }
   else
   {
      // Just move normally if we can't path.
      //setMoveDestination(pos, true);
      //return;
      throwCallback("onPathFailed");
      path->deleteObject();
      return false;
   }
}
Ejemplo n.º 6
0
void MovingPathScript::MovingPathScriptImpl::endMakingMovingPath(const EvtDataInputDrag & drag)
{
	assert(m_IsMakingPath && "MovingPathScriptImpl::endMakingMovingPath() the flag for making path is off.");

	if (isBackIndex(toGridIndex(drag.getPositionInWorld()))) {
		SingletonContainer::getInstance()->get<IEventDispatcher>()->vQueueEvent(std::make_unique<EvtDataMakeMovingPathEnd>(m_MovingPath));
	}

	clearPath();
	m_IsMakingPath = false;
}
Ejemplo n.º 7
0
void UnitBase::doAttackPos(int xPos, int yPos, bool bForced) {
    if(attackMode == CAPTURE) {
        doSetAttackMode(GUARD);
	}

	setDestination(xPos,yPos);
	setTarget(NULL);
	setForced(bForced);
	attackPos.x = xPos;
	attackPos.y = yPos;

	clearPath();
	findTargetTimer = 0;
}
Ejemplo n.º 8
0
void UnitBase::doMove2Pos(int xPos, int yPos, bool bForced) {
    if(attackMode == CAPTURE || attackMode == HUNT) {
        doSetAttackMode(GUARD);
	}

	if((xPos != destination.x) || (yPos != destination.y)) {
		clearPath();
		findTargetTimer = 0;
	}

	setTarget(NULL);
	setDestination(xPos,yPos);
	setForced(bForced);
	setGuardPoint(xPos,yPos);
}
Ejemplo n.º 9
0
bool PyVisInterface::InitPython() {
    if(0 != Py_IsInitialized() || g_PyVis != NULL)
        return true;

    std::unique_ptr<PyVis> pyVis(new PyVis()); 

    Py_Initialize();
    PyErr_Print();
    
    // Need to load sys and path in order to load modules from custom dirs
    PyObject* systemModule = PyImport_ImportModule("sys");
    ScopePyDecRef clearSystem(systemModule);
    if(!systemModule || !PyModule_Check(systemModule)) {
        printf("Error loading python module sys:\n");
        PyErr_Print();
        return false;
    }
    PyErr_Print();
    
    PyObject* sysPath = PyObject_GetAttrString(systemModule, "path");
    ScopePyDecRef clearPath(sysPath);
    if(!sysPath || !PyList_Check(sysPath)) {
        printf("Error loading python sys path:\n");
        PyErr_Print();
        return false;
    }
    PyList_Append(sysPath, PyString_FromString("pyvis"));
    PyList_Append(sysPath, PyString_FromString("pyvis/PIMCPy"));
    PyErr_Print();

    PyObject* mainModule = pyVis->LoadModule("__main__");
    pyVis->consoleGlobalContextDict = mainModule; 
    PyErr_Print();
    if(!mainModule) { return false; }
  
    //if(!LoadInitialModules(pyVis.get())) {
    //    return false;
    //}
    //PyErr_Print();

    if(0 == Py_IsInitialized()) {
        return false;
    }

    PyErr_Print();
    g_PyVis = pyVis.release();
    return true;
}
Ejemplo n.º 10
0
void LocalPlayer::stopWalking(bool sendToServer)
{
    if (mAction == WALK && mWalkingDir) {
        mWalkingDir = 0;
#ifdef TMWSERV_SUPPORT
        mLocalWalkTime = 0;
#endif
        Being::setDestination(getPosition().x,getPosition().y);
        if (sendToServer)
             Net::getPlayerHandler()->setDestination(getPosition().x,
                                                     getPosition().y);
        setAction(STAND);
    }

    clearPath();
}
Ejemplo n.º 11
0
void UnitBase::deviate(House* newOwner) {

    if(newOwner->getHouseID() == originalHouseID) {
        quitDeviation();
    } else {
        removeFromSelectionLists();
        setTarget(NULL);
        setGuardPoint(location);
        setDestination(location);
        clearPath();
        doSetAttackMode(GUARD);
        owner = newOwner;

        graphic = pGFXManager->getObjPic(graphicID,getOwner()->getHouseID());
        deviationTimer = DEVIATIONTIME;
    }
}
Ejemplo n.º 12
0
void MovingPathScript::MovingPathScriptImpl::updateAndShowPath(const GridIndex & destination)
{
	//If the area is expired, or the destination is not in the area, just do nothing and return.
	if (m_MovingArea.expired())
		return;
	auto area = m_MovingArea.lock();
	if (!area->hasIndex(destination))
		return;

	auto newPath = createPath(m_MovingPath, destination, *area);
	if (newPath != m_MovingPath) {
		clearPath();

		m_MovingPath = std::move(newPath);
		setChildrenGridActors(m_MovingPath, *m_OwnerActor.lock());
	}
}
Ejemplo n.º 13
0
void UnitBase::setLocation(int xPos, int yPos) {

	if((xPos == INVALID_POS) && (yPos == INVALID_POS)) {
		ObjectBase::setLocation(xPos, yPos);
	} else if (currentGameMap->tileExists(xPos, yPos)) {
		ObjectBase::setLocation(xPos, yPos);
		realX += TILESIZE/2;
		realY += TILESIZE/2;
		bumpyOffsetX = 0.0f;
		bumpyOffsetY = 0.0f;
	}

	moving = false;
	pickedUp = false;
	setTarget(NULL);

	clearPath();
}
Ejemplo n.º 14
0
void LayoutSVGRect::updateShapeFromElement()
{
    m_usePathFallback = false;

    // Fallback to LayoutSVGShape and path-based hit detection if the rect
    // has rounded corners or a non-scaling or non-simple stroke.
    SVGLengthContext lengthContext(toSVGRectElement(element()));
    if (lengthContext.valueForLength(styleRef().svgStyle().rx(), styleRef(), SVGLengthMode::Width) > 0
        || lengthContext.valueForLength(styleRef().svgStyle().ry(), styleRef(), SVGLengthMode::Height) > 0
        || hasNonScalingStroke()
        || !definitelyHasSimpleStroke(style()->svgStyle())) {
        LayoutSVGShape::updateShapeFromElement();
        m_usePathFallback = true;
        return;
    }

    clearPath();
}
/**
 * Receives path from PathPlanner and starts moving towards goal.
 */
void PathHandler::pathCb(const nav_msgs::Path &path)
{
	ROS_INFO("Received new path.");

	if (path.poses.size() == 0)
	{
		ROS_ERROR("Received empty path.");
		return;
	}

	clearPath();
	mCurrentPathIndex = 0;

	for (size_t i = 0; i < path.poses.size(); i++)
		mPath.push_back(path.poses[i].pose);

	mFollowState = FOLLOW_STATE_BUSY;
}
Ejemplo n.º 16
0
void UnitBase::doMove2Object(const ObjectBase* pTargetObject) {
	if(pTargetObject->getObjectID() == getObjectID()) {
		return;
	}

    if(attackMode == CAPTURE || attackMode == HUNT) {
        doSetAttackMode(GUARD);
	}

	setDestination(INVALID_POS,INVALID_POS);
	setTarget(pTargetObject);
	setForced(true);

	bFollow = true;

	clearPath();
	findTargetTimer = 0;
}
Ejemplo n.º 17
0
void SelfTestUtil::clearPath(const QString &curDir)
{
    QDir dir(curDir);
    QStringList fileList = dir.entryList(QDir::Files);
    for (int i = 0; i < fileList.size(); i ++)
        if (! dir.remove(fileList[i])) {
#ifdef LEMON_OS_WIN32
            QProcess::execute(QString("attrib -R \"") + curDir + fileList[i] + "\"");
#endif
#ifdef LEMON_OS_UNIX
            QProcess::execute(QString("chmod +w \"") + curDir + fileList[i] + "\"");
#endif
            dir.remove(fileList[i]);
        }
    QStringList dirList = dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot);
    for (int i = 0; i < dirList.size(); i ++) {
        clearPath(curDir + dirList[i] + QDir::separator());
        dir.rmdir(dirList[i]);
    }
}
Ejemplo n.º 18
0
void pathFinder::readPathFromDirMap( const vector2 &end )
{
	// 将旧的路径信息清空
	clearPath();

	vector2 curPos = end;

	// 逆向读取路径,逆向插入路径点数据,最后得到的就是正向的路径了
	int curDir = 0;
	do 
	{
		path.push_front( curPos );

		curDir = dirMap[curPos.x][curPos.y];
		curPos.x = curPos.x + dirArray[curDir].x;
		curPos.y = curPos.y + dirArray[curDir].y;
	} while ( dirMap[curPos.x][curPos.y] != MS_START );

	path.push_front( curPos );
}
Ejemplo n.º 19
0
NDFindPath::~NDFindPath()
{
	clearPath();
}
Ejemplo n.º 20
0
void SelfTestUtil::makeSelfTest(QWidget *widget, Contest *contest)
{
    QApplication::setOverrideCursor(Qt::WaitCursor);
    if (QDir(Settings::selfTestPath()).exists())
        clearPath(Settings::selfTestPath());
    if (! QDir(Settings::selfTestPath()).exists() && ! QDir().mkdir(Settings::selfTestPath())) {
        QApplication::restoreOverrideCursor();
        QMessageBox::warning(widget, tr("Lemon"), tr("Cannot make directory"), QMessageBox::Ok);
        return;
    }
    QList<Task*> taskList = contest->getTaskList();
    for (int i = 0; i < taskList.size(); i ++) {
        QDir(Settings::selfTestPath()).mkdir(taskList[i]->getProblemTile());
        QList<TestCase*> testCaseList = taskList[i]->getTestCaseList();
#ifdef LEMON_OS_WIN32
        QFile file(Settings::selfTestPath() + taskList[i]->getProblemTile() + QDir::separator() + "check.bat");
        if (! file.open(QFile::WriteOnly | QFile::Text)) {
            QApplication::restoreOverrideCursor();
            QMessageBox::warning(widget, tr("Lemon"), tr("Cannot write check.bat"), QMessageBox::Ok);
            return;
        }
        QFile dummy(Settings::selfTestPath() + taskList[i]->getProblemTile() + QDir::separator() + "enter");
        if (! dummy.open(QFile::WriteOnly | QFile::Text)) {
            QApplication::restoreOverrideCursor();
            QMessageBox::warning(widget, tr("Lemon"), tr("Cannot write enter"), QMessageBox::Ok);
            return;
        }
        QTextStream dummyStream(&dummy);
        dummyStream << endl;
        dummy.close();
#endif
#ifdef LEMON_OS_UNIX
        QFile file(Settings::selfTestPath() + taskList[i]->getProblemTile() + QDir::separator() + "check.sh");
        if (! file.open(QFile::WriteOnly | QFile::Text)) {
            QApplication::restoreOverrideCursor();
            QMessageBox::warning(widget, tr("Lemon"), tr("Cannot write check.sh"), QMessageBox::Ok);
            return;
        }
#endif
        QTextStream out(&file);
#ifdef LEMON_OS_WIN32
        out << "@echo off" << endl;
#endif
#ifdef LEMON_OS_UNIX
        out << "#!/bin/bash" << endl;
#endif
        if (taskList[i]->getComparisonMode() == Task::RealNumberMode) {
#ifdef LEMON_OS_WIN32
            QFile::copy(":/judge/realjudge_win32.exe",
                        Settings::selfTestPath() + taskList[i]->getProblemTile()
                        + QDir::separator() + "realjudge.exe");
            QProcess::execute(QString("attrib -R \"") + Settings::selfTestPath() + taskList[i]->getProblemTile()
                              + QDir::separator() + "realjudge.exe" + "\"");
#endif
#ifdef LEMON_OS_UNIX
            QFile::copy(":/judge/realjudge_linux",
                        Settings::selfTestPath() + taskList[i]->getProblemTile()
                        + QDir::separator() + "realjudge");
            QProcess::execute(QString("chmod +wx \"") + Settings::selfTestPath() + taskList[i]->getProblemTile()
                              + QDir::separator() + "realjudge" + "\"");
#endif
        }
        if (taskList[i]->getComparisonMode() == Task::SpecialJudgeMode) {
            if (! QFile::copy(Settings::dataPath() + taskList[i]->getSpecialJudge(),
                              Settings::selfTestPath() + taskList[i]->getProblemTile() + QDir::separator()
                              + QFileInfo(taskList[i]->getSpecialJudge()).fileName())) {
                QApplication::restoreOverrideCursor();
                QMessageBox::warning(widget, tr("Lemon"),
                                     tr("Cannot copy %1").arg(QFileInfo(taskList[i]->getSpecialJudge()).fileName()),
                                     QMessageBox::Ok);
                return;
            }
        }
        int index = 0;
        for (int j = 0; j < testCaseList.size(); j ++) {
            QStringList inputFiles = testCaseList[j]->getInputFiles();
            QStringList outputFiles = testCaseList[j]->getOutputFiles();
            for (int k = 0; k < inputFiles.size(); k ++) {
                index ++;
                QString inputFile, outputFile;
                if (taskList[i]->getTaskType() == Task::Traditional) {
                    inputFile = taskList[i]->getSourceFileName();
                    inputFile += QString("%1.in").arg(index);
                    outputFile = taskList[i]->getSourceFileName();
                    outputFile += QString("%1.out").arg(index);
                } else {
                    inputFile = QFileInfo(inputFiles[k]).fileName();
                    outputFile = QFileInfo(outputFiles[k]).fileName();
                }
                if (! QFile::copy(Settings::dataPath() + inputFiles[k],
                                  Settings::selfTestPath() + taskList[i]->getProblemTile() + QDir::separator()
                                  + inputFile)) {
                    QApplication::restoreOverrideCursor();
                    QMessageBox::warning(widget, tr("Lemon"),
                                         tr("Cannot copy %1").arg(QFileInfo(inputFiles[k]).fileName()),
                                         QMessageBox::Ok);
                    return;
                }
                if (! QFile::copy(Settings::dataPath() + outputFiles[k],
                                  Settings::selfTestPath() + taskList[i]->getProblemTile() + QDir::separator()
                                  + outputFile)) {
                    QApplication::restoreOverrideCursor();
                    QMessageBox::warning(widget, tr("Lemon"),
                                         tr("Cannot copy %1").arg(QFileInfo(outputFiles[k]).fileName()),
                                         QMessageBox::Ok);
                    return;
                }
#ifdef LEMON_OS_WIN32
                if (! taskList[i]->getStandardInputCheck() && taskList[i]->getTaskType() == Task::Traditional) {
                    out << QString("copy \"%1\" \"%2\" >nul").arg(inputFile,
                                                                  taskList[i]->getInputFileName()) << endl;
                }
                out << QString("echo Test Case: %1").arg(index) << endl;
                if (taskList[i]->getTaskType() == Task::Traditional) {
                    out << "time<enter" << endl;
                    QString cmd = QString("\"") + taskList[i]->getSourceFileName() + ".exe" + "\"";
                    if (taskList[i]->getStandardInputCheck()) {
                        cmd += QString(" <\"%1\"").arg(inputFile);
                    }
                    if (taskList[i]->getStandardOutputCheck()) {
                        cmd += QString(" >\"%1\"").arg("_tmpout");
                    }
                    out << cmd << endl;
                    out << "time<enter" << endl;
                }
                QString outputFileName;
                if (taskList[i]->getTaskType() == Task::Traditional) {
                    if (taskList[i]->getStandardOutputCheck()) {
                        outputFileName = "_tmpout";
                    } else {
                        outputFileName = taskList[i]->getOutputFileName();
                    }
                } else {
                    outputFileName = QFileInfo(inputFiles[k]).completeBaseName() + "."
                                     + taskList[i]->getAnswerFileExtension();
                }
                if (taskList[i]->getComparisonMode() == Task::LineByLineMode) {
                    out << QString("fc \"%1\" \"%2\"")
                           .arg(outputFileName, outputFile) << endl;
                }
                if (taskList[i]->getComparisonMode() == Task::IgnoreSpacesMode) {
                    out << QString("fc \"%1\" \"%2\" /W")
                           .arg(outputFileName, outputFile) << endl;
                }
                if (taskList[i]->getComparisonMode() == Task::ExternalToolMode) {
                    out << QString("fc \"%1\" \"%2\"")
                           .arg(outputFileName, outputFile) << endl;
                }
                if (taskList[i]->getComparisonMode() == Task::RealNumberMode) {
                    out << QString("realjudge.exe \"%1\" \"%2\" \"%3\"")
                           .arg(outputFileName).arg(outputFile).arg(taskList[i]->getRealPrecision()) << endl;
                }
                if (taskList[i]->getComparisonMode() == Task::SpecialJudgeMode) {
                    out << QString("\"%1\" \"%2\" \"%3\" \"%4\" \"%5\" \"%6\" \"%7\"")
                           .arg(QFileInfo(taskList[i]->getSpecialJudge()).fileName(),
                                inputFile, outputFileName, outputFile,
                                QString("%1").arg(testCaseList[j]->getFullScore()),
                                "_score", "_message") << endl;
                    out << "echo Your score:" << endl << "type _score" << endl;
                    out << "if exist _message (" << endl;
                    out << "echo Message:" << endl << "type _message" << endl << ")" << endl;
                }
                out << "pause" << endl;
                if (! taskList[i]->getStandardInputCheck() && taskList[i]->getTaskType() == Task::Traditional) {
                    out << QString("del \"%1\"").arg(taskList[i]->getInputFileName()) << endl;
                }
                if (taskList[i]->getTaskType() == Task::Traditional) {
                    if (! taskList[i]->getStandardOutputCheck()) {
                        out << QString("del \"%1\"").arg(taskList[i]->getOutputFileName()) << endl;
                    } else {
                        out << "del _tmpout" << endl;
                    }
                }
                if (taskList[i]->getComparisonMode() == Task::SpecialJudgeMode) {
                    out << "del _score" << endl << "del _message" << endl;
                }
                out << "echo." << endl << endl;
#endif
#ifdef LEMON_OS_UNIX
                if (! taskList[i]->getStandardInputCheck() && taskList[i]->getTaskType() == Task::Traditional) {
                    out << QString("cp %1 %2").arg(inputFile,
                                                   taskList[i]->getInputFileName()) << endl;
                }
                out << QString("echo \"Test Case: %1\"").arg(index) << endl;
                if (taskList[i]->getTaskType() == Task::Traditional) {
                    QString cmd = QString("\"") + taskList[i]->getSourceFileName() + "\"";
                    if (taskList[i]->getStandardInputCheck()) {
                        cmd += QString(" <\"%1\"").arg(inputFile);
                    }
                    if (taskList[i]->getStandardOutputCheck()) {
                        cmd += QString(" >\"%1\"").arg("_tmpout");
                    }
                    out << QString("time ./") << cmd << endl;
                }
                QString outputFileName;
                if (taskList[i]->getTaskType() == Task::Traditional) {
                    if (taskList[i]->getStandardOutputCheck()) {
                        outputFileName = "_tmpout";
                    } else {
                        outputFileName = taskList[i]->getOutputFileName();
                    }
                } else {
                    outputFileName = QFileInfo(inputFiles[k]).completeBaseName() + "."
                                     + taskList[i]->getAnswerFileExtension();
                }
                if (taskList[i]->getComparisonMode() == Task::LineByLineMode) {
                    QString arg = QString("\"%1\" \"%2\"").arg(outputFileName, outputFile);
                    out << "if ! diff " << arg << " --strip-trailing-cr -q;then" << endl;
                    out << "diff " << arg << " --strip-trailing-cr -y" << endl;
                    out << QString("echo \"Wrong answer\"") << endl;
                    out << "else" << endl;
                    out << QString("echo \"Correct answer\"") << endl;
                    out << "fi" << endl;
                }
                if (taskList[i]->getComparisonMode() == Task::IgnoreSpacesMode) {
                    QString arg = QString(" \"%1\" \"%2\"").arg(outputFileName, outputFile);
                    out << "if ! diff" << " --strip-trailing-cr -q --ignore-space-change" << arg << ";then" << endl;
                    out << "diff" << " --strip-trailing-cr -y --ignore-space-change" << arg << endl;
                    out << QString("echo \"Wrong answer\"") << endl;
                    out << "else" << endl;
                    out << QString("echo \"Correct answer\"") << endl;
                    out << "fi" << endl;
                }
                if (taskList[i]->getComparisonMode() == Task::ExternalToolMode) {
                    QString arg = QString(" \"%1\" \"%2\"").arg(outputFileName, outputFile);
                    out << "if ! diff " << taskList[i]->getDiffArguments() << arg << ";then" << endl;
                    out << "diff " << taskList[i]->getDiffArguments() << arg << endl;
                    out << QString("echo \"Wrong answer\"") << endl;
                    out << "else" << endl;
                    out << QString("echo \"Correct answer\"") << endl;
                    out << "fi" << endl;
                }
                if (taskList[i]->getComparisonMode() == Task::RealNumberMode) {
                    out << QString("./realjudge \"%1\" \"%2\" \"%3\"")
                           .arg(outputFileName).arg(outputFile).arg(taskList[i]->getRealPrecision()) << endl;
                }
                if (taskList[i]->getComparisonMode() == Task::SpecialJudgeMode) {
                    out << QString("./%1 \"%2\" \"%3\" \"%4\" \"%5\" \"%6\" \"%7\"")
                           .arg(QFileInfo(taskList[i]->getSpecialJudge()).fileName(),
                                inputFile, outputFileName, outputFile,
                                QString("%1").arg(testCaseList[j]->getFullScore()),
                                "_score", "_message") << endl;
                    out << "echo \"Your score:\"" << endl << "cat _score" << endl;
                    out << "if [ -e _message ];then" << endl;
                    out << "echo \"Message:\"" << endl << "cat _message" << endl << "fi" << endl;
                }
                out << "read -n1 -p \"Press enter to continue...\"" << endl;
                if (! taskList[i]->getStandardInputCheck() && taskList[i]->getTaskType() == Task::Traditional) {
                    out << QString("rm \"%1\"").arg(taskList[i]->getInputFileName()) << endl;
                }
                if (taskList[i]->getTaskType() == Task::Traditional) {
                    if (! taskList[i]->getStandardOutputCheck()) {
                        out << QString("rm \"%1\"").arg(taskList[i]->getOutputFileName()) << endl;
                    } else {
                        out << "rm _tmpout" << endl;
                    }
                }
                if (taskList[i]->getComparisonMode() == Task::SpecialJudgeMode) {
                    out << "rm _score" << endl << "rm _message" << endl;
                }
                out << "echo" << endl << endl;
#endif
            }
        }
        file.close();
#ifdef LEMON_OS_UNIX
        QProcess::execute(QString("chmod +x \"") + Settings::selfTestPath() + taskList[i]->getProblemTile()
                          + QDir::separator() + "check.sh" + "\"");
#endif
    }
    
    QApplication::restoreOverrideCursor();
    QMessageBox::information(widget, tr("Lemon"), tr("Self-test folder has been made"), QMessageBox::Ok);
}
void LLFloaterPathfindingConsole::updateControlsOnConsoleState()
{
	switch (mConsoleState)
	{
	case kConsoleStateUnknown :
	case kConsoleStateRegionNotEnabled :
	case kConsoleStateRegionLoading :
		mViewTestTabContainer->selectTab(XUI_VIEW_TAB_INDEX);
		mViewTab->setEnabled(FALSE);
		mShowLabel->setEnabled(FALSE);
		mShowWorldCheckBox->setEnabled(FALSE);
		mShowWorldMovablesOnlyCheckBox->setEnabled(FALSE);
		mShowNavMeshCheckBox->setEnabled(FALSE);
		mShowNavMeshWalkabilityLabel->setEnabled(FALSE);
		mShowNavMeshWalkabilityComboBox->setEnabled(FALSE);
		mShowWalkablesCheckBox->setEnabled(FALSE);
		mShowStaticObstaclesCheckBox->setEnabled(FALSE);
		mShowMaterialVolumesCheckBox->setEnabled(FALSE);
		mShowExclusionVolumesCheckBox->setEnabled(FALSE);
		mShowRenderWaterPlaneCheckBox->setEnabled(FALSE);
		mShowXRayCheckBox->setEnabled(FALSE);
		mTestTab->setEnabled(FALSE);
		mCtrlClickLabel->setEnabled(FALSE);
		mShiftClickLabel->setEnabled(FALSE);
		mCharacterWidthLabel->setEnabled(FALSE);
		mCharacterWidthUnitLabel->setEnabled(FALSE);
		mCharacterWidthSlider->setEnabled(FALSE);
		mCharacterTypeLabel->setEnabled(FALSE);
		mCharacterTypeComboBox->setEnabled(FALSE);
		mClearPathButton->setEnabled(FALSE);
		clearPath();
		break;
	case kConsoleStateLibraryNotImplemented :
		mViewTestTabContainer->selectTab(XUI_VIEW_TAB_INDEX);
		mViewTab->setEnabled(FALSE);
		mShowLabel->setEnabled(FALSE);
		mShowWorldCheckBox->setEnabled(FALSE);
		mShowWorldMovablesOnlyCheckBox->setEnabled(FALSE);
		mShowNavMeshCheckBox->setEnabled(FALSE);
		mShowNavMeshWalkabilityLabel->setEnabled(FALSE);
		mShowNavMeshWalkabilityComboBox->setEnabled(FALSE);
		mShowWalkablesCheckBox->setEnabled(FALSE);
		mShowStaticObstaclesCheckBox->setEnabled(FALSE);
		mShowMaterialVolumesCheckBox->setEnabled(FALSE);
		mShowExclusionVolumesCheckBox->setEnabled(FALSE);
		mShowRenderWaterPlaneCheckBox->setEnabled(FALSE);
		mShowXRayCheckBox->setEnabled(FALSE);
		mTestTab->setEnabled(FALSE);
		mCtrlClickLabel->setEnabled(FALSE);
		mShiftClickLabel->setEnabled(FALSE);
		mCharacterWidthLabel->setEnabled(FALSE);
		mCharacterWidthUnitLabel->setEnabled(FALSE);
		mCharacterWidthSlider->setEnabled(FALSE);
		mCharacterTypeLabel->setEnabled(FALSE);
		mCharacterTypeComboBox->setEnabled(FALSE);
		mClearPathButton->setEnabled(FALSE);
		clearPath();
		break;
	case kConsoleStateCheckingVersion :
	case kConsoleStateDownloading :
	case kConsoleStateError :
		mViewTestTabContainer->selectTab(XUI_VIEW_TAB_INDEX);
		mViewTab->setEnabled(FALSE);
		mShowLabel->setEnabled(FALSE);
		mShowWorldCheckBox->setEnabled(FALSE);
		mShowWorldMovablesOnlyCheckBox->setEnabled(FALSE);
		mShowNavMeshCheckBox->setEnabled(FALSE);
		mShowNavMeshWalkabilityLabel->setEnabled(FALSE);
		mShowNavMeshWalkabilityComboBox->setEnabled(FALSE);
		mShowWalkablesCheckBox->setEnabled(FALSE);
		mShowStaticObstaclesCheckBox->setEnabled(FALSE);
		mShowMaterialVolumesCheckBox->setEnabled(FALSE);
		mShowExclusionVolumesCheckBox->setEnabled(FALSE);
		mShowRenderWaterPlaneCheckBox->setEnabled(FALSE);
		mShowXRayCheckBox->setEnabled(FALSE);
		mTestTab->setEnabled(FALSE);
		mCtrlClickLabel->setEnabled(FALSE);
		mShiftClickLabel->setEnabled(FALSE);
		mCharacterWidthLabel->setEnabled(FALSE);
		mCharacterWidthUnitLabel->setEnabled(FALSE);
		mCharacterWidthSlider->setEnabled(FALSE);
		mCharacterTypeLabel->setEnabled(FALSE);
		mCharacterTypeComboBox->setEnabled(FALSE);
		mClearPathButton->setEnabled(FALSE);
		clearPath();
		break;
	case kConsoleStateHasNavMesh :
		mViewTab->setEnabled(TRUE);
		mShowLabel->setEnabled(TRUE);
		mShowWorldCheckBox->setEnabled(TRUE);
		setWorldRenderState();
		mShowNavMeshCheckBox->setEnabled(TRUE);
		setNavMeshRenderState();
		mShowWalkablesCheckBox->setEnabled(TRUE);
		mShowStaticObstaclesCheckBox->setEnabled(TRUE);
		mShowMaterialVolumesCheckBox->setEnabled(TRUE);
		mShowExclusionVolumesCheckBox->setEnabled(TRUE);
		mShowRenderWaterPlaneCheckBox->setEnabled(TRUE);
		mShowXRayCheckBox->setEnabled(TRUE);
		mTestTab->setEnabled(TRUE);
		mCtrlClickLabel->setEnabled(TRUE);
		mShiftClickLabel->setEnabled(TRUE);
		mCharacterWidthLabel->setEnabled(TRUE);
		mCharacterWidthUnitLabel->setEnabled(TRUE);
		mCharacterWidthSlider->setEnabled(TRUE);
		mCharacterTypeLabel->setEnabled(TRUE);
		mCharacterTypeComboBox->setEnabled(TRUE);
		mClearPathButton->setEnabled(TRUE);
		break;
	default :
		llassert(0);
		break;
	}
}
void LLFloaterPathfindingConsole::onClearPathClicked()
{
	clearPath();
}
Ejemplo n.º 23
0
void AutoSystem::automize(Entity _entity)
{
  // step through each of the behaviors in the given order
  for(unsigned int i=0;i<_entity->m_auto.m_behaviors.size();++i)
  {
    // check free space in accumulator
    m_accelSpace=_entity->m_flight.m_maxAcceleration-_entity->m_auto.m_accumulator.length();
    if(m_accelSpace<=0.0f)
    {
      // stop loop if empty
      break;
    }
    // assign behavior to string to allow quicker access
    std::string behavior=_entity->m_auto.m_behaviors[i];
    // below is a large, inefficient list of conditional checks to call the correct function
    // Would have liked to implement the following :-
    // Insane Coding (2007). Secrets to Optimization - Function Pointers [online]. [Accessed 2013].
    // Available from: <http://insanecoding.blogspot.co.uk/2007/05/secrets-to-optimization-function.html>.
    if(behavior=="containmentSphere")
    {
      containmentSphere(_entity);
    }
    else if(behavior=="followLeader")
    {
      followLeader(_entity);
    }
    else if(behavior=="clearPath")
    {
      clearPath(_entity);
    }
    else if(behavior=="targetPlayer")
    {
      targetPlayer(_entity);
    }
    else if(behavior=="avoidPlayer")
    {
      avoidPlayer(_entity);
    }
    else if(behavior=="collisionAvoidance")
    {
      collisionAvoidance(_entity);
    }
    else if(behavior=="velocityMatching")
    {
      velocityMatching(_entity);
    }
    else if(behavior=="flockCentering")
    {
      flockCentering(_entity);
    }
    else if(behavior=="seekTarget")
    {
      // the pursue function without inverse
      pursueTarget(_entity, false);
    }
    else if(behavior=="fleeTarget")
    {
      // the pursue function with inverse to create avoidance behavior
      pursueTarget(_entity, true);
    }
    else if(behavior=="wanderAround")
    {
      wanderAround(_entity);
    }
    else if(behavior=="arriveTarget")
    {
      arriveTarget(_entity);
    }
    else if(behavior=="death")
    {
      death(_entity);
    }
    else
    {
      std::cout<<"--INVALID BEHAVIOR--\n";
      return;
    }
  }
}
Ejemplo n.º 24
0
/**
 * This method calculates the moves for the AI player
 *
 * @param movePtr Pointer to move the move list into
 */
bool AIPlayer::getAIMove(Move *movePtr)
{
   *movePtr = NullMove;

   // Use the eye as the current position.
   MatrixF eye;
   getEyeTransform(&eye);
   Point3F location = eye.getPosition();
   Point3F rotation = getRotation();

#ifdef TORQUE_NAVIGATION_ENABLED
   if(mDamageState == Enabled)
   {
      if(mMoveState != ModeStop)
         updateNavMesh();
      if(!mFollowData.object.isNull())
      {
         if(mPathData.path.isNull())
         {
            if((getPosition() - mFollowData.object->getPosition()).len() > mFollowData.radius)
               followObject(mFollowData.object, mFollowData.radius);
         }
         else
         {
            if((mPathData.path->mTo - mFollowData.object->getPosition()).len() > mFollowData.radius)
               repath();
            else if((getPosition() - mFollowData.object->getPosition()).len() < mFollowData.radius)
            {
               clearPath();
               mMoveState = ModeStop;
            throwCallback("onTargetInRange");
            }
            else if((getPosition() - mFollowData.object->getPosition()).len() < mAttackRadius)
            {
            throwCallback("onTargetInFiringRange");
            }
         }
      }
   }
#endif // TORQUE_NAVIGATION_ENABLED

   // Orient towards the aim point, aim object, or towards
   // our destination.
   if (mAimObject || mAimLocationSet || mMoveState != ModeStop) 
   {
      // Update the aim position if we're aiming for an object
      if (mAimObject)
         mAimLocation = mAimObject->getPosition() + mAimOffset;
      else
         if (!mAimLocationSet)
            mAimLocation = mMoveDestination;

      F32 xDiff = mAimLocation.x - location.x;
      F32 yDiff = mAimLocation.y - location.y;

      if (!mIsZero(xDiff) || !mIsZero(yDiff)) 
      {
         // First do Yaw
         // use the cur yaw between -Pi and Pi
         F32 curYaw = rotation.z;
         while (curYaw > M_2PI_F)
            curYaw -= M_2PI_F;
         while (curYaw < -M_2PI_F)
            curYaw += M_2PI_F;

         // find the yaw offset
         F32 newYaw = mAtan2( xDiff, yDiff );
         F32 yawDiff = newYaw - curYaw;

         // make it between 0 and 2PI
         if( yawDiff < 0.0f )
            yawDiff += M_2PI_F;
         else if( yawDiff >= M_2PI_F )
            yawDiff -= M_2PI_F;

         // now make sure we take the short way around the circle
         if( yawDiff > M_PI_F )
            yawDiff -= M_2PI_F;
         else if( yawDiff < -M_PI_F )
            yawDiff += M_2PI_F;

         movePtr->yaw = yawDiff;

         // Next do pitch.
         if (!mAimObject && !mAimLocationSet) 
         {
            // Level out if were just looking at our next way point.
            Point3F headRotation = getHeadRotation();
            movePtr->pitch = -headRotation.x;
         }
         else 
         {
            // This should be adjusted to run from the
            // eye point to the object's center position. Though this
            // works well enough for now.
            F32 vertDist = mAimLocation.z - location.z;
            F32 horzDist = mSqrt(xDiff * xDiff + yDiff * yDiff);
            F32 newPitch = mAtan2( horzDist, vertDist ) - ( M_PI_F / 2.0f );
            if (mFabs(newPitch) > 0.01f) 
            {
               Point3F headRotation = getHeadRotation();
               movePtr->pitch = newPitch - headRotation.x;
            }
         }
      }
   }
   else 
   {
      // Level out if we're not doing anything else
      Point3F headRotation = getHeadRotation();
      movePtr->pitch = -headRotation.x;
   }

   // Move towards the destination
   if (mMoveState != ModeStop) 
   {
      F32 xDiff = mMoveDestination.x - location.x;
      F32 yDiff = mMoveDestination.y - location.y;

      // Check if we should mMove, or if we are 'close enough'
      if (mFabs(xDiff) < mMoveTolerance && mFabs(yDiff) < mMoveTolerance) 
      {
         mMoveState = ModeStop;
         onReachDestination();
      }
      else 
      {
         // Build move direction in world space
         if (mIsZero(xDiff))
            movePtr->y = (location.y > mMoveDestination.y) ? -1.0f : 1.0f;
         else
            if (mIsZero(yDiff))
               movePtr->x = (location.x > mMoveDestination.x) ? -1.0f : 1.0f;
            else
               if (mFabs(xDiff) > mFabs(yDiff)) 
               {
                  F32 value = mFabs(yDiff / xDiff);
                  movePtr->y = (location.y > mMoveDestination.y) ? -value : value;
                  movePtr->x = (location.x > mMoveDestination.x) ? -1.0f : 1.0f;
               }
               else 
               {
                  F32 value = mFabs(xDiff / yDiff);
                  movePtr->x = (location.x > mMoveDestination.x) ? -value : value;
                  movePtr->y = (location.y > mMoveDestination.y) ? -1.0f : 1.0f;
               }

         // Rotate the move into object space (this really only needs
         // a 2D matrix)
         Point3F newMove;
         MatrixF moveMatrix;
         moveMatrix.set(EulerF(0.0f, 0.0f, -(rotation.z + movePtr->yaw)));
         moveMatrix.mulV( Point3F( movePtr->x, movePtr->y, 0.0f ), &newMove );
         movePtr->x = newMove.x;
         movePtr->y = newMove.y;

         // Set movement speed.  We'll slow down once we get close
         // to try and stop on the spot...
         if (mMoveSlowdown) 
         {
            F32 speed = mMoveSpeed;
            F32 dist = mSqrt(xDiff*xDiff + yDiff*yDiff);
            F32 maxDist = mMoveTolerance*2;
            if (dist < maxDist)
               speed *= dist / maxDist;
            movePtr->x *= speed;
            movePtr->y *= speed;

            mMoveState = ModeSlowing;
         }
         else 
         {
            movePtr->x *= mMoveSpeed;
            movePtr->y *= mMoveSpeed;

            mMoveState = ModeMove;
         }

         if (mMoveStuckTestCountdown > 0)
            --mMoveStuckTestCountdown;
         else
         {
            // We should check to see if we are stuck...
            F32 locationDelta = (location - mLastLocation).len();
            if (locationDelta < mMoveStuckTolerance && mDamageState == Enabled) 
            {
               // If we are slowing down, then it's likely that our location delta will be less than
               // our move stuck tolerance. Because we can be both slowing and stuck
               // we should TRY to check if we've moved. This could use better detection.
               if ( mMoveState != ModeSlowing || locationDelta == 0 )
               {
                  mMoveState = ModeStuck;
                  onStuck();
               }
            }
         }
      }
   }

   // Test for target location in sight if it's an object. The LOS is
   // run from the eye position to the center of the object's bounding,
   // which is not very accurate.
   if (mAimObject)
   {
      if (checkInLos(mAimObject.getPointer()))
      {
         if (!mTargetInLOS)
         {
            throwCallback( "onTargetEnterLOS" );
            mTargetInLOS = true;
         }
   }
      else if (mTargetInLOS)
      {
            throwCallback( "onTargetExitLOS" );
            mTargetInLOS = false;
         }
      }

   Pose desiredPose = mPose;

   if ( mSwimming )  
      desiredPose = SwimPose;   
   else if ( mAiPose == 1 && canCrouch() )   
      desiredPose = CrouchPose;  
   else if ( mAiPose == 2 && canProne() )  
      desiredPose = PronePose;  
   else if ( mAiPose == 3 && canSprint() )  
      desiredPose = SprintPose;  
   else if ( canStand() )  
      desiredPose = StandPose;  
  
   setPose( desiredPose );
   
   // Replicate the trigger state into the move so that
   // triggers can be controlled from scripts.
   for( U32 i = 0; i < MaxTriggerKeys; i++ )
      movePtr->trigger[ i ] = getImageTriggerState( i );

#ifdef TORQUE_NAVIGATION_ENABLED
   if(mJump == Now)
   {
      movePtr->trigger[2] = true;
      mJump = None;
   }
   else if(mJump == Ledge)
   {
      // If we're not touching the ground, jump!
      RayInfo info;
      if(!getContainer()->castRay(getPosition(), getPosition() - Point3F(0, 0, 0.4f), StaticShapeObjectType, &info))
      {
         movePtr->trigger[2] = true;
         mJump = None;
      }
   }
#endif // TORQUE_NAVIGATION_ENABLED

   mLastLocation = location;

   return true;
}
/**
 * Updates path logic.
 */
void PathHandler::updatePath()
{
	geometry_msgs::Twist command;

	publishState();

	// no path? nothing to handle
	if (getPathSize() == 0)
		return;

	// update our position if possible.
	if (updateCurrentPosition() == false)
	{
		ROS_ERROR("Failed to update robot position.");
		return;
	}

	if (mCurrentPathIndex < getPathSize() - 1) // we are moving along a line segment in the path
	{
		geometry_msgs::Point robotPos;
		robotPos.x = mRobotPosition.getOrigin().x();
		robotPos.y = mRobotPosition.getOrigin().y();
		geometry_msgs::Point closestOnPath = closestPointOnLine(robotPos, mPath[mCurrentPathIndex].position, mPath[mCurrentPathIndex + 1].position);

		//ROS_INFO("robotPos[%lf, %lf], closestOnPath[%lf, %lf]", robotPos.x, robotPos.y, closestOnPath.x, closestOnPath.y);

		if (distanceBetweenPoints(closestOnPath, robotPos) > mResetDistanceTolerance)
		{
			ROS_INFO("Drove too far away from path, re-sending goal.");
			mFollowState = FOLLOW_STATE_IDLE;
			resendGoal();
			clearPath();
			return;
		}

		geometry_msgs::Point pointOnPath = getPointOnPathWithDist(closestOnPath, mLookForwardDistance);

		//ROS_INFO("closestOnPath[%lf, %lf], pointOnPath[%lf, %lf]", closestOnPath.x, closestOnPath.y, pointOnPath.x, pointOnPath.y);

		double angle = angleTo(pointOnPath);

		/*double robotYaw = tf::getYaw(mRobotPosition.getRotation()); // only used for printing
		ROS_INFO("Follow state: %d Robot pos: (%lf, %lf, %lf). Target pos: (%lf, %lf, %lf). RobotYaw: %lf. FocusYaw: %lf", mFollowState, mRobotPosition.getOrigin().getX(),
				mRobotPosition.getOrigin().getY(), mRobotPosition.getOrigin().getZ(), pointOnPath.x,
				pointOnPath.y, pointOnPath.z, robotYaw, angle);*/

		//ROS_INFO("Angle to path: %f", angle);

		command.linear.x = getScaledLinearSpeed(angle);
		command.angular.z = getScaledAngularSpeed(angle);

		if (distanceBetweenPoints(closestOnPath, mPath[mCurrentPathIndex + 1].position) < mDistanceTolerance)
		{
			//ROS_INFO("Moving to next line segment on path.");
			mCurrentPathIndex++;
		}

		publishLocalPath(command.linear.x * 3, angle);
	}
	else // only rotate for final yaw
	{
		double yaw = tf::getYaw(mPath[getPathSize() - 1].orientation);
		btVector3 orientation = btVector3(cos(yaw), sin(yaw), 0.0).rotate(btVector3(0,0,1), -tf::getYaw(mRobotPosition.getRotation()));
		double angle = atan2(orientation.getY(), orientation.getX());

		//ROS_INFO("Angle to final orientation: %f", angle);

		if (fabs(angle) > mFinalYawTolerance)
			command.angular.z = getScaledAngularSpeed(angle, true);
		else
		{
			// path is done!
			mFollowState = FOLLOW_STATE_FINISHED;
			clearPath();
		}

		publishLocalPath(1.0, angle);
	}

	mCommandPub.publish(command);
}
Ejemplo n.º 26
0
void pathFinder::findPath( p2DArray maze, const vector2 &start, const vector2 &end )
{
	// 起点或者终点无效,直接返回
	if( !isPointValid( start, maze ) ||
		!isPointValid( end, maze ) )
	{
		return;
	}
	else
	{
		clearPath();

		char mazeCopy[ROW][CEL];
		memcpy( dirMap, maze, sizeof(char)*ROW*CEL );
		memcpy( mazeCopy, maze, sizeof(char)*ROW*CEL );

		MyQueue openList;
		openList.push_back( start );

		vector2 curPos;
		vector2 temp;

		while ( 1 )
		{
			openList.pop_front( curPos );

			// 碰到了终点,可以停止了
			if( curPos == end )
			{
				dirMap[start.x][start.y] = MS_START;
//				readPathFromDirMap( end );
				return;
			}

			// 当前点有效才需要扩展
			if( isPointValid( curPos, mazeCopy ) )
			{
				mazeCopy[curPos.x][curPos.y] = MS_WALKED;

				int curDir = 0;
				while ( curDir < 4 )
				{
					temp.x = curPos.x + dirArray[curDir].x;
					temp.y = curPos.y + dirArray[curDir].y;
					if( isPointValid( temp, mazeCopy ) )
					{
						openList.push_back( temp );
						// 标记当前节点的上一节点
						dirMap[temp.x][temp.y] = getOppositeDir( curDir );
					}

					++curDir;
				}
			}

			// 扩展列表为空,只能退出了
			if( openList.isEmpty() )
			{
				return;
			}
		}
	}
}
Ejemplo n.º 27
0
void drawGameScreen() {
    clear();
    //draw exterior of game
    drawBox(10, 3, 44, 34, 0);
    
    //draw path walls
    drawBox(10, 7, 11, 3, 0);
    drawBox(18, 7, 4, 14, 0);
    drawBox(18, 18, 16, 3, 0);
    drawBox(31, 7, 4, 14, 0);
    drawBox(31, 7, 18, 3, 0);
    drawBox(46, 7, 4, 24, 0);
    drawBox(19, 28, 30, 3, 0);
    drawBox(19, 28, 4, 9, 0);

    //fix up the corners
    clearPath();
    fixCorners();

    //add beginning and ending chars
    mvaddch(8, 8, '>');
    mvaddch(37, 21, ACS_DARROW);

    //draw and fill the purchase portion of the screen
    attron(COLOR_PAIR(0));
    drawPurchaseArea();
    basicSetupScreen(1);
    updateScore(0);
    attroff(COLOR_PAIR(0));
    drawTowerExplain();

    //load arrays for drawing
    TowerArray* theTowerList = getTowerArray("assets/towersLevel1.txt");
    Path* thePath = getPathArray("assets/path.txt");
    UnitListHeader * unitList = malloc(sizeof(UnitListHeader));
    int moneyAmount = STARTINGMONEY;
    initializeList(unitList);
    drawUnitTypes(unitList);
    int theScore = 0;

    drawTowers(theTowerList);

    //go to entering unit purchases (gives control back to user)
    selectUnitsInterface(thePath,unitList,&moneyAmount,theTowerList,&theScore);

    //get lowest score of highscores
    ScoreHead scores;
    scores.size = 0;
    scores.first = NULL;
    ScoreNode * currScore = NULL;
    readScores(&scores);
    currScore = scores.first;
    int numScores = 1;
    int highestScore = 0;

    while ((currScore->next != NULL) && (numScores < 9)) { 
        numScores += 1;
        currScore = currScore->next;
    }

    highestScore = -1;
    if (numScores > 8 && currScore != NULL) {
        highestScore = currScore->score;
    }

    char * enterName;
    if (theScore > highestScore) {
        enterName = drawScore(theScore,1);
        if (enterName != NULL) {
            addScore(&scores, enterName, theScore);
            writeScores(&scores);
        }
    } else {
        drawScore(theScore,0);
    }

    if (scores.size > 0) destroyScores(&scores);

}
Ejemplo n.º 28
0
void UnitBase::engageTarget() {

    if(target && (target.getObjPointer() == NULL)) {
        // the target does not exist anymore
        releaseTarget();
        return;
    }

    if(target && (target.getObjPointer()->isActive() == false)) {
        // the target changed its state to inactive
        releaseTarget();
        return;
    }

    if(target && !targetFriendly && !canAttack(target.getObjPointer())) {
        // the (non-friendly) target cannot be attacked anymore
        releaseTarget();
        return;
    }

    if(target && !targetFriendly && !forced && !isInAttackRange(target.getObjPointer())) {
        // the (non-friendly) target left the attack mode range (and we were not forced to attack it)
        releaseTarget();
        return;
    }

    if(target) {
        // we have a target unit or structure

        Coord targetLocation = target.getObjPointer()->getClosestPoint(location);

        if(destination != targetLocation) {
            // the location of the target has moved
            // => recalculate path
            clearPath();
        }

        targetDistance = blockDistance(location, targetLocation);

        Sint8 newTargetAngle = lround(8.0f/256.0f*destinationAngle(location, targetLocation));
        if(newTargetAngle == 8) {
            newTargetAngle = 0;
        }

        if(bFollow) {
            // we are following someone
            setDestination(targetLocation);
            return;
        }

        if(targetDistance > getWeaponRange()) {
            // we are not in attack range
            // => follow the target
            setDestination(targetLocation);
            return;
        }

        // we are in attack range

        if(targetFriendly && !forced) {
            // the target is friendly and we only attack these if were forced to do so
            return;
        }

        if(goingToRepairYard) {
            // we are going to the repair yard
            // => we do not need to change the destination
            targetAngle = INVALID;
        } else if(attackMode == CAPTURE) {
            // we want to capture the target building
            setDestination(targetLocation);
            targetAngle = INVALID;
        } else if(isTracked() && target.getObjPointer()->isInfantry() && currentGameMap->tileExists(targetLocation) && !currentGameMap->getTile(targetLocation)->isMountain() && forced) {
            // we squash the infantry unit because we are forced to
            setDestination(targetLocation);
            targetAngle = INVALID;
        } else {
            // we decide to fire on the target thus we can stop moving
            setDestination(location);
            targetAngle = newTargetAngle;
        }

        if(getCurrentAttackAngle() == newTargetAngle) {
            attack();
        }

    } else if(attackPos) {
        // we attack a position

        targetDistance = blockDistance(location, attackPos);

        Sint8 newTargetAngle = lround(8.0f/256.0f*destinationAngle(location, attackPos));
        if(newTargetAngle == 8) {
            newTargetAngle = 0;
        }

        if(targetDistance <= getWeaponRange()) {
            // we are in weapon range thus we can stop moving
            setDestination(location);
            targetAngle = newTargetAngle;

            if(getCurrentAttackAngle() == newTargetAngle) {
                attack();
            }
        } else {
            targetAngle = INVALID;
        }
    }
}
Ejemplo n.º 29
0
void UnitBase::setAngle(int newAngle) {
	if(!moving && !justStoppedMoving && (newAngle >= 0) && (newAngle < NUM_ANGLES)) {
		angle = drawnAngle = newAngle;
		clearPath();
	}
}
Ejemplo n.º 30
0
void UnitBase::navigate() {

    if(isAFlyingUnit() || (((currentGame->getGameCycleCount() + getObjectID()*1337) % 5) == 0)) {
        // navigation is only performed every 5th frame

        if(!moving && !justStoppedMoving) {
            if(location != destination) {
                if(nextSpotFound == false)	{

                    if(pathList.empty() && (recalculatePathTimer == 0)) {
                        recalculatePathTimer = 100;

                        if(!SearchPathWithAStar() && (++noCloserPointCount >= 3)
                            && (location != oldLocation))
                        {	//try searching for a path a number of times then give up
                            if (target.getObjPointer() != NULL && targetFriendly
                                && (target.getObjPointer()->getItemID() != Structure_RepairYard)
                                && ((target.getObjPointer()->getItemID() != Structure_Refinery)
                                || (getItemID() != Unit_Harvester))) {
                                setTarget(NULL);
                            }

                            setDestination(location);	//can't get any closer, give up
                            forced = false;
                        }
                    }

                    if(!pathList.empty()) {
                        nextSpot = pathList.front();
                        pathList.pop_front();
                        nextSpotFound = true;
                        recalculatePathTimer = 0;
                        noCloserPointCount = 0;
                    }
                } else {
                    int tempAngle = currentGameMap->getPosAngle(location, nextSpot);
                    if(tempAngle != INVALID) {
                        nextSpotAngle = tempAngle;
                    }

                    if(!canPass(nextSpot.x, nextSpot.y)) {
                        clearPath();
                    } else {
                        if (drawnAngle == nextSpotAngle)	{
                            moving = true;
                            nextSpotFound = false;

                            assignToMap(nextSpot);
                            angle = drawnAngle;
                            setSpeeds();
                        }
                    }
                }
            } else if(!target) {
                if(((currentGame->getGameCycleCount() + getObjectID()*1337) % MILLI2CYCLES(UNITIDLETIMER)) == 0) {
                    idleAction();
                }
            }
        }
    }
}