Пример #1
0
void MainWindow::timer()
{
            if (soru_listesi.isEmpty())
            {
                        timer2();
                        zaman->stop();
            }
            else
            {
                        zamanci += 1;
                        QString kim ;

                        if(zamanci > soru_listesi.size()-1)
                        {
                                    zaman->stop();
                                    zamanci = -1 ;
                                    timer2();
                        }
                        else
                        {
                                    kim = soru_listesi.at(zamanci);
                                    ui->label_soru->setText(kim);
                        }
            }
}
Пример #2
0
int main()
{
    timer1();
    timer2();
    timer3();
    timer4();
    timer5();
    return 0;
}
Пример #3
0
int main(void)
{
    wdt_disable();
    cli();

    DDRC=0xFE;

    DDRD=0xFA;//P2 input
    PORTD=0xFF;//pullup
    DDRB=0xFf;
    uart_init();
    uart_stdio();

    ///set time
    char buff[10];
    strcpy(buff, __TIME__);
    buff[2]='\0';
    buff[5]='\0';

    hour=atoi(&buff[0]);
    min=atoi(&buff[3]);
    sec=atoi(&buff[6]);

    timer2();
    sei();
    int m=0;
    /////EXTERNAL LIBS INIT

    ir_init();

    ////////////////////////
    for(;;){    /* main event loop */

    leds_put(hour/10,m);
    leds_put(hour%10,m);
    leds_put(min/10,m);
    leds_put(min%10,m);
    leds_put(sec/10,m);
    leds_put(sec%10,m);
    leds_strobe();
    _delay_ms(1);

    leds_put(17,m);
    leds_put(17,m);
    leds_put(17,m);
    leds_put(17,m);
    leds_put(17,m);
    leds_put(17,m);
    leds_put(17,m);
    leds_strobe();

    _delay_ms(10);
    }
    return 0;
}
Пример #4
0
static void
choose_prime(primedata *S, GEN pol, GEN dpol)
{
  byteptr di = diffptr + 1;
  long i, j, k, r, lcm, oldlcm, pp, N = degpol(pol), minp = N*N / 4;
  GEN Z, p, ff, oldff, n, oldn;
  pari_sp av;

  if (DEBUGLEVEL) (void)timer2();
  p = utoipos(2);
  while (p[2] <= minp) NEXT_PRIME_VIADIFF(p[2], di);
  oldlcm = 0;
  oldff = oldn = NULL; pp = 0; /* gcc -Wall */
  av = avma;
  for(k = 1; k < 11 || !oldlcm; k++,avma = av)
  {
    do NEXT_PRIME_VIADIFF(p[2], di); while (!smodis(dpol, p[2]));
    if (k > 5 * N) pari_err(talker,"sorry, too many block systems in nfsubfields");
    ff = (GEN)FpX_factor(pol, p)[1];
    r = lg(ff)-1;
    if (r == N || r >= BIL) continue;

    n = cgetg(r+1, t_VECSMALL); lcm = n[1] = degpol(ff[1]);
    for (j=2; j<=r; j++) { n[j] = degpol(ff[j]); lcm = clcm(lcm, n[j]); }
    if (lcm <= oldlcm) continue; /* false when oldlcm = 0 */

    if (DEBUGLEVEL) fprintferr("p = %ld,\tlcm = %ld,\torbits: %Z\n",p[2],lcm,n);
    pp = p[2];
    oldn = n;
    oldff = ff;
    oldlcm = lcm; if (r == 1) break;
    av = avma;
  }
  if (DEBUGLEVEL) fprintferr("Chosen prime: p = %ld\n", pp);
  S->ff = oldff;
  S->lcm= oldlcm;
  S->p  = utoipos(pp);
  S->pol = FpX_red(pol, S->p); init_primedata(S);

  n = oldn; r = lg(n); Z = cgetg(r,t_VEC);
  for (k=0,i=1; i<r; i++)
  {
    GEN t = cgetg(n[i]+1, t_VECSMALL); gel(Z,i) = t;
    for (j=1; j<=n[i]; j++) t[j] = ++k;
  }
  S->Z = Z;
}
Пример #5
0
void
fixupAstSymbolTables( SgNode* node )
   {
  // DQ (7/7/2005): Introduce tracking of performance of ROSE.
     TimingPerformance timer1 ("Fixup symbol tables:");

  // DQ (1/31/2006): Modified to build all types in the memory pools
  // DQ (6/26/2005): The global function type symbol table should be rebuilt (since the names of templates 
  // used in qualified names of types have been reset (in post processing).
  // extern SgFunctionTypeTable Sgfunc_type_table;
  // fixupGlobalFunctionSymbolTable(Sgfunc_type_table);
     ROSE_ASSERT(SgNode::get_globalFunctionTypeTable() != NULL);
     fixupGlobalFunctionSymbolTable(SgNode::get_globalFunctionTypeTable());

  // DQ (5/16/2006): Fixup the parent of the globalFunctionTypeTable to be either the SgProject or SgFile
     if (SgNode::get_globalFunctionTypeTable()->get_parent() == NULL)
        {
          SgProject* project = isSgProject(node);
          SgFile*    file    = isSgFile(node);
          if (project != NULL || file != NULL)
               SgNode::get_globalFunctionTypeTable()->set_parent(node);
        }

  // DQ (7/25/2010): Set the parent of the global type table to the SgProject
     if (SgNode::get_globalTypeTable()->get_parent() == NULL)
        {
          SgProject* project = isSgProject(node);
          SgFile*    file    = isSgFile(node);
          if (project != NULL || file != NULL)
               SgNode::get_globalTypeTable()->set_parent(node);
        }

  // DQ (7/7/2005): Introduce tracking of performance of ROSE.
     TimingPerformance timer2 ("Fixup local symbol tables:");

  // Now fixup the local symbol tables
  // This simplifies how the traversal is called!
     FixupAstSymbolTables astFixupTraversal;

  // I think the default should be preorder so that the interfaces would be more uniform
     astFixupTraversal.traverse(node,preorder);
   }
