Cycle greedIt(const Matrix &mat) { size_t n = mat.size(); Cycle cycle; vector<bool> visited(n, false); visited[0] = true; int i = 0; while (cycle.size() != n) { int best_j = 0; int best_val = INT32_MAX; for (int j = 0; j < n; j++) { if (visited[j] || best_val < mat[i][j]) continue; best_j = j; best_val = mat[i][j]; } cycle.push_back(best_j); visited[best_j] = true; i = best_j; } cycle.push_front(0); return cycle; }
// takes a dfs stack and a transaction that is visited twice, and returns the corresponding cycle // last access in the dfs stack belongs to tx // the first and last access in the cycle belong to tx Cycle* AspEventHandler::extract_cycle(DFSStack& stack, Transaction* tx) { num_cycles_++; // all cycles // if we have seen another cycle with tx as the revisited transaction, skip reporting this cycle if(txset_in_cycle.find(tx) != txset_in_cycle.end()) { return NULL; } // record this transaction, so we do not report cycles with the same revisited transaction txset_in_cycle.insert(tx); //---------------------------- Cycle* cycle = new Cycle(); num_unique_cycles_++; // unique cycles DFSStack::iterator itr = stack.begin(); for(; itr < stack.end(); ++itr) { DFSStackElement current_elt = (*itr); if(current_elt.tx_ == tx) { break; } } for(; itr < stack.end(); ++itr) { DFSStackElement current_elt = (*itr); Edge edge = *(current_elt.begin_); cycle->push_back(edge.first); cycle->push_back(edge.second); } assert(cycle->front()->tx() == tx); assert(cycle->back()->tx() == tx); return cycle; }
void displayCycle(const Matrix &mat, Cycle cycle) { Cycle::const_iterator it; for (it = cycle.begin(); it != cycle.end(); ++it) cout << *it + 1 << endl; }
ProgramComponent* CommandParser::ParseCycle(char* pBuffer) { char countBuf[5]; //find first step char* pStep = strchr(pBuffer, '['); //get cycle count int countLen = pStep - pBuffer; strncpy(countBuf, pBuffer, countLen); countBuf[countLen] = '\0'; int cycCount = atoi(countBuf); Cycle* pCycle = gpThermocycler->GetCyclePool().AllocateComponent(); pCycle->SetNumCycles(cycCount); //add steps while (pStep != NULL) { *pStep++ = '\0'; char* pStepEnd = strchr(pStep, ']'); *pStepEnd++ = '\0'; Step* pNewStep = ParseStep(pStep); pCycle->AddComponent(pNewStep); pStep = strchr(pStepEnd, '['); } return pCycle; }
Cycle * XeoTerm::defaultCycle(QString _context, QDateTime _time){ if(contain(_context)){ VariableContextSpec * pcs = (*this->contextCollection)[_context]; if(pcs->get_defCycle()!=NULL){ Cycle * v = new Cycle(); v->set_context(_context); for(std::list<std::pair<QDateTime, QString> >::iterator it = pcs->get_defCycle()->get_vals()->begin();it!=pcs->get_defCycle()->get_vals()->end();++it) { std::pair<DynamicValueBase*,QDateTime> p =std::make_pair(new DynamicValue(it->first,it->second),_time); v->add_cycleValue(p); } if(pcs->get_unitSet()->get_defUnit()!=NULL) { v->set_unit(pcs->get_unitSet()->get_defUnit()->get_symbol()); } v->set_timepoint(_time); return v; } else return NULL; } else{ return NULL; } }
// Extract component border void MoleculeLayoutGraph::_getBorder (Cycle &border) const { QS_DEF(Array<int>, vertices); QS_DEF(Array<int>, edges); int i, n = 0; for (i = edgeBegin(); i < edgeEnd(); i = edgeNext(i)) if (_layout_edges[i].type == ELEMENT_BOUNDARY) n++; if (n == 0) return; vertices.clear(); edges.clear(); for (i = edgeBegin(); i < edgeEnd(); i = edgeNext(i)) if (_layout_edges[i].type == ELEMENT_BOUNDARY) break; Edge edge = getEdge(i); vertices.push(edge.beg); edges.push(i); while (edge.end != vertices[0]) { const Vertex &vert = getVertex(edge.end); bool found = false; for (int i = vert.neiBegin(); !found && i < vert.neiEnd(); i = vert.neiNext(i)) { int nei_v = vert.neiVertex(i); int nei_e = vert.neiEdge(i); if (getEdgeType(nei_e) == ELEMENT_BOUNDARY && nei_v != edge.beg) { edge.beg = edge.end; edge.end = nei_v; vertices.push(edge.beg); edges.push(nei_e); found = true; } } if (!found || vertices.size() > n) throw Error("corrupted border"); } border.copy(vertices, edges); border.canonize(); }
int countCycle(const Matrix &mat, Cycle cycle) { Cycle::const_iterator it; int cycle_mat = 0; for (it = cycle.begin(); it != cycle.end(); ++it) { if (it != cycle.begin()) cycle_mat += mat[*it][*prev(it)]; } return cycle_mat; }
Cycle* CommandParser::ParseProgram(char* pBuffer) { Cycle* pProgram = gpThermocycler->GetCyclePool().AllocateComponent(); pProgram->SetNumCycles(1); char* pCycBuf = strtok(pBuffer, "()"); while (pCycBuf != NULL) { pProgram->AddComponent(ParseCycle(pCycBuf)); pCycBuf = strtok(NULL, "()"); } return pProgram; }
double MoleculeLayoutGraphSmart::_get_square() { Cycle cycle; _getBorder(cycle); int len = cycle.vertexCount(); double sq = 0; for (int i = 1; i < len - 1; i++) sq += Vec2f::cross(getPos(cycle.getVertex(i)) - getPos(cycle.getVertex(0)), getPos(cycle.getVertex(i + 1)) - getPos(cycle.getVertex(0))); return abs(sq / 2); }
void MoleculeLayoutGraph::_assignFirstCycle (const Cycle &cycle) { // TODO: Start drawing from vertex with maximum code and continue to the right with one of two which has maximum code int i, n; float phi; n = cycle.vertexCount(); for (i = 0; i < n; i++) { _layout_vertices[cycle.getVertex(i)].type = ELEMENT_BOUNDARY; _layout_edges[cycle.getEdge(i)].type = ELEMENT_BOUNDARY; } _first_vertex_idx = cycle.getVertex(0); _layout_vertices[cycle.getVertex(0)].pos.set(0.f, 0.f); _layout_vertices[cycle.getVertex(1)].pos.set(1.f, 0.f); phi = (float)M_PI * (n - 2) / n; for (i = 1; i < n - 1; i++) { const Vec2f &v1 = _layout_vertices[cycle.getVertex(i - 1)].pos; const Vec2f &v2 = _layout_vertices[cycle.getVertex(i)].pos; _layout_vertices[cycle.getVertex(i + 1)].pos.rotateAroundSegmentEnd(v1, v2, phi); } }
void process(NxF32 dtime) { _controlfp(_PC_64,_MCW_PC); gJobSwarmContext->processSwarmJobs(); Cycle c; c.Begin(); while ( !mFinished ) { if ( mPreview ) { mPreview = fc_process(mPreviewFractal,dtime); if ( mPreview == false && mPreviewOnly ) { mFinished = true; NxU32 wid,hit; terrainComplete(mPreviewTerrain, fc_getData(mPreviewFractal,wid,hit) ); NxF32 rot = getRotation(mPreviewTerrain); setRotation(mTerrain,rot); } } else { if ( mTexture && mFractal && !mPreviewOnly ) { bool morework = fc_process(mFractal,dtime); if ( !morework ) { NxU32 wid,hit; terrainComplete(mTerrain, fc_getData(mFractal,wid,hit) ); NxF32 rot = getRotation(mPreviewTerrain); setRotation(mTerrain,rot); mFinished = true; NxF32 stopTime = CLOCK::getSystemTime(); NxF32 diff = stopTime-mStartTime; gLog->Display("Fractal took: %0.2f seconds to process.\r\n", diff ); } } } NxU64 cycles = c.End(); if ( cycles > gMaxClockCycles ) break; } }
Grapher::CycleList Grapher::cycles() const { // vertex indices QList<Vertex> indices = m_vertices.keys(); QTime swatch; swatch.start(); int numEdges = 0; // construct the graph using vertex indices as vertex identifiers // math::Graph graph(m_vertices.size()); for (VertexMap::const_iterator it = m_vertices.begin(); it != m_vertices.end(); ++it) { Vertex const & v1 = it.key(); AdjacencyList const & adjs = it.value(); for (AdjacencyList::const_iterator jt = adjs.begin(); jt != adjs.end(); ++jt) { Vertex const & v2 = jt->v; // vertex identifiers // int gv1 = indices.indexOf(v1) + 1; int gv2 = indices.indexOf(v2) + 1; graph.connect(gv1,gv2); ++numEdges; } } numEdges /= 2; // undirected graph qDebug() << "graph contains" << m_vertices.size() << "vertices and" << numEdges << "edges"; // obtain the graph's MCB (this could take a while) QList<math::Graph::VertexList> mcb = graph.minimumCycleBasis(CompareCycles(indices)); // construct cycle list from the graph's MCB // CycleList result; foreach (math::Graph::VertexList gcycle, mcb) { Cycle cycle; foreach (math::Graph::Vertex gv, gcycle) { cycle.append(indices[gv-1]); }
void KeyFace::addCycle(const Cycle & cycle) { cycles_ << cycle; foreach(KeyCell * cell, cycle.cells()) addMeToSpatialStarOf_(cell); geometryChanged_(); }
float MoleculeLayoutGraphSmart::_get_square() { Cycle cycle; _getBorder(cycle); int len = cycle.vertexCount(); float sq = 0; for (int i = 1; i < len - 1; i++) sq += Vec2f::cross(getPos(cycle.getVertex(i)) - getPos(cycle.getVertex(0)), getPos(cycle.getVertex(i + 1)) - getPos(cycle.getVertex(0))); //printf("sq = %.20f\n", sq); return fabs(sq / 2); }
typename SimplexWithVertices<V>::Cycle SimplexWithVertices<V>:: boundary() const { Cycle bdry; if (dimension() == 0) return bdry; for (typename VertexContainer::const_iterator cur = vertices_.begin(); cur != vertices_.end(); ++cur) { bdry.push_back(*this); Self& s = bdry.back(); s.vertices_.erase(*cur); } return bdry; }
void DynamicPersistenceTrails<D,CT,OT,E,Cmp,CCmp>:: rearrange(Iter i) { order().rearrange(i); consistent_order().rearrange(i); // Resort the cycles Cycle z; for(iterator i = begin(); i != end(); ++i) { Parent::swap_cycle(i, z); z.sort(ccmp_); Parent::swap_cycle(i, z); } }
// The same but with mapping bool MoleculeLayoutGraph::_isPointOutsideCycleEx(const Cycle &cycle, const Vec2f &p, const Array<int> &mapping) const { Random rand(SOME_MAGIC_INT_FOR_RANDOM_3); // TODO: check that point 'p' is equal to the one of cycle points (sometimes it happens) float a, b; int tries = 0; while (tries < 50) { tries++; // Choose random direction a = (float)rand.nextDouble(); b = (float)rand.nextDouble(); a = 2.f * (a - 0.5f); b = 2.f * (b - 0.5f); // Calculate number of intersection with boundary int count = 0; for (int i = 0; i < cycle.vertexCount(); i++) { int ret = _isRayIntersectWithCheck(a, b, p, getPos(mapping[cycle.getVertex(i)]), getPos(mapping[cycle.getVertex((i + 1) % cycle.vertexCount())]), true); if (ret == -1) { // Ray is too near to the point. Choose another one point count = -1; break; } if (ret == 1) count++; } if (count == -1) // Try again continue; // If number of intersections is even then point is outside if (count & 1) return false; return true; } // Return any value hoping it will never happen return false; }
// TODO(elmas): report more information about the cycle void AspEventHandler::report_cycles(CyclePtrList cycles) { int i = 1; fprintf(report_file_, "Number of unique cycles: %d\n\n", cycles.size()); for(CyclePtrList::iterator itr = cycles_.begin(); itr < cycles_.end(); itr = cycles_.erase(itr)) { Cycle* cycle = (*itr); // report cycle fprintf(report_file_, "Cycle no: %d\n", i); for(Cycle::iterator iter = cycle->begin(); iter < cycle->end(); ++iter) { AccessBase* access = (*iter); fprintf(report_file_, "%s\n", access->ToString().c_str()); } fprintf(report_file_, "\n"); delete cycle; ++i; } }
// Check if point is outside cycle // By calculating number of intersections of ray bool MoleculeLayoutGraphSmart::_isPointOutsideCycle(const Cycle &cycle, const Vec2f &p) const { QS_DEF(Array<Vec2f>, point); float rotate_angle = 0; int size = cycle.vertexCount(); point.resize(size + 1); for (int i = 0; i <= size; i++) point[i] = _layout_vertices[cycle.getVertexC(i)].pos - p; for (int i = 0; i < size; i++) { float cs = Vec2f::dot(point[i], point[i + 1]) / (point[i].length() * point[i + 1].length()); if (cs > 1) cs = 1; if (cs < -1) cs = -1; float angle = acos(cs); if (Vec2f::cross(point[i], point[i + 1]) < 0) angle = -angle; rotate_angle += angle; } // if point is outside, rotate angle is equals to 0. If point is inside rotate angle is equals to 2*PI of -2*PI return abs(rotate_angle) < PI; }
bool MoleculeLayoutGraph::Cycle::contains (const Cycle &another) const { if (vertexCount() < another.vertexCount()) return false; QS_DEF(Array<int>, vertex_found); vertex_found.clear_resize(_max_idx + 1); vertex_found.zerofill(); for (int i = 0; i < vertexCount(); i++) vertex_found[_vertices[i]] = 1; for (int i = 0; i < another.vertexCount(); i++) if (another._vertices[i] >= vertex_found.size() || vertex_found[another._vertices[i]] == 0) return false; return true; }
void StaticPersistence<D, CT, OT, E, Cmp>:: initialize(const Filtration& filtration) { order_.assign(filtration.size(), OrderElement()); rLog(rlPersistence, "Initializing persistence"); OffsetMap<typename Filtration::Index, iterator> om(filtration.begin(), begin()); for (typename Filtration::Index cur = filtration.begin(); cur != filtration.end(); ++cur) { Cycle z; BOOST_FOREACH(const typename Filtration::Simplex& s, std::make_pair(cur->boundary_begin(), cur->boundary_end())) z.push_back(index(om[filtration.find(s)])); z.sort(ocmp_); iterator ocur = om[cur]; swap_cycle(ocur, z); set_pair(ocur, ocur); } }
std::vector< value_type > cycle_notation() const { typedef value_type Cycle; const value_type &p = oneLineNotation; const size_t n = p.size(); std::vector<bool> v(n, false); std::vector<Cycle> ret; for (size_t i = 0; i < n; ++i) if (v[i] == false) { Cycle cycle; size_t j = i; do { cycle.push_back(j); v[j] = true; j = p[j]; } while (j != i); ret.push_back(cycle); } return ret; }
void Engine::run() const { Cycle cycle; cycle.add_page("First page"); mw::Database db = *cycle.get_last_database(); db.add_entry("Travel", mw::Money(5000)); db.add_record("Travel", mw::Money(250), mw::Record::BS_INCOME, "Unplanned income"); db.add_record("Travel", mw::Money(500), mw::Record::BS_EXPENSE, "Food in the hotel"); db.add_entry("Incorporation", mw::Money(10000)); db.add_record("Incorporation", mw::Money(1250), mw::Record::BS_EXPENSE, "New smartphone"); db.add_entry("Transport", mw::Money(1000)); db.add_record("Transport", mw::Money(700), mw::Record::BS_EXPENSE, "Metro ticket"); db.add_entry("Food", mw::Money(2500)); db.add_record("Food", mw::Money(600), mw::Record::BS_EXPENSE, "Ice cream coffee"); db.add_record("Food", mw::Money(1200), mw::Record::BS_EXPENSE, "Corston's hotel food"); db.list(); }
void Thermocycler::ProcessCommand(SCommand& command) { if (command.command == SCommand::EStart) { //find display cycle Cycle* pProgram = command.pProgram; Cycle* pDisplayCycle = pProgram; int largestCycleCount = 0; for (int i = 0; i < pProgram->GetNumComponents(); i++) { ProgramComponent* pComp = pProgram->GetComponent(i); if (pComp->GetType() == ProgramComponent::ECycle) { Cycle* pCycle = (Cycle*)pComp; if (pCycle->GetNumCycles() > largestCycleCount) { largestCycleCount = pCycle->GetNumCycles(); pDisplayCycle = pCycle; } } } GetThermocycler().SetProgram(pProgram, pDisplayCycle, command.name, command.lidTemp); GetThermocycler().Start(); } else if (command.command == SCommand::EStop) { GetThermocycler().Stop(); //redundant as we already stopped during parsing } else if (command.command == SCommand::EConfig) { //update displayed ipDisplay->SetContrast(command.contrast); //update stored contrast ProgramStore::StoreContrast(command.contrast); } }
// Split border in two parts by two vertices void MoleculeLayoutGraph::_splitBorder (int v1, int v2, Array<int> &part1v, Array<int> &part1e, Array<int> &part2v, Array<int> &part2e) const { Cycle border; _getBorder(border); int idx1 = border.findVertex(v1); int idx2 = border.findVertex(v2); int i; if (idx1 == -1 || idx2 == -1) throw Error("border division by non-boundary vertex"); if (idx1 > idx2) __swap(idx1, idx2, i); part1v.clear(); part1e.clear(); part2v.clear(); part2e.clear(); for (i = idx1; i < idx2 + 1; i++) { part1v.push(border.getVertex(i)); part1e.push(border.getEdge(i)); } part1e.pop(); // edge count is less for (i = idx2; i < border.vertexCount(); i++) { part2v.push(border.getVertex(i)); part2e.push(border.getEdge(i)); } for (i = 0; i < idx1 + 1; i++) { part2v.push(border.getVertex(i)); part2e.push(border.getEdge(i)); } part2e.pop(); // edge count is less }
// Check if point is outside cycle // By calculating number of intersections of ray bool MoleculeLayoutGraphSimple::_isPointOutsideCycle(const Cycle &cycle, const Vec2f &p) const { Random rand(SOME_MAGIC_INT_FOR_RANDOM_3); int i, count = 0; float a, b; Vec2f v1, v2; const float eps = 0.01f; bool success = false; while (!success) { success = true; a = (float)rand.nextDouble(); b = (float)rand.nextDouble(); a = 2.f * (a - 0.5f); b = 2.f * (b - 0.5f); if (fabs(a) < eps || fabs(b) < eps) { success = false; continue; } for (i = 0; i < cycle.vertexCount(); i++) { const Vec2f &pos = getPos(cycle.getVertex(i)); if (fabs((pos.x - p.x) / a - (pos.y - p.y) / b) < EPSILON) { count++; if (count > 50) return false; success = false; break; } } } // Calculate count = 0; for (i = 0; i < cycle.vertexCount(); i++) if (_isRayIntersect(a, b, p, getPos(cycle.getVertex(i)), getPos(cycle.getVertex((i + 1) % cycle.vertexCount())))) count++; if (count & 1) return false; return true; }
Cycle twoOptAllowNeg(const Matrix &mat, Cycle cycle, int default_neg, int diff_d, int min) { size_t cycle_size = cycle.size(); int improve = 0; bool distance_treshold = false; while (improve < 10) { int neg_imp = default_neg; int best_distance = countCycle(mat, cycle); for (int i = 1; i < cycle_size - 1; i++) { for (int j = i + 1; j < cycle_size - 1; j++) { Cycle new_cycle = swapCities(cycle, i, j); int new_distance = countCycle(mat, new_cycle); int diff_distance = new_distance - best_distance; if (distance_treshold) { if ((new_distance < min) && (new_distance < best_distance)) { improve = 0; neg_imp--; cycle = new_cycle; best_distance = new_distance; } } else { if (new_distance < best_distance || (diff_distance < diff_d && neg_imp > 0)) { improve = 0; neg_imp--; cycle = new_cycle; best_distance = new_distance; if (new_distance < min) distance_treshold = true; } } } } improve++; } return cycle; }
Cycle swapCities(const Cycle &cycle, const int &a, const int &b) { Cycle n_cycle; size_t cycle_size = cycle.size(); Cycle::const_iterator it; vector<int> vcycle; for (const auto &c : cycle) vcycle.push_back(c); for ( int c = 0; c <= a - 1; ++c ) n_cycle.push_back(vcycle[c]); for (int c = a, dec = 0; c <= b; ++c, dec++) n_cycle.push_back(vcycle[b - dec]); for ( int c = b + 1; c < cycle_size; ++c ) n_cycle.push_back(vcycle[c]); return n_cycle; }
int main() { font.loadFromFile("font.ttf"); sf::Clock fclock; // frame fclock sf::Clock clock; // accumulative clock sf::Text fps {"", font, 12}; fps.setPosition(5.f, 5.f); std::ostringstream fps_s; sf::Text winner {"", font, 24}; std::ostringstream win_s; bool paused {true}; sf::RenderWindow window { sf::VideoMode(800, 600, 32), "Light Cycles" }; window.setVerticalSyncEnabled(false); window.setFramerateLimit(120); sf::View view (window.getView()); sf::Event event; sf::RectangleShape bounds {v2f(790.f, 590.f)}; bounds.setPosition(5.f, 5.f); bounds.setFillColor(sf::Color(30, 30, 30)); std::list<Cycle*> player; // TODO dynamically assign these? std::array<v2f, 4> starts { v2f(105.f, 300.f), v2f(695.f, 300.f), v2f(400.f, 5.f), v2f(400.f, 595.f) }; std::array<float, 4> startds { 0.f, 180.f, 90.f, 270.f }; std::array<sf::Color, 10> colors { sf::Color(255, 0, 0), sf::Color(0, 255, 0), sf::Color(0, 0, 255), sf::Color(255, 0, 255), sf::Color(127, 0, 255), sf::Color(255, 255, 0), sf::Color(230, 127, 0), sf::Color(0, 255, 255), sf::Color(0, 100, 0), sf::Color(150, 150, 150) }; float timescale = 1.f; set_up(window, view, winner, player); while (window.isOpen()) { // process input while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); else if (event.type == sf::Event::Resized) set_up(window, view, winner, player); // quit if (event.type == sf::Event::KeyReleased && event.key.code == sf::Keyboard::Escape) window.close(); if (paused) { // add players if (input_is(event, sf::Keyboard::Return, 7)) { int joystick = get_joystick(event); // check if the controller is taken bool taken = false; for (auto p : player) { if (p->joystick == joystick) { p->set_ready(true); taken = true; break; } } // if we can accomodate more players if (!taken && player.size() < 4) { // find color and starting position that aren't being used sf::Color c; for (auto& col : colors) { bool taken = false; for (auto p : player) { if (p->color == col) { taken = true; break; } } if (!taken) { c = col; break; } } v2f s; int i = 0; // TODO HACKY AS BALLS for (auto strt : starts) { bool taken = false; for (auto p : player) { if (p->start == strt) { taken = true; break; } } if (!taken) { s = strt; break; } i++; } player.push_back(new Cycle(s, startds[i], c, font, joystick)); player.back()->set_text_pos(view.getCenter()); } } // remove/unready players else if (input_is(event, sf::Keyboard::BackSpace, 6)) { int joystick = get_joystick(event); for (auto p : player) { if (p->joystick == joystick) { if (p->ready) p->set_ready(false); else player.remove(p); break; } } } // change colors else if (input_is(event, sf::Keyboard::C, 5)) { int joystick = get_joystick(event); for (auto p : player) { if (p->joystick == joystick) { unsigned int color_index; // find current color for (color_index = 0; color_index < colors.size(); color_index++) if (colors[color_index] == p->color) break; unsigned int current_color = color_index; color_index++; // find next available color for (; color_index % colors.size() != current_color; color_index++) { bool taken = false; for (auto q : player) { if (q->color == colors[color_index % colors.size()]) { taken = true; break; } } if (!taken) { p->set_color(colors[color_index % colors.size()]); break; } } break; } } } } else { for (auto p : player) p->bind(event); } } float time = fclock.getElapsedTime().asSeconds(); fclock.restart(); // slow motion start float stime = clock.getElapsedTime().asSeconds(); timescale = std::min(3.f, stime) / 3.f; if (paused) { bool all_ready {true}; for (auto p : player) { if (!(p->ready)) { all_ready = false; break; } } if (all_ready && player.size() > 1) { paused = false; for (auto p : player) p->reset(); clock.restart(); } } else { for (auto p : player) p->move(time * timescale); // TODO better way? for (auto p1 : player) { for (auto p2 : player) { if (p1 != p2) { p1->check_collision(*p2); p2->check_collision(*p1); } } } for (auto p : player) p->in(bounds); // TODO visual bug when players collide head-on for (auto p : player) p->backup(); win_s.str(""); bool match_over = true; Cycle* survivor = nullptr; for(auto p : player) if (!(p->crashed)) { if (survivor == nullptr) survivor = p; else { match_over = false; break; } } if (match_over) { if (survivor == nullptr) { win_s << "DRAW"; winner.setColor(sf::Color(255, 255, 255)); } else { win_s << "WINNER!"; winner.setColor(survivor->color); survivor->scored(); } paused = true; for (auto p : player) p->set_ready(false); } winner.setString(win_s.str()); sf::FloatRect size = winner.getGlobalBounds(); winner.setOrigin(size.width / 2, size.height / 2); } fps_s.str(""); fps_s << "FPS " << int (1.f / time); fps.setString(fps_s.str()); window.clear(sf::Color(255, 255, 255)); window.draw(bounds); for (auto p : player) p->draw(window); for (auto p : player) p->draw_text(window, paused); window.draw(fps); window.draw(winner); window.display(); } return EXIT_SUCCESS; }
int _tmain(int argc, _TCHAR* argv[]){ // resize console window HWND console = GetConsoleWindow(); RECT r; GetWindowRect(console, &r); //stores the console's current dimensions MoveWindow(console, r.left, r.top, 800, 500, TRUE); // 800 width, 500 height ////////////////////// // Main Game Loop // ////////////////////// const int GAME_SPEED = 100; const int LEVEL_UP_SCORE = 1000; const int SCORE_MULTIPLIER = 10; int clockMultiplier = 0, playerPoints = 0, points = 0; bool replay = false; int keyPressed; bool gameOver = false; do { //setup game board Board b; Cycle player; Cycle comp(true); b.clear(); b.drawBoard(); player.showCycle(b); comp.showCycle(b); b.welcomeScreen(); //wait for player to begin bool ready = false; while (!ready){ if (_kbhit()){ ready = true; } } /////////////////////// // Inner Game Loop // /////////////////////// b.clear(); b.drawBoard(); player.showCycle(b); comp.showCycle(b); while (!gameOver) { Sleep(GAME_SPEED - clockMultiplier); //test for player input if (_kbhit()){ keyPressed = _getch(); // key is only assigned a valid value. try { player.changeDirection(keyPressed); } catch (const char* msg){ cerr << msg << endl; } } //player move char p = player.markTrail(); int row = player.getRow(); int col = player.getColumn(); b.setBoard(row, col, p); player.moveCycle(); gameOver = player.collisionTest(b); player.showCycle(b); //computer move if (gameOver == false){ comp.testForMove(b); char c = comp.markTrail(); row = comp.getRow(); col = comp.getColumn(); b.setBoard(row, col, c); comp.moveCycle(); gameOver = comp.collisionTest(b); comp.showCycle(b); } } //end inner game loop if (player.testAlive() == false) { b.gotoXY(18, 34); cout << "Game Over!"; clockMultiplier -= 10; } else { b.gotoXY(18, 36); cout << "You Win!"; points = LEVEL_UP_SCORE + (clockMultiplier * SCORE_MULTIPLIER); playerPoints += points; clockMultiplier += 10; } b.gotoXY(22, 27); cout << "Your score this round: " << points; b.gotoXY(24, 30); cout << "Your total score: " << playerPoints; b.gotoXY(28, 20); cout << "Would you like to play again? (y,n) "; char n; cin >> n; if (n == 'y' || n == 'Y'){ replay = true; gameOver = false; } } while (replay == true); //end main game loop return 0; }