Пример #6
0
int main() {
	log() << "-- start" << std::endl;

	boost::asio::io_service io;
	boost::asio::io_service::strand strand(io);

	boost::asio::deadline_timer timer1( io, boost::posix_time::seconds(1) );
	boost::asio::deadline_timer timer2( io, boost::posix_time::seconds(1) );

	timer1.async_wait( strand.wrap( boost::bind( timer_expired, "timer1", boost::asio::placeholders::error)));
	timer2.async_wait( strand.wrap( boost::bind( timer_expired, "timer2", boost::asio::placeholders::error)));

	std::thread butler1( [&]() { io.run(); } );
	std::thread butler2( [&]() { io.run(); } );

	butler1.join();
	butler2.join();

	log() << "-- end" << std::endl;
}
Пример #7
0
unsigned int CppCheck::processFile(const std::string& filename, std::istream& fileStream)
{
    exitcode = 0;

    // only show debug warnings for accepted C/C++ source files
    if (!Path::acceptFile(filename))
        _settings.debugwarnings = false;

    if (_settings.terminated())
        return exitcode;

    if (_settings.quiet == false) {
        std::string fixedpath = Path::simplifyPath(filename);
        fixedpath = Path::toNativeSeparators(fixedpath);
        _errorLogger.reportOut(std::string("Checking ") + fixedpath + std::string("..."));
    }

    bool internalErrorFound(false);
    try {
        Preprocessor preprocessor(_settings, this);
        std::list<std::string> configurations;
        std::string filedata;

        {
            Timer t("Preprocessor::preprocess", _settings.showtime, &S_timerResults);
            preprocessor.preprocess(fileStream, filedata, configurations, filename, _settings.includePaths);
        }

        if (_settings.checkConfiguration) {
            return 0;
        }

        // Run define rules on raw code
        for (std::list<Settings::Rule>::const_iterator it = _settings.rules.begin(); it != _settings.rules.end(); ++it) {
            if (it->tokenlist == "define") {
                Tokenizer tokenizer2(&_settings, this);
                std::istringstream istr2(filedata);
                tokenizer2.list.createTokens(istr2, filename);

                for (const Token *tok = tokenizer2.list.front(); tok; tok = tok->next()) {
                    if (tok->str() == "#define") {
                        std::string code = std::string(tok->linenr()-1U, '\n');
                        for (const Token *tok2 = tok; tok2 && tok2->linenr() == tok->linenr(); tok2 = tok2->next())
                            code += " " + tok2->str();
                        Tokenizer tokenizer3(&_settings, this);
                        std::istringstream istr3(code);
                        tokenizer3.list.createTokens(istr3, tokenizer2.list.file(tok));
                        executeRules("define", tokenizer3);
                    }
                }
                break;
            }
        }

        if (!_settings.userDefines.empty() && _settings.maxConfigs==1U) {
            configurations.clear();
            configurations.push_back(_settings.userDefines);
        }

        if (!_settings.force && configurations.size() > _settings.maxConfigs) {
            if (_settings.isEnabled("information")) {
                tooManyConfigsError(Path::toNativeSeparators(filename),configurations.size());
            } else {
                tooManyConfigs = true;
            }
        }

        // write dump file xml prolog
        std::ofstream fdump;
        if (_settings.dump) {
            const std::string dumpfile(filename + ".dump");
            fdump.open(dumpfile.c_str());
            if (fdump.is_open()) {
                fdump << "<?xml version=\"1.0\"?>" << std::endl;
                fdump << "<dumps>" << std::endl;
            }
        }

        std::set<unsigned long long> checksums;
        unsigned int checkCount = 0;
        for (std::list<std::string>::const_iterator it = configurations.begin(); it != configurations.end(); ++it) {
            // bail out if terminated
            if (_settings.terminated())
                break;

            // Check only a few configurations (default 12), after that bail out, unless --force
            // was used.
            if (!_settings.force && ++checkCount > _settings.maxConfigs)
                break;

            cfg = *it;

            // If only errors are printed, print filename after the check
            if (_settings.quiet == false && it != configurations.begin()) {
                std::string fixedpath = Path::simplifyPath(filename);
                fixedpath = Path::toNativeSeparators(fixedpath);
                _errorLogger.reportOut("Checking " + fixedpath + ": " + cfg + "...");
            }

            if (!_settings.userDefines.empty()) {
                if (!cfg.empty())
                    cfg = ";" + cfg;
                cfg = _settings.userDefines + cfg;
            }

            Timer t("Preprocessor::getcode", _settings.showtime, &S_timerResults);
            std::string codeWithoutCfg = preprocessor.getcode(filedata, cfg, filename);
            t.Stop();

            codeWithoutCfg += _settings.append();

            if (_settings.preprocessOnly) {
                if (codeWithoutCfg.compare(0,5,"#file") == 0)
                    codeWithoutCfg.insert(0U, "//");
                std::string::size_type pos = 0;
                while ((pos = codeWithoutCfg.find("\n#file",pos)) != std::string::npos)
                    codeWithoutCfg.insert(pos+1U, "//");
                pos = 0;
                while ((pos = codeWithoutCfg.find("\n#endfile",pos)) != std::string::npos)
                    codeWithoutCfg.insert(pos+1U, "//");
                pos = 0;
                while ((pos = codeWithoutCfg.find(Preprocessor::macroChar,pos)) != std::string::npos)
                    codeWithoutCfg[pos] = ' ';
                reportOut(codeWithoutCfg);
                continue;
            }

            Tokenizer _tokenizer(&_settings, this);
            if (_settings.showtime != SHOWTIME_NONE)
                _tokenizer.setTimerResults(&S_timerResults);

            try {
                // Create tokens, skip rest of iteration if failed
                std::istringstream istr(codeWithoutCfg);
                Timer timer("Tokenizer::createTokens", _settings.showtime, &S_timerResults);
                bool result = _tokenizer.createTokens(istr, filename.c_str());
                timer.Stop();
                if (!result)
                    continue;

                // skip rest of iteration if just checking configuration
                if (_settings.checkConfiguration)
                    continue;

                // Check raw tokens
                checkRawTokens(_tokenizer);

                // Simplify tokens into normal form, skip rest of iteration if failed
                Timer timer2("Tokenizer::simplifyTokens1", _settings.showtime, &S_timerResults);
                result = _tokenizer.simplifyTokens1(cfg);
                timer2.Stop();
                if (!result)
                    continue;

                // dump xml if --dump
                if (_settings.dump && fdump.is_open()) {
                    fdump << "<dump cfg=\"" << cfg << "\">" << std::endl;
                    preprocessor.dump(fdump);
                    _tokenizer.dump(fdump);
                    fdump << "</dump>" << std::endl;
                }

                // Skip if we already met the same simplified token list
                if (_settings.force || _settings.maxConfigs > 1) {
                    const unsigned long long checksum = _tokenizer.list.calculateChecksum();
                    if (checksums.find(checksum) != checksums.end())
                        continue;
                    checksums.insert(checksum);
                }

                // Check normal tokens
                checkNormalTokens(_tokenizer);

                // simplify more if required, skip rest of iteration if failed
                if (_simplify) {
                    // if further simplification fails then skip rest of iteration
                    Timer timer3("Tokenizer::simplifyTokenList2", _settings.showtime, &S_timerResults);
                    result = _tokenizer.simplifyTokenList2();
                    timer3.Stop();
                    if (!result)
                        continue;

                    // Check simplified tokens
                    checkSimplifiedTokens(_tokenizer);
                }

            } catch (const InternalError &e) {
                if (_settings.isEnabled("information") && (_settings.debug || _settings.verbose))
                    purgedConfigurationMessage(filename, cfg);
                internalErrorFound=true;
                std::list<ErrorLogger::ErrorMessage::FileLocation> locationList;
                ErrorLogger::ErrorMessage::FileLocation loc;
                if (e.token) {
                    loc.line = e.token->linenr();
                    const std::string fixedpath = Path::toNativeSeparators(_tokenizer.list.file(e.token));
                    loc.setfile(fixedpath);
                } else {
                    ErrorLogger::ErrorMessage::FileLocation loc2;
                    loc2.setfile(Path::toNativeSeparators(filename.c_str()));
                    locationList.push_back(loc2);
                    loc.setfile(_tokenizer.list.getSourceFilePath());
                }
                locationList.push_back(loc);
                const ErrorLogger::ErrorMessage errmsg(locationList,
                                                       Severity::error,
                                                       e.errorMessage,
                                                       e.id,
                                                       false);

                reportErr(errmsg);
            }
        }

        // dumped all configs, close root </dumps> element now
        if (_settings.dump && fdump.is_open())
            fdump << "</dumps>" << std::endl;

    } catch (const std::runtime_error &e) {
        internalError(filename, e.what());
    } catch (const InternalError &e) {
        internalError(filename, e.errorMessage);
        exitcode=1; // e.g. reflect a syntax error
    }

    // In jointSuppressionReport mode, unmatched suppressions are
    // collected after all files are processed
    if (!_settings.jointSuppressionReport && (_settings.isEnabled("information") || _settings.checkConfiguration)) {
        reportUnmatchedSuppressions(_settings.nomsg.getUnmatchedLocalSuppressions(filename, unusedFunctionCheckIsEnabled()));
    }

    _errorList.clear();
    if (internalErrorFound && (exitcode==0)) {
        exitcode=1;
    }
    return exitcode;
}
Пример #8
0
void CppCheck::checkFile(const std::string &code, const char FileName[])
{
    if (_settings.terminated() || _settings.checkConfiguration)
        return;

    Tokenizer _tokenizer(&_settings, this);
    bool result;

    // Tokenize the file
    std::istringstream istr(code);

    Timer timer("Tokenizer::tokenize", _settings._showtime, &S_timerResults);
    result = _tokenizer.tokenize(istr, FileName, cfg);
    timer.Stop();
    if (!result)
    {
        // File had syntax errors, abort
        return;
    }

    Timer timer2("Tokenizer::fillFunctionList", _settings._showtime, &S_timerResults);
    _tokenizer.fillFunctionList();
    timer2.Stop();

    // call all "runChecks" in all registered Check classes
    for (std::list<Check *>::iterator it = Check::instances().begin(); it != Check::instances().end(); ++it)
    {
        if (_settings.terminated())
            return;

        Timer timerRunChecks((*it)->name() + "::runChecks", _settings._showtime, &S_timerResults);
        (*it)->runChecks(&_tokenizer, &_settings, this);
    }

    Timer timer3("Tokenizer::simplifyTokenList", _settings._showtime, &S_timerResults);
    result = _tokenizer.simplifyTokenList();
    timer3.Stop();
    if (!result)
        return;

    Timer timer4("Tokenizer::fillFunctionList", _settings._showtime, &S_timerResults);
    _tokenizer.fillFunctionList();
    timer4.Stop();

    if (_settings.isEnabled("unusedFunction") && _settings._jobs == 1)
        _checkUnusedFunctions.parseTokens(_tokenizer);

    // call all "runSimplifiedChecks" in all registered Check classes
    for (std::list<Check *>::iterator it = Check::instances().begin(); it != Check::instances().end(); ++it)
    {
        if (_settings.terminated())
            return;

        Timer timerSimpleChecks((*it)->name() + "::runSimplifiedChecks", _settings._showtime, &S_timerResults);
        (*it)->runSimplifiedChecks(&_tokenizer, &_settings, this);
    }

#ifdef HAVE_RULES
    // Are there extra rules?
    if (!_settings.rules.empty())
    {
        std::ostringstream ostr;
        for (const Token *tok = _tokenizer.tokens(); tok; tok = tok->next())
            ostr << " " << tok->str();
        const std::string str(ostr.str());
        for (std::list<Settings::Rule>::const_iterator it = _settings.rules.begin(); it != _settings.rules.end(); ++it)
        {
            const Settings::Rule &rule = *it;
            if (rule.pattern.empty() || rule.id.empty() || rule.severity.empty())
                continue;

            const char *error = 0;
            int erroffset = 0;
            pcre *re = pcre_compile(rule.pattern.c_str(),0,&error,&erroffset,NULL);
            if (!re && error)
            {
                ErrorLogger::ErrorMessage errmsg(std::list<ErrorLogger::ErrorMessage::FileLocation>(),
                                                 Severity::error,
                                                 error,
                                                 "pcre_compile",
                                                 false);

                reportErr(errmsg);
            }
            if (!re)
                continue;

            int pos = 0;
            int ovector[30];
            while (0 <= pcre_exec(re, NULL, str.c_str(), (int)str.size(), pos, 0, ovector, 30))
            {
                unsigned int pos1 = (unsigned int)ovector[0];
                unsigned int pos2 = (unsigned int)ovector[1];

                // jump to the end of the match for the next pcre_exec
                pos = (int)pos2;

                // determine location..
                ErrorLogger::ErrorMessage::FileLocation loc;
                loc.setfile(_tokenizer.getFiles()->front());
                loc.line = 0;

                unsigned int len = 0;
                for (const Token *tok = _tokenizer.tokens(); tok; tok = tok->next())
                {
                    len = len + 1 + tok->str().size();
                    if (len > pos1)
                    {
                        loc.setfile(_tokenizer.getFiles()->at(tok->fileIndex()));
                        loc.line = tok->linenr();
                        break;
                    }
                }

                const std::list<ErrorLogger::ErrorMessage::FileLocation> callStack(1, loc);

                // Create error message
                std::string summary;
                if (rule.summary.empty())
                    summary = "found '" + str.substr(pos1, pos2 - pos1) + "'";
                else
                    summary = rule.summary;
                const ErrorLogger::ErrorMessage errmsg(callStack, Severity::fromString(rule.severity), summary, rule.id, false);

                // Report error
                reportErr(errmsg);
            }

            pcre_free(re);
        }
    }
#endif
}
Пример #9
0
int main (int argc, char** argv)
{
    if (argc != 2)
    {
        std::cerr << "Usage: " << argv[0] << " <num-iter>" << std::endl;
        return EXIT_FAILURE;
    }

    const unsigned NUM_ITER = atoi(argv[1]);

    // open first face in the font
    FT_Library ft_library = 0;
    FT_Error error = FT_Init_FreeType(&ft_library);
    if (error) throw std::runtime_error("Failed to initialize FreeType2 library");

    FT_Face ft_face[NUM_EXAMPLES];
    FT_New_Face(ft_library, "fonts/DejaVuSerif.ttf", 0, &ft_face[ENGLISH]);
    FT_New_Face(ft_library, "fonts/amiri-0.104/amiri-regular.ttf", 0, &ft_face[ARABIC]);
    FT_New_Face(ft_library, "fonts/fireflysung-1.3.0/fireflysung.ttf", 0, &ft_face[CHINESE]);

    // Get our harfbuzz font structs
    hb_font_t *hb_ft_font[NUM_EXAMPLES];
    hb_ft_font[ENGLISH] = hb_ft_font_create(ft_face[ENGLISH], NULL);
    hb_ft_font[ARABIC]  = hb_ft_font_create(ft_face[ARABIC] , NULL);
    hb_ft_font[CHINESE] = hb_ft_font_create(ft_face[CHINESE], NULL);

    {
        std::cerr << "Starting ICU shaping:" << std::endl;
        progress_timer timer1(std::clog,"ICU shaping done");
        UErrorCode err = U_ZERO_ERROR;
        for (unsigned i = 0; i < NUM_ITER; ++i)
        {
            for (unsigned j = 0; j < NUM_EXAMPLES; ++j)
            {
                UnicodeString text = UnicodeString::fromUTF8(texts[j]);
                int32_t length = text.length();
                UnicodeString reordered;
                UnicodeString shaped;
                UBiDi *bidi = ubidi_openSized(length, 0, &err);
                ubidi_setPara(bidi, text.getBuffer(), length, UBIDI_DEFAULT_LTR, 0, &err);
                ubidi_writeReordered(bidi, reordered.getBuffer(length),
                                     length, UBIDI_DO_MIRRORING, &err);
                ubidi_close(bidi);
                reordered.releaseBuffer(length);
                u_shapeArabic(reordered.getBuffer(), length,
                              shaped.getBuffer(length), length,
                              U_SHAPE_LETTERS_SHAPE | U_SHAPE_LENGTH_FIXED_SPACES_NEAR |
                              U_SHAPE_TEXT_DIRECTION_VISUAL_LTR, &err);
                shaped.releaseBuffer(length);
                if (U_SUCCESS(err))
                {
                    U_NAMESPACE_QUALIFIER StringCharacterIterator iter(shaped);
                    for (iter.setToStart(); iter.hasNext();)
                    {
                        UChar ch = iter.nextPostInc();
                        int32_t glyph_index = FT_Get_Char_Index(ft_face[j], ch);
                        if (i == 0)
                        {
                            std::cerr << glyph_index <<  ":";
                        }
                    }
                    if (i == 0) std::cerr << std::endl;
                }
            }
        }
    }

    {
        const char **shaper_list = hb_shape_list_shapers();
        for ( ;*shaper_list; shaper_list++)
        {
            std::cerr << *shaper_list << std::endl;
        }

        std::cerr << "Starting Harfbuzz shaping" << std::endl;
        progress_timer timer2(std::clog,"Harfbuzz shaping done");
        const char* const shapers[]  = { /*"ot",*/"fallback" };
        hb_buffer_t *buffer(hb_buffer_create());

        for (unsigned i = 0; i < NUM_ITER; ++i)
        {
            for (unsigned j = 0; j < NUM_EXAMPLES; ++j)
            {
                UnicodeString text = UnicodeString::fromUTF8(texts[j]);
                int32_t length = text.length();
                hb_buffer_clear_contents(buffer);
                //hb_buffer_set_unicode_funcs(buffer.get(), hb_icu_get_unicode_funcs());
                hb_buffer_pre_allocate(buffer, length);
                hb_buffer_add_utf16(buffer, text.getBuffer(), text.length(), 0, length);
                hb_buffer_set_direction(buffer, text_directions[j]);
                hb_buffer_set_script(buffer, scripts[j]);
                hb_buffer_set_language(buffer,hb_language_from_string(languages[j], std::strlen(languages[j])));
                //hb_shape(hb_ft_font[j], buffer.get(), 0, 0);
                hb_shape_full(hb_ft_font[j], buffer, 0, 0, shapers);
                unsigned num_glyphs = hb_buffer_get_length(buffer);
                hb_glyph_info_t *glyphs = hb_buffer_get_glyph_infos(buffer, NULL);
                //hb_glyph_position_t *positions = hb_buffer_get_glyph_positions(buffer.get(), NULL);
                for (unsigned k=0; k<num_glyphs; ++k)
                {
                    int32_t glyph_index = glyphs[k].codepoint;
                    if (i == 0)
                    {
                        std::cerr  <<  glyph_index << ":";
                    }
                }
                if (i == 0) std::cerr << std::endl;
            }
        }
        hb_buffer_destroy(buffer);
    }

    // cleanup
    for (int j=0; j < NUM_EXAMPLES; ++j)
    {
        hb_font_destroy(hb_ft_font[j]);
    }
    FT_Done_FreeType(ft_library);

    return EXIT_SUCCESS;
}
Пример #10
0
unsigned int CppCheck::processFile(const std::string& filename, const std::string &cfgname, std::istream& fileStream)
{
    exitcode = 0;

    // only show debug warnings for accepted C/C++ source files
    if (!Path::acceptFile(filename))
        _settings.debugwarnings = false;

    if (_settings.terminated())
        return exitcode;

    if (!_settings.quiet) {
        std::string fixedpath = Path::simplifyPath(filename);
        fixedpath = Path::toNativeSeparators(fixedpath);
        _errorLogger.reportOut(std::string("Checking ") + fixedpath + ' ' + cfgname + std::string("..."));

        if (_settings.verbose) {
            _errorLogger.reportOut("Defines: " + _settings.userDefines);
            std::string includePaths;
            for (std::list<std::string>::const_iterator I = _settings.includePaths.begin(); I != _settings.includePaths.end(); ++I)
                includePaths += " -I" + *I;
            _errorLogger.reportOut("Includes:" + includePaths);
            _errorLogger.reportOut(std::string("Platform:") + _settings.platformString());
        }
    }

    if (plistFile.is_open()) {
        plistFile << ErrorLogger::plistFooter();
        plistFile.close();
    }

    CheckUnusedFunctions checkUnusedFunctions(nullptr, nullptr, nullptr);

    bool internalErrorFound(false);
    try {
        Preprocessor preprocessor(_settings, this);
        std::set<std::string> configurations;

        simplecpp::OutputList outputList;
        std::vector<std::string> files;
        simplecpp::TokenList tokens1(fileStream, files, filename, &outputList);

        // If there is a syntax error, report it and stop
        for (simplecpp::OutputList::const_iterator it = outputList.begin(); it != outputList.end(); ++it) {
            bool err;
            switch (it->type) {
            case simplecpp::Output::ERROR:
            case simplecpp::Output::INCLUDE_NESTED_TOO_DEEPLY:
            case simplecpp::Output::SYNTAX_ERROR:
            case simplecpp::Output::UNHANDLED_CHAR_ERROR:
                err = true;
                break;
            case simplecpp::Output::WARNING:
            case simplecpp::Output::MISSING_HEADER:
            case simplecpp::Output::PORTABILITY_BACKSLASH:
                err = false;
                break;
            };

            if (err) {
                const ErrorLogger::ErrorMessage::FileLocation loc1(it->location.file(), it->location.line);
                std::list<ErrorLogger::ErrorMessage::FileLocation> callstack;
                callstack.push_back(loc1);

                ErrorLogger::ErrorMessage errmsg(callstack,
                                                 "",
                                                 Severity::error,
                                                 it->msg,
                                                 "syntaxError",
                                                 false);
                _errorLogger.reportErr(errmsg);
                return 1;
            }
        }

        preprocessor.loadFiles(tokens1, files);

        if (!_settings.plistOutput.empty()) {
            std::string filename2;
            if (filename.find('/') != std::string::npos)
                filename2 = filename.substr(filename.rfind('/') + 1);
            else
                filename2 = filename;
            filename2 = _settings.plistOutput + filename2.substr(0, filename2.find('.')) + ".plist";
            plistFile.open(filename2);
            plistFile << ErrorLogger::plistHeader(version(), files);
        }

        // write dump file xml prolog
        std::ofstream fdump;
        if (_settings.dump) {
            const std::string dumpfile(_settings.dumpFile.empty() ? (filename + ".dump") : _settings.dumpFile);
            fdump.open(dumpfile.c_str());
            if (fdump.is_open()) {
                fdump << "<?xml version=\"1.0\"?>" << std::endl;
                fdump << "<dumps>" << std::endl;
                fdump << "  <platform"
                      << " name=\"" << _settings.platformString() << '\"'
                      << " char_bit=\"" << _settings.char_bit << '\"'
                      << " short_bit=\"" << _settings.short_bit << '\"'
                      << " int_bit=\"" << _settings.int_bit << '\"'
                      << " long_bit=\"" << _settings.long_bit << '\"'
                      << " long_long_bit=\"" << _settings.long_long_bit << '\"'
                      << " pointer_bit=\"" << (_settings.sizeof_pointer * _settings.char_bit) << '\"'
                      << "/>\n";
                fdump << "  <rawtokens>" << std::endl;
                for (unsigned int i = 0; i < files.size(); ++i)
                    fdump << "    <file index=\"" << i << "\" name=\"" << ErrorLogger::toxml(files[i]) << "\"/>" << std::endl;
                for (const simplecpp::Token *tok = tokens1.cfront(); tok; tok = tok->next) {
                    fdump << "    <tok "
                          << "fileIndex=\"" << tok->location.fileIndex << "\" "
                          << "linenr=\"" << tok->location.line << "\" "
                          << "str=\"" << ErrorLogger::toxml(tok->str) << "\""
                          << "/>" << std::endl;
                }
                fdump << "  </rawtokens>" << std::endl;
            }
        }

        // Parse comments and then remove them
        preprocessor.inlineSuppressions(tokens1);
        tokens1.removeComments();
        preprocessor.removeComments();

        if (!_settings.buildDir.empty()) {
            // Get toolinfo
            std::string toolinfo;
            toolinfo += CPPCHECK_VERSION_STRING;
            toolinfo += _settings.isEnabled(Settings::WARNING) ? 'w' : ' ';
            toolinfo += _settings.isEnabled(Settings::STYLE) ? 's' : ' ';
            toolinfo += _settings.isEnabled(Settings::PERFORMANCE) ? 'p' : ' ';
            toolinfo += _settings.isEnabled(Settings::PORTABILITY) ? 'p' : ' ';
            toolinfo += _settings.isEnabled(Settings::INFORMATION) ? 'i' : ' ';
            toolinfo += _settings.userDefines;

            // Calculate checksum so it can be compared with old checksum / future checksums
            const unsigned int checksum = preprocessor.calculateChecksum(tokens1, toolinfo);
            std::list<ErrorLogger::ErrorMessage> errors;
            if (!analyzerInformation.analyzeFile(_settings.buildDir, filename, cfgname, checksum, &errors)) {
                while (!errors.empty()) {
                    reportErr(errors.front());
                    errors.pop_front();
                }
                return exitcode;  // known results => no need to reanalyze file
            }
        }

        // Get directives
        preprocessor.setDirectives(tokens1);
        preprocessor.simplifyPragmaAsm(&tokens1);

        preprocessor.setPlatformInfo(&tokens1);

        // Get configurations..
        if (_settings.userDefines.empty() || _settings.force) {
            Timer t("Preprocessor::getConfigs", _settings.showtime, &S_timerResults);
            configurations = preprocessor.getConfigs(tokens1);
        } else {
            configurations.insert(_settings.userDefines);
        }

        if (_settings.checkConfiguration) {
            for (std::set<std::string>::const_iterator it = configurations.begin(); it != configurations.end(); ++it)
                (void)preprocessor.getcode(tokens1, *it, files, true);

            return 0;
        }

        // Run define rules on raw code
        for (std::list<Settings::Rule>::const_iterator it = _settings.rules.begin(); it != _settings.rules.end(); ++it) {
            if (it->tokenlist != "define")
                continue;

            std::string code;
            const std::list<Directive> &directives = preprocessor.getDirectives();
            for (std::list<Directive>::const_iterator dir = directives.begin(); dir != directives.end(); ++dir) {
                if (dir->str.compare(0,8,"#define ") == 0)
                    code += "#line " + MathLib::toString(dir->linenr) + " \"" + dir->file + "\"\n" + dir->str + '\n';
            }
            Tokenizer tokenizer2(&_settings, this);
            std::istringstream istr2(code);
            tokenizer2.list.createTokens(istr2);
            executeRules("define", tokenizer2);
            break;
        }

        if (!_settings.force && configurations.size() > _settings.maxConfigs) {
            if (_settings.isEnabled(Settings::INFORMATION)) {
                tooManyConfigsError(Path::toNativeSeparators(filename),configurations.size());
            } else {
                tooManyConfigs = true;
            }
        }

        std::set<unsigned long long> checksums;
        unsigned int checkCount = 0;
        for (std::set<std::string>::const_iterator it = configurations.begin(); it != configurations.end(); ++it) {
            // bail out if terminated
            if (_settings.terminated())
                break;

            // Check only a few configurations (default 12), after that bail out, unless --force
            // was used.
            if (!_settings.force && ++checkCount > _settings.maxConfigs)
                break;

            cfg = *it;

            // If only errors are printed, print filename after the check
            if (!_settings.quiet && (!cfg.empty() || it != configurations.begin())) {
                std::string fixedpath = Path::simplifyPath(filename);
                fixedpath = Path::toNativeSeparators(fixedpath);
                _errorLogger.reportOut("Checking " + fixedpath + ": " + cfg + "...");
            }

            if (!_settings.userDefines.empty()) {
                if (!cfg.empty())
                    cfg = ";" + cfg;
                cfg = _settings.userDefines + cfg;
            }

            if (_settings.preprocessOnly) {
                Timer t("Preprocessor::getcode", _settings.showtime, &S_timerResults);
                std::string codeWithoutCfg = preprocessor.getcode(tokens1, cfg, files, true);
                t.Stop();

                if (codeWithoutCfg.compare(0,5,"#file") == 0)
                    codeWithoutCfg.insert(0U, "//");
                std::string::size_type pos = 0;
                while ((pos = codeWithoutCfg.find("\n#file",pos)) != std::string::npos)
                    codeWithoutCfg.insert(pos+1U, "//");
                pos = 0;
                while ((pos = codeWithoutCfg.find("\n#endfile",pos)) != std::string::npos)
                    codeWithoutCfg.insert(pos+1U, "//");
                pos = 0;
                while ((pos = codeWithoutCfg.find(Preprocessor::macroChar,pos)) != std::string::npos)
                    codeWithoutCfg[pos] = ' ';
                reportOut(codeWithoutCfg);
                continue;
            }

            Tokenizer _tokenizer(&_settings, this);
            if (_settings.showtime != SHOWTIME_NONE)
                _tokenizer.setTimerResults(&S_timerResults);

            try {
                bool result;

                // Create tokens, skip rest of iteration if failed
                Timer timer("Tokenizer::createTokens", _settings.showtime, &S_timerResults);
                const simplecpp::TokenList &tokensP = preprocessor.preprocess(tokens1, cfg, files);
                _tokenizer.createTokens(&tokensP);
                timer.Stop();
                if (tokensP.empty())
                    continue;

                // skip rest of iteration if just checking configuration
                if (_settings.checkConfiguration)
                    continue;

                // Check raw tokens
                checkRawTokens(_tokenizer);

                // Simplify tokens into normal form, skip rest of iteration if failed
                Timer timer2("Tokenizer::simplifyTokens1", _settings.showtime, &S_timerResults);
                result = _tokenizer.simplifyTokens1(cfg);
                timer2.Stop();
                if (!result)
                    continue;

                // dump xml if --dump
                if (_settings.dump && fdump.is_open()) {
                    fdump << "<dump cfg=\"" << ErrorLogger::toxml(cfg) << "\">" << std::endl;
                    preprocessor.dump(fdump);
                    _tokenizer.dump(fdump);
                    fdump << "</dump>" << std::endl;
                }

                // Skip if we already met the same simplified token list
                if (_settings.force || _settings.maxConfigs > 1) {
                    const unsigned long long checksum = _tokenizer.list.calculateChecksum();
                    if (checksums.find(checksum) != checksums.end()) {
                        if (_settings.isEnabled(Settings::INFORMATION) && (_settings.debug || _settings.verbose))
                            purgedConfigurationMessage(filename, cfg);
                        continue;
                    }
                    checksums.insert(checksum);
                }

                // Check normal tokens
                checkNormalTokens(_tokenizer);

                // Analyze info..
                if (!_settings.buildDir.empty())
                    checkUnusedFunctions.parseTokens(_tokenizer, filename.c_str(), &_settings, false);

                // simplify more if required, skip rest of iteration if failed
                if (_simplify) {
                    // if further simplification fails then skip rest of iteration
                    Timer timer3("Tokenizer::simplifyTokenList2", _settings.showtime, &S_timerResults);
                    result = _tokenizer.simplifyTokenList2();
                    timer3.Stop();
                    if (!result)
                        continue;

                    // Check simplified tokens
                    checkSimplifiedTokens(_tokenizer);
                }

            } catch (const InternalError &e) {
                internalErrorFound=true;
                std::list<ErrorLogger::ErrorMessage::FileLocation> locationList;
                ErrorLogger::ErrorMessage::FileLocation loc;
                if (e.token) {
                    loc.line = e.token->linenr();
                    const std::string fixedpath = Path::toNativeSeparators(_tokenizer.list.file(e.token));
                    loc.setfile(fixedpath);
                } else {
                    ErrorLogger::ErrorMessage::FileLocation loc2;
                    loc2.setfile(Path::toNativeSeparators(filename));
                    locationList.push_back(loc2);
                    loc.setfile(_tokenizer.list.getSourceFilePath());
                }
                locationList.push_back(loc);
                ErrorLogger::ErrorMessage errmsg(locationList,
                                                 _tokenizer.list.getSourceFilePath(),
                                                 Severity::error,
                                                 e.errorMessage,
                                                 e.id,
                                                 false);

                reportErr(errmsg);
            }
        }

        // dumped all configs, close root </dumps> element now
        if (_settings.dump && fdump.is_open())
            fdump << "</dumps>" << std::endl;

    } catch (const std::runtime_error &e) {
        internalError(filename, e.what());
    } catch (const std::bad_alloc &e) {
        internalError(filename, e.what());
    } catch (const InternalError &e) {
        internalError(filename, e.errorMessage);
        exitcode=1; // e.g. reflect a syntax error
    }

    analyzerInformation.setFileInfo("CheckUnusedFunctions", checkUnusedFunctions.analyzerInfo());
    analyzerInformation.close();

    // In jointSuppressionReport mode, unmatched suppressions are
    // collected after all files are processed
    if (!_settings.jointSuppressionReport && (_settings.isEnabled(Settings::INFORMATION) || _settings.checkConfiguration)) {
        reportUnmatchedSuppressions(_settings.nomsg.getUnmatchedLocalSuppressions(filename, isUnusedFunctionCheckEnabled()));
    }

    _errorList.clear();
    if (internalErrorFound && (exitcode==0)) {
        exitcode=1;
    }
    return exitcode;
}
Пример #11
0
int main(){
  
////////////////////GAME PROPERTIES///////////////////////////////////

	//window properties
	sf::RenderWindow pong(sf::VideoMode(RENDERWIDTH, RENDERHEIGHT, 32), "Tungu");
	pong.setMouseCursorVisible(false);
	pong.setFramerateLimit(60);

	//music
	sf::Music bgm;
	bgm.openFromFile("multimedia/audio/background.wav");
	bgm.setPitch(1.5);
	bgm.setLoop(true);
	bgm.play();

	//sound
	sf::SoundBuffer buffer1;
	buffer1.loadFromFile("multimedia/audio/bounce.wav");
	sf::Sound bounce;
	bounce.setBuffer(buffer1);
	sf::SoundBuffer buffer2;
	buffer2.loadFromFile("multimedia/audio/point.wav");
	sf::Sound point;
	point.setBuffer(buffer2);
	
	//ncp properties
	sf::RectangleShape ncp(sf::Vector2f(5, RENDERHEIGHT / 1.6));
	ncp.setFillColor(sf::Color(50, 50, 50));
	ncp.setPosition(RENDERWIDTH / 2, RENDERHEIGHT / 2 - (RENDERHEIGHT / 1.6) / 2 );

	//player 1 properties
	int p1Len = 100;
	sf::RectangleShape player1(sf::Vector2f(15, p1Len));
	player1.setFillColor(sf::Color(0, 0, 255));
	player1.setPosition(0, RENDERHEIGHT / 2 - player1.getSize().y / 2);
	int player1Score = 0;

	//player 2 properties
	int p2Len = 100;
	sf::RectangleShape player2(sf::Vector2f(15, p2Len));
	player2.setFillColor(sf::Color(0, 255, 0));
	player2.setPosition(RENDERWIDTH - player2.getSize().x, RENDERHEIGHT / 2 - player2.getSize().y / 2);
	int player2Score = 0;

	//ball properties
	sf::CircleShape ball(10, 25);
	ball.setFillColor(sf::Color(255, 255, 255));
	ball.setPosition(RENDERWIDTH / 2 - ball.getRadius(), RENDERHEIGHT / 2 - ball.getRadius());
	float BALLSPEED = 15;
	float ballVelX = -BALLSPEED, ballVelY = -BALLSPEED;
	float ballX = RENDERWIDTH / 2 - ball.getRadius(), ballY = RENDERHEIGHT / 2 - ball.getRadius();
	float ballDiameter = ball.getRadius() * 2;
	
	//score-timer text
	sf::Font font;
	font.loadFromFile("fonts/LiberationSerif-Regular.ttf");
	sf::Text score1("0", font, 80);
	score1.setPosition(RENDERWIDTH / 4, 0);
	sf::Text score2("0", font, 80);
	score2.setPosition(3 * RENDERWIDTH / 4 - score2.getLocalBounds().width, 0);
	sf::Text timer1("", font, 50);
	timer1.setPosition(0 , 5 * RENDERHEIGHT / 6);
	sf::Text timer2("", font, 50);
	timer2.setPosition(RENDERWIDTH / 2 - timer2.getLocalBounds().width, 5 * RENDERHEIGHT / 6);
	int time1 = 0;
	int time2 = 0;
	
	//gameover
	sf::Text gameover("GAME OVER", font, 120);
	gameover.setColor(sf::Color::Red);
	gameover.setPosition(0, RENDERHEIGHT / 3);
	
		
	///////////////CAMERA FUNTIONS//////////////////////

      CvCapture* capture =0;   
    
      capture = cvCaptureFromCAM(0);


     	 if(!capture){

		printf("Capture failure\n");

		return -1;
      }
      
      IplImage* frame=0;

      frame = cvQueryFrame(capture);  
         
      if(!frame) return -1;
  
     //create a blank image and assigned to 'imgTracking' which has the same size of original video

     imgTracking=cvCreateImage(cvGetSize(frame),IPL_DEPTH_8U, 3);

     cvZero(imgTracking); //covert the image, 'imgTracking' to black

     //cvNamedWindow("Player1"); 
    
     ///cvNamedWindow("Player2");

      //iterate through each frames of the video
     
      while(player1Score + player2Score != 7){

		frame = cvQueryFrame(capture); 
          
		if(!frame) break;

		frame=cvCloneImage(frame); 
            
		cvSmooth(frame, frame, CV_GAUSSIAN,3,3); //smooth the original image using Gaussian kernel

			/////////////////// Player 1 ////////////////////

			IplImage* imgHSV = cvCreateImage(cvGetSize(frame), IPL_DEPTH_8U, 3); 

			cvCvtColor(frame, imgHSV, CV_BGR2HSV); //Change the color format from BGR to HSV

			IplImage* imgThresh = GetThresholdedImage(imgHSV, 85, 143, 40, 116, 256, 159); //guante cyan
	 
			cvSmooth(imgThresh, imgThresh, CV_GAUSSIAN,3,3); //smooth the binary image using Gaussian kernel
	    
			player100 =  trackObject(imgThresh, 255, 0, 0, 1);

			/////////////////// Player 2 ////////////////////

			IplImage* imgHSV2 = cvCreateImage(cvGetSize(frame), IPL_DEPTH_8U, 3); 
	    
			cvCvtColor(frame, imgHSV2, CV_BGR2HSV);//Change the color format from BGR to HSV

			IplImage* imgThresh2 = GetThresholdedImage(imgHSV2, 26, 145, 31, 73, 256, 111); //guante verde

 			cvSmooth(imgThresh2, imgThresh2, CV_GAUSSIAN,3,3); //smooth the binary image using Gaussian kernel

			player200 = trackObject(imgThresh2, 0, 255, 0, 2);

            	// Add the tracking image and the frame

		cvAdd(frame, imgTracking, frame);

		//cvShowImage("Player1", imgThresh);
 
		//cvShowImage("Player2", imgThresh2); 
		
		cvMoveWindow("Video", 1800, 0);

		cvResizeWindow("Video", 100, 240);
           
		cvShowImage("Video", frame);
           
           //Clean up used images

           cvReleaseImage(&imgHSV);

	   cvReleaseImage(&imgHSV2);

           cvReleaseImage(&imgThresh);

	   cvReleaseImage(&imgThresh2);   
          
           cvReleaseImage(&frame);

            //Wait 10mS
            int c = cvWaitKey(10);

            //If 'ESC' is pressed, break the loop
            if((char)c==27 ) break;  


/////////////////////////////Scores///////////////////////////////////

		//score for player one winning
		if(player1Score == player2Score + 1)
		{
		    timer1.setString(convertInt(time1 += 2));
		    timer2.setString(convertInt(time2 += 1));
		}
		
		if(player1Score == player2Score + 2)
		{
		    timer1.setString(convertInt(time1 += 4));
		    timer2.setString(convertInt(time2 += 1));
		}
		
		if(player1Score == player2Score + 3)
		{
		    timer1.setString(convertInt(time1 += 8));
		    timer2.setString(convertInt(time2 += 1));
		}
		
		if(player1Score == player2Score + 4)
		{
		    timer1.setString(convertInt(time1 += 16));
		    timer2.setString(convertInt(time2 += 1));
		}
		
		if(player1Score == player2Score + 5)
		{
		    timer1.setString(convertInt(time1 += 32));
		    timer2.setString(convertInt(time2 += 1));
		}
		
		if(player1Score == player2Score + 6)
		{
		    timer1.setString(convertInt(time1 += 64));
		    timer2.setString(convertInt(time2 += 1));
		}
		
		//score on equals
		if(player1Score == player2Score)
		{
		    timer1.setString(convertInt(time1 += 1));
		    timer2.setString(convertInt(time2 += 1));
		}
		
		//score for player two winning
		if(player2Score == player1Score + 1)
		{
		    timer2.setString(convertInt(time2 += 2));
		    timer1.setString(convertInt(time1 += 1));
		}
		
		if(player2Score == player1Score + 2)
		{
		    timer2.setString(convertInt(time2 += 4));
		    timer1.setString(convertInt(time1 += 1));
		}
		
		if(player2Score == player1Score + 3)
		{
		    timer2.setString(convertInt(time2 += 8));
		    timer1.setString(convertInt(time1 += 1));
		}
		
		if(player2Score == player1Score + 4)
		{
		    timer2.setString(convertInt(time2 += 16));
		    timer1.setString(convertInt(time1 += 1));
		}
		
		if(player2Score == player1Score + 5)
		{
		    timer2.setString(convertInt(time2 += 32));
		    timer1.setString(convertInt(time1 += 1));
		}
		
		if(player2Score == player1Score + 6)
		{
		    timer2.setString(convertInt(time2 += 64));
		    timer1.setString(convertInt(time1 += 1));
		}

//////////////////////////////Game////////////////////////////////////

		//player 1 movement muy lento
		
		if(player100==6)
			
			player1.move(0, -(vel-3));

		else if(player100==-6)

			player1.move(0, vel-3);

		//player 1 movement LENTO	
		
		if(player100==1)
			
			player1.move(0, -vel);

		else if(player100==-1)

			player1.move(0, vel);


		//player 1 movement MEDIO
		
		if(player100==2)
			
			player1.move(0, -(vel+10));

		else if(player100==-2)

			player1.move(0, vel+10);

		//player 1 movement RAPIDO
		
		if(player100==3)
			
			player1.move(0, -(vel+20));

		else if(player100==-3)

			player1.move(0, vel+20);

		//player 1 movement muy rapido
		
		if(player100==4)
			
			player1.move(0, -(vel+25));

		else if(player100==-4)

			player1.move(0, vel+25);

		//player 1 movement Extreme
		
		if(player100==5)
			
			player1.move(0, -(vel+30));

		else if(player100==-5)

			player1.move(0, vel+30);

		
		//MOVIMIENTO GOLPE PLAYER1

		if(player100==0)

			player1.move(0,0);
			
		
	
		if (player1.getPosition().x <= 10){

		if(player100==22)
			
			player1.move(10, 0);
			
			
		}


		//player 2 movement muy LENTO

		if(player200==6)

			player2.move(0, -(vel-3));

		else if(player200==-6)

			player2.move(0, vel-3);

		//player 2 movement LENTO

		if(player200==1)

			player2.move(0, -vel);

		else if(player200==-1)

			player2.move(0, vel);

		//player 2 movement MEDIO

		if(player200==2)

			player2.move(0, -(vel+10));

		else if(player200==-2)

			player2.move(0, vel+10);

		//player 2 movement RAPIDO

		if(player200==3)

			player2.move(0, -(vel+20));

		else if(player200==-3)

			player2.move(0, vel+20);

		//player 2 movement muy rapido

		if(player200==4)

			player2.move(0, -(vel+25));

		else if(player200==-4)

			player2.move(0, vel+25);

		//player 2 movement Extreme

		if(player200==5)
			player2.move(0, -(vel+30));

		else if(player200==-5)

			player2.move(0, vel+30);

		
		if(player200==0) 

			player2.move(0,0);

		//MOVIMIENTO GOLPE PLAYER2
		
		if (player2.getPosition().x >= RENDERWIDTH-player2.getSize().x-10){
			  
		if(player200==-22)
			
			player2.move(-10, 0);
			
			
		}

		//player 1 and wall collision

		if(player1.getPosition().y <= 0)

			player1.setPosition(0, 0);

		if(player1.getPosition().y >= RENDERHEIGHT - player1.getSize().y)

			player1.setPosition(0, RENDERHEIGHT - player1.getSize().y);

		//PLAYER1 AND WALL BACK COLLISION

		if(player1.getPosition().x != 0)

			player1.move(-1,0);
		
		//PLAYER2 AND WALL BACK COLLISION

		if(player2.getPosition().x != RENDERWIDTH-player2.getSize().x)

			player2.move(1,0);
		
		//player 2 and wall collision

		if(player2.getPosition().y <= 0)

			player2.setPosition(RENDERWIDTH - player2.getSize().x, 0);

		if(player2.getPosition().y >= RENDERHEIGHT - player2.getSize().y)

			player2.setPosition(RENDERWIDTH - player2.getSize().x, RENDERHEIGHT - player2.getSize().y);

		//ball and wall collision

		if(ball.getPosition().y <= 0 || ball.getPosition().y >= RENDERHEIGHT - ballDiameter){


			ballVelY *= -1;

			bounce.play();

		}

		//ball and player 1 collision

		if (ball.getPosition().x <= player1.getPosition().x + player1.getSize().x){


			if ((ball.getPosition().y + ballDiameter >= player1.getPosition().y && ball.getPosition().y + ballDiameter <= player1.getPosition().y + player1.getSize().y) || ball.getPosition().y <= player1.getPosition().y + player1.getSize().y && ball.getPosition().y >= player1.getPosition().y){


	if (player1.getPosition().x > 14){

				ballVelX = (ballVelX - 5) * -1;

				ball.setFillColor(sf::Color(255,0,0));

				
			}

	else if (player1.getPosition().x <= 14){

				ballVelX = (ballVelX - 3) * -1;

				ball.setFillColor(sf::Color(0,0,255));

				bounce.play();
}
			

			}

			else{
				ball.setFillColor(sf::Color(255,255,255));

				point.play();

				player2Score += 1;  

				ballX = RENDERWIDTH / 2 - ball.getRadius();

				if (BALLSPEED < 8)

					BALLSPEED += 0.2;

				ballVelX = BALLSPEED;

				score2.setString(convertInt(player2Score));

				score2.setPosition(3 * RENDERWIDTH / 4 - score2.getLocalBounds().width, 0);

				if (p2Len > 40)

					p2Len -= 10;

				player2.setSize(sf::Vector2f(15, p2Len));

				if (p1Len < 100)

					p1Len += 10;

				player1.setSize(sf::Vector2f(15, p1Len));
				
			}
		}

		//ball and player 2 collision

		if (ball.getPosition().x + ballDiameter >= player2.getPosition().x){

		
			if ((ball.getPosition().y + ballDiameter >= player2.getPosition().y && ball.getPosition().y + ballDiameter <= player2.getPosition().y + player2.getSize().y) || ball.getPosition().y <= player2.getPosition().y + player2.getSize().y && ball.getPosition().y >= player2.getPosition().y){
			


				if (player2.getPosition().x < (RENDERWIDTH-9-player2.getSize().x)){

					ballVelX = (ballVelX + 5) * -1;

					ball.setFillColor(sf::Color(255,0,0));

					
				
				}

				else if (player2.getPosition().x >= (RENDERWIDTH-9-player2.getSize().x)){

					ballVelX = (ballVelX + 3) * -1;

					ball.setFillColor(sf::Color(0,255,0));

					bounce.play();
			}
		}
				
			
				else{
			
					ball.setFillColor(sf::Color(255,255,255));

					point.play();

					player1Score += 1;

					ballX = RENDERWIDTH / 2 - ball.getRadius();

					if (BALLSPEED < 8)

						BALLSPEED += 0.5;

					ballVelX = -BALLSPEED;

					score1.setString(convertInt(player1Score));

					if (p1Len > 40)
						p1Len -= 10;

					player1.setSize(sf::Vector2f(15, p1Len));

					if (p2Len < 100)

						p2Len += 10;

					player2.setSize(sf::Vector2f(15, p2Len));
			}
		}

		//ball position update
		ballX += ballVelX;
		ballY += ballVelY;
		ball.setPosition(ballX, ballY);

		//render updates
		
		pong.clear();
		pong.draw(score1);
		pong.draw(timer1);
		pong.draw(timer2);
		pong.draw(score2);
		pong.draw(player1);
		pong.draw(player2);
		pong.draw(ball);
		pong.draw(ncp);
		pong.display();


		while(player1Score + player2Score == 7){

			if(player1Score > player2Score)
				timer1.setString(convertInt(time1 += 500));
			if(player1Score < player2Score)
				timer2.setString(convertInt(time2 += 500));
		
			pong.clear(sf::Color::Black);
			pong.draw(score1);
			pong.draw(timer1);
			pong.draw(timer2);
			pong.draw(score2);
			pong.draw(gameover);
			pong.display();

			counter(3);
			break;
		}

/////////////////////Finish Game/////////////////////////////////


    
      }

	std::stringstream ss;
	ss.str (timer1.getString());
	std::string scorePlayer1 = ss.str();
	ss.str (timer2.getString());
	std::string scorePlayer2 = ss.str();
	std::cout << "Final Score:" << '\n';
	std::cout << "Player1: " + scorePlayer1 << '\n';
	std::cout << "Player2: " + scorePlayer2 << '\n';

	
	std::ofstream myfile ("highscores.txt", std::ofstream::in | std::ofstream::out | std::ofstream::app);
  	if (myfile.is_open())
  	{
  		myfile << scorePlayer1 << std::endl;
    		myfile << scorePlayer2 << std::endl;
    		myfile.close();
  	}

  	else std::cout << "Unable to open file";

      cvDestroyAllWindows() ;
      cvReleaseImage(&imgTracking);
      cvReleaseCapture(&capture);     

      return 0;
}
Пример #12
0
void MainWindow::on_secButton_clicked()
{
            //    zaman->start(111);
            timer2();
}
Пример #13
0
int main()
{
    //window properties
    sf::RenderWindow pong(sf::VideoMode(RENDERWIDTH, RENDERHEIGHT, 32), "GameName", sf::Style::Fullscreen);
    pong.setMouseCursorVisible(false);
    pong.setFramerateLimit(60);

    //music
    sf::Music bgm;
    bgm.openFromFile("multimedia/audio/musica.wav");
    bgm.setPitch(1);
    bgm.setLoop(true);
    bgm.play();

    //sound
    sf::SoundBuffer buffer1;
    buffer1.loadFromFile("multimedia/audio/bounce.wav");
    sf::Sound bounce;
    bounce.setBuffer(buffer1);
    sf::SoundBuffer buffer2;
    buffer2.loadFromFile("multimedia/audio/point.wav");
    sf::Sound point;
    point.setBuffer(buffer2);

    //ncp properties
    sf::RectangleShape ncp(sf::Vector2f(5, RENDERHEIGHT / 1.6));
    ncp.setFillColor(sf::Color(50, 50, 50));
    ncp.setPosition(RENDERWIDTH / 2, RENDERHEIGHT / 2 - (RENDERHEIGHT / 1.6) / 2 );

    //player 1 properties
    int p1Len = 100;
    sf::RectangleShape player1(sf::Vector2f(10, p1Len));
    player1.setFillColor(sf::Color(0, 0, 255));
    player1.setPosition(0, RENDERHEIGHT / 2 - player1.getSize().y / 2);
    int player1Score = 0;

    //player 2 properties
    int p2Len = 100;
    sf::RectangleShape player2(sf::Vector2f(10, p2Len));
    player2.setFillColor(sf::Color(255, 0, 0));
    player2.setPosition(RENDERWIDTH - player2.getSize().x, RENDERHEIGHT / 2 - player2.getSize().y / 2);
    int player2Score = 0;

    //ball properties
    sf::CircleShape ball(10, 25);
    ball.setFillColor(sf::Color(255, 255, 255));
    ball.setPosition(RENDERWIDTH / 2 - ball.getRadius(), RENDERHEIGHT / 2 - ball.getRadius());
    float BALLSPEED = 2;
    float ballVelX = -BALLSPEED, ballVelY = -BALLSPEED;
    float ballX = RENDERWIDTH / 2 - ball.getRadius(), ballY = RENDERHEIGHT / 2 - ball.getRadius();
    float ballDiameter = ball.getRadius() * 2;

    //score-timer text
    sf::Font font;
    font.loadFromFile("fonts/LiberationSerif-Regular.ttf");
    sf::Text score1("0", font, 80);
    score1.setPosition(RENDERWIDTH / 4, 0);
    sf::Text score2("0", font, 80);
    score2.setPosition(3 * RENDERWIDTH / 4 - score2.getLocalBounds().width, 0);
    sf::Text timer1("", font, 80);
    timer1.setPosition(0 , 5 * RENDERHEIGHT / 6);
    sf::Text timer2("", font, 80);
    timer2.setPosition(RENDERWIDTH / 2 - timer2.getLocalBounds().width, 5 * RENDERHEIGHT / 6);
    int time1 = 0;
    int time2 = 0;

    //gameover
    sf::Text gameover("GAME OVER", font, 120);
    gameover.setColor(sf::Color::Red);
    gameover.setPosition(0, RENDERHEIGHT / 3);


    //game loop
    while(player1Score + player2Score != 3)
    {
        sf::Event event;
        while(pong.pollEvent(event))
        {
            if(event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape)
                pong.close();
        }


        //score for player one winning
        if(player1Score == player2Score + 1)
        {
            timer1.setString(convertInt(time1 += 2));
            timer2.setString(convertInt(time2 += 1));
        }

        if(player1Score == player2Score + 2)
        {
            timer1.setString(convertInt(time1 += 4));
            timer2.setString(convertInt(time2 += 1));
        }

        if(player1Score == player2Score + 3)
        {
            timer1.setString(convertInt(time1 += 8));
            timer2.setString(convertInt(time2 += 1));
        }

        if(player1Score == player2Score + 4)
        {
            timer1.setString(convertInt(time1 += 16));
            timer2.setString(convertInt(time2 += 1));
        }

        if(player1Score == player2Score + 5)
        {
            timer1.setString(convertInt(time1 += 32));
            timer2.setString(convertInt(time2 += 1));
        }

        if(player1Score == player2Score + 6)
        {
            timer1.setString(convertInt(time1 += 64));
            timer2.setString(convertInt(time2 += 1));
        }

        //score on equals
        if(player1Score == player2Score)
        {
            timer1.setString(convertInt(time1 += 1));
            timer2.setString(convertInt(time2 += 1));
        }

        //score for player two winning
        if(player2Score == player1Score + 1)
        {
            timer2.setString(convertInt(time2 += 2));
            timer1.setString(convertInt(time1 += 1));
        }

        if(player2Score == player1Score + 2)
        {
            timer2.setString(convertInt(time2 += 4));
            timer1.setString(convertInt(time1 += 1));
        }

        if(player2Score == player1Score + 3)
        {
            timer2.setString(convertInt(time2 += 8));
            timer1.setString(convertInt(time1 += 1));
        }

        if(player2Score == player1Score + 4)
        {
            timer2.setString(convertInt(time2 += 16));
            timer1.setString(convertInt(time1 += 1));
        }

        if(player2Score == player1Score + 5)
        {
            timer2.setString(convertInt(time2 += 32));
            timer1.setString(convertInt(time1 += 1));
        }

        if(player2Score == player1Score + 6)
        {
            timer2.setString(convertInt(time2 += 64));
            timer1.setString(convertInt(time1 += 1));
        }

        //player 1 movement
        if(sf::Keyboard::isKeyPressed(sf::Keyboard::W))
            player1.move(0, -10);
        else if(sf::Keyboard::isKeyPressed(sf::Keyboard::S))
            player1.move(0, 10);

        //player 2 movement
        if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
            player2.move(0, -10);
        else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
            player2.move(0, 10);

        //player 1 and wall collision
        if(player1.getPosition().y <= 0)
            player1.setPosition(0, 0);
        if(player1.getPosition().y >= RENDERHEIGHT - player1.getSize().y)
            player1.setPosition(0, RENDERHEIGHT - player1.getSize().y);

        //player 2 and wall collision
        if(player2.getPosition().y <= 0)
            player2.setPosition(RENDERWIDTH - player2.getSize().x, 0);
        if(player2.getPosition().y >= RENDERHEIGHT - player2.getSize().y)
            player2.setPosition(RENDERWIDTH - player2.getSize().x, RENDERHEIGHT - player2.getSize().y);

        //ball and wall collision
        if(ball.getPosition().y <= 0 || ball.getPosition().y >= RENDERHEIGHT - ballDiameter)
        {
            ballVelY *= -1;
            bounce.play();
        }

        //ball and player 1 collision
        if (ball.getPosition().x <= player1.getPosition().x + player1.getSize().x)
        {
            if ((ball.getPosition().y + ballDiameter >= player1.getPosition().y
                    && ball.getPosition().y + ballDiameter <= player1.getPosition().y + player1.getSize().y)
                    || ball.getPosition().y <= player1.getPosition().y + player1.getSize().y
                    && ball.getPosition().y >= player1.getPosition().y)
            {
                ballVelX = (ballVelX - 1) * -1;
                bounce.play();
            }
            else
            {
                point.play();
                player2Score += 1;
                ballX = RENDERWIDTH / 2 - ball.getRadius();
                if (BALLSPEED < 8)
                    BALLSPEED += 0.5;
                ballVelX = BALLSPEED;
                score2.setString(convertInt(player2Score));
                score2.setPosition(3 * RENDERWIDTH / 4 - score2.getLocalBounds().width, 0);
                if (p2Len > 30)
                    p2Len -= 10;
                player2.setSize(sf::Vector2f(10, p2Len));
                if (p1Len < 80)
                    p1Len += 10;
                player1.setSize(sf::Vector2f(10, p1Len));
            }
        }

        //ball and player 2 collision
        if (ball.getPosition().x + ballDiameter >= player2.getPosition().x)
        {
            if ((ball.getPosition().y + ballDiameter >= player2.getPosition().y
                    && ball.getPosition().y + ballDiameter <= player2.getPosition().y + player2.getSize().y)
                    || ball.getPosition().y <= player2.getPosition().y + player2.getSize().y
                    && ball.getPosition().y >= player2.getPosition().y)
            {
                ballVelX = (ballVelX + 1) * -1;
                bounce.play();
            }
            else
            {
                point.play();
                player1Score += 1;
                ballX = RENDERWIDTH / 2 - ball.getRadius();
                if (BALLSPEED < 8)
                    BALLSPEED += 0.5;
                ballVelX = -BALLSPEED;
                score1.setString(convertInt(player1Score));
                if (p1Len > 30)
                    p1Len -= 10;
                player1.setSize(sf::Vector2f(10, p1Len));
                if (p2Len < 80)
                    p2Len += 10;
                player2.setSize(sf::Vector2f(10, p2Len));
            }
        }

        //ball position update
        ballX += ballVelX;
        ballY += ballVelY;
        ball.setPosition(ballX, ballY);

        //render updates
        pong.clear();
        pong.draw(score1);
        pong.draw(timer1);
        pong.draw(timer2);
        pong.draw(score2);
        pong.draw(player1);
        pong.draw(player2);
        pong.draw(ball);
        pong.draw(ncp);
        pong.display();

        while(player1Score + player2Score == 3)
        {
            if(player1Score > player2Score)
                timer1.setString(convertInt(time1 += 10000));
            if(player1Score < player2Score)
                timer2.setString(convertInt(time2 += 10000));

            pong.clear(sf::Color::Black);
            pong.draw(score1);
            pong.draw(timer1);
            pong.draw(timer2);
            pong.draw(score2);
            pong.draw(gameover);
            pong.display();

            counter(3);
            break;
        }

    }

    std::stringstream ss;
    ss.str (timer1.getString());
    std::string scorePlayer1 = ss.str();
    ss.str (timer2.getString());
    std::string scorePlayer2 = ss.str();
    std::cout << "Final Score:" << '\n';
    std::cout << "Player1: " + scorePlayer1 << '\n';
    std::cout << "Player2: " + scorePlayer2 << '\n';


    std::ofstream myfile ("highscores.txt", std::ofstream::in | std::ofstream::out | std::ofstream::app);
    if (myfile.is_open())
    {
        myfile << scorePlayer1 << std::endl;
        myfile << scorePlayer2 << std::endl;
        myfile.close();
    }
    else std::cout << "Unable to open file";

    return 0;
}