blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 117 | path stringlengths 3 268 | src_encoding stringclasses 34
values | length_bytes int64 6 4.23M | score float64 2.52 5.19 | int_score int64 3 5 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | text stringlengths 13 4.23M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
46608a352379dda9e04a17994526158072788e22 | C++ | apache/trafficserver | /plugins/esi/lib/Expression.h | UTF-8 | 3,255 | 2.78125 | 3 | [
"TCL",
"LicenseRef-scancode-proprietary-license",
"BSD-3-Clause",
"LicenseRef-scancode-openssl",
"LicenseRef-scancode-ssleay-windows",
"ISC",
"OpenSSL",
"MIT",
"HPND",
"Apache-2.0",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain",
"Licen... | permissive | /** @file
A brief file description
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#pragma once
#include <string>
#include <cstdlib>
#include "ComponentBase.h"
#include "Variables.h"
namespace EsiLib
{
class Expression : private ComponentBase
{
public:
Expression(const char *debug_tag, ComponentBase::Debug debug_func, ComponentBase::Error error_func, Variables &variables);
/** substitutes variables (if any) in given expression */
const std::string &expand(const char *expr, int expr_len = -1);
/** convenient alternative for method above */
const std::string &
expand(const std::string &expr)
{
return expand(expr.data(), expr.size());
}
/** evaluates boolean value of given expression */
bool evaluate(const char *expr, int expr_len = -1);
/** convenient alternative for method above */
bool
evaluate(const std::string &expr)
{
return evaluate(expr.data(), expr.size());
}
~Expression() override{};
private:
static const std::string EMPTY_STRING;
static const std::string TRUE_STRING;
Variables &_variables;
std::string _value;
// these are arranged in parse priority format indices correspond to op strings array
enum Operator {
OP_EQ,
OP_NEQ,
OP_LTEQ,
OP_GTEQ,
OP_LT,
OP_GT,
OP_NOT,
OP_OR,
OP_AND,
N_OPERATORS,
};
struct OperatorString {
const char *str;
int str_len;
OperatorString(const char *s = nullptr, int s_len = -1) : str(s), str_len(s_len){};
};
static const OperatorString OPERATOR_STRINGS[N_OPERATORS];
inline void _trimWhiteSpace(const char *&expr, int &expr_len) const;
inline bool _stripQuotes(const char *&expr, int &expr_len) const;
inline int _findOperator(const char *expr, int expr_len, Operator &op) const;
inline bool
_isBinaryOperator(Operator &op) const
{
return ((op == OP_EQ) || (op == OP_NEQ) || (op == OP_LT) || (op == OP_GT) || (op == OP_LTEQ) || (op == OP_GTEQ) ||
(op == OP_OR) || (op == OP_AND));
}
inline bool
_convert(const std::string &str, double &value)
{
size_t str_size = str.size();
if (str_size) {
char *endp;
const char *str_ptr = str.c_str();
// Solaris is messed up, in that strtod() does not honor C99/SUSv3 mode.
value = strtold(str_ptr, &endp);
return (static_cast<unsigned int>(endp - str_ptr) == str_size);
}
return false;
}
inline bool _evalSimpleExpr(const char *expr, int expr_len);
};
}; // namespace EsiLib
| true |
794db9a95ebf4f7b693043e541e2b7fa99c212f2 | C++ | Asa-to/c-prac | /atcoder/old/abc140c.cpp | UTF-8 | 348 | 2.546875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main(void){
int n;
cin >> n;
vector<int> a(n-1);
int sum = 0;
for(int i = 0; i < n-1; i++){
cin >> a[i];
if( i == 0){
sum += a[i];
}else{
sum += min(a[i], a[i-1]);
}
}
cout << sum + a[n-2] << endl;
return 0;
} | true |
59c32574b3015a20492b4fc1023c0b4bd88cd844 | C++ | HaozheGuAsh/Undergraduate | /Visual Studio/Projects/ECS165BPROJECT/ECS165BPROJECT/rewriter.cpp | UTF-8 | 8,645 | 2.5625 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include "stdlib.h"
#include <stdio.h>
#include "string.h"
#include <vector>
#include "errno.h"
#include "unistd.h"
#include "fcntl.h"
#include <inttypes.h>
#include "HW6-expr.h"
//#include "HW4-expression.h"
using namespace std;
#define OP_VAR 257
#define MAXRULES 100
exprnode *lhs[MAXRULES], *rhs[MAXRULES];;
/***********************************************************************************************/
/* Rule table - preloading prevents abuse, loading from a file allows experimentation **********/
/***********************************************************************************************/
char *rules[MAXRULES] = {
"(PROJECTION (ITERATE $1 $2) $3) => (ITERATE $1 (PROJECTROW $2 $3))",
"(PROJECTION (TABLENAME $1 ) $2) => (ITERATE (TABLENAME $1) (PROJECTROW (GETNEXT (TABLENAME $1)) $2))",
"(SELECTION (ITERATE $1 $2) $3) => (ITERATE $1 (SELECTROW $2 $3))",
"(SELECTION (TABLENAME $1) $2) => (ITERATE (TABLENAME $1) (SELECTROW (GETNEXT (TABLENAME $1)) $2))",
};
int rulecnt = 4;
void
init_rules();
/*global*/
extern struct myopmap opmap[256];
/*char *
op_name(int op_num)
{
if (op_num < 1 || op_num > OP_EOF) {
return "INVALID";
}
return opmap[op_num].name;
}
int
opnum(char *str)
{
int i;
for (i = 1; i<256; i++) {
if (!opmap[i].name) continue;
if (!strcmp(opmap[i].name, str)) return i;
}
return 0;
}
*/
/***********************************************************************************************/
/* Function to convert rules into an expression tree *****************************/
/***********************************************************************************************/
exprnode *
getexpr(char *str)
{
int off = 0, op;
int n, rv;
char opname[MAXDATA + 1];
exprnode *v1, *v2;
int varnum;
n = 0; rv = sscanf(str, " ( %[a-zA-Z0-9] %n", opname, &n);
if (rv != 1) { printf("Badly formed rule segment %s\n", str); exit(1); }
op = opnum(opname);
strcpy(str, str + n);
n = 0; rv = sscanf(str, " ) %n", &n);
if (n) {
strcpy(str, str + n);
return (exprnode *)makeexpr(op, 0, 0, 0);
}
/* One argument *************************************************************/
n = 0; rv = sscanf(str, " $%d %n", &varnum, &n);
if (rv == 1) {
strcpy(str, str + n);
v1 = (exprnode *)makeexpr(OP_VAR, 1, (expr)varnum, (expr)0);
}
else {
n = 0; rv = sscanf(str, " ( %n", &n);
if (n) {
v1 = getexpr(str);
}
else { printf("Badly formed rule segment %s\n", str); exit(1); }
}
n = 0; rv = sscanf(str, " ) %n", &n);
if (n) {
strcpy(str, str + n);
return (exprnode *)makeexpr(op, 1, (expr)v1, 0);
}
/* Two arguments ************************************************************/
n = 0; rv = sscanf(str, " $%d %n", &varnum, &n);
if (rv == 1) {
strcpy(str, str + n);
v2 = (exprnode *)makeexpr(OP_VAR, 1, (expr)varnum, (expr)0);
}
else {
n = 0; rv = sscanf(str, " ( %n", &n);
if (n) {
v2 = getexpr(str);
}
else { printf("Badly formed rule segment %s\n", str); exit(1); }
}
n = 0; rv = sscanf(str, " ) %n", &n);
if (n) {
strcpy(str, str + n);
return (exprnode *)makeexpr(op, 2, (expr)v1, (expr)v2);
}
/* More than two not supported *********************************************/
printf("Too many arguments in rule %s\n", str);
exit(1);
}
/***********************************************************************************************/
/***********************************************************************************************/
void
init_rules()
{
//FILE *fid;
int i = 0;
int c;
char *rp;
char buf[MAXDATA + 1];
/*fid = fopen("data/rules", "r");
if (fid) {
while ((c = fgetc(fid))>0) {
if (c == '\n') {
buf[i] = 0;
rules[rulecnt] = (char*)malloc(strlen(buf) + 1);
strcpy(rules[rulecnt], buf);
i = 0; rulecnt++;
continue;
}
buf[i++] = toupper(c);
}
fclose(fid);
}*/
for (i = 0; i<MAXRULES; i++) {
if (!rules[i]) return;
//printf("Loading rule: %s\n", rules[i]);
rp = strstr(rules[i], "=>");
strncpy(buf, rules[i], rp - rules[i]);
lhs[i] = getexpr(buf);
//printf("got LHS \n");
//print_e(lhs[i], 0);
strcpy(buf, rp + 2);
rhs[i] = getexpr(buf);
//printf("got RHS \n");
//print_e(rhs[i], 0);
}
}
/***********************************************************************************************/
/* Rule Matcher - matches a rule to a tree, remembering the values of the variables ************/
/* NOTE: This matcher supports "unification" where a variable may appear more than ************/
/* once on the left hand side (LHS) of a rule, if it matches to the same value ***********/
/* everywhere it occurs. ************/
/* Does not support "any" function matches. ************/
/***********************************************************************************************/
exprnode *var[100];
int
matchrule(exprnode *e, exprnode *r)
{
register int i;
//cout << "in match rule" << endl;
if (e == r) return 1;
if (!e || !r) return 0;
//printf("Matching %s vs %s\n", opmap[e->func].name, opmap[r->func].name);
if (e->func != r->func) {
//printf("failed func match\n");
return 0;
}
if (e->count != r->count) {
//printf("failed count match%d %d\n", e->count, r->count);
return 0;
}
for (i = 0; i<e->count; i++) {
if (r->values[i].ep->func == OP_VAR) {
if (var[r->values[i].ep->values[0].num] == 0) {
var[r->values[i].ep->values[0].num] = e->values[i].ep;
//printf("success - assign var\n");
continue;
}
else if (var[r->values[i].ep->values[0].num] == e->values[i].ep) {
/* Support Unification - variable may appear more than once on LHS */
//printf("success - matching var\n");
continue;
}
//printf("failed conflict\n");
return 0; /* Conflicting assignment */
}
/* Some nodes dont really have subnodes */
switch (e->func) {
case OP_NULL: printf("failed OP_NULL\n"); return 0;
case OP_NUMBER: if (e->values[0].num == r->values[0].num) return 1; else return 0;
case OP_STRING: if (!strcmp(e->values[0].data, r->values[0].data)) return 1; else return 0;
case OP_COLNAME: if (!strcmp(e->values[0].name, r->values[0].name)) return 1; else return 0;
case OP_TABLENAME: if (!strcmp(e->values[0].name, r->values[0].name)) return 1; else return 0;
case OP_FNAME: if (!strcmp(e->values[0].name, r->values[0].name)) return 1; else return 0;
}
//printf("checking subnodes\n");
if (!matchrule(e->values[i].ep, r->values[i].ep)) {
//printf("subnode fail\n");
return 0;
}
}
//printf("success\n");
return 1;
}
/***********************************************************************************************/
/* The Rewriter - creates a new expression with all the variables replaced *********************/
/***********************************************************************************************/
exprnode *
rhs_with_vars(exprnode *r)
{
exprnode *v1, *v2;
if (!r) return 0;
if (r->func == OP_VAR) {
return var[r->values[0].num];
}
v1 = rhs_with_vars(r->values[0].ep);
v2 = rhs_with_vars(r->values[1].ep);
return (exprnode *)makeexpr(r->func, r->count, (expr)v1, (expr)v2);
}
/***********************************************************************************************/
/* Compilation step - try to make sure everything is implementable *****************************/
/***********************************************************************************************/
exprnode *
rcompile(exprnode *x)
{
int i, j;
exprnode *a1, *a2;
if (!x) return 0;
//printf("Compile on %s\n", opmap[x->func].name);
/* Some nodes dont really have subnodes */
switch (x->func) {
case OP_NULL:
case OP_NUMBER:
case OP_STRING:
case OP_COLNAME:
case OP_TABLENAME:
case OP_FNAME:
return x;
}
/* Make sure the arguments are implementable */
/* Use same tree if no changes */
a1 = rcompile(x->values[0].ep); a2 = rcompile(x->values[1].ep);
if ((a1 != (x->values[0].ep)) || (a2 != (x->values[1].ep))) {
x = (exprnode *)makeexpr(x->func, x->count, (expr)a1, (expr)a2);
}
/* Try rewrite if not implementable */
if (!(opmap[x->func].flag & IMPLEMENTED)) {
for (i = 0; lhs[i]; i++) {
for (j = 0; j<100; j++) var[j] = 0;
if (matchrule(x, lhs[i])) {
printf("matched rule %d\n", i);
x = rhs_with_vars(rhs[i]);
//print_e(x,0);
x = rcompile(x);
break;
}
}
}
return x;
}
exprnode *
subcompile(exprnode *x)
{
init_rules();
//printf("Before compilation\n");
//PrintTree(x, 0);
x = rcompile(x);
//printf("After compilation\n");
PrintTree(x, 0);
return x;
}
exprnode *
optimize(exprnode *x)
{
return x;
}
| true |
79079cf31a9aa50ed1179fbe1a0d397b3009c096 | C++ | Mthomas3/Bomberman | /include/commons/IS/Map/Tile.hpp | UTF-8 | 1,388 | 2.65625 | 3 | [] | no_license | #pragma once
#include <cstdint>
#include <functional>
#include <iostream>
#include <utility>
#include <IS/Map/Map.hpp>
namespace IS
{
struct Map::Tile
{
Tile() : _type(None), _upos(0, 0), _init(nullptr) { throw std::exception(); }
Tile(TileType type, f_init const &init, insT *construtor)
: _type(type), _upos(0, 0), _construtor(construtor), _init(init)
{
_instances = new std::vector<objT*>();
_index = _instances->end();
}
TileType getType() const { return (_type); }
objT *getInstance() { return (*_index); }
void _new(unitPos const& upos, realPos const& rpos)
{
_upos = upos;
_instances->push_back(_init(rpos, _construtor));
_index = _instances->end();
}
void _delete()
{
delete(*_index);
_instances->erase(_index);
_index = _instances->begin();
}
objT *_release()
{
objT *ptr;
ptr = *_index;
_instances->erase(_index);
_index = _instances->begin();
return (ptr);
}
void _clear()
{
std::for_each(_instances->begin(), _instances->end(), [](objT *data) { delete (data); });
_instances->clear();
}
std::shared_ptr<Tile> clone() { return (std::make_shared<Tile>(*this)); }
private:
TileType _type;
unitPos _upos;
std::vector<objT*> *_instances;
std::vector<objT*>::iterator _index;
insT *_construtor;
f_init _init;
};
} | true |
4701ed9f564d1c1b3fec15ffe5714ebfe5bcfd46 | C++ | qingswu/Transim | /Transims60/SysLib/Utility/Smooth_Data.cpp | UTF-8 | 9,032 | 2.921875 | 3 | [] | no_license | //*********************************************************
// Smooth_Data.cpp - data smoothing class
//*********************************************************
#include "Smooth_Data.hpp"
//---------------------------------------------------------
// Smooth_Data constructor
//---------------------------------------------------------
Smooth_Data::Smooth_Data (int num_in, int iterations, bool loop_flag, int group_size,
double forward, double backward, int num_sub, bool dup_flag)
{
Setup (num_in, iterations, loop_flag, group_size, forward, backward, num_sub, dup_flag);
}
//---------------------------------------------------------
// Setup
//---------------------------------------------------------
bool Smooth_Data::Setup (int in, int iter, bool flag, int group, double front, double back, int sub, bool dup)
{
niter = iter;
loop_flag = flag;
size = group;
forward = front;
backward = back;
num_sub = sub;
dup_flag = dup;
interpolate = false;
return (Num_Input (in));
}
//---------------------------------------------------------
// Interpolate
//---------------------------------------------------------
bool Smooth_Data::Interpolate (int in, double inc, int iter, int group, double front, double back, bool dup)
{
niter = iter;
loop_flag = false;
size = group;
forward = front;
backward = back;
num_sub = 1;
dup_flag = dup;
interpolate = true;
increment = inc;
return (Num_Input (in));
}
//---------------------------------------------------------
// Clear
//---------------------------------------------------------
void Smooth_Data::Clear (void)
{
num_in = num_out = 0;
input.clear ();
output.clear ();
current.clear ();
}
//---------------------------------------------------------
// Num_Input
//---------------------------------------------------------
bool Smooth_Data::Num_Input (int num)
{
int max_iter, max_size;
double factor;
bool stat = true;
Clear ();
//---- number of input values ----
if (num < 3) {
if (num != 0) {
exe->Warning (String ("Number of Input Values %d is Out of Range (>= 3)") % num);
stat = false;
}
num = 24;
}
input.assign (num, 0.0);
num_in = num;
//---- number of output values ----
if (num_sub < 1) {
exe->Warning (String ("Number of Subdivisions %d is Out of Range (>= 1)") % num_sub);
num_sub = 1;
stat = false;
}
if (interpolate) {
if (increment < 0.1) {
exe->Warning (String ("Smoothing Increment %.2lf is Out of Range (>= 0.1)") % increment);
increment = 1.0;
}
num_out = (int) ((num_in - 1) * increment + 0.9) + 1;
} else {
num_out = num_in * num_sub;
}
max_iter = ((num_in + 2) / 3) * num_out / num_in;
max_size = ((num_in + 18) / 20) * 2 + 1;
output.assign (num_out, 0.0);
current.assign (num_out, 0.0);
//---- number of iterations ----
if (niter < 1 || niter > max_iter) {
exe->Warning (String ("Number of Iterations %d is Out of Range (1-%d)") % niter % max_iter);
if (niter < 1) {
niter = 1;
} else {
niter = max_iter;
}
stat = false;
}
//---- group size ----
if (size < 3 || size > max_size) {
exe->Warning (String ("Smooth Group Size %d is Out of Range (3..%d)") % size % max_size);
if (size < 3) {
size = 3;
} else if (size > max_size) {
size = max_size;
}
stat = false;
}
if ((size % 2) != 1) {
exe->Warning (String ("Smooth Group Size %d must be an Odd Number") % size);
size += 1;
stat = false;
}
//---- percent forward ----
factor = 100.0 - (50.0 / size);
if (forward < 0.0 || forward > factor) {
exe->Warning (String ("Forward Percentage %.1lf is Out of Range (0..%.1lf)") % forward % factor);
if (forward < 0.0) {
forward = 20.0;
} else if (forward > factor) {
forward = factor;
}
stat = false;
}
//---- read the percent distributed backward ----
if (backward < 0.0 || backward > factor) {
exe->Warning (String ("Backward Percentage %.1lf is Out of Range (0..%.1lf)") % backward % factor);
if (backward < 0.0) {
backward = 20.0;
} else if (backward > factor) {
backward = factor;
}
stat = false;
}
weight = forward + backward;
factor = 100.0 - (100.0 / size);
if (weight < 5.0 || weight > factor) {
exe->Warning (String ("Combined Percentage %.1lf is Out of Range (5..%.0lf)") % weight % factor);
if (weight < 5.0) {
forward += 2.5;
backward += 2.5;
} else if (weight > factor) {
factor /= weight;
forward *= factor;
backward *= factor;
}
stat = false;
}
//---- adjust the factors ----
weight = 0.0;
max_size = size / 2;
for (max_iter=1; max_iter <= max_size; max_iter++) {
weight += max_iter;
}
weight = 1.0 / weight;
return (stat);
}
//---------------------------------------------------------
// Smooth
//---------------------------------------------------------
int Smooth_Data::Smooth (int num_rec)
{
int i, j, n, i1, i2, num, nout;
double share, forward_total, backward_total, delta, cum;
nout = num_out;
if (num_rec <= 0 || num_rec > num_in) {
num_rec = num_in;
} else if (!interpolate) {
if (num_sub > 1) {
nout = num_rec * num_sub;
} else {
nout = num_rec;
}
}
//---- initialize the output data ----
if (interpolate) {
delta = 1.0 / increment;
backward_total = 0;
forward_total = input [0];
output.assign (nout, 0.0);
for (i=n=0, cum=0; n < nout; n++, cum += delta) {
if (cum >= i) {
backward_total = forward_total;
if (++i > num_rec) break;
if (i == num_rec) {
forward_total = 0;
} else {
forward_total = input [i];
}
}
output [n] = (cum - i + 1) * (forward_total - backward_total) + backward_total;
}
} else if (num_sub > 1) {
for (i=n=0; i < num_rec; i++) {
if (dup_flag) {
share = input [i];
} else {
share = input [i] / num_sub;
}
for (j=0; j < num_sub; j++) {
output [n++] = share;
}
}
} else {
output.assign (input.begin (), input.end ());
}
num = size / 2;
//---- process each iteration ----
for (n=0; n < niter; n++) {
current.assign (output.begin (), output.end ());
output.assign (nout, 0.0);
for (i=0; i < nout; i++) {
share = current [i];
forward_total = share * forward / 100.0;
backward_total = share * backward / 100.0;
output [i] += share - forward_total - backward_total;
i1 = i2 = i;
forward_total *= weight;
backward_total *= weight;
for (j=num; j > 0; j--) {
i1--;
i2++;
if (i1 < 0) {
i1 = (loop_flag) ? nout - 1 : 0;
}
if (i2 >= nout) {
i2 = (loop_flag) ? 0 : nout - 1;
}
output [i1] += backward_total * j;
output [i2] += forward_total * j;
}
}
}
if (interpolate && dup_flag) {
forward_total = backward_total = 0.0;
for (i=0; i < num_rec; i++) {
backward_total += input [i];
}
for (j=0; j < nout; j++) {
forward_total += output [j];
}
if (forward_total > 0.0) {
share = backward_total / forward_total;
for (j=0; j < nout; j++) {
output [j] *= share;
}
}
}
return (nout);
}
//---------------------------------------------------------
// Add_Keys
//---------------------------------------------------------
void Smooth_Data::Add_Keys (void)
{
Control_Key smooth_data_keys [] = { //--- code, key, level, status, type, default, range, help ----
{ SMOOTH_GROUP_SIZE, "SMOOTH_GROUP_SIZE", LEVEL0, OPT_KEY, INT_KEY, "3", "0, >= 3", NO_HELP },
{ PERCENT_MOVED_FORWARD, "PERCENT_MOVED_FORWARD", LEVEL0, OPT_KEY, FLOAT_KEY, "20", "> 0.0", NO_HELP },
{ PERCENT_MOVED_BACKWARD, "PERCENT_MOVED_BACKWARD", LEVEL0, OPT_KEY, FLOAT_KEY, "20", "> 0.0", NO_HELP },
{ NUMBER_OF_ITERATIONS, "NUMBER_OF_ITERATIONS", LEVEL0, OPT_KEY, INT_KEY, "3", "> 0", NO_HELP },
{ CIRCULAR_GROUP_FLAG, "CIRCULAR_GROUP_FLAG", LEVEL0, OPT_KEY, BOOL_KEY, "TRUE", BOOL_RANGE, NO_HELP },
END_CONTROL
};
if (exe != 0) {
exe->Key_List (smooth_data_keys);
}
}
//---------------------------------------------------------
// Read_Control
//---------------------------------------------------------
bool Smooth_Data::Read_Control (void)
{
if (exe == 0) return (false);
if (!exe->Check_Control_Key (SMOOTH_GROUP_SIZE)) return (false);
//---- read the number smooth records ----
size = exe->Get_Control_Integer (SMOOTH_GROUP_SIZE);
if (size == 0) return (false);
//---- read the percent distributed forward ----
forward = exe->Get_Control_Double (PERCENT_MOVED_FORWARD);
//---- read the percent distributed backwarde ----
backward = exe->Get_Control_Double (PERCENT_MOVED_BACKWARD);
//---- number of iterations ----
niter = exe->Get_Control_Integer (NUMBER_OF_ITERATIONS);
//---- read the circular smoothing flag ----
loop_flag = exe->Get_Control_Flag (CIRCULAR_GROUP_FLAG);
return (true);
}
| true |
608d72ce6776d79f9c9113bec8d0b2ba097ee02e | C++ | arpitsangwan/Friendly-contests | /15 Fifteenth/72. Edit Distance.cpp | UTF-8 | 804 | 2.71875 | 3 | [] | no_license | //https://leetcode.com/problems/edit-distance/
class Solution {
public:
vector<vector<int>> dp;
string s,t;
int minop(int i,int j){
if(i==s.length()){return t.length()-j;}
if(j==t.length()){return s.length()-i;}
if(dp[i][j]!=-1){return dp[i][j];}
int ans=INT_MAX;
if(s[i]==t[j]){
ans=minop(i+1,j+1);
}
else{
ans=1+minop(i+1,j+1);
}
int a=1+minop(i,j+1);
int b=1+minop(i+1,j);
ans=min(ans,min(a,b));
dp[i][j]=ans;
return ans;
}
int minDistance(string word1, string word2) {
s=word1;t=word2;
dp.assign(s.length(),vector<int>(t.length(),-1));
return minop(0,0);
}
}; | true |
07365cbacdcccd65e89b617a4224317574475094 | C++ | alex-mitrevski/text_classifier | /include/PerceptronTrainer.hpp | UTF-8 | 1,050 | 2.6875 | 3 | [
"MIT"
] | permissive | #ifndef PERCEPTRON_TRAINER_HPP
#define PERCEPTRON_TRAINER_HPP
#include "FrequencyHashTable.hpp"
#include "WordHashTable.hpp"
#include <vector>
#include <string>
#include <fstream>
using std::vector;
using std::string;
using std::ofstream;
class PerceptronTrainer
{
public:
PerceptronTrainer(vector<string>, vector<string>);
~PerceptronTrainer();
void trainClassifier();
private:
void findDistinctCategories();
void countVocabulary();
void initializeTransformedDocuments();
void getMostFrequentWordsFromVocabulary();
void convertCategoriesToNumbers();
void transformDocuments();
void findDocumentWords(unsigned int);
void initializeWeights();
void normalizeCategories(int);
void saveTrainedDataToFile() const;
vector<string> documents;
vector<string> categories;
vector<string> distinctCategories;
int* categoriesInNumbers;
int** transformedDocuments;
double** weights;
FrequencyHashTable* words;
FrequencyHashTable* documentWords;
double vocabularySize;
int transformedDocumentSize;
string* mostFrequentWords;
};
#endif
| true |
3a6395aeec6c46ca2fae121b6327d4be15cb38e0 | C++ | karolbogdanski/uczelnia | /aisd/listy/1&2.cpp | UTF-8 | 674 | 3.65625 | 4 | [] | no_license | #include <iostream>
using namespace std;
struct node{
int val;
node *next;
};
void push(node *&H, int x){
node *p = new node;
p->val = x;
p->next = H;
H = p;
}
void show(node *H){
node *p = H;
cout << "Head->";
while(p != NULL){
cout << p->val << "->";
p=p->next;
}
cout << "NULL" << endl << endl;
}
void MakeItDouble(node *H){
node *p = H;
while(p != NULL){
for(int i = 1; i < p->val; i++){
push(p->next, p->val);
p = p->next;
}p = p->next;
}
}
int main(int argc, char **argv)
{
node *H = NULL;
push(H, 1);
push(H, 2);
push(H, 3);
push(H, 4);
push(H, 5);
show(H);
MakeItDouble(H);
show(H);
return 0;
}
| true |
71883117c70c1e3449c9ee4e293eb2a9abc7c322 | C++ | natural7/cpp-concurrent-test | /03/people/people.h | UTF-8 | 547 | 2.96875 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <stdint.h>
using namespace std;
class people
{
public:
people(string name, uint32_t age):age(age),name(name)
{
cout<<"hello people"<<endl;
};
people(void);
~ people(void);
people(const people &p);
void set_age(uint32_t age);
int get_age(void) const;
string get_name(void)const;
void print_people(void);
virtual void life_style(void);
virtual void spend_life(void) = 0;
private:
string name;
uint32_t age;
}; | true |
a1ec5ac45c81b8ff4cda399dfa814ee58632fd4b | C++ | BossOfCreeps/NeuroHackathon-NSK-2019 | /Arduino/arduino_v1.ino | UTF-8 | 378 | 2.703125 | 3 | [] | no_license | #include <Servo.h>
Servo myservo;
void setup() {
Serial.begin(9600);
myservo.attach(9);
myservo.write(90);
}
void loop() {
if(Serial.available() > 0) {
char data = Serial.read();
char str[2];
str[0] = data;
if (data=='0')
myservo.write(100);
if (data=='1')
myservo.write(120);
str[1] = '\0';
Serial.print(str);
}
}
| true |
d543a0f7dcfb261e1d1048cb952ed2c36048bc9f | C++ | wojcu/STLRaycast | /math/vec4.cpp | UTF-8 | 1,878 | 3.15625 | 3 | [] | no_license | #include "vec4.hpp"
#include <cmath>
vec4::vec4(double x, double y, double z, double w) {
m_components[0] = x;
m_components[1] = y;
m_components[2] = z;
m_components[3] = w;
}
vec4::vec4(const vec3 &v, double w) : vec4(v.at(0), v.at(1), v.at(2), w) {}
vec4::vec4(const vec2 &v, double z, double w) : vec4(v.at(0), v.at(1), z, w) {}
vec4::vec4() : vec4(0, 0, 0, 1) {}
double &vec4::at(size_t index) { return m_components[index]; }
double vec4::at(size_t index) const { return m_components[index]; }
vec4 vec4::operator*(double fac) const {
return vec4(at(0) * fac, at(1) * fac, at(2) * fac, at(3) * fac);
}
vec4 vec4::operator-(const vec4 &other) const {
return vec4(at(0) - other.at(0), at(1) - other.at(1), at(2) - other.at(2),
at(3) - other.at(3));
}
vec4 vec4::operator+(const vec4 &other) const {
return vec4(at(0) + other.at(0), at(1) + other.at(1), at(2) + other.at(2),
at(3) + other.at(3));
}
vec4 vec4::operator/(double fac) const {
return vec4(at(0) / fac, at(1) / fac, at(2) / fac, at(3) / fac);
}
vec4 vec4::operator*(const vec4 &other) const {
return vec4(at(0) * other.at(0), at(1) * other.at(1), at(2) * other.at(2),
at(3) * other.at(3));
}
vec4 vec4::operator-() const { return (*this) * (-1); }
double vec4::length_squared() const {
return m_components[0] * m_components[0] +
m_components[1] * m_components[1] +
m_components[2] * m_components[2] +
m_components[3] * m_components[3];
}
double vec4::length() const { return std::sqrt(length_squared()); }
vec4 vec4::normalized() const { return *this / length(); }
double vec4::dot(const vec4 &other) const {
vec4 tmp = (*this) * other;
return tmp.at(0) + tmp.at(1) + tmp.at(2) + tmp.at(3);
}
vec3 vec4::to_affine() const { return vec3(at(0), at(1), at(2)) / at(3); }
| true |
a5f33dd89897e0ba25fecc3e112e1c2196c52dc0 | C++ | kohn/leetcode-sol | /HIndexII.cpp | UTF-8 | 1,110 | 3.40625 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <map>
#include <queue>
#include <algorithm>
using namespace std;
void print(vector<int> &v){
for(auto i:v){
cout << i << " ";
}
cout << endl;
}
class Solution {
public:
// int hIndex(vector<int>& citations) {
// int h = 0;
// int size = citations.size();
// for(int i=size-1; i>=0; i--){
// int n = citations[i];
// int tmp_h = min(n, size-i);
// if(h<tmp_h)
// h = tmp_h;
// }
// return h;
// }
int hIndex(vector<int>& citations) {
int lo = 0;
int hi = citations.size()-1;
int max_h = 0;
int size = citations.size();
while(lo <= hi){
int mid = lo + (hi-lo)/2;
int n = citations[mid];
int h;
if(n > size-mid){
h = size-mid;
hi = mid-1;
} else{
h = n;
lo = mid+1;
}
if(h > max_h)
max_h = h;
}
return max_h;
}
};
int main(int argc, char *argv[]) {
Solution sol;
vector<int> citations{0,1,3,5,6};
cout << sol.hIndex(citations) << endl;
return 0;
}
| true |
8763579b3a3a01d081aee433adf5b399203e4bcb | C++ | StevenChenZJU/myshell | /manual.cpp | UTF-8 | 5,148 | 3.171875 | 3 | [] | no_license | #include "manual.h"
using namespace std;
// raw string literal和unicode结合
// 前缀u8R
// 并且raw string 需要用括号()括起来
extern const string HELP =
u8R"(Myshell用户手册
基本介绍
Myshell是一个C++实现的简化版的shell,具备Linux操作系统用户接口的基本交互功能。Myshell类似于bash,支持内部指令,外部程序/指令调用,IO重定向(仅支持内部指令的输出重定向),文件作为命令行输入,管道操作以及**作业控制**。同时,Myshell还支持变量赋值,并且echo能够替换变量。
内部指令
Myshell支持如下内部指令:bg、cd 、clr、dir、echo 、exec 、exit 、environ、fg 、help、jobs 、pwd 、quit、set 、shift 、test 、time 、umask、unset
**具体指令的介绍如下:**
1. bg ,fg ,jobs
用于作业控制的三个指令,将进程在前后台之间调度
(有关作业控制和前后台的调度见后文**作业调度**章节)
**bg** <command> 后台运行某个指令(通常情况下,该指令会被暂停)
**jobs** 用于列举所有还放在后台的指令
**fg** <jobno> 用于将后台的指令(编号为jobno的后台指令)转到前台
2. cd, pwd
**cd** <pathname>指令用于转换工作目录,当前工作目录会显示在命令提示符上
**pwd** 用于输出当前工作目录
3. clr
清屏并将光标移到左上角
4. dir <directory>
列出某一个文件夹中的所有文件
5. echo <string>
显示字符串,**支持字符串替换**
6. exec <command>
运行一个程序后(替换当前的进程)并退出Myshell
7. exit, quit
退出Myshell
8. environ, set
这两个指令用于显示环境变量和用户定义的变量
其中**environ** 只显示环境变量,**set** 既显示环境变量又显示用户定义的变量。
这里的环境变量指的是**进程环境/程序环境**中的环境变量,是由Linux内核管理控制的,并提供了编程接口让程序(myshell)能过管理这些环境变量。
9. unset <variable>
清除用户变量或环境变量的定义
10. help
显示用户帮助手册并用**more** 作为pager过滤
11. shift [N]
将参数移动N位,仅在以文件为输入时有意义
当不输入N时,默认移动一位
12. test <expression>
测试后面跟着的待测表达式是真或假,待测表达式
支持的表达式包括:
1. -z 是否为空给
2. -d 是否为文件夹
3. -eq 二者是否相等
4. -ne 二者是否不等
13. time
输出当前时间比如:Tue Aug 11 19:57:59 2020
14. umask
显示或设置umask(建立文件时预设的权限掩码。)
当没有参数是显示当前umask
umask可用来设定**权限掩码**。**权限掩码**是由3个八进制的数字所组成,将现有的存取权限减掉权限掩码后,即可产生建立文件时预设的权限。
外部程序调用
Myshell支持外部程序或指令的调用,通过exec系列函数实现。
外部程序调用相当于在myshell程序内部运行别的程序。
这些外部指令包括ls,cat等等,只要该程序在PATH环境变量指定的路径下能被找到,就能被调用。
IO重定向
Myshell支持输出的重定向,**包括内部和外部指令**。
其中`> <filename>`表示覆写该文件,如果该文件不存在则创建
而 `>> <filename>`表示在文件末尾加上该文件,如果该文件不存在则创建
文件作为命令行输入
当调用myshell时传入参数,第一个参数被认为是脚本文件
比如`myshell test.sh`
test.sh 中的内容每一行被当作一条指令顺序执行
而如果在文件名后还有后续参数,myshell将他们保存起来
作为第一、二.......个参数, 可以被echo引用
第零个参数是test.sh
管道操作
管道(pipe)是Linux支持的一种文件数据流动的一种特殊方式。管道一般用在两个进程间的通信。通过建立管道的方式,一个进程可以把输出链接到另一个进程的输入,从而实现单向(也可以是双向的,如果有两个管道的话)的进程通信。管道利用了Linux的文件描述符链接管道和两个进程。
作业控制
作业控制指的是Linux终端上对于前后台进程的切换和管理。
前台进程指的是拥有与用户交互的终端的标准输入输出权限的进程。而后台进程想要使用这个输入输出会产生其他信号SIGTTOU和SIGTTIN。在Myshell中后台进程都被暂停了,在转为前台后继续运行。在myshell(bash中也相同)中,内部指令是在与终端同一进程运行的,所以内部指令不会被转换为后台进程。
Myshell中支持:
1. 前台进程的Ctrl+Z暂停;
2. & 或bg命令后台运行进程(实际上进程被暂停);
3. jobs查看后台(被暂停的)进程;
4. fg将后台的进程)"; | true |
c4e5450d91b93f3beb20567ff288ff229cb620fd | C++ | kaycbas/dslib_bastoul-master | /hw5/speedtest/plusonearraylist.h | UTF-8 | 446 | 3.109375 | 3 | [] | no_license | using namespace std;
template <class T>
class PlusOneArrayList : public ArrayList<T>
{
private:
T* temp;
public:
PlusOneArrayList();
bool resize ();
};
template <class T>
PlusOneArrayList<T>::PlusOneArrayList()
{
}
template <class T>
bool PlusOneArrayList<T>::resize()
{
int size = this->getSIZE();
T* temp = new T [size+1];
for (int i=0; i<(size); i++)
{
temp[i] = this->get(i);
}
size++;
this->setArray(temp, size);
}
| true |
80e2f90e846ab55ac27db2ec0ad22d480b716cb5 | C++ | GabeOchieng/ggnn.tensorflow | /program_data/PKU_raw/33/127.c | UTF-8 | 540 | 2.546875 | 3 | [] | no_license | int main()
{
int n,i,j,k,m;
char str2[256]={0};
char str1[256];
cin>>n;
for(i=0;i<n;i++)
{
cin>>str1;
str2[255]=0;
for(j=0;j<255&&str1[j]!='\0';j++)
{
if(str1[j]==65)
{
str2[j]=84;
}
if(str1[j]==84)
{
str2[j]=65;
}
if(str1[j]==67)
{
str2[j]=71;
}
if(str1[j]==71)
{
str2[j]=67;
}
}
str2[j]=0;
for(k=0;k<255&&str2[k]!=0;k++)
{
cout<<str2[k];
}
cout<<endl;
str1[255]=0;
}
return 0;
}
| true |
feaceeafbe4d02cac9671d31a8e7e84943037e94 | C++ | parduman/lovebabbar450 | /C++/function/classForDiagonalMatrix.cpp | UTF-8 | 1,057 | 3.703125 | 4 | [] | no_license | #include <iostream>
#include <stdio.h>
#include <bits/stdc++.h>
using namespace std;
class Diagonal{
private:
int *A;
int n;
public:
Diagonal(){
this->n = 2;
A = new int[2];
}
Diagonal(int n){
(*this).n = n;
this->A = new int[n];
}
~Diagonal(){
delete this->A;
}
void Set(int i, int j, int x);
int Get(int i, int j);
void Display();
};
void Diagonal::Set(int i, int j, int x){
if(i ==j){
this->A[i-1] = x;
}
}
int Diagonal::Get(int i, int j){
if (i == j){
return this->A[i-1];
} else {
return 0;
}
}
void Diagonal::Display(){
for(int i =0; i< this->n; i++){
for(int j=0; j< this->n; j++){
if(i == j)
cout << this-> A[i] <<" ";
else
cout << "0 ";
}
cout << endl;
}
}
int main() {
Diagonal d(4);
d.Set(1,1,5); d.Set(4,4,12);
d.Display();
return 0;
}
| true |
8f358091a27f3a7f0117eb06824ad56ffca5a37d | C++ | anmoldp7/SPOJ-List | /POCRI/pocri.cpp | UTF-8 | 696 | 2.9375 | 3 | [] | no_license | //A problem on Josephus Algorithm.
#include<bits/stdc++.h>
using namespace std;
int josephus(int n,int k){
if(n==1)
return 1;
else
return ((josephus(n-1,k)+k-1)%n+1);
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int arr[101],n;
for(int i=0;i<13;i++)
arr[i]=1;
for(int n=13;n<=100;n++){
int flag=1,c;
for(int i=1;flag;i++){
c=josephus(n,i)-i+1;
while(c<=0)
c+=n;
if(c==13){
flag=0;
arr[n]=i;
}
}
}
cin>>n;
while(n!=0){
cout<<arr[n]<<"\n";
cin>>n;
}
return 0;
}
| true |
59d21e6f2ffef1d7de87f665e199df22ba800d43 | C++ | 8847870981/lab-4b | /CPP15.cpp | UTF-8 | 702 | 4.3125 | 4 | [] | no_license | #include <iostream>
using namespace std;
//C++ program to determine the maximum and minmum of all array elements using recursion.
void min_max(int numbers[],int c,int size,int min,int max)
{
if(c<size)
{
if(numbers[c]<min)
min=numbers[c];
if(numbers[c]>max)
max=numbers[c];
min_max(numbers,++c,size,min,max);
}
else
{
cout<<"Maximum equals "<<max<<endl;
cout<<"Minimum equals "<<min<<endl;
}
}
int main()
{
int size;
cout<<"C++ program to display all array elements using recursion";
cout<<"\n \nEnter the size of array: ";
cin>>size;
int arr[size];
for(int i=0;i<size;i++)
{
cout<<"Enter your element:";
cin>>arr[i];
}
min_max(arr,0,size);
return 0;
}
| true |
0e338d647819ce8b86caa6acfef6ca983d26b8e9 | C++ | AdityaKarn/cp-cpp | /codechef/may 18/plus.cpp | UTF-8 | 676 | 2.90625 | 3 | [] | no_license | #include<iostream>
#include<climits>
using namespace std;
int main(){
int T; cin>>T;
for(int k = 0; k< T; k++){
int n, m, sum;
cin>>n>>m;
int arr[n][m];
for(int i = 0; i< n ; i++){
for(int j=0; j< m; j++){
cin>>arr[i][j];
}
}
int maxplus = INT_MIN;
for(int i =1; i< n-1; i++){
for(int j = 1; j< m-1; j++){
sum = arr[i][j]+ arr[i-1][j]+ arr[i+1][j]+ arr[i][j-1]+ arr[i][j+1];
if(sum> maxplus){
maxplus = sum;
}
}
}
cout<<maxplus;
}
return 0;
} | true |
76da71abcb38cdd27003366dd5b4c9ea865a5710 | C++ | shossjer/fimbulwinter | /code/src/utility/lookup_table.hpp | UTF-8 | 4,345 | 3 | 3 | [
"ISC"
] | permissive |
#ifndef UTILITY_LOOKUP_TABLE_HPP
#define UTILITY_LOOKUP_TABLE_HPP
#include "concepts.hpp"
#include "type_traits.hpp"
#include <array>
#include <tuple>
namespace utility
{
namespace detail
{
template <typename Key, std::size_t N>
struct lookup_table_keys
{
std::array<Key, N> keys;
template <typename ...Ps>
constexpr lookup_table_keys(Ps && ...ps)
: keys{{std::forward<Ps>(ps)...}}
{}
constexpr bool contains(const Key & key) const
{
return find(key) != std::size_t(-1);
}
constexpr std::size_t find(const Key & key) const
{
return find_impl(key, mpl::index_constant<0>{});
}
template <std::size_t I,
REQUIRES((I < N))>
constexpr const Key & get_key() const { return std::get<I>(keys); }
constexpr const Key & get_key(std::ptrdiff_t index) const { return keys[index]; }
private:
constexpr std::size_t find_impl(const Key & /*key*/, mpl::index_constant<N>) const
{
return std::size_t(-1);
}
template <std::size_t I>
constexpr std::size_t find_impl(const Key & key, mpl::index_constant<I>) const
{
return std::get<I>(keys) == key ? I : find_impl(key, mpl::index_constant<I + 1>{});
}
};
template <typename Key, typename Value, std::size_t N>
struct lookup_table_value_array : lookup_table_keys<Key, N>
{
using base_type = lookup_table_keys<Key, N>;
enum { all_values_same_type = true };
std::array<Value, N> values;
template <typename ...Pairs>
constexpr explicit lookup_table_value_array(Pairs && ...pairs)
: base_type(pairs.first...)
, values{{pairs.second...}}
{}
constexpr std::ptrdiff_t find_value(const Value & value) const
{
return find_value_impl(value, mpl::index_constant<0>{});
}
template <std::size_t I,
REQUIRES((I < N))>
constexpr const Value & get_value() const { return std::get<I>(values); }
constexpr const Value & get_value(std::ptrdiff_t index) const { return values[index]; }
private:
constexpr std::size_t find_value_impl(const Value & /*value*/, mpl::index_constant<N>) const
{
return std::size_t(-1);
}
template <std::size_t I>
constexpr std::size_t find_value_impl(const Value & value, mpl::index_constant<I>) const
{
return std::get<I>(values) == value ? I : find_value_impl(value, mpl::index_constant<I + 1>{});
}
};
template <typename Key, typename ...Values>
struct lookup_table_value_tuple : lookup_table_keys<Key, sizeof...(Values)>
{
using base_type = lookup_table_keys<Key, sizeof...(Values)>;
enum { all_values_same_type = false };
std::tuple<Values...> values;
template <typename ...Pairs>
constexpr explicit lookup_table_value_tuple(Pairs && ...pairs)
: base_type(pairs.first...)
, values(pairs.second...)
{}
template <std::size_t I,
REQUIRES((I < sizeof...(Values)))>
constexpr const mpl::type_at<I, Values...> & get_value() const { return std::get<I>(values); }
};
template <typename Key, typename ...Values>
using lookup_table_values = mpl::conditional_t<mpl::is_same<Values...>::value, lookup_table_value_array<Key, mpl::car<Values...>, sizeof...(Values)>, lookup_table_value_tuple<Key, Values...>>;
}
template <typename Key, typename ...Values>
class lookup_table : public detail::lookup_table_values<Key, Values...>
{
public:
enum { capacity = sizeof...(Values) };
private:
using base_type = detail::lookup_table_values<Key, Values...>;
using this_type = lookup_table<Key, Values...>;
public:
template <typename ...Pairs,
#if defined(_MSC_VER) && _MSC_VER <= 1916
REQUIRES((sizeof...(Pairs) == sizeof...(Values))),
#else
REQUIRES((sizeof...(Pairs) == capacity)),
#endif
REQUIRES((sizeof...(Pairs) != 1 || !mpl::is_same<this_type, mpl::decay_t<Pairs>...>::value ))>
constexpr explicit lookup_table(Pairs && ...pairs)
: base_type(std::forward<Pairs>(pairs)...)
{}
public:
constexpr std::size_t size() const { return capacity; }
};
template <typename Pair, typename ...Pairs>
constexpr auto make_lookup_table(Pair && pair, Pairs && ...pairs)
{
return lookup_table<typename Pair::first_type, typename Pair::second_type, typename Pairs::second_type...>(std::forward<Pair>(pair), std::forward<Pairs>(pairs)...);
}
}
#endif /* UTILITY_LOOKUP_TABLE_HPP */
| true |
2c298af890cff761a778f6169378458beba24fec | C++ | DataYI/cplusplus | /OJ/acm.nyist.net/01语言入门/0025.cpp | UTF-8 | 563 | 2.984375 | 3 | [
"AFL-2.0"
] | permissive |
#include<iostream>
#include<string>
using namespace std;
string trans(string a) {
string b = "";
if (a[1] == '#') {
b += char((a[0] - 'A' + 1) % 7 + 'A');
b += 'b';
} else {
b += char((a[0] - 'A' + 6) % 7 + 'A');
b += '#';
}
return b;
}
int main() {
string a, b;
for (int t = 1; cin >> a >> b; t++) {
cout << "Case " << t << ": ";
if (a.length() == 1)
cout << "UNIQUE" << endl;
else
cout << trans(a) << " " << b << endl;
}
return 0;
}
| true |
454f5bfcd1cdabbab1c530e055c619c1c555bc96 | C++ | Sebanisu/tonberry | /D3D9CallbackSC2/ext/Engine/Simple Mesh/BaseMeshBounding.cpp | UTF-8 | 3,073 | 3.171875 | 3 | [
"MIT"
] | permissive | /*
BaseMeshBounding.cpp
Written by Matthew Fisher
BaseMesh is an abstract mesh class that defines basic mesh functionality. It also includes source for most
of the manipulation (shape generation, file loading, etc.) that is possible under this generic structure.
Each mesh must be associated with a graphics device before most operations can be performed.
Because there are so many associated functions, they are grouped into various files.
BaseMeshBounding.cpp contains functions about bounding and determining the size of the mesh.
*/
Rectangle3f BaseMesh::BoundingBox() const
{
UINT VC = VertexCount();
const MeshVertex *V = Vertices();
if(VC == 0)
{
return Rectangle3f(Vec3f::Origin, Vec3f::Origin);
}
Vec3f Min = V[0].Pos, Max = V[0].Pos;
for(UINT i = 1; i < VC; i++)
{
Min = Vec3f::Minimize(Min, V[i].Pos);
Max = Vec3f::Maximize(Max, V[i].Pos);
}
return Rectangle3f(Min, Max);
}
Rectangle3f BaseMesh::BoundingBox(const Matrix4 &transform) const
{
UINT vertexCount = VertexCount();
const MeshVertex *vertices = Vertices();
if(vertexCount == 0)
{
return Rectangle3f(Vec3f::Origin, Vec3f::Origin);
}
Vec3f pos0 = transform.TransformPoint(vertices[0].Pos);
Vec3f Min = pos0, Max = pos0;
for(UINT i = 1; i < vertexCount; i++)
{
Vec3f pos = transform.TransformPoint(vertices[i].Pos);
Min = Vec3f::Minimize(Min, pos);
Max = Vec3f::Maximize(Max, pos);
}
return Rectangle3f(Min, Max);
}
float BaseMesh::SurfaceArea() const
{
UINT TriangleCount = FaceCount();
const DWORD *MyIndices = Indices();
const MeshVertex *MyVertices = Vertices();
float Result = 0.0f;
for(UINT TriangleIndex = 0; TriangleIndex < TriangleCount; TriangleIndex++)
{
Vec3f V[3];
for(UINT LocalVertexIndex = 0; LocalVertexIndex < 3; LocalVertexIndex++)
{
V[LocalVertexIndex] = MyVertices[MyIndices[TriangleIndex * 3 + LocalVertexIndex]].Pos;
}
Result += Math::TriangleArea(V[0], V[1], V[2]);
}
return Result;
}
float BaseMesh::Radius()
{
UINT VC = VertexCount();
MeshVertex *V = Vertices();
if(VC == 0)
{
return 0.0f;
}
float LargestDistance = V[0].Pos.Length();
for(UINT i = 1; i < VC; i++)
{
float Result = V[i].Pos.Length();
LargestDistance = Math::Max(Result, LargestDistance);
}
return LargestDistance;
}
float BaseMesh::Radius(const Vec3f &Center)
{
UINT VC = VertexCount();
MeshVertex *V = Vertices();
if(VC == 0)
{
return 0.0f;
}
float LargestDistance = (V[0].Pos - Center).Length();
for(UINT i = 1; i < VC; i++)
{
float Result = (V[i].Pos - Center).Length();
LargestDistance = Math::Max(Result, LargestDistance);
}
return LargestDistance;
}
Matrix4 BaseMesh::UnitSphereTransform()
{
Vec3f Center = BoundingBox().Center();
float Scale = 1.0f / Radius(Center);
return Matrix4::Translation(-Center) * Matrix4::Scaling(Scale);
} | true |
ccc7ba5a9d848cd7a0e1e505bef5421d96c37517 | C++ | a16620/P2PNet | /Utils.h | UTF-8 | 876 | 3.625 | 4 | [] | no_license | #pragma once
#include <atomic>
template <class K, class V>
class Minimum {
K initialKey;
V initialValue;
public:
Minimum(K&& key, V&& value) {
initialKey = move(key);
initialValue = move(value);
}
void Update(K&& key, V&& value) {
if (key < initialKey) {
initialKey = std::move(key);
initialValue = std::move(value);
}
}
auto& getKey() {
return initialKey;
}
auto& getValue() {
return initialValue;
}
};
template <class K, class V>
class AtomicMinimum {
atomic<K> initialKey;
atomic<V> initialValue;
public:
AtomicMinimum(K key, V value) {
initialKey = key;
initialValue = value;
}
void Update(K key, V value) {
if (key < initialKey) {
initialKey = key;
initialValue = value;
}
}
K getKey() {
return initialKey;
}
V getValue() {
return initialValue;
}
}; | true |
5b1d715afecf0e0d4a72a4077c94cbd590dfd4ee | C++ | kingkellingson/project-5-git | /IDAutomaton.h | UTF-8 | 2,349 | 3.265625 | 3 | [] | no_license | //
// Created by Kyle Ellingson on 5/5/21.
//
#ifndef PROJECT_0_IDAUTOMATON_H
#define PROJECT_0_IDAUTOMATON_H
#include "Automaton.h"
class IDAutomaton : public Automaton
{
private:
void S1(std::string& input);
public:
IDAutomaton() : Automaton(TokenType::ID) {} // Call the base constructor
void S0(std::string& input);
};
void IDAutomaton::S0(std::string& input) {
if (isalpha(input[index])) {
inputRead++;
index++;
S1(input);
}
else {
Serr();
}
}
void IDAutomaton::S1(std::string& input) { //Loops the middle of the string. Error if not letter or digit
for (size_t i = 5; i<8; ++i)
{
switch (i)
{
case 5:
if (input.substr(index, i)=="Facts"||input.substr(index, i)=="Rules")
{
//if it either has a space next or an endline character next, then it ran into an existing token.
if (!isalnum(input.at(index+1))||input.substr(index, 6)=="0endl0") { return; }
//if not, then it must be a part of the ID
else { break; }
}
case 6:
if (input.substr(index, i)=="0endl0")
{
return; //return because it has reached the end of the ID token
}
case 7:
if (input.substr(index, i)=="Schemes"||input.substr(index, i)=="Queries")
{
//if it either has a space next or an endline character next, then it ran into an existing token.
if (!isalnum(input.at(index+1))||input.substr(index, 6)=="0endl0") { return; }
//if not, then it must be a part of the ID
else { break; }
}
/*case 8:
if (input.substr(index, i)=="EOF_TYPE")
{
if (!isalnum(input.at(index+1))||input.substr(index, 6)=="0endl0") { return; }
else { break; }
}*////don't think it will ever run into my EOF_TYPE token
default: ;
}
}
if (isalnum(input[index])) {//If it runs into an alphanumeric symbol
inputRead++;
index++;
S1(input);
}
else {
return;
}
}
#endif //PROJECT_0_IDAUTOMATON_H
| true |
a8c97e6c39af23bbad3ab4e5ab9c796ced157572 | C++ | matbot/Monster-Arena | /monsterArena/creatureStack.hpp | UTF-8 | 734 | 3.234375 | 3 | [] | no_license | /***********************************************
* *Author: Mathew McDade
* *Date: Sat Nov 19 20:48:37 PST 2016
* *Description: Stack-like, LIFO, class for
* storing pointers to Creature class objects.
* *********************************************/
#ifndef MMCD_CREATURESTACK_HPP
#define MMCD_CREATURESTACK_HPP
#include "creature.hpp"
class CreatureStack
{
private:
class StackNode
{
friend class CreatureStack;
Creature* creature;
StackNode* next;
StackNode(Creature* nextCritter, StackNode* nextNode = NULL)
{
creature = nextCritter;
next = nextNode;
}
};
StackNode* top;
public:
CreatureStack();
~CreatureStack();
void push(Creature*);
Creature* pop();
bool isEmpty() const;
void clear();
};
#endif
| true |
33f5235130d2177d5aa7d50fc9ee918f1095d69b | C++ | yifeng-pan/competitive_programming | /kattis/solutions/conundrum.cpp | UTF-8 | 255 | 2.546875 | 3 | [
"Unlicense"
] | permissive | /*
https://open.kattis.com/problems/conundrum
*/
#include <iostream>
int main() {
char p, e, r;
int sum = 0;
while(std::cin >> p >> e >> r){
if(p != 'P') sum += 1;
if(e != 'E') sum += 1;
if(r != 'R') sum += 1;
}
std::cout << sum;
return 0;
} | true |
70b71af431d73d1cebdd23660a1e6567733b7173 | C++ | Nurzhan011/acmp | /acmp 324.cpp | UTF-8 | 295 | 3.109375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int a1 = n % 10;
int a2 = n / 10 % 10;
int a3 = n / 100 % 10;
int a4 = n / 1000 % 10;
if(a1==a4 && a2==a3)
cout << "YES";
else
cout << "NO";
}
| true |
0ef77c305af03005e79b685db1526382ec25641d | C++ | sanjaykazi/My-Random-Learnings | /Sorting/ExperimentaltimeAnalysis.cpp | UTF-8 | 1,817 | 3.140625 | 3 | [] | no_license | #include<iostream>
#include <sys/time.h>
using namespace std;
long getTimeInMicroSeconds(){
struct timeval currentTime;
gettimeofday(¤tTime, NULL);
return currentTime.tv_sec * (int)1e6 + currentTime.tv_usec;
}
void mergeArrays(int x[],int y[],int a[],int s,int e){
int mid = (s+e)/2;
int i=s;
int j = mid+1;
int k = s;
while(i<=mid && j<=e){
if(x[i] < y[j]){
a[k] = x[i];
i++;
k++;
}else{
a[k] = y[j];
j++;
k++;
}
}
while(i<=mid){
a[k] = x[i];
k++;
i++;
}
while(j<=e){
a[k] = y[j];
k++;
j++;
}
}
int *x = new int[10000000];
int *y = new int[10000000];
void mergeSort(int a[],int s,int e){
if(s>=e){
return;
}
int mid = (s+e)/2;
for(int i=s;i<=mid;i++){
x[i] = a[i];
}
for(int i=mid+1;i<=e;i++){
y[i] = a[i];
}
mergeSort(x,s,mid);
mergeSort(y,mid+1,e);
mergeArrays(x,y,a,s,e);
}
void selectionSort(int a[],int n){
for(int i=0;i<=n-2;i++){
int smallest = i;
for(int j=i+1;j<=n-1;j++){
if(a[j]<a[smallest]){
smallest = j;
}
}
swap(a[i],a[smallest]);
}
}
int main(){
for(int n=10;n<=10000000; n *= 10){
int *arr = new int[n];
long startTime , endTime;
for(int i=0;i<n;i++){
arr[i] = n-i;
}
startTime = getTimeInMicroSeconds();
mergeSort(arr,0,n-1);
///selectionSort(arr,n);
endTime = getTimeInMicroSeconds();
cout<<"Merge sort n = "<<n<<" time = "<<endTime-startTime<<endl;
///cout<<"Selection sort n = "<<n<<" time = "<<endTime-startTime<<endl;
delete []arr;
}
return 0;
}
| true |
7a5dce7173ad78a78905dcf57c21163b6749f597 | C++ | Tandaradei/conrast | /src/render/Framebuffer.hpp | UTF-8 | 1,526 | 2.734375 | 3 | [] | no_license | #ifndef FRAMEBUFFER_HPP
#define FRAMEBUFFER_HPP
#include <vector>
#include "utils/Vec.hpp"
#include "color/Color.hpp"
namespace conrast { namespace render {
class Framebuffer
{
public:
Framebuffer(const utils::Vec2i size, const float near, const float far);
color::RGB8 getColor(utils::Vec2i position) const;
void setColor(utils::Vec2i position, color::RGB8 color);
color::RGB8* getColorData(utils::Vec2i position = { 0, 0 });
// Returned depth is between 0 (near) and 1 (far)
float getDepthNormalized(utils::Vec2i position) const;
// depth must be between 0 (near) and 1 (far)
void setDepthNormalized(utils::Vec2i position, float depth);
// Returns true if passed depth is nearer than saved depth and update saved depth with passed depth
bool updateDepth(utils::Vec2i position, float depth);
// depth must be between 0 (near) and 1 (far)
// Returns true if passed depth is nearer than saved depth and update saved depth with passed depth
bool updateDepthNormalized(utils::Vec2i position, float depth);
bool isSavedNearer(utils::Vec2i position, float depth) const;
float* getDepthData(utils::Vec2i position = { 0, 0 });
float normalizeDepth(float depth) const;
void clear(color::RGB8 color = color::Black, float depth = 1.0f);
private:
const utils::Vec2i m_SIZE;
const float m_near;
const float m_far;
const float m_depthTransformSummand;
const float m_depthTransformFactor;
std::vector<color::RGB8> m_color;
std::vector<float> m_depth;
};
} }
#endif // FRAMEBUFFER_HPP
| true |
e1525bf0b2a9c3a68692880f01fa78974edaf6ee | C++ | DanielRibble/RelationalDataBase | /Scheme.h | UTF-8 | 322 | 2.90625 | 3 | [] | no_license | #pragma once
#include <string>
#include <vector>
using namespace std;
class Scheme: public vector<string>{
/*
private:
vector<string> name_list;
public:
Scheme (vector<string> name_list){
this->name_list = name_list;
}
~Scheme(){}
string at(unsigned pos){
return name_list[pos];
}
*/
}; | true |
d1f8908514d20b50c5c9aaf7a29467f81e502462 | C++ | djh-sudo/Stone-Interpreter | /source/ASTList.h | GB18030 | 1,277 | 2.78125 | 3 | [] | no_license | #pragma once
#include "ASTree.h"
#include <ostream>
#include <string>
// ̳AST Ҷ
/*
ASTList [Base]
-> Postfix
-> ArrayLiteral
-> ParameterList
-> BinaryExpr
-> NegExpr
-> PrimaryExpr
-> BlockStmt
-> ClassBody
-> ClassStmt
-> DefStmt
-> IfStmt
-> WhileStmt
-> NullStmt
-> ForStmt
*/
class ASTList :public ASTree {
protected:
// 飬ﲻǶǶ
std::vector<ASTree::cptr>mChildren;
public:
// ĬϹ캯
ASTList() = default;
~ASTList() = default;
// ع캯
ASTList(const std::vector<ASTree::cptr>& list);
// жǷΪҶ
virtual bool isLeaf()const override;
//
virtual int numberChildren()const override;
// token
virtual Token::cptr token()const override;
// ±귵غӶ
virtual ASTree::cptr child(rsize_t t)const override;
// ȡӦλõĽַ
virtual std::string location()const override;
// תΪַ
virtual std::string toString()const override;
// ǰ
virtual Object::ptr eval(Environment& env)const override;
};
// I/O
std::ostream& operator<<(std::ostream& os, const ASTree::cptr& ast);
| true |
edfc890c75a42bf6dbf3f72e614fafeb5e54862c | C++ | HekpoMaH/Olimpiads | /codeforces/round171/e.cpp | UTF-8 | 1,171 | 2.921875 | 3 | [] | no_license | #include<iostream>
#include<string>
using namespace std;
string s;
int br0,br1;
string ff;
bool cmp(string x,string y)
{
if(x.size()>y.size())return true;
if(x.sise()<y.size())return false;
for(int i=0;i<x.size();i++)
{
if(x[i]<y[i])return true;
if(x[i]>y[i]) return false;
}
}
int substr(string &x,string y)
{
int u1=x.size(),u2=y.size();
while(u1>=0&&u2>=0)
{
if(x[u1]=='1'&&y[u2]=='0')ff+='1';
if(x[u1]=='1'&&y[u2]=='1')ff+='0';
if(x[u1]=='0'&&y[u2]=='0')ff+='0';
if(x[u1]=='0'&&y[u2]=='1')
{
ff+='1';
for(int i=u1;i>=0;i--)
{
if(x[i]=='0')x[i]='1';
else {x[i]='0';break;}
}
}
u1--;u2--;
}
int brr=0;
//cout<<ff<<endl;
for(int i=0;i<ff.size();i++)if(ff[i]=='1')brr++;
x=ff;
return brr+1
}
int main()
{
cin>>s;
for(int i=0;i<s.size();i++){if(s[i]=='0')br0++;else br1++;}
if(br0==0){cout<<2<<endl;return 0;}
if(br1==1){cout<<1<<endl;return 0;}
string s1="1";
for(int i=0;i<s.size();i++)s1+='0';
while(cmp(s1,s)==true)
{
}
}
| true |
7fe9648b9423696229ca7afad7b5fa78f3bd400f | C++ | Manan-jn/CoDing-Problems | /painters_problem.cpp | UTF-8 | 1,555 | 3.375 | 3 | [] | no_license | //Under Progress
#include <iostream>
using namespace std;
bool isPossible(int time, int painters, int boardsLength[], int sum, int n)
{
//need to check if it is possible to paint
//all the boards in "mid" amount of time
int boards = 0;
//will bring painters one by one
//will give them time and count their number of boards
//will check if the number of boards >= sum of boardslength
//return true;
for (int i = 0; i < painters; i++)
{
int currentTime = 0;
while (currentTime <= time)
{
for (int j = 0; j < n; j++)
{
int board = boardsLength[j];
currentTime += board;
boards++;
if (currentTime > time)
{
break;
}
}
}
}
if (boards >= n)
{
return true;
}
else
{
return false;
}
}
int main()
{
int k;
cin >> k;
int n;
cin >> n;
int boardsLength[10];
for (int i = 0; i < n; i++)
{
cin >> boardsLength[i];
}
int s = boardsLength[n - 1];
int sum = 0;
for (int i = 0; i < n; i++)
{
sum = sum + boardsLength[i];
}
int e = sum;
int ans = 0;
while (s <= e)
{
int mid = (s + e) / 2;
if (isPossible(mid, k, boardsLength, sum, n))
{
ans = mid;
e = mid - 1;
}
else
{
s = mid + 1;
}
}
cout << ans << endl;
return 0;
}
| true |
ac1e748dcddc2e7b932daf2ea6ddafffe24dbd35 | C++ | JulianLiao5/cpp_basics | /boost/connection/test_connection.cpp | UTF-8 | 824 | 2.9375 | 3 | [] | no_license | /*************************************************************************
> File Name: test_boost.cpp
> Author:
> Mail:
> Created Time: 2019年04月08日 星期一 15时04分52秒
************************************************************************/
#include <iostream>
using namespace std;
#include <boost/signals2/signal.hpp>
struct HelloWorld {
void operator()() const;
};
void HelloWorld::operator()() const {
std::cout << "Hello, liaomeng!" << std::endl;
}
int main(int argc, char *argv[]) {
// Signal with no arguments and a void return value
boost::signals2::signal<void()> sig;
boost::signals2::connection c = sig.connect(HelloWorld());
std::cout << "c is connected\n";
sig();
c.disconnect();
std::cout << "c is disconnected\n";
sig();
return 0;
}
| true |
c3b43e274e6c5da6033ce3aef00a9c5ad1ac7422 | C++ | Yaamani/compression-algorithms | /my_tree.h | UTF-8 | 758 | 2.640625 | 3 | [
"MIT"
] | permissive | #pragma once
#include <string>
#include <list>
//#define INITIAL_DICTIONARY_SIZE 65536 // total number of all chars a 'wchar_t' can hold
#define INITIAL_DICTIONARY_SIZE 166416 // wchar_t on mac and linux is 32bits not 16bits, so there're some chars > 65536 on my labtop
struct DictionaryTree;
struct Node
{
DictionaryTree* base;
std::list<Node*> children;
wchar_t c;
int index;
int freq;
Node(DictionaryTree*, wchar_t);
Node* addChild(wchar_t);
Node* searchInChildren(wchar_t);
std::list<Node*>& getChildren();
};
struct DictionaryTree
{
std::list<Node*> children;
int size;
DictionaryTree();
Node* addChild(wchar_t);
Node* searchInChildren(wchar_t);
std::list<Node*>& getChildren();
};
| true |
b757fea78c45349217b7fc3e365e61346be74dfb | C++ | w18600843158/FPAnalysis | /src/fpUtil.cpp | UTF-8 | 8,210 | 2.9375 | 3 | [] | no_license | #include "fpUtil.h"
double fpUtil::i64ToDouble(uint64_t i) {
return *(double*)(&i);
}
uint64_t fpUtil::doubleToI64(double d) {
return *(uint64_t*)(&d);
}
float fpUtil::i32ToFloat(uint32_t i) {
return *(float*)(&i);
}
uint32_t fpUtil::floatToI32(float f) {
return *(uint32_t*)(&f);
}
uint64_t fpUtil::getDoubleSign(double d) {
uint64_t i = doubleToI64(d);
return (i & DBL_SIGNMASK) >> 63;
}
uint64_t fpUtil::getDoubleExpo(double d) {
uint64_t i = doubleToI64(d);
return (i & DBL_EXPOMASK) >> 52;
}
uint64_t fpUtil::getDoubleFrac(double d) {
uint64_t i = doubleToI64(d);
return (i & DBL_FRACMASK);
}
uint32_t fpUtil::getFloatSign(float f) {
uint32_t i = floatToI32(f);
return (i & FLT_SIGNMASK) >> 31;
}
uint32_t fpUtil::getFloatExpo(float f) {
uint32_t i = floatToI32(f);
return (i & FLT_EXPOMASK) >> 23;
}
uint32_t fpUtil::getFloatFrac(float f) {
uint32_t i = floatToI32(f);
return (i & FLT_FRACMASK);
}
double fpUtil::buildDouble(uint64_t sign, uint64_t expo, uint64_t frac) {
uint64_t bits;
bits = (sign << 63) & DBL_SIGNMASK;
bits |= (expo << 52) & DBL_EXPOMASK;
bits |= (frac & DBL_FRACMASK);
return i64ToDouble(bits);
}
float fpUtil::buildFloat(uint32_t sign, uint32_t expo, uint32_t frac) {
uint32_t bits;
bits = (sign << 31) & FLT_SIGNMASK;
bits |= (expo << 23) & FLT_EXPOMASK;
bits |= (frac & FLT_FRACMASK);
return i32ToFloat(bits);
}
double fpUtil::doubleULP(double d) {
uint64_t bits = doubleToI64(d);
// make it positive.
bits = bits & (DBL_EXPOMASK | DBL_FRACMASK);
d = i64ToDouble(bits);
double d_plus = i64ToDouble(bits+1);
return d_plus - d;
}
float fpUtil::floatULP(float f) {
uint32_t bits = floatToI32(f);
// make it positive.
bits = bits & (FLT_EXPOMASK | FLT_FRACMASK);
f = i32ToFloat(bits);
float f_plus = i32ToFloat(bits+1);
return f_plus - f;
}
uint64_t fpUtil::doubleDist(double d1, double d2) {
uint64_t dist, bits1, bits2;
bits1 = doubleToI64(d1) & (DBL_EXPOMASK | DBL_FRACMASK);
bits2 = doubleToI64(d2) & (DBL_EXPOMASK | DBL_FRACMASK);
if ((d1 > 0 && d2 < 0) || (d1 < 0 && d2 > 0)) {
dist = bits1 + bits2;
}
else {
if (bits1 > bits2)
dist = bits1 - bits2;
else
dist = bits2 - bits1;
}
return dist;
}
uint32_t fpUtil::floatDist(float f1, float f2) {
uint32_t dist, bits1, bits2;
bits1 = doubleToI64(f1) & (FLT_EXPOMASK | FLT_FRACMASK);
bits2 = doubleToI64(f2) & (FLT_EXPOMASK | FLT_FRACMASK);
if ((f1 > 0 && f2 < 0) || (f1 < 0 && f2 > 0)) {
dist = bits1 + bits2;
}
else {
if (bits1 > bits2)
dist = bits1 - bits2;
else
dist = bits2 - bits1;
}
return dist;
}
uint64_t fpUtil::rand64() {
// important to make the generator 'static' here.
static std::mt19937_64 mt_generator_64(0xdeadbeef);
return mt_generator_64();
}
//mindis not included,maxdis included.
double fpUtil::randNeighbor(double x,uint64_t mindis,uint64_t maxdis){
uint64_t tmp;
uint64_t bits = 0;
uint64_t sign = fpUtil::getDoubleSign(x);
uint64_t expo = fpUtil::getDoubleExpo(x);
uint64_t frac = fpUtil::getDoubleFrac(x);
uint64_t newfrac;
//buggy
//uint64_t nlower = fmax(0,frac - maxdis);
//uint64_t nupper = fmax(0,frac - mindis);
uint64_t nlower = frac < maxdis ? 0 : frac-maxdis;
uint64_t nupper = frac < mindis ? 0 : frac-mindis;
uint64_t nrange = nupper-nlower;
uint64_t plower = fmin(DBL_FRACMASK,frac + mindis);
uint64_t pupper = fmin(DBL_FRACMASK,frac + maxdis);
uint64_t prange = pupper - plower;
assert(nrange+prange > 1);
//use rand64(?)
uint64_t r = rand64()%(nrange+prange);
if(r<nrange)
newfrac = r + nlower;
else
newfrac = (r-nrange) + plower + 1;
if(newfrac > frac)assert(newfrac-frac >= mindis && newfrac-frac <= maxdis);
else assert(frac-newfrac >= mindis && frac-newfrac <= maxdis);
return fpUtil::buildDouble(sign,expo,newfrac);
}
uint32_t fpUtil::rand32() {
// important to make the generator 'static' here.
static std::mt19937 mt_generator_32(0xdeadbeef);
return mt_generator_32();
}
double fpUtil::randDouble() {
return i64ToDouble(rand64());
}
float fpUtil::randFloat() {
return i32ToFloat(rand32());
}
double fpUtil::rand01()
{
return fabs(fpUtil::randDouble()/fpUtil::DBL_POSINF);
}
double fpUtil::revisedCondition(uint64_t opcode, double lhs, double rhs) {
double cond1, cond2;
double dzdist;
switch(opcode) {
case OP_ADD:
dzdist = fabs(lhs+rhs);
cond1 = fabs(lhs) / dzdist;
cond2 = fabs(rhs) / dzdist;
return cond1 + cond2 - dzdist; // ????
case OP_SUB:
dzdist = fabs(lhs-rhs);
cond1 = fabs(lhs) / dzdist;
cond2 = fabs(rhs) / dzdist;
return cond1 + cond2 - dzdist;
case OP_SIN:
// cond1 = fabs(lhs / tan(lhs));
// x \to n*pi, n \in Z.
cond1 = 1 / fabs(remainder(lhs, fpUtil::PI));
return cond1;
case OP_COS:
// cond1 = fabs(lhs * tan(lhs));
// x \to n*pi + pi/2, n \in Z.
cond1 = 1 / fabs(remainder((remainder(lhs, fpUtil::PI)-fpUtil::PI_2),fpUtil::PI));
return cond1;
case OP_TAN:
// cond1 = fabs(lhs / (sin(lhs) * cos(lhs)));
// x \to n*pi/2, n \in Z.
cond1 = 1 / fabs(remainder(lhs, fpUtil::PI_2));
return cond1;
case OP_ASIN:
cond1 = fabs(lhs / (sqrt(1-lhs*lhs) * asin(lhs)));
return cond1;
case OP_ACOS:
cond1 = fabs(lhs / (sqrt(1-lhs*lhs) * acos(lhs)));
return cond1;
case OP_SINH:
cond1 = fabs(lhs / tanh(lhs));
return cond1;
case OP_COSH:
cond1 = fabs(lhs * tanh(lhs));
return cond1;
case OP_LOG:
dzdist = fabs(lhs - 1);
cond1 = fabs(1 / log(lhs));
return cond1 - dzdist;
case OP_LOG10:
dzdist = fabs(lhs - 1);
cond1 = fabs(1 / log(lhs));
return cond1 - dzdist;
case OP_POW:
cond1 = fabs(rhs);
cond2 = fabs(rhs * log(lhs));
return cond1 + cond2;
default:
return -DBL_MAX;
}
return -DBL_MAX;
}
double fpUtil::rawCondition(uint64_t opcode, double lhs, double rhs) {
double cond1, cond2, dzdist;
switch(opcode) {
case OP_ADD:
dzdist = fabs(lhs+rhs);
cond1 = fabs(lhs) / dzdist;
cond2 = fabs(rhs) / dzdist;
return cond1 + cond2;
case OP_SUB:
dzdist = fabs(lhs-rhs);
cond1 = fabs(lhs) / dzdist;
cond2 = fabs(rhs) / dzdist;
return cond1 + cond2;
case OP_SIN:
cond1 = fabs(lhs / tan(lhs));
return cond1;
case OP_COS:
cond1 = fabs(lhs * tan(lhs));
return cond1;
case OP_TAN:
cond1 = fabs(lhs / (sin(lhs) * cos(lhs)));
return cond1;
case OP_ASIN:
cond1 = fabs(lhs / (sqrt(1-lhs*lhs) * asin(lhs)));
return cond1;
case OP_ACOS:
cond1 = fabs(lhs / (sqrt(1-lhs*lhs) * acos(lhs)));
return cond1;
case OP_SINH:
cond1 = fabs(lhs / tanh(lhs));
return cond1;
case OP_COSH:
cond1 = fabs(lhs * tanh(lhs));
return cond1;
case OP_LOG:
dzdist = fabs(lhs - 1);
cond1 = fabs(1 / log(lhs));
return cond1;
case OP_LOG10:
dzdist = fabs(lhs - 1);
cond1 = fabs(1 / log(lhs));
return cond1;
case OP_POW:
cond1 = fabs(rhs);
cond2 = fabs(rhs * log(lhs));
return cond1 + cond2;
default:
return 1;
}
return 1;
}
double fpUtil::negInvRevisedCondition(uint64_t opcode, double lhs, double rhs){
return -1.0/(revisedCondition(opcode,lhs,rhs));
} | true |
f93ab54c49a25b1dba8034813d1b3e88ee2f026b | C++ | yvs314/dp-monster | /src/spinlock.h | UTF-8 | 470 | 2.90625 | 3 | [
"MIT"
] | permissive | #pragma once
#include <thread>
class spinlock_t {
std::atomic_flag lock_flag;
public:
spinlock_t() { lock_flag.clear(); }
bool try_lock() { return !lock_flag.test_and_set(std::memory_order_acquire); }
void lock() { for (size_t i = 0; !try_lock(); ++i) if (i % 100 == 0) std::this_thread::yield(); }
void unlock() { lock_flag.clear(std::memory_order_release); }
// void unlock_shared() { lock(); }
// bool try_lock_shared() { try_lock(); }
}; | true |
3e48e25e10c28965559ef489b88e2b2cfea80635 | C++ | zerg-ga/zerg | /UserOperators.cpp | UTF-8 | 1,841 | 2.640625 | 3 | [] | no_license | #include "UserOperators.h"
#include <iostream>
#include <stdlib.h>
using namespace std;
using namespace zerg;
UserOperators::UserOperators(int pop_size, int number_parameters)
:BasicOperators(pop_size, number_parameters)
{
// number_of_creation_methods = 6;
// tol_similarity = 1.0e-2;
}
UserOperators::~UserOperators(){}
void UserOperators::startUserOperators()
{
startBasicOperators();
}
bool UserOperators::create_individual(int creation_type,int target, int parent1, int parent2)
{
cout << "UserOperators::operatorAdministration is not active - contact developers" << endl;
exit(1);
switch(creation_type)
{
case 0:
x_vec[target] = generate_random_individual();
break;
case 1:
make_crossover_mean(target,parent1,parent2);
break;
case 2:
make_crossover_2_points(target, parent1, parent2);
break;
case 3:
make_mutation(target, parent1);
break;
case 4:
make_crossover_probability(target, parent1, parent2);
break;
default:
cout << "Creation type not avaible" << endl;
return false;
}
return true;
}
bool UserOperators::operatorAdministration(int method, const std::vector<double> &operatorPerformance)
{
cout << "UserOperators::operatorAdministration is not active - contact developers" << endl;
exit(1);
// if it has an administrator, pass to him.
switch(method)
{
case 0:
break;
case 1:
//if(operatorPerformance[0] > 2.0e0)
//crossoverWeight = AuxMathGa::randomNumber(0.5e0,0.9e0);
break;
case 2:
break;
case 3:
//if(operatorPerformance[0] > 2.0e0)
//mutationValue = AuxMathGa::randomNumber(0.05e0,0.3e0);
break;
case 4:
//if(operatorPerformance[0] > 2.0e0)
//crossoverWeight = AuxMathGa::randomNumber(0.5e0,0.9e0);
break;
default:
cout << " administration of this operator undefined - contact developers " << endl;
exit(2);
}
return true;
}
| true |
dc47d966dc920ffc77727ee7996f4d76df46a428 | C++ | raj075512/Coding-Questions | /Climbing_the_Leaderboard.cpp | UTF-8 | 1,691 | 4.03125 | 4 | [] | no_license | /*
Alice is playing an arcade game and wants to climb to the top of the leaderboard and wants to track her ranking.
The game uses Dense Ranking, so its leaderboard works like this:
The player with the highest score is ranked number on the leaderboard.
Players who have equal scores receive the same ranking number, and the next player(s) receive the immediately
following ranking number.
For example, the four players on the leaderboard have high scores of 100, 90 , 90 , and 80 . Those players will have ranks
1 , 2 , 2 , and 3 , respectively. If Alice's scores are 70, 80 and 105, her rankings after each game are 4th, 3rd and 1st.
Function Description
Complete the climbingLeaderboard function in the editor below. It should return an integer array where each element
represents Alice's rank after the jth game.
climbingLeaderboard has the following parameter(s):
scores: an array of integers that represent leaderboard scores
alice: an array of integers that represent Alice's scores
Sample Input 1:
7
100 100 50 40 40 20 10
4
5 25 50 120
Sample Output 1:
6 4 2 1
Sample Input 2:
6
100 90 90 80 75 60
5
50 65 77 90 102
Sample Output 2:
6 5 4 2 1
*/
vector<int> climbingLeaderboard(vector<int> s, vector<int> a)
{
vector<int> v(a.size());
int i,j=0,pos=1,k=a.size()-1;
for(i=k;i>=0;i--)
{
for(;j<s.size();j++)
{
if(a[i]>=s[j])
{
v[k--]=pos;
break;
}
if(s[j]!=s[j-1])
{
pos++;
}
}
}
while(k>=0)
{
v[k--]=pos;
}
return v;
} | true |
ef6f0dcc04af26f65aa76f4da02357a5fc57cc10 | C++ | AbhishekChahar/Concept_Building_All | /5Searching-Sorting/Sorting/7_Merge.cpp | UTF-8 | 773 | 2.578125 | 3 | [] | no_license | // #include<bits/stdc++.h>
// using namespace std;
// int main(){
// int n,m;
// cin>>n>>m;
// int arr1[n];
// int arr2[m];
// for(int i =0 ; i< n ; i++){
// cin>>arr1[i];
// }
// for(int i =0 ; i< m ; i++){
// cin>>arr2[i];
// }
// int merge[n+m];
// int first=0, second=0;
// for(int i=0; i< n+m; i++){
// if(first == n){
// merge[i] = arr2[second++];
// }
// else if(second==m){
// merge[i] = arr1[first++];
// }
// else if(arr1[first]<=arr2[second] && first<n){
// merge[i] = arr1[first++];
// }
// else if(arr1[first]>arr2[second] && second<m){
// merge[i] = arr2[second++];
// }
// }
// cout<<endl;
// for(auto x: merge){
// cout<<x<<" ";
// }
// return 0;
// } | true |
248ff4f6720b60f7038e1465cbf0172e71256c29 | C++ | RevealMind/itmo | /algorithms_and_data_structures/term_3/lab_3/a.cpp | UTF-8 | 1,144 | 2.859375 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <vector>
std::string s;
using std::size_t;
using std::vector;
void solve() {
size_t k, a, b, c, d;
std::cin >> s >> k;
size_t n = s.size();
vector<long long> pow(n);
vector<long long> hash(n);
pow[0] = 1;
for (int i = 1; i < n; ++i) {
pow[i] = pow[i - 1] * 31;
}
for (int i = 0; i < n; i++) {
hash[i] = (s[i] - 'a' + 1) * pow[i] + ((i) ? hash[i - 1] : 0);
}
for (int i = 0; i < k; ++i) {
std::cin >> a >> b >> c >> d;
if ((b - a) == (d - c)) {
long long hash_first = hash[b - 1] - ((a - 1) ? hash[a - 2] : 0);
long long hash_second = hash[d - 1] - ((c - 1) ? hash[c - 2] : 0);
if (a < c) {
hash_first *= pow[c - a];
} else {
hash_second *= pow[a - c];
}
if (hash_first == hash_second) {
std::cout << "Yes";
} else {
std::cout << "No";
}
} else {
std::cout << "No";
}
std::cout << "\n";
}
}
int main() {
solve();
return 0;
} | true |
ca9acb920891b2803f37c1119d8b282008c7604e | C++ | ethankuehler/image_Maker | /image_maker/image_maker/Main.cpp | UTF-8 | 1,062 | 3.4375 | 3 | [
"BSD-3-Clause"
] | permissive | #include <iostream>
#include "easybmp.h"
#include <memory>
#include <functional>
const float PI = 3.14159265359;
const float DTOR = PI / 180;
std::unique_ptr<BMP> Make_Image(std::function<RGBApixel(int,int)> Func, int width, int hight);
int main(int argc, char* argv[]) {
auto func = [](int x, int y) -> RGBApixel {
++y;
++x;
int color = tan((x * y) * DTOR) * 255;
int other = tan((x * y) * DTOR) * 255;
int fith = tan((y * x) * DTOR) * 255;
RGBApixel pixel;
pixel.Red = color;
pixel.Blue = other;
pixel.Green = fith;
return pixel;
};
std::unique_ptr<BMP> image = Make_Image(func, 1920, 1080);
image->WriteToFile("C:/My Documents/visual studio 2015/Projects/image_Maker/image_maker/Debug/test.bmp");
return 0;
}
std::unique_ptr<BMP> Make_Image(std::function<RGBApixel(int, int)> Func, int width, int hight) {
std::unique_ptr<BMP> image = std::make_unique<BMP>();
image->SetSize(width, hight);
for(int x = 0; x < width; x++) {
for(int y = 0; y < hight; y++) {
image->SetPixel(x, y, Func(x,y));
}
}
return image;
}
| true |
eea382c48672a4cb1b7b4b4617c9748e32f16949 | C++ | VanshikaSingh10/DataStructures-Algorithms | /Leetcode Daily Challenge/May-2021/07. Delete Operation for Two Strings.cpp | UTF-8 | 1,045 | 3.71875 | 4 | [
"MIT"
] | permissive | /*
Delete Operation for Two Strings
================================
Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same.
In one step, you can delete exactly one character in either string.
Example 1:
Input: word1 = "sea", word2 = "eat"
Output: 2
Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea".
Example 2:
Input: word1 = "leetcode", word2 = "etco"
Output: 4
Constraints:
1 <= word1.length, word2.length <= 500
word1 and word2 consist of only lowercase English letters.
*/
class Solution
{
public:
int minDistance(string A, string B)
{
vector<vector<int>> dp(A.size() + 1, vector<int>(B.size() + 1, 0));
for (int i = 1; i <= A.size(); ++i)
{
for (int j = 1; j <= B.size(); ++j)
{
if (A[i - 1] == B[j - 1])
dp[i][j] = 1 + dp[i - 1][j - 1];
else
dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]);
}
}
return A.size() + B.size() - 2 * dp[A.size()][B.size()];
}
};
| true |
73ef7d37ee67190da727611e03963bad15b309b2 | C++ | PeterXUYAOHAI/basic_algo | /cpp/include/Stack_dynamic.h | UTF-8 | 657 | 3 | 3 | [] | no_license | //
// Created by XU YAOHAI on 4/2/2018.
//
// this stack uses dynamic memory to store references of the objects
#ifndef CPP_STACK_DYNAMIC_H
#define CPP_STACK_DYNAMIC_H
#include <cstdio>
template<typename T>
class Stack_dynamic{
public:
Stack_dynamic(size_t size); //constructor
Stack_dynamic(const Stack_dynamic&) = default; //Copy Constructor it will do shadowll copy
~Stack_dynamic(void);
void push(const T &item);
void pop(T &item);
bool isEmpty(void) const;
bool isFull(void) const;
private:
size_t _top,_size;
T *_stack;
};
#include "../src/Stack_dynamic.cpp"
//模板类必须写在一个文件里
#endif
| true |
7ce91c09fbc17f6e7ff53bff8b073e662a780392 | C++ | eitos/RTOS | /EiTOS/examples/mutexes.cpp | UTF-8 | 1,797 | 2.78125 | 3 | [
"Apache-2.0"
] | permissive | #include <avr/io.h>
#include <util/delay.h>
#include <OS.hpp>
#include <avr/interrupt.h>
#include "../drivers/serial.hpp"
Serial serial;
mutex mutex1;
mutex serialMutex;
void Task1() {
static uint8_t count = 0;
while (1) {
serialMutex.take();
serial.printf("Test %d\r\n", count++);
serialMutex.give();
}
}
void Task2() {
while (1) {
PORTB ^= (1 << PB1);
_delay_ms(100);
}
}
void Task3() {
while (1) {
PORTB ^= (1 << PB2);
_delay_ms(200);
}
}
void Task4() {
PORTB ^= (1 << PB0);
mutex1.take();
for (uint8_t i = 0; i < 50; ++i) {
serialMutex.take();
serial.printf("mutex taken %d!\n\r", i);
serialMutex.give();
PORTB ^= (1 << PB0);
_delay_ms(100);
}
mutex1.take(); // can't take second time - will halt here!
while (1) {
serialMutex.take();
serial.printf("error !\n\r");
serialMutex.give();
}
}
void mainTask() {
mutex1.take();
serialMutex.give();
sys::taskCreate(&Task1, 1, 0xFF);
sys::taskCreate(&Task2, 1, 0x20);
sys::taskCreate(&Task3, 1, 0x20);
sys::taskCreate(&Task4, 2, 0x20);
for (uint8_t i = 20; i > 0; --i) {
serialMutex.take();
serial.printf("Waiting... %d\r\n", i);
serialMutex.give();
_delay_ms(50);
}
mutex1.give(); // will unlock Task4 - with higer priority
while (1) {
serialMutex.take();
serial.printf("idle task\n\r");
serialMutex.give();
}
}
int main() {
serial.init(115200U);
serial.printf("START\n\r");
DDRB = (1 << PB0)|(1 << PB1)|(1 << PB2);
PORTB = 0;
sys::taskCreate(&mainTask, 1, 0xFF);
serial.printf("System BOOT\n\r");
sys::boot();
return 0;
}
| true |
996fcc3a27eec0f11d1ac26255caa2ece3d7a553 | C++ | svetthesaiyan/uni-projects-1st-year-2nd-trimester | /2021.02.19 Exercise 3/exercise_3.cpp | UTF-8 | 1,187 | 3.328125 | 3 | [] | no_license | // Да се сортира масив от 10 случайно генерирани цели числа в интервала от 0 до 100 във възходящ ред като се използва сортиране чрез вмъкване. Да се напишат функции за генериране на числата, извеждане на елементите на масива и за сортиране.
#include <iostream>
#include <ctime>
using namespace std;
void InsertionSort(int A[], int n)
{
int k, index;
for(int j=1; j<n; j++)
{
index=A[j];
k=j;
while(k>0&&(A[k-1]>index))
{
A[k]=A[k-1];
k=k-1;
}
A[k]=index;
}
}
void read(int numbers[], int array_size)
{
srand(static_cast<unsigned>(time(NULL)));
for(int i=0; i<array_size; i++)
{
numbers[i]=rand()%(100);
}
}
void print(int numbers[], int array_size)
{
for(int i=0; i<array_size; i++)
{
cout<<numbers[i]<<" ";
cout<<endl;
}
}
int main ()
{
int a[10];
read(a, 10);
cout<<"Изход преди сортиране: "<<endl;
print(a, 10);
InsertionSort(a,10);
cout<<"Изход след сортиране: "<<endl;
print(a, 10);
system("pause");
return 0;
}
| true |
8aab5d64da457d6022449da656604b0e2b12b262 | C++ | jagadeeshnelaturu/codeforces_solutions | /556A.cpp | UTF-8 | 287 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <cmath>
int main() {
int n;
std::cin >> n;
int numOnes = 0, numZeros = 0;
char temp;
while(n--) {
std::cin >> temp;
if(temp == '0') ++numZeros;
else if(temp == '1') ++numOnes;
}
std::cout << std::abs(numOnes - numZeros) << '\n';
}
| true |
7b1f4de92bd37ce24d2f0d7d7d1fa77afb9191bd | C++ | jiangqn/algorithm_problems_and_templates | /problems_classified_by_sources/codeforces/Round#477(div2)/A/A.cpp | UTF-8 | 1,049 | 2.640625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int INF = 0x3f3f3f3f;
const int maxn = 1005;
struct Node{
int h, m;
}E[maxn], F[maxn];
int diff(const Node& a, const Node& b){
return (b.h * 60 + b.m) - (a.h * 60 + a.m);
}
Node inc(Node a, int b){
a.h += b / 60;
a.m += b % 60;
if(a.m >= 60){
a.h++;
a.m -= 60;
}
return a;
}
int main()
{
int n, s;
scanf("%d%d", &n, &s);
for(int i = 0; i < n; i++){
scanf("%d%d", &E[i].h, &E[i].m);
F[i] = inc(E[i], 1);
}
bool flag = false;
Node base;
base.h = 0;
base.m = 0;
if(diff(base, E[0]) >= s + 1){
puts("0 0");
flag = true;
}
for(int i = 0; !flag && i < n - 1; i++){
int d = diff(F[i], E[i + 1]);
if(d >= 2 * s + 1){
Node t = inc(F[i], s);
printf("%d %d\n", t.h, t.m);
flag = true;
}
}
if(!flag){
Node t = inc(F[n - 1], s);
printf("%d %d\n", t.h, t.m);
}
return 0;
}
| true |
dda5eb7540b49b9696d9c8b5fb015b77253388df | C++ | asandler/mipt | /code/algorithms_oop/semester_4/06_bwt.cpp | UTF-8 | 2,636 | 2.875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string bwt_encode(const string& source) {
int p[1000] = {0}, c[1000] = {0}, cnt[1000] = {0}, pn[1000], cn[1000], n = source.length() + 1, classes = 1;
string s = source + '~';
for (int i = 0; i < n; i++) {
cnt[s[i]]++;
}
for (char c = 32; c < 127; c++) {
cnt[c] += cnt[c - 1];
// the last index in p[] on which string c* could be placed
// numbering from 1
}
for (int i = 0; i < n; i++) {
p[--cnt[s[i]]] = i;
}
c[p[0]] = 0;
for (int i = 1; i < n; i++) {
if (s[p[i]] != s[p[i - 1]]) {
classes++;
}
c[p[i]] = classes - 1;
}
for (int h = 0; (1 << h) < n; h++) {
for (int i = 0; i < n; i++) {
pn[i] = p[i] - (1 << h);
if (pn[i] < 0) {
pn[i] += n;
}
}
for (int i = 0; i < 1000; i++) {
cnt[i] = 0;
}
for (int i = 0; i < n; i++) {
cnt[c[pn[i]]]++;
}
for (int i = 1; i < classes; i++) {
cnt[i] += cnt[i - 1];
}
for (int i = n - 1; i >= 0; i--) {
p[--cnt[c[pn[i]]]] = pn[i];
}
cn[p[0]] = 0;
classes = 1;
for (int i = 1; i < n; i++) {
int mid1 = (p[i] + (1 << h)) % n, mid2 = (p[i - 1] + (1 << h)) % n;
if (c[p[i]] != c[p[i - 1]] || c[mid1] != c[mid2]) {
++classes;
}
cn[p[i]] = classes - 1;
}
for (int i = 0; i < n; i++) {
c[i] = cn[i];
}
}
string answer = "";
for (int i = 0; i < n; i++) {
answer += s[(p[i] + n - 1) % n];
/* printing the BWT table */
/*
for (int j = 0; j < n; j++) {
cout << s[(p[i] + j) % n];
}
cout << endl;
*/
}
return answer;
}
bool comp(const pair<char, int> a, const pair<char, int> b) {
return a.first < b.first;
}
string bwt_decode(const string& code) {
pair<char, int> c[code.length() + 1];
int n = code.length();
string answer = "";
for (int i = 0; i < n; i++) {
c[i] = make_pair(code[i], i);
}
stable_sort(c, c + n, &comp);
int start = 0;
for (int i = 0; i < n && code[i] != '~'; i++, start++)
;
for (int i = 0; i < n - 1; i++) {
answer += c[start].first;
start = c[start].second;
}
return answer;
}
int main() {
string s;
cin >> s;
cout << bwt_decode(bwt_encode(s)) << endl;
}
| true |
af977980dcbb03a9ae7b5688fa4e10eb3dc06093 | C++ | demonsheart/C- | /rongyu/homework1/file/2017047011_1182_正确_439.cpp | UTF-8 | 596 | 2.90625 | 3 | [] | no_license | #include<iostream>
#include<cstring>
#define N 100
using namespace std;
char *strAdd(char *s1, char *s2)
{
char *s3;
s3=new char[200];
int i,j;
i=j=0;
while(*(s1+j)!='\0')
{
s3[i]=s1[j];
j++;
i++;
}
j=0;
while(*(s2+j)!='\0')
{
s3[i]=s2[j];
j++;
i++;
}
return s3;
}
int main()
{
int t,leng;
char str1[N],str2[N],str3[N];
char *p1,*p2,*p3;
cin>>t;
cin.ignore(1,'\n');
while(t--)
{
cin.getline(str1,100);
cin.getline(str2,100);
p1=str1;
p2=str2;
p3=str3;
p3=strAdd(p1,p2);
cout<<str1<<' ';
cout<<str2<<' ';
cout<<p3<<endl;
}
}
| true |
1b48d625610882cac0441abe6edecb1af6fa367f | C++ | Meaha7/DSA-Marathon | /Graphs/component_detection.cpp | UTF-8 | 945 | 3.234375 | 3 | [] | no_license | #include<iostream>
#include<vector>
using namespace std;
int get_comp(vector<vector<int>>&adjlst, int visited[], int curr)
{
if(visited[curr])
return 0;
visited[curr]=1;
int ans=1;
for(auto i : adjlst[curr])
{
if(visited[i]==0)
{
ans+=get_comp(adjlst,visited,i);
}
}
return ans;
}
int main()
{
int i,j,v,e,x,y;
cout<<"Enter the num of Vertices and Edges : ";
cin>>v>>e;
vector<vector<int>>adjlst(v);
cout<<"\nEnter the Edges : ";
for(i=0;i<e;i++)
{
cin>>x>>y;
//x -- y
adjlst[x].push_back(y);
adjlst[y].push_back(x);
}
int visited[v]={0};
vector<int>components;
for(i=0;i<v;i++)
{
if(visited[i]==0)
{
int size=get_comp(adjlst,visited,i);
components.push_back(size);
}
}
} | true |
0d1fa1e9839cdd7b31bfc550f54554d796247f48 | C++ | AmrARaouf/algorithm-detection | /graph-source-code/416-E/7359875.cpp | UTF-8 | 2,261 | 2.765625 | 3 | [
"MIT"
] | permissive | //Language: GNU C++0x
#include <iostream>
#include <vector>
int IntMaxVal = (int) 1e20;
#define minimize(a, b) { a = min(a, b); }
using namespace std;
template <typename T> vector<T> readVector(int n) { vector<T> res(n); for (int i = 0 ; i < n ; i++) cin >> res[i]; return res; }
const int MAXN = 500;
vector<int> allVertices; // helper array to iterate all vertices
int allMinDist[MAXN + 1][MAXN + 1];
class cEdge {
public:
int v1;
int v2;
int len;
};
istream& operator >>(istream& is, cEdge &e) { is >> e.v1 >> e.v2 >> e.len; return is; }
void FloydWarshall(vector<cEdge> &edges) {
for (auto v1 : allVertices) for (auto v2 : allVertices) allMinDist[v1][v2] = IntMaxVal;
for (auto v : allVertices) allMinDist[v][v] = 0;
for (auto &edge : edges) {
allMinDist[edge.v1][edge.v2] = allMinDist[edge.v2][edge.v1] = edge.len;
}
for (auto v3 : allVertices) for (auto v1 : allVertices) for (auto v2 : allVertices) {
if (allMinDist[v1][v3] != IntMaxVal && allMinDist[v3][v2] != IntMaxVal) {
minimize(allMinDist[v1][v2], allMinDist[v1][v3] + allMinDist[v3][v2]);
allMinDist[v2][v1] = allMinDist[v1][v2];
}
}
}
int main() {
int n; cin >> n;
int m; cin >> m;
for (int i = 0 ; i < n ; i++) allVertices.push_back(i + 1);
auto edges = readVector<cEdge>(m);
FloydWarshall(edges);
int inEdges[n + 1][n + 1];
for (auto v1 : allVertices) for (auto v2 : allVertices) inEdges[v1][v2] = 0;
for (auto &edge : edges) {
for (auto v : allVertices) {
if (allMinDist[v][edge.v1] + edge.len == allMinDist[v][edge.v2]) inEdges[v][edge.v2]++;
if (allMinDist[v][edge.v2] + edge.len == allMinDist[v][edge.v1]) inEdges[v][edge.v1]++;
}
}
for (auto source : allVertices) {
for (int j = source + 1 ; j <= n ; j++) {
int count = 0;
for (auto mid : allVertices) {
if (allMinDist[source][mid] + allMinDist[mid][j] == allMinDist[source][j]) count += inEdges[source][mid];
}
cout << count << ' ';
}
}
} | true |
c39484ce8aeaed59d99d5ef7b23a061d11c65528 | C++ | staddy/IntelligentDesign | /entitycontainer.h | UTF-8 | 672 | 2.6875 | 3 | [] | no_license | #ifndef ENTITYCONTAINER_H
#define ENTITYCONTAINER_H
#include <memory>
#include <functional>
#include "entity.h"
namespace evol {
class EntityContainer {
public:
EntityContainer() = default;
virtual ~EntityContainer() = default;
virtual void clear() = 0;
virtual bool emplace(std::shared_ptr<Entity>&& entity_) = 0;
virtual void update(std::function<void(std::shared_ptr<Entity>&& entity_)> emplaceToParent_ = nullptr) = 0;
virtual std::vector<std::shared_ptr<Entity> > entities(const Rectangle& bounds_ = Rectangle::INF) = 0;
virtual std::vector<std::shared_ptr<Entity> > entities(const Entity& entity_);
};
}
#endif // ENTITYCONTAINER_H
| true |
2a9ca3d12736d272e8fb02f2a6a53b4ea0fd80a9 | C++ | songxinjianqwe/CppPrimerCode | /Charpter16/src/600templateParameterInference.cpp | GB18030 | 17,631 | 3.734375 | 4 | [] | no_license | /*
* 600templateParameterInference.cpp
*
* Created on: 2016929
* Author: songx
*/
#include <iostream>
#include <string>
#include <type_traits>
using namespace std;
//ģʵƶ
//ںģ壬õеĺʵȷģӺʵȷģʵεḺ́Ϊģʵƶϡ
//ģʵƶϹУʹúеʵѰģʵΣЩģʵɵĺ汾ĺΪƥ
//
//תģͲ
//
//ֻкļתԶӦЩʵΡͨǶʵνתһµģʵ
//constᱻ
//תУڵӦںģİ
//constת:constתconstáָ룩
//ָתתΪԪָ룻תΪָ룩
//תתתԼûתںģ
//ע⣺ͬģΪãʵСͬôͨΪͬ
//ϣԺʵνתǿԽģ嶨ΪͲ
template<typename A,typename B>
int flexibleCompare(const A & v1,const B& v2){
if(v1 < v2){
return -1;
}else if(v1 > v2){
return 1;
}else{
return 0;
}
}
//ģ ͨ͵IJֺʵβԽת
template<typename T>
ostream & print(ostream &os,const T & obj){
return os<<obj;
}
//һʵοofstreamתΪostream &
//Ͳģʵνת
//**********************************************************************************
//ģʾʵ
//ijЩ£ƶϳģʵεͣ£ϣûģʵбκͶͬʱ֡
//ָʽģʵ
//
template <typename T1,typename T2,typename T3>
T1 sum(T2 t1,T3 t2){
return t1+t2;
}
//ûκκʵεͿƶT1͡ÿεsumʱ߶ΪT1ṩһʾģʵΡ
//ṩʽģʵεķʽ붨ģʵķʽͬʾģʵڼиλں֮б֮ǰ
int i = 2;
long lng = 23;
auto val3 = sum<long long>(i,lng);
//ʽģʵɴҵ˳Ӧģƥ䣻һģʵһģƥ䣬ơ
//ֻҲʽģʵοԺԣǰǿԴӺƶϳ
//
template <typename T1,typename T2,typename T3>
T3 alternative_sum(T2 t1 ,T1 t2){
return t1+t2;
}
//Ҫ
auto val2 = alternative_sum<long long,int,long>(i,lng);
//ģͲѾʽָ˵ĺʵΣҲת
template<typename T>
int compare(T t1,T t2){
if(t1 < t2){
return -1;
}else if(t1 > t2){
return 1;
}else{
return 0;
}
}
void test40(){
compare<long>(lng,1024);//ȷʵcompare(long,long)
compare<int>(lng,1024);//ȷʵcompare(int,int)
}
//ʽָģͲͿԽתˡˣcompare<long>1024ԶתΪlong;compare<int>lngԶתΪint
//****************************************************************************************************************
//β÷ת
//ϣûȷʱʽģʾģ庯ķЧ
//£Ҫʽָģʵλû⸺Ҳʲôô
//template <typename It>
//??? & fcn(It being,It end){
// return *begin;
//}
//Dz֪ؽȷ֪ͣеԪ
//֪Ӧ÷*begin֪ǿdecltype(*begin)ȡ˱ʽ
//ǣڱIJб֮ǰbeginDzڵġΪ˶˺DZʹβ÷͡
//β÷سںб֮ʹúIJ
template<typename It>
auto fcn(It begin,It end) -> decltype(*begin){
return *begin;
}
//һֵ
//ʹתıģ
//ʱֱӻҪͣϣһԪصֵ
//еԪأֻԪصá
//Ϊ˻Ԫصͣǿʹñתģ塣ͷļtype_traitsС
//ǿʹremove_referenceԪ࣬ģһģͲһΪtypeͳԱ
//һʵremove_referencetypeʾõ͡
//ʵremove_reference<int&>typeԱint
//remove_reference<decltype(*begin)>::typebeginָԪصֵ
//ȥãʣԪͱ
template<typename It>
auto fcn2(It begin,It end) ->typename remove_reference<decltype(*begin)>::type{
return *begin;
}
//typeһijԱһģˣDZڷ͵ʹtypename֪typeʾһ͡
//emove_reference
//add_const
//add_lvalue_reference
//add_rvalue_reference
//remove_pointer
//ÿģ嶼һΪtypepublicԱʾһ͡
//תģtypeԱģͱ
//**************************************************************************************************************
//һģʼһָΪһָ븳ֵʱʹָƶģʵΡ
template<typename T>
int compare(const T &,const T &);
int (*pf)(const int &,const int &) = compare;
//pfв;Tģʵ͡TģʵΪintָpfָcompareint汾ʵܴӺָȷʵΣ
void func(int(*)(const string & ,const string &));
void func(int(*)(const int &,const int &));
void test41(){
// func(compare);
//
}
//ͨfuncIJȷģʵεΨһ
//ǿͨʹʽģʵfunc
//func(compare<int>);
//˱ʽõfunc汾һָ룬ָָĺconst int &
//һģʵĵַʱı㣻ÿģΨһȷͻֵ
//************************************************************************************************************
//ģʵƶϺ
//ֵúƶ
//һģͲһֵͨã涨ǣֻܴݸһֵ
//ʵοconstͣҲԲǣʵconstTƶΪconst
template<typename T>
void f1(T&){//ʵαΪһֵ
}
void test46(){
int i = 2;
f1(i);
long lng = 23;
f1(lng);
// f1(5);//error ֵ
}
//һconst T&İǿԴݸκ͵ʵΣһʱ
//constʱTƶϽһconst͡constѾǺ͵һ֡ˣҲģ͵һ֡
template<typename T>
void f2(const T &){//Խһֵֵ
}
void test47(){
int i = 2;
f2(i);
const int ci = 23;
f2(ci);
f2(5);
//ΪTconstģʵеconstص
//ÿУf2ĺƶΪconst int &TƶΪint
}
//ֵúƶ
//һֵͣT&&ǿԴݸһֵʱƶϹֵͨúƶϹ̡
//ƶϳTǸֵʵε
template<typename T>
void f3(T&&){
}
//f3(42);//ʵint&&ģTΪint
//ƶǸTη& && consttͣTt͵һ֣const T &/&& tʵ
//f(T&) f(i) T = int type(i) = T & = int &
//f(T) f(42) T = int
//f(T &) f(ci) T = const int type(ci) = T & = const int &
//ǣһֵôT&&,ʵDzԵģΪֵָ֧۵ʵƶϺDzͬġ
//T&& = ͣT = ͣȻ &&ٽ۵
//f(T &&) f(i) T = int & type(i) = T && = int & && = int &
//f(T &&) f(42) T = int && type(42) = T && = int && && = int &&
//*****************************************************************************************************************
//۵ֵò
//iintͣôf3(i)DzϷģΪiһֵͨܽһֵðֵϡ
//C++֮ⶨְmoveĻ
//һǵǽһֵݸֵòҴֵģͲT&&ʱƶģͲ(!Ǻ)Ϊʵεֵ͡
//ΪTƶΪint &,T&& int & &&
//ͨDzֱӶһõãͨͱͨģͲӶǿԵġ
//ڴ£ڶǣǼӴһõãЩγ۵£һ⣩û۵һֵͨ͡
//ֻһû۵Ϊֵãֵõֵá
//X
//X & X& && X&& & ᱻ۵X&
//X&& && ᱻ۵X&&
//۵ֻڼӴõãͱģ
//ǿԽκͲݸf3.ǽһֵݸf3ʱƶTΪһֵá
//f3(i) T-> int &
//f3(ci) T-> const int &
//һģƶΪͣ۵ǺT&&۵Ϊһֵ͡
//ڣvoid f3<int &>(int & &&)
//ʹf3IJʽһֵã˵Ҳһֵʵf3
//void f3<int &>(int &)
//Ҫ
//1.һһָģͲֵãԱһֵ
//2.ʵʱһֵƶϳģʵһֵãҺʵΪһֵͨòT&
//Խ͵ʵδݸT&&͵ĺ͵ĺԴݸֵҲԴݸֵ
//дֵòģ庯
template <typename T>
void f4(T && val){
T t = val;//ǰ
t = fcn(t);//ֵֻıtǼȸıtָıval
if(val == t){
}
}
//漰ͼȿǷͣҲʱдȷĴͱ÷dzѡ
//ʵֵͨģתʵλģ
//***********************************************************************************************************
//move
//Ȼֱӽһֵðһֵϣmoveһֵϵֵ
//moveĶ
template<typename T>
typename remove_reference<T>::type && move(T && t){
return static_cast<typename remove_reference<T>::type &&>(t);
}
//moveĺT&&һָģͲֵáͨ۵˲κ͵ʵƥ䡣ǼȿԴݸmoveһֵֿԴݸmoveһֵ
//ʾ1
//move(string("bye"));
//ƶϳTstring
//ˣremove_referenceʹstringʵ
//remove_reference<string>typeԱstring
//moveķstring&&
//moveIJtstring&&
//ʵmove: string&&move(string&& t)
//תʲô˵õĽֵܵ
//ʾ2
//string s1("bye");
//move(s1);
//ƶϳTstring&
//ˣremove_referenceʹstring&ʵ
//remove_reference<string&>ijԱstring
//moveķstring&&
//moveĺtʵΪstring& && ۵Ϊstring&
//ʵstring && move(string & t)
//һֵstatic_castһֵ
//*********************************************************************************
//ת
//ijЩҪһʵͬͲתڴ£Ҫֱתʵε,ʵǷconstԼʵֵorֵ
template <typename F,typename T1,typename T2>
void flip1(F f,T1 t1,T2 t2){
f(t2,t1);
}
//fΪһòĺǻ
void f(int v1,int & v2){
cout<<v1<<" "<<++v2<<endl;
}
//fı˰v2ʵεֵͨflip1ffĸıͲӰʵΡ
//flip(f,j,42)
//jݸt1һͨintint&jֵt1,t1ĸı䲻Ӱj
//ˣflip1ʵΪ
//void flip1(void (*fcn)(int, int &),int t1,int t2);
//ܱϢĺ
//ϣֵorֵԣϣֲconstԡ
//ͨΪһָģͲֵãǿԱӦʵεϢ
//ʹòʹǿԱconstԣ
//Ϊеconstǵײģconst& ãָͨĶֵconst * ָָ룬ָͨıָĶֵ
//ǽΪT1 && T2 &&ͨ۵ͿԱַתʵεֵԡ
template<typename F,typename T1,typename T2>
void flip2(F f,T1 && t1,T2 && t2){
f(t2,t1);
}
//һָģͲֵãӦʵεconstԺֵԽõ֡
//汾һ⣬ڽһֵõĺúܺãڽֵòĺ
void g(int && i,int &j){
cout<<i<<" "<<j<<endl;
}
//ͨflip2gôt2ݸgֵòiʹǴݸһֵflip2
//flip2(g,i,42)//errorܴһֵʵint&&
//καһֵʽȻt2ֵãһʱʽһֵ
//ֵDzֱӰֵϵģ
//ת std:;forward
//ǿʹforwardʩflip2IJܱԭʼʵεͣʱƶϳͣ
//forwardͷļutilityС
//forwardͨʽģʵãظʾʵε͵ֵãforward<T> ķT&&
//ͨ£ʹforwardЩΪģͲֵõĺͨ䷵ϵ۵forwardԱָʵεֵԡ
template <typename Type>
void intermediary(Type && args){
finalFcn(forward<Type>(args));
}
//TypeforwardʽģʵͣǴargsƶϳġ
//argsһģʵεֵãTypeʾݸargsʵεϢ
//ʵһֵôTypeһͨ(Type && = args && --> Type = args)forward<Type>Type&&
//ʵһֵͨ۵Typeһֵ (Type = args & )
//forward<Type>۵һֵ
//!!!!!!!!!!!!!!ؼforward<Type> еTypeǵʱƶϳͣҲģʵεͣûתġ
//ʾ
template<typename F,typename T1,typename T2>
void flip(F f, T1 && t1,T2 && t2){
f(forward<T2>(t2),forward<T1>(t1));
}
| true |
c2d02b2cb8eff86f4d6c24fdf29db9cd0b2d36b7 | C++ | DarkMaguz/rpr01 | /rpr01/src/direct_io_test.cpp | UTF-8 | 3,126 | 2.6875 | 3 | [
"FSFAP"
] | permissive | /*
* direct_io_test.cpp
*
* Created on: 05/12/2015
* Author: magnus
*/
//
// How to access GPIO registers from C-code on the Raspberry-Pi
// Example program
// 15-January-2012
// Dom and Gert
// Revised: 15-Feb-2013
#define PI_VERSION 2
// Access from ARM Running Linux
#if PI_VERSION == 1
#define BCM2708_PERI_BASE 0x20000000
#elif PI_VERSION == 2
#define BCM2708_PERI_BASE 0x3F000000
#endif
#define GPIO_BASE (BCM2708_PERI_BASE + 0x200000) // GPIO controller
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#define PAGE_SIZE (4*1024)
#define BLOCK_SIZE (4*1024)
int mem_fd;
void *gpio_map;
// I/O access
volatile unsigned *gpio;
// GPIO setup macros. Always use INP_GPIO(x) before using OUT_GPIO(x) or SET_GPIO_ALT(x,y)
#define INP_GPIO(g) *(gpio+((g)/10)) &= ~(7<<(((g)%10)*3))
#define OUT_GPIO(g) *(gpio+((g)/10)) |= (1<<(((g)%10)*3))
#define SET_GPIO_ALT(g,a) *(gpio+(((g)/10))) |= (((a)<=3?(a)+4:(a)==4?3:2)<<(((g)%10)*3))
#define GPIO_SET *(gpio+7) // sets bits which are 1 ignores bits which are 0
#define GPIO_CLR *(gpio+10) // clears bits which are 1 ignores bits which are 0
#define GET_GPIO(g) (*(gpio+13)&(1<<g)) // 0 if LOW, (1<<g) if HIGH
#define GPIO_PULL *(gpio+37) // Pull up/pull down
#define GPIO_PULLCLK0 *(gpio+38) // Pull up/pull down clock
void setup_io();
void printButton( int g )
{
if ( GET_GPIO( g ) ) // !=0 <-> bit is 1 <- port is HIGH=3.3V
printf( "Button pressed!\n" );
else
// port is LOW=0V
printf( "Button released!\n" );
}
int main( int argc, char **argv )
{
// Set up gpi pointer for direct register access
setup_io();
/************************************************************************\
* You are about to change the GPIO settings of your computer. *
* Mess this up and it will stop working! *
* It might be a good idea to 'sync' before running this program *
* so at least you still have your code changes written to the SD-card! *
\************************************************************************/
int g = 4;
// Set GPIO pin 4 to output
INP_GPIO( g ); // must use INP_GPIO before we can use OUT_GPIO
OUT_GPIO( g );
for ( int i = 0; i < 3; i++ )
{
GPIO_SET = 1 << g;
sleep( 1 );
GPIO_CLR = 1 << g;
sleep( 1 );
}
return 0;
}
// Set up a memory regions to access GPIO
void setup_io()
{
// open /dev/mem
if ( ( mem_fd = open( "/dev/mem", O_RDWR | O_SYNC ) ) < 0 )
{
printf( "can't open /dev/mem \n" );
exit( -1 );
}
// mmap GPIO
gpio_map = mmap(
NULL, //Any adddress in our space will do
BLOCK_SIZE, //Map length
PROT_READ | PROT_WRITE, // Enable reading & writting to mapped memory
MAP_SHARED, //Shared with other processes
mem_fd, //File to map
GPIO_BASE //Offset to GPIO peripheral
);
close( mem_fd ); //No need to keep mem_fd open after mmap
if ( gpio_map == MAP_FAILED )
{
printf( "mmap error %d\n", (int)gpio_map ); //errno also set!
exit( -1 );
}
// Always use volatile pointer!
gpio = (volatile unsigned *)gpio_map;
}
| true |
488f0fce9a311770b8f8896c3fd48787804321dc | C++ | mkuthan/example-arduino | /DigitalReadSerial/DigitalReadSerial.ino | UTF-8 | 274 | 2.671875 | 3 | [] | no_license | int pushButton = 2;
int led = 13;
void setup() {
Serial.begin(9600);
pinMode(pushButton, INPUT);
pinMode(led, OUTPUT);
}
void loop() {
int buttonState = digitalRead(pushButton);
int ledState = (buttonState == 1) ? HIGH : LOW;
digitalWrite(led, ledState);
}
| true |
e49c1fc2f13ec2c5c29cbf946a217dab741e5319 | C++ | RocketfarmAS/iot-examples | /vibration/vibration.ino | UTF-8 | 672 | 2.84375 | 3 | [] | no_license |
const int knockSensor = A0; // the piezo is connected to analog pin 0
const int threshold = 400; // threshold value to decide when the detected sound is a knock or not
int sensorReading = 0; // variable to store the value read from the sensor pin
int ledState = LOW; // variable used to store the last LED status, to toggle the light
void setup() {
// Init usb logging
Serial.begin(19200);
}
void loop() {
sensorReading = analogRead(knockSensor);
if (sensorReading >= threshold) {
Serial.println("Knock!");
// Poor mans debounce :)
delay(150);
}
delay(10); // delay to avoid overloading the serial port buffer
}
| true |
db89414205953d48eb7cf585fc6971f5b62b80ed | C++ | se-prashant/Data-Structures-And-Algorithms | /Maths And Array/13_SearchIn2DMatrix.cpp | UTF-8 | 548 | 2.9375 | 3 | [] | no_license | class Solution {
public:
bool searchMatrix(vector<vector<int>>& mat, int target) {
int N = mat.size();
int M = mat[0].size();
int s = 0;
int e = (N*M)-1;
while(s<=e){
int mid = (s+e)/2;
int row = mid/M;
int col = mid%M;
if(mat[row][col]==target){
return true;
}
if(mat[row][col]>target){
e = mid-1;
}else{
s = mid+1;
}
}
return false;
}
};
| true |
75233b5f9fb8bd7f0a1df2c78514cc292e777d1b | C++ | mayankagg9722/Placement-Preparation | /leetcode/bottomLeftMostTree.cpp | UTF-8 | 1,159 | 3.5625 | 4 | [] | no_license | /**
513. Find Bottom Left Tree Value
Given a binary tree, find the leftmost value in the last row of the tree.
Example 1:
Input:
2
/ \
1 3
Output:
1
Example 2:
Input:
1
/ \
2 3
/ / \
4 5 6
/
7
Output:
7
Note: You may assume the tree (i.e., the given root node) is not NULL.
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int height=INT_MIN;
int ans;
void util(TreeNode* root,int h){
if(root==NULL){
return;
}
int x=h;
int val;
TreeNode* temp=root;
while(temp!=NULL){
x++;
val=temp->val;
temp=temp->left;
}
if(height<x){
height=x;
ans=val;
}
util(root->left,h+1);
util(root->right,h+1);
}
int findBottomLeftValue(TreeNode* root) {
if(root==NULL){
return 0;
}
util(root,1);
return ans;
}
}; | true |
8e021389f91e220b9753243de8f8f60211ebb8d3 | C++ | yolunghiu/algo_code | /nowcoder/class5/10_NodeNumber.cpp | UTF-8 | 1,376 | 3.71875 | 4 | [] | no_license | #include <iostream>
#include <BinaryTreeUtils.h>
#include <cmath>
using namespace std;
// 已知一棵完全二叉树, 求其节点个数, 要求时间复杂度低于O(n)
int getHeight(Node *root)
{
int height = 0;
Node *p = root;
while (p != nullptr)
{
height++;
p = p->left;
}
return height;
}
int getNodeNumber(Node *root)
{
if (root == nullptr)
return 0;
int height = getHeight(root);
int rightHeight = getHeight(root->right);
if (rightHeight == height - 1) // 左子树为完全二叉树
{
return pow(2, height - 1) + getNodeNumber(root->right);
} else // rightHeight == height - 2, 右子树为完全二叉树
{
return pow(2, rightHeight) + getNodeNumber(root->left);
}
}
int main()
{
Node *root = new Node(1);
root->left = new Node(2);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->right = new Node(3);
root->right->left = new Node(6);
root->right->right = new Node(7);
root->left->left->left = new Node(8);
// printTree(root);
cout << getNodeNumber(root) << endl;
root->left->left->right = new Node(9);
root->left->right->left = new Node(10);
root->left->right->right = new Node(11);
root->right->left->left = new Node(12);
cout << getNodeNumber(root) << endl;
return 0;
} | true |
ba6885a7072e76b421045ce59f4c15dc8e3f3d33 | C++ | rezwanh001/Image-Processing-using-Opencv-in-Cpp | /(09,10)Min_Max_Filter.cpp | UTF-8 | 1,391 | 2.890625 | 3 | [
"MIT"
] | permissive | #include <stdio.h>
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace cv;
using namespace std;
/*
(09,10)Min_Max_Filter.cpp
*/
int main(int argc, char const *argv[])
{
Mat img = imread("blurry_moon.tif", CV_LOAD_IMAGE_GRAYSCALE);
imshow("Input", img);
waitKey();
// Average filter
Mat avgImage ;
boxFilter(img, avgImage, -1, Size(3,3)); // // Perform mean filtering on image using boxfilter
imshow("Average Filter", avgImage);
waitKey();
// The functions "erode" and "dilate" are min and max filters, respectively.
Mat ker; // Use the default structuring element (kernel) for erode and dilate
// Min Filter
Mat minImage;
erode(img, minImage, ker);
imshow("Min Filter", minImage);
waitKey();
// Max filter
Mat maxImage;
dilate(img, maxImage, ker);
imshow("Max Filter", minImage);
waitKey();
/*********************/
float kdata4[9] = {
0, -1, 0,
-1,4, -1,
0,-1,0
};
Mat kernel = Mat(3, 3, CV_32F, kdata4);
Mat out, out2;
filter2D(img, out, CV_32F, kernel, Point(-1, -1));
imshow("Filter", out);
waitKey();
out2 = abs(out);
imshow("Abs Filter", out2);
waitKey();
Mat out3;
normalize(out2, out3, 0, 255, NORM_MINMAX, CV_8U);
imshow("NormMin_MAx", out3);
waitKey();
Mat fin = img + out3;
imshow("Final", fin);
waitKey();
return 0;
} | true |
ed751fcd89bb3e70def89e4be0b2455a113880b5 | C++ | sivikt/memoria | /include/memoria/core/packed/sseq/small_symbols_buffer.hpp | UTF-8 | 4,213 | 2.546875 | 3 | [
"BSD-3-Clause",
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive |
// Copyright 2015 Victor Smirnov
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <memoria/core/types.hpp>
#include <memoria/core/tools/dump.hpp>
#include <memoria/core/tools/assert.hpp>
#include <memoria/core/tools/bitmap.hpp>
namespace memoria {
template <int32_t BitsPerSymbol_, int32_t BufSize_ = BitsPerSymbol_ == 8 ? 16 : 1>
class SmallSymbolBuffer {
public:
static constexpr int32_t BitsPerSymbol = BitsPerSymbol_;
static constexpr int32_t BufSize = BufSize_;
private:
uint64_t symbols_[BufSize];
int32_t size_ = 0;
public:
uint64_t* symbols() {
return &symbols_[0];
}
const uint64_t* symbols() const {
return &symbols_[0];
}
int32_t symbol(int32_t n) const
{
MEMORIA_ASSERT(n, <, size_);
return GetBits(symbols(), n, BitsPerSymbol);
}
void set_symbol(int32_t n, int32_t symbol)
{
MEMORIA_ASSERT(n, <, size_);
SetBits(symbols(), n, symbol, BitsPerSymbol);
}
void set_symbols(int32_t n, int32_t symbol, int32_t nsyms)
{
MEMORIA_ASSERT(n, <, size_);
MEMORIA_ASSERT(nsyms, <=, (int32_t)sizeof(int32_t) * 8 / BitsPerSymbol);
return SetBits(symbols(), n, symbol, BitsPerSymbol * nsyms);
}
static constexpr int32_t max_size() {
return sizeof(uint64_t) * 8 / BitsPerSymbol;
}
int32_t capacity() const
{
int32_t max_size0 = max_size();
return max_size0 - size_;
}
void resize(int32_t size)
{
MEMORIA_ASSERT(size, <=, max_size());
this->size_ = size;
}
int32_t size() const {
return size_;
}
void append(int32_t symbol)
{
MEMORIA_ASSERT(size_, <, max_size());
int32_t pos = size_;
size_ += 1;
set_symbol(pos, symbol);
}
void dump(std::ostream& out = std::cout) const
{
dumpSymbols<int32_t>(out, size_, BitsPerSymbol, [this](int32_t pos) -> int32_t {
return this->symbol(pos);
});
}
};
template <int32_t BufSize_>
class SmallSymbolBuffer<8, BufSize_> {
public:
static constexpr int32_t BitsPerSymbol = 8;
static constexpr int32_t BufSize = BufSize_;
private:
uint8_t symbols_[BufSize];
int32_t size_ = 0;
public:
uint8_t* symbols() {
return &symbols_[0];
}
const uint8_t* symbols() const {
return &symbols_[0];
}
int32_t symbol(int32_t n) const
{
MEMORIA_ASSERT(n, <, size_);
return symbols_[n];
}
void set_symbol(int32_t n, int32_t symbol)
{
MEMORIA_ASSERT(n, <, size_);
symbols_[n] = symbol;
}
void set_symbols(int32_t n, int32_t symbols, int32_t nsyms)
{
MEMORIA_ASSERT(n, <, size_);
MEMORIA_ASSERT(nsyms, <, (int32_t)sizeof(int32_t));
for (int32_t c = 0; c < nsyms; c++)
{
symbols_[c + n] = (symbols & 0xFF);
symbols >>= 8;
}
}
static constexpr int32_t max_size() {
return BufSize;
}
int32_t capacity() const
{
int32_t max_size0 = max_size();
return max_size0 - size_;
}
void resize(int32_t size)
{
MEMORIA_ASSERT(size, <=, max_size());
this->size_ = size;
}
int32_t size() const {
return size_;
}
void append(int32_t symbol)
{
MEMORIA_ASSERT(size_, <, max_size());
int32_t pos = size_;
size_ += 1;
set_symbol(pos, symbol);
}
void dump(std::ostream& out = std::cout) const
{
dumpSymbols<int32_t>(out, size_, 8, [this](int32_t pos) -> int32_t {
return this->symbol(pos);
});
}
};
}
| true |
805e42629b5f5d356395d7aba7ac71acc5ea3175 | C++ | charitha22/workspace | /kd_tree/main.cpp | UTF-8 | 1,464 | 3.421875 | 3 | [] | no_license | #include <iostream>
#include "kd_tree.h"
int main(int, char**) {
srand (time(NULL));
// generate a set of 2d points
std::cout << "generate a set of points :" << std::endl;
std::vector<point<int,2>> points_2d;
generate_points<2>(points_2d,5);
std::for_each(points_2d.begin(), points_2d.end(),
[](point<int,2>& p){
std::cout << p << " ";
}
);
std::cout << "\n\n";
// construct a kd-tree with the points
std::cout << "TEST 01 : contruct a tree" << std::endl;
kd_tree<int, 2> tree(points_2d);
std::cout << tree << "\n\n";
// search for some point
std::cout << "TEST 02 : searching the tree for a point"<< std::endl;
std::vector<int> v1 = {1,2};
point<int,2> p1(v1);
std::cout << "point " << p1 <<
" FOUND : " << tree.search_point(p1) << "\n\n";
// add a point and search for it
std::cout << "TEST 03 : add a point and serach for it"<< std::endl;
std::vector<int> v2 = {32,982};
point<int,2> p2(v2);
tree.add_point(p2);
std::cout << "point " << p2 <<
" FOUND : " << tree.search_point(p2) << "\n\n";
// find nearset neighbor of a point
std::cout << "TEST 04 : find nearest neighbor of a point"<< std::endl;
std::vector<int> v3 = {32, 982};
point<int,2> p3(v3);
std::cout << "nearset neighbor of point " << p3 << " is " <<
tree.find_nearest_neighbour(p3) << "\n";
return 0;
}
| true |
813372ee5f1ebe42cecef3a27ca2af63748541ba | C++ | kerozou/kyopuro | /Atcoder解答/ARC解答/ARC002 C - コマンド入力.cpp | UTF-8 | 1,613 | 2.875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < n; i++)
#define all(x)(x).begin(), (x).end() // 昇順ソート
#define rall(v)(v).rbegin(), (v).rend() // 降順ソート
#define INF 1LL << 60
typedef long long int LL;
typedef long long int ll;
#define pll pair < ll, ll >
#define F first
#define S second
const int MOD = 1000000007;
template < class T > bool chmax(T & a,const T & b) { if (a < b) { a = b; return true; } return false; }
template < class T > bool chmin(T & a,const T & b) { if (a > b) { a = b; return true; } return false; }
// 任意のlogは 対数の底の変換を使う log(N) / log(任意の底)
int N;
string s;
int cal(char a,char b,char c,char d){
string L;
L += a;
L += b;
string R;
R += c;
R += d;
int ct = 0;
rep(i,N){
ct++;
if(i == N-1)break;
if(s.substr(i,2) == L || s.substr(i,2) == R)i++;
}
return ct;
}
int main() {
cin >> N;
cin >> s;
string lis = "ABXY";
int ans = 1e9;
for(auto a : lis){
for(auto b : lis){
for(auto c : lis){
for(auto d : lis){
ans = min(ans,cal(a,b,c,d));
}
}
}
}
cout << ans << endl;
}
// ARC002 C - コマンド入力
/*
substr の使いどころさん
基本的に毎ターンなんらかのボタンを押さなければならないので、とりあえずct++する。
そんで、2連結文字でいけるならそっちを採用してindexを一つ飛ばすという感じ。
結局貪欲。
*/ | true |
7782244a935e71dee20a7808bd2e1498b641face | C++ | zee7985/LeetCode | /DP/416. Partition Equal Subset Sum.cpp | UTF-8 | 1,332 | 3.359375 | 3 | [] | no_license | 416. Partition Equal Subset Sum
Medium
Given a non-empty array nums containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
Example 1:
Input: nums = [1,5,11,5]
Output: true
Explanation: The array can be partitioned as [1, 5, 5] and [11].
Example 2:
Input: nums = [1,2,3,5]
Output: false
Explanation: The array cannot be partitioned into equal sum subsets.
Constraints:
1 <= nums.length <= 200
1 <= nums[i] <= 100
class Solution {
public:
bool helper(vector<int>&nums,int i,int total,vector<vector<int>>&dp)
{
if(total==0)
{
return true;
}
if(i==nums.size()-1 || total<0)
{
return false;
}
if(dp[i][total]!=-1)
{
return dp[i][total];
}
int ans=(helper(nums,i+1,total-nums[i],dp)|| helper(nums,i+1,total,dp));
return dp[i][total]=ans;
}
bool canPartition(vector<int>& nums) {
int total=0;
for(auto a:nums)
{
total+=a;
}
if(total%2!=0) return false;
total/=2;
int n=nums.size();
vector<vector<int>> dp(n + 1, vector<int>(total + 1, -1));
return helper(nums,0,total,dp);
}
};
| true |
8201e1407333232fbe9d93b034b4ffd1360666aa | C++ | fjand5/arduino-tutorial | /struct_code/main/rtc.ino | UTF-8 | 747 | 2.53125 | 3 | [] | no_license |
// ============================== rtc.ino ==================================================
#include <Wire.h>
#include <RTC.h>
static DS1307 RTC;
void setupRTC() {
RTC.begin();
RTC.startClock();
}
String cvt2num(int num){
return num<10?String("0")+num:String(num);
}
String getDays(){
String day = cvt2num(RTC.getDay());
String month = cvt2num(RTC.getMonth());
String year = cvt2num(RTC.getYear());
return String(day + "/" + month + "/" + year);
}
String getTimes(){
String hours = cvt2num(RTC.getHours());
String minutes = cvt2num(RTC.getMinutes());
String seconds = cvt2num(RTC.getSeconds());
return String(hours + ":" + minutes + ":" + seconds);
}
void loopRTC() {
// put your main code here, to run repeatedly:
}
| true |
886d4bfc51cfb9d1ea92341ec4285f48f1935a25 | C++ | Ewenwan/ZJU_PAT | /Advanced_Level/1042. Shuffling Machine (20).cpp | UTF-8 | 869 | 3.203125 | 3 | [] | no_license | #include<iostream>
using namespace std;
const int M = 54;
/*
题意:按照给定交换规则排序。基础逻辑题
思路:比较简单,用两个数组a,b
a存储交换前的,b存储交换后的。
*/
int main(void)
{
freopen("in.txt", "r", stdin);
int a[M], b[M], ord[M];
int n;
char ch[5] = { 'S', 'H', 'C', 'D', 'J' };//为了便于输出
cin >> n;
for (int i = 0; i < M; i++)//初始化
a[i] = i;
for (int i = 0; i < M; i++)
{
int tem;
cin >> tem;
ord[i] = tem - 1;//为了便于处理,把题中的位置-1;
}
for (int i = 0; i < n; i++)//循环洗牌n次
{
for (int j = 0; j < M; j++)
b[ord[j]] = a[j];
for (int j = 0; j < M; j++)
a[j] = b[j];
}
for (int i = 0; i < M; i++)//输出
{
if (i == 0)
cout << ch[a[i] / 13] << a[i] % 13 + 1;
else
cout << ' ' << ch[a[i] / 13] << a[i] % 13 + 1;
}
return 0;
}
| true |
d7556127bd7ed37568e21487ff8516200e4820fe | C++ | Ferrari95/AI-Lab | /homework1/src/min_distance.cpp | UTF-8 | 1,069 | 2.5625 | 3 | [] | no_license | #include "ros/ros.h"
#include "stdlib.h"
#include "string.h"
#include "std_msgs/String.h"
#include "sensor_msgs/LaserScan.h"
typedef const boost::function < void(const sensor_msgs::LaserScan::ConstPtr&) > callback;
class minimumClass {
public:
ros::Publisher pub;
void minimum(const sensor_msgs::LaserScan::ConstPtr& msg);
};
void minimumClass::minimum(const sensor_msgs::LaserScan::ConstPtr& msg) {
int size = msg->ranges.size();
float min = msg->ranges[0];
for(int i = 0; i < size; i++)
if(msg->ranges[i] < min)
min = msg->ranges[i];
std_msgs::String toPublishMsg;
toPublishMsg.data = std::to_string(min);
this->pub.publish(toPublishMsg);
ROS_INFO("Min: [%lf]", min);
}
int main(int argc, char **argv) {
ros::init(argc, argv, "min_distance");
ros::NodeHandle node;
minimumClass mc;
mc.pub = node.advertise<std_msgs::String>("min_distance_topic", 1000);
callback boundedMinimum = boost::bind(&minimumClass::minimum, &mc, _1);
ros::Subscriber sub = node.subscribe("base_scan", 1000, boundedMinimum);
ros::spin();
return 0;
}
| true |
98feb999f598c1b0177ed82035672a83c7e4b2b6 | C++ | rahul2412/C_plus_plus | /exceptcalc.cpp | UTF-8 | 337 | 2.96875 | 3 | [] | no_license | #include<iostream>
using namespace std;
main()
{ int a,b;
cin>>a>>b;
int i;
cout<<"choose operation";
cin>>i;
switch(i)
{case 1:
cout<<a+b;
break;
case 2:
cout<<a-b;
break;
case 3:
cout<<a*b;
break;
case 4:
try{
if(b==0)
throw "error as b=0";
else
cout<<a/b;
}
catch(const char *msg)
{cout<<msg;}} }
| true |
af34fa50c5e8b87579b76831426a7ca2fa45bff0 | C++ | CIEProject/Electric-Circuit | /Actions/ActionAddGround.cpp | UTF-8 | 1,359 | 2.578125 | 3 | [] | no_license | #include "ActionAddGround.h"
#include "..\ApplicationManager.h"
#include "..\UI\UI.h"
ActionAddGround::ActionAddGround(ApplicationManager* pApp) :Action(pApp)
{
}
ActionAddGround::~ActionAddGround(void)
{
}
void ActionAddGround::Execute()
{
//Get a Pointer to the user Interfaces
UI* pUI = pManager->GetUI();
//Print Action Message
pUI->PrintMsg("Adding a Ground: Click anywhere to add");
//Get Center point of the area where the Comp should be drawn
pUI->GetPointClicked(Cx, Cy);
while (!(Cy > UI::getToolBarHeight() + UI::getCompHeight() / 2
&& Cy < UI::Height() - UI::getStatusBarHeight() - UI::getCompHeight() / 2
&& Cx > UI::getCompWidth() / 2
&& Cx < UI::getWidth() - UI::getCompWidth() / 2)) {
pUI->GetPointClicked(Cx, Cy);
}
//Clear Status Bar
pUI->ClearStatusBar();
GraphicsInfo* pGInfo = new GraphicsInfo(2); //Gfx info to be used to construct the Comp
//Calculate the rectangle Corners
int compWidth = pUI->getCompWidth();
int compHeight = pUI->getCompHeight();
pGInfo->PointsList[0].x = Cx - compWidth / 2;
pGInfo->PointsList[0].y = Cy - compHeight / 2;
pGInfo->PointsList[1].x = Cx + compWidth / 2;
pGInfo->PointsList[1].y = Cy + compHeight / 2;
Ground* pG = new Ground(pGInfo);
pUI->ClearStatusBar();
pManager->AddComponent(pG);
}
void ActionAddGround::Undo()
{}
void ActionAddGround::Redo()
{}
| true |
9056931e5527ad7e9e8012d42875c68f4b29518c | C++ | kimxyz/cocos2dx-dev | /MagicalTree/Classes/PlayerGround.cpp | UHC | 9,174 | 2.578125 | 3 | [] | no_license | #include "PlayerGround.h"
#include "Player.h"
#include "PlayerFSM.h"
#include "GameLayer.h"
PlayerGround::PlayerGround(Player* pPlayer)
: PlayerState(pPlayer, PLAYER_GROUND)
{
m_dir = 0;
}
PlayerGround::~PlayerGround()
{
}
bool PlayerGround::IsValidGroundPos(CCPoint pos)
{
Player* pOwner = GetOwner();
GameLayer* pLayer = pOwner->GetGameLayer();
int width = pLayer->_gameMap->getMapSize().width;
int groundWidth = pLayer->_gameMap->getTileSize().width * width;
if (pos.x > 0 && pos.x < groundWidth)
return true;
return false;
}
bool PlayerGround::CheckRopeInteraction(CCPoint& touchPoint)
{
Player* pOwner = GetOwner();
GameLayer* pLayer = pOwner->GetGameLayer();
bool bIntersect = pLayer->CheckIntersect(touchPoint, pLayer->_ropeLayer);
bool bIntersect2 = pLayer->CheckIntersect(pOwner->getPosition(), pLayer->_ropeLayer);
if (touchPoint.y < pOwner->getPosition().y)
{
CCPoint belowTilePos = pOwner->getPosition();
belowTilePos.y = belowTilePos.y - pLayer->_gameMap->getTileSize().height;
if (bIntersect && pLayer->CheckIntersect(belowTilePos, pLayer->_ropeLayer))
{
pOwner->setPosition(belowTilePos);
pOwner->SetDesiredPosition(belowTilePos);
return true;
}
}
//ΰ ִ ¿ Ŭ.. ·
else if (bIntersect == true && bIntersect2 == true)
{
return true;
}
return false;
}
void PlayerGround::OnTouch(CCPoint& touchPoint)
{
Player* pOwner = GetOwner();
GameLayer* pLayer = pOwner->GetGameLayer();
if (IsValidGroundPos(touchPoint) == false)
return;
if (true == CheckRopeInteraction(touchPoint))
{
pOwner->ResetPhysicsParam();
pOwner->GetFSM()->ChangeState(PLAYER_ROPE);
return;
}
m_targetPos = pOwner->getPosition();
if (touchPoint.x > pOwner->getPosition().x)
{
m_dir = 1;
}
else if(touchPoint.x < pOwner->getPosition().x)
{
m_dir = -1;
}
else
{
m_dir = 0;
}
if (touchPoint.y - pOwner->getPosition().y > 50)
{
pOwner->mightAsWellJump = true;
if (touchPoint.x - pOwner->getPosition().x > 40)
pOwner->jumpingForforwardMarch = 1;
else if (touchPoint.x - pOwner->getPosition().x < -40)
pOwner->jumpingForforwardMarch = -1;
else
pOwner->jumpingForforwardMarch = 0;
}
m_targetPos.x = touchPoint.x;
}
void PlayerGround::OnMoved(CCPoint& touchPoint)
{
Player* pOwner = GetOwner();
if (touchPoint.x > pOwner->getPosition().x)
{
pOwner->forwardMarch = 1;
}
else if (touchPoint.x < pOwner->getPosition().x)
{
pOwner->forwardMarch = -1;
}
else
{
pOwner->forwardMarch = 0;
}
m_targetPos = touchPoint;
}
void PlayerGround::OnTouchEnd(CCPoint& touchPoint)
{
Player* pOwner = GetOwner();
pOwner->forwardMarch = 0;
}
/*void PlayerGround::update(float dt)
{
Player* pOwner = GetOwner();
CCPoint forwardMove = ccp(800.0, 0.0);
CCPoint forwardStep = ccpMult(forwardMove, dt);
CCPoint& velocity = pOwner->GetVelocity();
velocity = ccp(velocity.x * 0.90, 0);
if (pOwner->forwardMarch > 0) {
velocity = ccpAdd(velocity, forwardStep);
}
else if (pOwner->forwardMarch < 0) {
velocity = ccpAdd(velocity, forwardStep * -1);
}
CCPoint jumpForce = ccp(0.0, 310.0);
float jumpCutoff = 150.0;
if (pOwner->mightAsWellJump) {
velocity = ccpAdd(velocity, jumpForce);
//SimpleAudioEngine::sharedEngine()->playEffect("jump.wav");
}
else if (!pOwner->mightAsWellJump && velocity.y > jumpCutoff) {
velocity = ccp(velocity.x, jumpCutoff);
}
CCPoint minMovement = ccp(-120.0, -450.0);
CCPoint maxMovement = ccp(120.0, 250.0);
velocity = ccpClamp(velocity, minMovement, maxMovement);
CCPoint stepVelocity = ccpMult(velocity, dt);
if (pOwner->mightAsWellJump == true)
{
pOwner->GetFSM()->ChangeState(PLAYER_VOID);
}
pOwner->SetDesiredPosition(ccpAdd(pOwner->getPosition(), stepVelocity));
if (pOwner->desiredPosition.x < pOwner->getContentSize().width / 2)
pOwner->desiredPosition.x = pOwner->getContentSize().width / 2;
if (pOwner->desiredPosition.x > 320 - pOwner->getContentSize().width / 2)
pOwner->desiredPosition.x = 320 - pOwner->getContentSize().width / 2;
}*/
void PlayerGround::CheckCollison(GameLayer* pLayer)
{
Player* p = GetOwner();
CCArray *tiles = pLayer->getSurroundingTilesAtPosition(p->getPosition(), pLayer->_toeholdLayer);
bool bGround = false;
CCObject* it = NULL;
CCARRAY_FOREACH(tiles, it)
{
CCDictionary *dic = dynamic_cast<CCDictionary*>(it);
CCRect pRect = p->boundingBox();
CCInteger* pValue = (CCInteger*)dic->objectForKey("gid");
if (pValue->getValue() && pValue->getValue() != -1) {
CCFloat* pValue2 = (CCFloat*)dic->objectForKey("x");
CCFloat* pValue3 = (CCFloat*)dic->objectForKey("y");
CCRect tileRect = CCRectMake(pValue2->getValue(),
pValue3->getValue(),
pLayer->_gameMap->getTileSize().width,
pLayer->_gameMap->getTileSize().height);
if (pRect.intersectsRect(tileRect)) {
CCRect intersection = CCRectMake(max(pRect.getMinX(), tileRect.getMinX()), max(pRect.getMinY(), tileRect.getMinY()), 0, 0);
intersection.size.width = min(pRect.getMaxX(), tileRect.getMaxX()) - intersection.getMinX();
intersection.size.height = min(pRect.getMaxY(), tileRect.getMaxY()) - intersection.getMinY();
//CCRect intersection = CCRectIntersection(pRect, tileRect);
int tileIndx = tiles->indexOfObject(dic);
if (tileIndx == 0) {
p->SetDesiredPosition(ccp(p->desiredPosition.x, p->desiredPosition.y + intersection.size.height));
bGround = true;
}
else if (tileIndx == 1) {
//tile is directly above player
// p->desiredPosition = ccp(p->desiredPosition.x, p->desiredPosition.y - intersection.size.height);
// p->velocity = ccp(p->velocity.x, 0.0); //////Here
}
else if (tileIndx == 2) {
//tile is left of player
p->desiredPosition = ccp(p->desiredPosition.x + intersection.size.width, p->desiredPosition.y);
}
else if (tileIndx == 3) {
//tile is right of player
p->desiredPosition = ccp(p->desiredPosition.x - intersection.size.width, p->desiredPosition.y);
}
else if (tileIndx == 8)
{
int i = 1;
}
else {
/*if (intersection.size.width > intersection.size.height) {
//tile is diagonal, but resolving collision vertially
p->velocity = ccp(p->velocity.x, 0.0); //////Here
float resolutionHeight;
if (tileIndx > 5) {
resolutionHeight = intersection.size.height;
p->onGround = true; //////Here
}
else {
resolutionHeight = -intersection.size.height;
}
p->desiredPosition = ccp(p->desiredPosition.x, p->desiredPosition.y + resolutionHeight);
}
else {
float resolutionWidth;
if (tileIndx == 6 || tileIndx == 4) {
resolutionWidth = intersection.size.width;
}
else {
resolutionWidth = -intersection.size.width;
}
p->desiredPosition = ccp(p->desiredPosition.x + resolutionWidth, p->desiredPosition.y);
}*/
}
}
}
}
p->setPosition(p->desiredPosition);
if (bGround == false)
{
p->forwardMarch = 0;
p->jumpingForforwardMarch = 0;
p->GetFSM()->ChangeState(PLAYER_VOID);
}
}
void PlayerGround::update(float dt)
{
Player* pOwner = GetOwner();
if (m_targetPos.x == pOwner->getPosition().x)
return;
CCPoint forwardMove = ccp(800.0, 0.0);
CCPoint forwardStep = ccpMult(forwardMove, dt);
CCPoint& velocity = pOwner->GetVelocity();
//velocity.x = 0;
if (m_dir == 1)
{
if (m_targetPos.x - pOwner->getPosition().x > 0)
{
velocity = ccpAdd(velocity, forwardStep);
}
else
{
m_dir = 0;
pOwner->setPositionX(m_targetPos.x);
}
}
else if (m_dir == -1)
{
if (m_targetPos.x - pOwner->getPosition().x < 0)
{
velocity = ccpAdd(velocity, forwardStep * -1);
}
else
{
m_dir = 0;
pOwner->setPositionX(m_targetPos.x);
}
}
else
{
velocity.x = 0;
}
CCPoint minMovement = ccp(-120.0, -450.0);
CCPoint maxMovement = ccp(120.0, 250.0);
velocity = ccpClamp(velocity, minMovement, maxMovement);
CCPoint stepVelocity = ccpMult(velocity, dt);
if (pOwner->mightAsWellJump == true)
{
CCPoint jumpForce = ccp(0.0, 310.0);
velocity = ccpAdd(velocity, jumpForce);
SimpleAudioEngine::sharedEngine()->playEffect("jump.wav");
pOwner->GetFSM()->ChangeState(PLAYER_VOID);
}
pOwner->SetDesiredPosition(ccpAdd(pOwner->getPosition(), stepVelocity));
if (pOwner->desiredPosition.x < pOwner->getContentSize().width / 2)
pOwner->desiredPosition.x = pOwner->getContentSize().width / 2;
if (pOwner->desiredPosition.x > 320 - pOwner->getContentSize().width / 2)
pOwner->desiredPosition.x = 320 - pOwner->getContentSize().width / 2;
}
void PlayerGround::OnEnter(PlayerState* pPrevState)
{
Player* pOwner = GetOwner();
m_targetPos = pOwner->getPosition();
m_dir = 0;
pOwner->velocity = ccp(0, 0);
}
void PlayerGround::OnExit()
{
} | true |
1ac732330e1a74850493f4b80a578fc767738be1 | C++ | kaushikacharya/binarysearch | /src/tree_with_distinct_parities.cpp | UTF-8 | 1,285 | 3.5 | 4 | [] | no_license | /**
* https://binarysearch.com/problems/Tree-with-Distinct-Parities
* Dec 27, 2020
*/
#include <tree_with_distinct_parities.hpp>
using namespace std;
int solve(Tree* root) {
if (root == nullptr){
return 0;
}
pair<int, int> result = compute_parities(root);
return result.second;
}
pair<int, int> compute_parities(Tree* node){
int sum_subtree = node->val;
int count_perfect_nodes = 0;
pair<int, int> left_result;
pair<int, int> right_result;
// Compute parities for left subtree
if (node->left){
left_result = compute_parities(node->left);
sum_subtree += left_result.first;
count_perfect_nodes += left_result.second;
}
// Compute parities for right subtree
if (node->right){
right_result = compute_parities(node->right);
sum_subtree += right_result.first;
count_perfect_nodes += right_result.second;
}
// check if the input subtree's root is a perfect node or not
if ((node->left) && (node->right)){
if (((left_result.first % 2 == 0) && (right_result.first % 2 == 1)) || ((left_result.first % 2 == 1) && (right_result.first % 2 == 0))){
count_perfect_nodes += 1;
}
}
return make_pair(sum_subtree, count_perfect_nodes);
}
| true |
63d0a3a6bad85b66ac5a0368d1cba5f3e2e3bd7b | C++ | zie87/sdl2_cxx | /src/test/detail/type_traits_test.cxx | UTF-8 | 1,237 | 2.859375 | 3 | [] | no_license | /**
* @file type_traits_test.cxx
* @Author: zie87
* @Date: 2017-10-09 20:21:14
* @Last Modified by: zie87
* @Last Modified time: 2017-10-18 22:08:51
*
**/
#include <sdl2_cxx/detail/type_traits.hxx>
#include <catch.hpp>
enum class enum_test_a : unsigned char
{
zero =0b00000000,
one =0b00000001,
two =0b00000010,
three =0b00000011
};
namespace sdl2
{
template<>
struct enable_bitmask_operators<enum_test_a>{ static const bool enable=true; };
}
TEST_CASE( "bitmask combination", "[detail]" )
{
using namespace sdl2;
enum_test_a a1 = enum_test_a::one | enum_test_a::two;
REQUIRE( a1 == enum_test_a::three );
a1 = enum_test_a::one;
a1 |= enum_test_a::two;
REQUIRE( a1 == enum_test_a::three );
enum_test_a a2 = enum_test_a::one & enum_test_a::two;
REQUIRE( a2 == enum_test_a::zero);
a2 = enum_test_a::one;
a2 &= enum_test_a::three;
REQUIRE( a2 == enum_test_a::one );
enum_test_a a3 = enum_test_a::one ^ enum_test_a::three;
REQUIRE( a3 == enum_test_a::two );
a3 = enum_test_a::one;
a3 ^= enum_test_a::three;
REQUIRE( a3 == enum_test_a::two );
auto a4 = static_cast<unsigned short>( ~a2 );
REQUIRE( a4 == 254 );
}
| true |
5354ef073602c93ce0f1f8b80b43bad20bd34799 | C++ | hamko/sample | /wu_method/poly.cpp | UTF-8 | 7,904 | 2.84375 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <assert.h>
#include <string>
#include <limits.h>
#include <vector>
#include "poly.hpp"
#include "util.hpp"
#include <stdio.h>
using namespace std;
/* Poly */
void Poly::addMonoPoly(const MonoPoly* mono)
{
MonoPoly tmp = *mono;
m_func.push_back(tmp);
}
void Poly::initPolyAs(PolyInfrastructure* pi)
{
m_func.clear();
m_pi = pi;
}
Poly::Poly(PolyInfrastructure* pi)
{
m_pi = pi;
}
Poly::Poly(PolyInfrastructure* pi, vector <MonoPoly> func)
{
m_pi = pi;
for (int i = 0; i < func.size(); i++)
m_func.push_back(func[i]);
}
const int Poly::getMonoPolyNum(void) const
{
return m_func.size();
}
int Poly::getVarNum(void) const
{
return m_pi->getVarNum();
}
const void Poly::Print(void) const
{
if (!getMonoPolyNum()) {
cout << "nil";
return;
}
m_func[0].Print();
for (int i = 1; i < this->getMonoPolyNum(); i++) {
if (getMonoPolyWithIndex(i)->getCoeff() >= 0)
cout << " + ";
m_func[i].Print();
}
}
const MonoPoly* Poly::getMonoPolyWithIndex(int index) const
{
return &m_func[index];
}
double MonoPoly::getCoeff(void) const
{
return m_coeff;
}
void MonoPoly::setCoeff(double coeff)
{
m_coeff = coeff;
}
MonoPoly* Poly::getMonoPolyWithIndex(int index)
{
return &m_func[index];
}
void Poly::setMonoPolyCoeffWithIndex(int index, double coeff)
{
m_func[index].setCoeff(coeff);
}
const vector<int> Poly::getPowerWithIndex(int index) const
{
return m_func[index].getPower();
}
int Poly::searchSameDimMonoPoly(const MonoPoly* obj) const
{
for (int i = 0; i < this->getMonoPolyNum(); i++)
if (obj->getPower() == getMonoPolyWithIndex(i)->getPower())
return i;
return -1;
}
// if this have a expression including obj, return the index of expression
int Poly::searchIncludeDimMonoPoly(const MonoPoly* obj) const
{
for (int i = 0; i < getMonoPolyNum(); i++) {
bool faf = true;
for (int j = 0; j < m_pi->getVarNum(); j++) {
if (!obj->getPower()[j])
continue;
if (obj->getPower()[j] > getMonoPolyWithIndex(i)->getPower()[j]) {
faf = false;
break;
}
}
if (faf)
return i;
}
return -1;
}
class EraseZeroPoly
{
public:
bool operator()(MonoPoly mp) const {return DBL_EQ(mp.getCoeff(), 0.0); }
};
void Poly::cleanPoly(void)
{
vector<MonoPoly>::iterator it = remove_if(m_func.begin(), m_func.end(), EraseZeroPoly());
m_func.erase(it, m_func.end());
}
bool Poly::isZeroPoly(void) const
{
return !m_func.size();
}
Poly Poly::operator+(const Poly& obj) const
{
Poly tmp = Poly(this->m_pi);
// This
for (int i = 0; i < this->getMonoPolyNum(); i++)
tmp.addMonoPoly(this->getMonoPolyWithIndex(i));
// obj
for (int i = 0; i < obj.getMonoPolyNum(); i++) {
int index;
if ((index = tmp.searchSameDimMonoPoly(obj.getMonoPolyWithIndex(i))) == -1) {
tmp.addMonoPoly(obj.getMonoPolyWithIndex(i));
} else {
tmp.setMonoPolyCoeffWithIndex(index,
tmp.getMonoPolyWithIndex(index)->getCoeff()
+ obj.getMonoPolyWithIndex(i) ->getCoeff());
}
}
tmp.cleanPoly();
return tmp;
}
Poly Poly::operator+(const MonoPoly& obj) const
{
Poly tmp = Poly(this->m_pi);
// This
for (int i = 0; i < this->getMonoPolyNum(); i++)
tmp.addMonoPoly(this->getMonoPolyWithIndex(i));
// obj
int index;
if ((index = tmp.searchSameDimMonoPoly(&obj)) == -1) {
tmp.addMonoPoly(&obj);
} else {
tmp.setMonoPolyCoeffWithIndex(index,
tmp.getMonoPolyWithIndex(index)->getCoeff()
+ obj.getCoeff());
}
tmp.cleanPoly();
return tmp;
}
Poly Poly::operator-(const Poly& obj) const
{
Poly tmp = Poly(this->m_pi);
// This
for (int i = 0; i < this->getMonoPolyNum(); i++)
tmp.addMonoPoly(this->getMonoPolyWithIndex(i));
// obj
for (int i = 0; i < obj.getMonoPolyNum(); i++) {
int index;
if ((index = tmp.searchSameDimMonoPoly(obj.getMonoPolyWithIndex(i))) == -1) {
MonoPoly minus = -*(obj.getMonoPolyWithIndex(i));
tmp.addMonoPoly(&minus);
} else {
tmp.setMonoPolyCoeffWithIndex(index,
tmp.getMonoPolyWithIndex(index)->getCoeff()
- obj.getMonoPolyWithIndex(i) ->getCoeff());
}
}
tmp.cleanPoly();
return tmp;
}
Poly Poly::operator-(const MonoPoly& obj) const
{
Poly tmp = Poly(this->m_pi);
// This
for (int i = 0; i < this->getMonoPolyNum(); i++)
tmp.addMonoPoly(this->getMonoPolyWithIndex(i));
// obj
int index;
if ((index = tmp.searchSameDimMonoPoly(&obj)) == -1) {
tmp.addMonoPoly(&obj);
} else {
tmp.setMonoPolyCoeffWithIndex(index,
tmp.getMonoPolyWithIndex(index)->getCoeff()
- obj.getCoeff());
}
tmp.cleanPoly();
return tmp;
}
Poly Poly::operator*(const Poly& obj) const
{
Poly tmp = Poly(this->m_pi);
// This
for (int i = 0; i < this->getMonoPolyNum(); i++) {
for (int j = 0; j < obj.getMonoPolyNum(); j++) {
MonoPoly toadd = *(obj.getMonoPolyWithIndex(j)) * *(this->getMonoPolyWithIndex(i));
tmp = tmp + toadd;
}
}
tmp.cleanPoly();
return tmp;
}
Poly Poly::operator*(const MonoPoly& obj) const
{
Poly tmp; tmp = *this * obj;
tmp.cleanPoly();
return tmp;
}
Poly Poly::operator*(double dbl) const
{
Poly tmp = Poly(m_pi);
// This
for (int i = 0; i < getMonoPolyNum(); i++) {
MonoPoly toadd = *(this->getMonoPolyWithIndex(i));
toadd.setCoeff(toadd.getCoeff() * dbl);
tmp = tmp + toadd;
}
tmp.cleanPoly();
return tmp;
}
Poly Poly::operator/(double dbl) const
{
Poly tmp = Poly(m_pi);
// This
for (int i = 0; i < getMonoPolyNum(); i++) {
MonoPoly toadd = *(this->getMonoPolyWithIndex(i));
toadd.setCoeff(toadd.getCoeff() / dbl);
tmp = tmp + toadd;
}
tmp.cleanPoly();
return tmp;
}
Poly Poly::operator()(const Poly& obj, string str) const
{
// Copy
Poly f; f = *this;
// get one of the highest term.
MonoPoly h0 = *(obj.getHighestTerm(str));
double h0_coeff = h0.getCoeff();
// calc.
// f - t + (t * h0_coeff / h0) * ((h0 - obj) / h0_coeff)
// where
// t = term including hterm
while (1) {
// search which includes hterm.
int index;
if ((index = f.searchIncludeDimMonoPoly(&h0)) == -1) { // if not break
break;
} else { // if any substitute
MonoPoly t = *(f.getMonoPolyWithIndex(index));
f = (f - t) + (t * h0_coeff / h0) * ((h0 - obj) / h0_coeff);
}
}
f.cleanPoly();
return f;
}
const MonoPoly* Poly::getHighestTerm(string str) const
{
if (!getMonoPolyNum())
return NULL;
int maximum = INT_MIN;
const MonoPoly* maxmp;
int index = m_pi->getVarIndexNameOf(str); // index of PolyInfrastructure
for (int i = 0; i < getMonoPolyNum(); i++) {
const MonoPoly* mp = getMonoPolyWithIndex(i);
int tmp = mp->getPowerWithIndex(index);
if (maximum < tmp) {
maximum = tmp;
maxmp = mp;
}
}
return maxmp;
}
PolyInfrastructure* Poly::getPolyInfrastructure(void) const
{
return m_pi;
}
Poly& Poly::operator=(const MonoPoly& obj)
{
initPolyAs(obj.getPolyInfrastructure());
*this = *this + obj;
return *this;
}
Poly Poly::operator-(void) const
{
Poly tmp = Poly(this->m_pi);
tmp = tmp - *this;
return tmp;
}
| true |
d78ed0e275304e6ee8fc173dfbdb8c8fc1f84758 | C++ | sayanel/luminolGL | /src/lights/Light.cpp | UTF-8 | 10,022 | 2.546875 | 3 | [] | no_license |
#include "lights/Light.hpp"
#define DEBUG 0
namespace Light{
LightHandler::LightHandler(){
}
void LightHandler::addPointLight(glm::vec3 pos, glm::vec3 color, float intensity, float attenuation, PointLightBehavior type, int lastChangeDir, float multVelocity){
_pointLights.push_back(PointLight(pos,color,intensity,attenuation, type, lastChangeDir, multVelocity));
}
void LightHandler::addPointLight(PointLight pl){
_pointLights.push_back(PointLight(pl._pos, pl._color, pl._intensity, pl._attenuation, pl._type));
}
void LightHandler::setDirectionalLight(glm::vec3 pos, glm::vec3 color, float intensity, float attenuation){
setDirectionalLight(DirectionalLight(pos, color, intensity, attenuation));
}
void LightHandler::setDirectionalLight(const DirectionalLight& dl){
_directionalLight = dl;
}
void LightHandler::addSpotLight(glm::vec3 pos, glm::vec3 dir, glm::vec3 color, float intensity, float attenuation, float angle, float falloff){
_spotLights.push_back(SpotLight(pos,dir,color,intensity,attenuation,angle,falloff));
}
void LightHandler::addSpotLight(const SpotLight& sl){
_spotLights.push_back(sl);
}
glm::mat4 LightHandler::rotationMatrix(glm::vec3 axis, float angle)
{
axis = normalize(axis);
float s = sin(angle);
float c = cos(angle);
float oc = 1.0 - c;
return glm::mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0,
oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0,
oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0,
0.0, 0.0, 0.0, 1.0);
}
bool LightHandler::isOnScreen(const glm::mat4 & MVP, std::vector<glm::vec2> & littleQuadVertices, const glm::vec3 &pos, const glm::vec3 & color, const float & intensity, const float & attenuation, const PointLightBehavior & type, float & t){
float linear = 1.7;
float maxBrightness = std::max(std::max(color.r, color.g), color.b);
float radius = 1.0;
radius = ( (-linear + std::sqrt(linear * linear - 4 * attenuation * (1.0 - (256.0 / 5.0)
* maxBrightness))) / (2 * attenuation) ) /4 ;
// radius = intensity / attenuation * 50;
float dx = radius;
if(DEBUG) std::cout << "radius: " << dx << " && attenuation: " << attenuation << " && maxBrightness: " << maxBrightness << std::endl;
// création d'un cube d'influence autour de la point light
std::vector<glm::vec3> cube;
float px = pos.x; float py = pos.y; float pz = pos.z;
cube.push_back(glm::vec3(px-dx,py-dx,pz-dx)); // left bot back
cube.push_back(glm::vec3(px+dx,py-dx,pz-dx)); // right bot back
cube.push_back(glm::vec3(px-dx,py-dx,pz+dx)); // left bot front
cube.push_back(glm::vec3(px+dx,py-dx,pz+dx)); // right bot front
cube.push_back(glm::vec3(px+dx,py+dx,pz-dx)); // right top back
cube.push_back(glm::vec3(px-dx,py+dx,pz-dx)); // left top back
cube.push_back(glm::vec3(px-dx,py+dx,pz+dx)); // left top front
cube.push_back(glm::vec3(px+dx,py+dx,pz+dx)); // right top front
glm::vec3 axis = glm::vec3(0.0,1.0,0.0);
float w = 0;
if(type == PointLightBehavior::TORNADO){
axis = glm::vec3(0.0,-1.0,0.0);
w = t;
}
glm::mat4 rotateMatrix = rotationMatrix(axis , w);
glm::vec4 projInitPoint = MVP * rotateMatrix * glm::vec4(cube[0], 1.0);
if(projInitPoint.z < 0) return false;
projInitPoint /= projInitPoint.w;
float xmin = projInitPoint.x;
float xmax = projInitPoint.x;
float ymin = projInitPoint.y;
float ymax = projInitPoint.y;
for(auto& point : cube){
glm::vec4 projPoint = MVP * rotateMatrix * glm::vec4(point, 1.0);
projPoint /= projPoint.w;
if( projPoint.x < xmin) xmin = projPoint.x;
if( projPoint.y > ymax) ymax = projPoint.y;
if( projPoint.x > xmax) xmax = projPoint.x;
if( projPoint.y < ymin) ymin = projPoint.y;
}
if(DEBUG) std::cout << "Left: " << xmin << " Right: " << xmax << " Top: " << ymax << " Bottom: " << ymin << std::endl;
float m = 0.02f; // mult
if(type == PointLightBehavior::SUN){
m = 2.f;
}
littleQuadVertices.push_back(glm::vec2(xmin-m, ymin-m));
littleQuadVertices.push_back(glm::vec2(xmax+m, ymin-m));
littleQuadVertices.push_back(glm::vec2(xmin-m, ymax+m));
littleQuadVertices.push_back(glm::vec2(xmax+m, ymax+m));
float limit = 1.1;
// if( ( (xmin > -limit && xmin < limit) || (xmax > -limit && xmax < limit) ) && ( (ymax > -limit && ymax < limit) || (ymin > -limit && ymin < limit) ) )
if(!( (xmax<-limit) || (ymax<-limit) || (xmin>limit) || (ymin>limit) ) )
{
if(DEBUG) std::cout << "visible" << std::endl;
return true;
}
if(DEBUG) std::cout << "NON visible" << std::endl;
return false;
}
void LightHandler::createFirefliesTornado(int fd, int rayon, int step, const int & nbFireflies, const int & multCounterCircle, float w, float yFirstHeight){
srand (time(NULL));
int counterCircle = 0;
for(int i = 0; i < nbFireflies; ++i){
if( i == counterCircle*multCounterCircle ){
counterCircle++;
rayon += step;
}
glm::vec3 fireflyPosition = glm::vec3(
fd + 3 * cos(i+w*2* M_PI /nbFireflies)
,yFirstHeight + rayon
,fd + 3 * sin(i+w*2* M_PI /nbFireflies)
);
glm::vec3 fireflyColor = getRandomColors(counterCircle);
fireflyColor = glm::vec3(0.8,0.2,0.8);
float intensity = 0.1;
addPointLight(fireflyPosition, fireflyColor, intensity, 2.0, Light::PointLightBehavior::TORNADO);
}
}
void LightHandler::createRisingFireflies(const int nbFireflies, const int x, const int z, const int y, const glm::vec3 center){
srand (time(NULL));
for(int i = 0; i < nbFireflies; ++i){
glm::vec3 fireflyPosition = center + glm::vec3(
rand() % (2*x) + 1 - x
, 10 - rand() % y
, rand() % (2*z) + 1 - z
);
// glm::vec3 fireflyColor = getRandomColors(i);
glm::vec3 fireflyColor = getNotSoRandomColors(i);
float multVelocity = ( rand() % 30 + 10 ) / 10;
float intensity = 0.05;
addPointLight(fireflyPosition, fireflyColor, intensity, 2.0, Light::PointLightBehavior::RISING, 5, multVelocity);
}
}
void LightHandler::createRandomFireflies(const int nbFireflies, const int x, const int z, const int y, const glm::vec3 center){
srand (time(NULL));
for(int i = 0; i < nbFireflies; ++i){
glm::vec3 fireflyPosition = center + glm::vec3(
rand() % (2*x) + 1 - x
, rand() % y + 5
, rand() % (2*z) + 1 - z
);
// glm::vec3 fireflyColor = getRandomColors(i);
glm::vec3 fireflyColor = getNotSoRandomColors(i);
int lastChangeDir = rand() % 7 + 4;
float multVelocity = ( rand() % 30 + 10 ) / 10;
float intensity = 0.05;
addPointLight(fireflyPosition, fireflyColor, intensity, 2.0, Light::PointLightBehavior::RANDOM_DISPLACEMENT, lastChangeDir, multVelocity);
}
}
glm::vec3 LightHandler::getRandomColors(int i){
// float red = fmaxf(sin(i)+cos(i), 0.1);
// float green = fmaxf(cos(i), 0.1);
// float blue = fmaxf(sin(i)+cos(i), 0.1);
float red = ( rand() % 10 ) / 10.f;
float green = ( rand() % 10 ) / 10.f;
float blue = ( rand() % 10 ) / 10.f;
// si la lumière n'est pas assez puissante on va booster un channel au hasard
if(red<0.4 && green <0.4 && blue < 0.4){
int r = rand() % 3 + 1;
if(r==1) blue +=0.5; else if(r==2) green +=0.5; else red +=0.5;
}
else if(red > 0.8 && green > 0.8 && blue > 0.8){
int r = rand() % 3 + 1;
if(r==1) blue -=0.6; else if(r==2) green -=0.6; else red -=0.6;
}
else if(red > 0.8 && blue > 0.8){
int r = rand() % 2 + 1;
if(r==1) blue -=0.3; else red -=0.3;
}
// std::cout << red << " " << green << " " << blue << std::endl;
return glm::vec3( red , green , blue);
}
glm::vec3 LightHandler::getNotSoRandomColors(int i){
std::vector<glm::vec3> colors;
colors.push_back(glm::vec3(0.9999, 0.921568627, 0.517647059));
colors.push_back(glm::vec3(0.592156863, 0.9999, 0.407843137));
colors.push_back(glm::vec3(0.9999, 0.607843137, 0.407843137));
colors.push_back(glm::vec3(0.9999, 0.77254902, 0.71372549));
colors.push_back(glm::vec3(0.698039216, 0.309803922, 0.215686275));
// colors.push_back(glm::vec3(0, 0, 0));
int size = colors.size();
int j = rand() % size -1;
float red = colors[j].x;
float green = colors[j].y;
float blue = colors[j].z;
float kr = ( rand() % 20 -10) / 10;
float kg = ( rand() % 20 -10) / 10;
float kb = ( rand() % 20 -10) / 10;
if(red >= 0.3 && red <= 0.8) red += kr;
if(green >= 0.3 && green <= 0.8) green += kb;
if(blue >= 0.3 && blue <= 0.8) blue += kb;
// si la lumière n'est pas assez puissante on va booster un channel au hasard
// if(red<0.4 && green <0.4 && blue < 0.4){
// int r = rand() % 3 + 1;
// if(r==1) blue +=0.5; else if(r==2) green +=0.5; else red +=0.5;
// }
// else if(red > 0.8 && green > 0.8 && blue > 0.8){
// int r = rand() % 3 + 1;
// if(r==1) blue -=0.6; else if(r==2) green -=0.6; else red -=0.6;
// }
// else if(red > 0.8 && blue > 0.8){
// int r = rand() % 2 + 1;
// if(r==1) blue -=0.3; else red -=0.3;
// }
return glm::vec3(red, green, blue);
}
}
| true |
2764d95675ac869a5e9a727e0525608808b2218d | C++ | AlexMaz99/WDI | /lab9,10/zad24'.cpp | UTF-8 | 1,971 | 3.9375 | 4 | [] | no_license | #include <iostream>
using namespace std;
struct node {
int w;
node *next;
};
// with guard
//1 2 5 8 9
//9 2 12 7 1
int remove(node *&first, node *&second) {
if (first == NULL || second == NULL) return 0;
node *f = new node;
f->next = first;
first = f;
node *s = new node;
s->next = second;
second = s;
int result = 0;
while (f->next != NULL && s->next != NULL) {
if (f->next->w < s->next->w)
f = f->next;
else if (f->next->w > s->next->w) {
s = s->next;
f = first;
} else if (f->next->w == s->next->w) {
node *d = f->next;
f->next = d->next;
delete d;
node *r = s->next;
s->next = r->next;
delete r;
result += 2;
f = first;
}
}
f = first;
s = second;
first = first->next;
second = second->next;
delete s;
delete f;
return result;
}
void insert_last(node *&first, int n) //dodawanie elementu na koniec listy
{
node *p = new node;
p->w = n;
p->next = NULL;
if (first == NULL) first = p;
else {
node *r = first;
while (r->next != NULL) {
r = r->next;
}
r->next = p;
}
}
int main() {
node *first = new node;
first = NULL;
node *second = new node;
second = NULL;
insert_last(first, 1);
insert_last(first, 2);
insert_last(first, 5);
insert_last(first, 8);
insert_last(first, 9);
insert_last(first, 13);
insert_last(second, 9);
insert_last(second, 2);
insert_last(second, 12);
insert_last(second, 7);
insert_last(second, 1);
cout << remove(first, second) << endl;
while (first != NULL) {
cout << first->w << " ";
first = first->next;
}
cout << endl;
while (second != NULL) {
cout << second->w << " ";
second = second->next;
}
return 0;
} | true |
aa7496252c456f94a6eebdbc027b27fe95a003b1 | C++ | dhruv7294/DataStructure | /DFS/Search_Sorting/Programs/MERGESOR.CPP | UTF-8 | 772 | 2.890625 | 3 | [] | no_license |
#include<iostream.h>
#include<conio.h>
#define SIZE 20
void main()
{
int A[SIZE],B[SIZE],C[SIZE];
int i,j,k,n1,n2,n3;
clrscr();
cout<<"\n\tEnter n for Array A :-->";
cin>>n1;
for(i=0;i<n1;i++)
{
cout<<"Enter No "<<i+1<<":-->";
cin>>A[i];
}
cout<<"\n\tEnter n for Array B :-->";
cin>>n2;
for(i=0;i<n2;i++)
{
cout<<"Enter No "<<i+1<<":-->";
cin>>B[i];
}
i=0,j=0,k=0;
while(i<n1 && j<n2)
{
if(A[i]<=B[j])
{
C[k++]=A[i++];
}
else
{
C[k++]=B[j++];
}
}
if (j<n2)
{
while(j<n2)
{
C[k++]=B[j++];
}
}
if (i<n1)
{
while(i<n1)
{
C[k++]=A[i++];
}
}
n3=n1+n2;
cout<<"\n\tThird Array...\n\t";
for(k=0;k<n3;k++)
{
cout<<" "<<C[k]<<" ";
}
getch();
}
| true |
977b1d268074d46d5130a2317003caca13aa8c64 | C++ | Nagan0/vision | /task4/task4_2/sobel.cpp | UTF-8 | 2,234 | 2.671875 | 3 | [] | no_license | #include <opencv2/opencv.hpp>
#include <iostream>
#include <fstream>
using namespace std;
using namespace cv;
int main(int argc, const char* argv[])
{
double gain = 0.2;
int offset = 127;
int kernel_size = 3;
double kernel[2][3][3] = {
{ {-2, -4, -2},
{0, 0, 0},
{2, 4, 2}},
{ {-2, 0, 2},
{-4, 0, 4},
{-2, 0, 2}}
};
string filename;
cout <<"Open File Name >";
cin >> filename;
//read image file
Mat color_image = cv::imread(filename, cv::IMREAD_COLOR);
if (color_image.empty()) {
cerr << "Failed to open image file." << endl;
return -1;
}
Mat gray_image;
cvtColor(color_image, gray_image,CV_BGR2GRAY);
namedWindow("Image", CV_WINDOW_AUTOSIZE);
imshow("Image", color_image);
namedWindow("grayImage", CV_WINDOW_AUTOSIZE);
imshow("grayImage", gray_image);
waitKey(100);
Mat conv_image[2];
conv_image[0] = Mat(cv::Size(gray_image.cols, gray_image.rows), CV_8U, cv::Scalar(0));
conv_image[1] = Mat(cv::Size(gray_image.cols, gray_image.rows), CV_8U, cv::Scalar(0));
int margin = kernel_size/2;
for(int y=margin; y < gray_image.rows-margin; y++) {
for(int x=margin; x < gray_image.cols-margin; x++) {
for(int k = 0; k < 2; k++) {
double conv = 0;
for (int i = -margin; i <= margin; i++) {
for (int j = -margin; j <= margin; j++) {
conv += (double)gray_image.at<unsigned char>(y+i, x+j)*kernel[k][i+margin][j+margin];
}
}
conv = offset + conv*gain;
if(conv < 0) conv = 0;
if(conv > 255) conv = 255;
conv_image[k].at<unsigned char>(y, x) = conv;
}
}
}
namedWindow("Horiz", CV_WINDOW_AUTOSIZE);
namedWindow("Vert", CV_WINDOW_AUTOSIZE);
imshow("Horiz", conv_image[0]);
imshow("Vert", conv_image[1]);
ofstream fout;
fout.open((filename+"_sobel.txt").c_str());
for(int y=margin; y < gray_image.rows-margin; y++) {
for(int x=margin; x < gray_image.cols-margin; x++) {
fout << (int)conv_image[0].at<unsigned char>(y, x)-127 << "\t";
fout << (int)conv_image[1].at<unsigned char>(y, x)-127 << endl;
}
}
fout.close();
waitKey(0);
destroyAllWindows();
return 0;
}
| true |
9059a8fb417880326666ed1983f4370e85a455ba | C++ | mophy1109/code_learning | /prim.cpp | UTF-8 | 323 | 3.25 | 3 | [] | no_license | //分解质因数算法
#include <iostream>
using namespace std;
void prim(int m, int n = 2)
{
if (m >= n) {
while (m % n)
n++;
m /= n;
prim(m, n);
cout << n << endl;
}
}
int main(int argc, char const *argv[])
{
int m;
cin >> m;
prim(m,3);
return 0;
}
| true |
c8b0e137ef18d692d7b5955f0bcb4e0b08cb84ac | C++ | GabeOchieng/ggnn.tensorflow | /program_data/PKU_raw/41/657.c | UTF-8 | 829 | 3.3125 | 3 | [] | no_license | /*
* 4.cpp
*
* Created on: 2012-11-9
* Author: AK
*/
int main(){
int a,b,c,d,e;
for(a=1;a<=5;a++)
for(b=1;b<=5;b++)
{
if(a==b) continue;
for(c=1;c<=5;c++)
{
if(c==a||c==b) continue;
for(d=1;d<=5;d++)
{
if(d==a||d==b||d==c) continue;
for(e=1;e<=5;e++)
{
if(e==a||e==b||e==c||e==d||e==2||e==3) continue;
if(a<=2&&e!=1) continue;
if(a>2&&e==1) continue;
if(b<=2&&b!=2) continue;
if(b>2&&b==2) continue;
if(c<=2&&a!=5) continue;
if(c>2&&a==5) continue;
if(d<=2&&c==1) continue;
if(d>2&&c!=1) continue;
if(e<=2&&d!=1) continue;
if(e>2&&d==1) continue;
cout<<a<<' '<<b<<' '<<c<<' '<<d<<' '<<e<<endl;
}
}
}
}
return 0;
} | true |
33351e92ed61689e4a9f75cd8f57998b46fa877c | C++ | leehn5/The_Final-Station | /FadeInAndOut.h | WINDOWS-1252 | 767 | 2.828125 | 3 | [] | no_license | #pragma once
class FadeInAndOut
{
private:
float alpha;
Callback_Function_Parameter _cbFP;
bool isStart;
bool isFadeInEnd;
bool isFadeOutEnd;
private:
static void FadeIn(void* obj);
static void FadeOut(void* obj);
public:
FadeInAndOut()
: alpha(0.f), isStart(false), isFadeInEnd(false), isFadeOutEnd(false) { }
void Update();
void Render();
//
void FadeInStart();
// ο
void FadeOutStart();
bool GetIsFadeInEnd();
bool GetIsFadeOutEnd();
void SetAlpha(float value) { alpha = value; }
float GetAlpha() { return alpha; }
void SetIsStart(bool start) { isStart = start; }
void SetIsFadeInEnd(bool fadeInEnd) { isFadeInEnd = fadeInEnd; }
void SetIsFadeOutEnd(bool fadeOutEnd) { isFadeOutEnd = fadeOutEnd; }
};
| true |
b2b62c4ea170d22185acb3da23b996da8cffa590 | C++ | n-inja/kyoupro | /src/other/scr1h.cpp | UTF-8 | 1,589 | 2.953125 | 3 | [] | no_license | #include<iostream>
#include<fstream>
#include<stdio.h>
#include<string>
#include<vector>
#include<map>
#include<math.h>
#include<algorithm>
#include<iomanip>
#include<set>
#include<utility>
const long long PRIME = 1000000007;
using namespace std;
struct segtree {
int N, dat[800001];
segtree() {}
segtree(int n) {
N = 1;
while(N < n) N *= 2;
for(int i = 0; i < 2*N-1; i++)
dat[i] = 0;
}
// update k th element
void update(int k, int a) {
k += N-1; // leaf
dat[k] = a;
while(k > 0) {
k = (k - 1) / 2;
dat[k] = min(dat[k*2+1], dat[k*2+2]);
}
}
// min [a, b)
int query(int a, int b) { return query(a, b, 0, 0, N); }
int query(int a, int b, int k, int l, int r) {
if(r <= a or b <= l) return 0;
if(a <= l and r <= b) return dat[k];
int m = (l + r) / 2;
return min(query(a, b, k*2+1, l, m), query(a, b, k*2+2, m, r));
}
};
class N {
public:
int val, id;
N(int _, int __) {
val = _;
id = __;
}
bool operator>(const N &rhs) const {
return this->val > rhs.val;
}
bool operator<(const N &rhs) const {
return this->val < rhs.val;
}
};
int main() {
int n;
cin >> n;
segtree s(n);
vector<int> v(n);
vector<N> node;
for(int i = 0; i < n; i++) {
cin >> v[i];
node.push_back(N(v[i], i));
}
sort(node.begin(), node.end());
for(int i = 0; i < n; i++) {
int mi = s.query(0, node[i].id);
s.update(node[i].id, mi - 1);
}
cout << -s.query(0, n) << endl;
return 0;
}
| true |
47b55975af282eec3425aa590da5bb69875ae137 | C++ | vastus/chanchan | /test/chanchan_test.cpp | UTF-8 | 1,338 | 3.015625 | 3 | [] | no_license | #include "chanchan/chanchan.h"
#include <assert.h>
#include <iostream>
#include <memory>
#include <optional>
#include <type_traits>
namespace chan = chanchan;
using namespace std;
template <int I = 0, typename T, typename F>
constexpr void for_each(const T& t, F f) {
if constexpr (I < tuple_size<T>::value) {
f(get<I>(t));
for_each<I + 1>(t, f);
}
}
int main(void) {
{
static auto mutual = chan::mutual<int>{};
static auto sender = chan::sender<int>{nullptr};
static auto receiver = chan::receiver<int>{nullptr};
auto entities = make_tuple(move(mutual), move(sender), move(receiver));
for_each(entities, [](auto& e){
// using T = typename remove_cvref<decltype(e)>::type;
using T = remove_cvref_t<decltype(e)>;
static_assert(is_final_v<T>);
static_assert(!is_copy_constructible_v<T>);
static_assert(is_nothrow_move_constructible_v<T>);
});
}
{
auto [tx, rx] = chan::make_channel<int>();
tx.send(42);
int x = rx.recv().value();
std::cout << "x=" << x << "\n";
assert(x == 42);
}
{
auto [tx, rx] = chan::make_channel<int>();
// no sender - if receiver doesn't check for the number of senders the
// receiver will block forever
tx.~sender();
auto x = rx.recv();
std::cout << "x=" << (x.has_value() ? "something" : "nothing") << "\n";
assert (!x.has_value());
}
}
| true |
57901f0671676203c1e93504472d389602fa0e92 | C++ | SEDS/mangrove-catalog | /alloc-using-property/alloc-using-property.cpp | UTF-8 | 695 | 2.5625 | 3 | [] | no_license | // Juliet CWE680_Integer_Overflow_to_Buffer_Overflow__new_listen_socket_84_goodG2B.cpp
// Structure: alloc-using-property
#include "alloc-using-property.h"
#include <stdio.h>
AllocUsingProperty::AllocUsingProperty()
{
data = 20;
}
AllocUsingProperty::~AllocUsingProperty()
{
int i;
size_t dataBytes = data * sizeof(int); /* sizeof array in bytes */
int * intPointer = (int*)new char[dataBytes];
for (i = 0; i < data; i++)
{
intPointer[i] = 7;
}
// Tool C FP: Uninitialized variable. *intPointer was not initialized
// Tool B FP: none
// Tool A: none
printf("int: %d\n", intPointer[0]);
delete [] intPointer;
} | true |
c77838e1d1c7ad43bbb5e699948d89a8e5fc8726 | C++ | Adityasharma15/Agorithms | /DigitsinFactorial.cpp | UTF-8 | 259 | 2.703125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main()
{
long long int n;
cout << "Enter no to find digits in factorial of" << endl;
cin >> n;
long long int fac = 1;
for(int i=1;i<=n;i++)
{
fac*=i;
}
cout << floor(log10(fac)) + 1 << endl;
}
| true |
bd2fb69f6f7428a328b8c9ab53425510f622355a | C++ | wartech0/ablative | /AblativeGL/Icosphere.h | UTF-8 | 815 | 2.75 | 3 | [
"MIT"
] | permissive | #ifndef ICOSPHERE_H
#define ICOSPHERE_H
#include <vector>
#include <map>
#include <math.h>
#include <stdint.h>
#include <glm\glm.hpp>
struct Indices
{
int v1;
int v2;
int v3;
Indices(int v1, int v2, int v3)
{
this->v1 = v1;
this->v2 = v2;
this->v3 = v3;
}
};
class Icosphere
{
public:
Icosphere(int iterations);
~Icosphere();
void GenerateNormals();
glm::vec3* GetVertices();
glm::vec3* GetNormals();
int* GetIndices();
int GetNumberOfVertices();
int GetNumberOfNormals();
int GetNumberOfIndices();
private:
std::vector<glm::vec3> normals;
std::vector<glm::vec3> vertices;
std::vector<int> indices;
std::vector<Indices> faces;
std::map<int64_t, int> middle_point_cache;
int index;
int getMiddlePoint(int point1, int point2);
int addVertex(const glm::vec3& vertex);
};
#endif | true |
3cb698f7fbf85082bf46bf6a7e57e8212cb3f6ec | C++ | LuisJorgeLozano/CodeforcesSoluciones | /A. Hulk - Problem 705A/main.cpp | UTF-8 | 821 | 3.40625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
int a;
string firstWord = "I hate ";
string secondWord = "I love ";
string stringResult = "";
bool flag = true;
cin >> a;
for(int i=0; i < a; i++){
if(i != a-1){
if(flag){
stringResult = stringResult + firstWord + "that ";
flag = false;
}else{
stringResult = stringResult + secondWord + "that ";
flag = true;
}
}else{
if(flag){
stringResult = stringResult + firstWord + "it ";
flag = false;
}else{
stringResult = stringResult + secondWord + "it ";
flag = true;
}
}
}
cout << stringResult << endl;
} | true |
b0e85b85bec717ebd0c6524ad4ea385e92694be0 | C++ | gerard-geer/Tile2D | /src/Framebuffer.cpp | UTF-8 | 4,860 | 2.78125 | 3 | [] | no_license | #include "Framebuffer.h"
Framebuffer::Framebuffer()
{
this->width = 0;
this->height = 0;
this->framebuffer = 0;
this->renderbuffer = 0;
this->depthbuffer = 0;
}
Framebuffer::~Framebuffer()
{
}
const char * getFramebufferError(GLenum e)
{
switch(e)
{
case GL_FRAMEBUFFER_UNDEFINED : return "GL_FRAMEBUFFER_UNDEFINED";
case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT : return "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT";
case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT : return "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";
case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER : return "GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER";
case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER : return "GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER";
case GL_FRAMEBUFFER_UNSUPPORTED : return "GL_FRAMEBUFFER_UNSUPPORTED";
case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE : return "GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE";
case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS : return "GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS";
case GL_FRAMEBUFFER_COMPLETE : return "GL_FRAMEBUFFER_COMPLETE";
case 0 :
{ // Oh snap an error occured when calling glCheckFramebufferStatus()
int error = glGetError();
switch(error)
{
case GL_INVALID_ENUM : return "GL_INVALID_ENUM";
case GL_INVALID_OPERATION : return "GL_INVALID_OPERATION";
default: return "NO ERROR";
}break;
}
default: return "unknown";
}
}
bool Framebuffer::init(GLuint width, GLuint height)
{
// First, store the width and height.
this->width = width;
this->height = height;
// Create the color attachment.
glGenTextures(1, &this->renderbuffer);
glBindTexture(GL_TEXTURE_2D, this->renderbuffer);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, this->width, this->height,
0, GL_BGRA, GL_UNSIGNED_BYTE, NULL);
// Create the depth attachment.
glGenTextures(1, &this->depthbuffer);
glBindTexture(GL_TEXTURE_2D, this->depthbuffer);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, this->width, this->height,
0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL);
// Create the framebuffer.
glGenFramebuffers(1, &this->framebuffer);
glBindFramebuffer(GL_FRAMEBUFFER, this->framebuffer);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glBindTexture(GL_TEXTURE_2D, this->renderbuffer);
// Attach the color texture as the framebuffer's color attachment.
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D, this->renderbuffer, 0);
// Attach the depth texture as the framebuffer's depth attachment.
glBindTexture(GL_TEXTURE_2D, this->depthbuffer);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
GL_TEXTURE_2D, this->depthbuffer, 0);
// Enable depth testing.
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
// Best practice to check framebuffer completeness.
GLenum e = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER);
// Go ahead and set the render target back to the window's backbuffer.
glBindFramebuffer(GL_FRAMEBUFFER, 0);
return e == GL_FRAMEBUFFER_COMPLETE;
}
bool Framebuffer::resize(GLuint width, GLuint height)
{
// Delete the old stuff...
this->destroy();
// ...To initialize it anew.
return this->init(width,height);
}
void Framebuffer::setAsRenderTarget()
{
// Tell OpenGL to do what we want.
glBindFramebuffer(GL_FRAMEBUFFER, this->framebuffer);
// Make sure that we're rendering to the framebuffer's dimensions.
glViewport(0,0, this->width, this->height);
}
GLuint Framebuffer::getWidth()
{
return this->width;
}
GLuint Framebuffer::getHeight()
{
return this->height;
}
GLuint Framebuffer::getRenderTexture()
{
return this->renderbuffer;
}
GLuint Framebuffer::getDepthTexture()
{
return this->depthbuffer;
}
void Framebuffer::destroy()
{
// Delete everything we had on the GPU.
glDeleteFramebuffers(1, &this->framebuffer);
glDeleteRenderbuffers(1, &this->depthbuffer);
glDeleteTextures(1, &this->renderbuffer);
}
| true |
82e55cf4a915c383fbeaf2727c0e784bf532333b | C++ | harleenp/MyTunes-Library | /UI.cpp | UTF-8 | 433 | 3.015625 | 3 | [] | no_license |
#include <iostream>
#include <iomanip>
#include <string>
#include "UI.h"
#include <vector>
using namespace std;
void UI::promptForStr(string prompt, string& str)
{
cout << prompt << ": ";
getline(cin, str);
}
void UI::printMessage(string message)
{
cout << message << endl;
}
void UI::printParsedCommand(vector<string>& parsed) {
for (auto it = parsed.begin(); it != parsed.end(); it++)
cout << *it << endl;
}
| true |
a82f18f5a12bcb1b536c7991420589de52cb5400 | C++ | BiermanM/Data-Structures-Projects | /Project 2/HW 3.cpp | UTF-8 | 19,611 | 3.6875 | 4 | [] | no_license | /*
Assignment: Homework #3
Author: Matthew Bierman
Course: CS 3345.502 (Data Structures and Introduction to Algorithmic Analysis)
Instructor: Professor Kamran Khan
Date Due: October 8, 2017 at 11:30pm
*/
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <string>
#include <cmath>
using namespace std;
class Word {
public:
string name, type, definition;
unsigned int hashCode;
// constructors
Word() {
name = "";
type = "";
definition = "";
hashCode = 0;
}
Word(string n) {
name = convertToProper(n);
type = "";
definition = "";
hashCode = hashFunc();
}
Word(string n, string t, string d) {
name = n;
type = t;
definition = d;
hashCode = hashFunc();
}
// replace all spaces with underscores and convert all uppercase to lowercase
string convertToProper(string str) {
string newStr = "";
for (int i = 0; i < str.length(); i++) {
if (str.at(i) == ' ')
newStr += '_';
else if (str.at(i) >= 65 && str.at(i) <= 90)
newStr += (str.at(i) + 32);
else
newStr += str.at(i);
}
return newStr;
}
// get hash for word
unsigned int hashFunc() {
unsigned int hash = 0;
for (int i = 0; i < name.length(); i++)
hash = (29 * hash) + (name.at(i) * 5);
return hash;
}
// print the name, type, definition, and hash code for the word
void print() {
cout << "{" << name << "}, {" << type << "}, {" << definition << "}, hash code = " << hashCode << endl;
}
};
class Node {
public:
Word * word;
Node * next;
// constructors
Node() {
word = nullptr;
next = nullptr;
}
Node(Word * w) {
word = w;
next = nullptr;
}
Node(Word * w, Node * n) {
word = w;
next = n;
}
};
class OpenAddressing {
public:
int tableSize, numUsedCells;
Word ** table;
// default constructor
OpenAddressing() {
tableSize = 13;
numUsedCells = 0;
table = new Word * [tableSize]();
}
// insert word if table uses linear probing
void insertLinearProbing(Word * w) {
int tableIndex = 0;
// if index from hashing is already filled, add one to the index until an empty index is found
for (int i = 0; i < tableSize; i++) {
tableIndex = (w->hashCode + i) % tableSize;
if (table[tableIndex] == nullptr) {
table[tableIndex] = w;
numUsedCells++;
break;
}
}
// check if table needs rehashing
rehash('l');
}
// insert word if table uses quadratic probing
void insertQuadraticProbing(Word * w) {
int tableIndex = 0;
// if index from hashing is already filled, add one and square the index until an empty index is found
for (int i = 0; i < tableSize; i++) {
tableIndex = (w->hashCode + (int) pow(i, 2)) % tableSize;
if (table[tableIndex] == nullptr) {
table[tableIndex] = w;
numUsedCells++;
break;
}
}
// check if table needs rehashing
rehash('q');
}
// a different hashing function to be used in Double Hashing
unsigned int secondHash(Word * w) {
unsigned int hash2 = 0;
for (int i = 0; i < w->name.length(); i++)
hash2 = (37 * hash2) + (w->name.at(i) * 47);
return hash2;
}
// insert word if table uses double hashing
void insertDoubleHashing(Word * w) {
unsigned int hash2 = secondHash(w);
int tableIndex = 0;
// if index from hashing is already filled, use a second hashing function and
// multiply the result of the second hashing function by the index until an
// empty index is found
for (int i = 0; i < tableSize; i++) {
tableIndex = (w->hashCode + ((unsigned) i * hash2)) % tableSize;
if (table[tableIndex] == nullptr) {
table[tableIndex] = w;
numUsedCells++;
break;
}
}
// check if table needs rehashing
rehash('d');
}
// get next prime number that is the smallest number that is larger than double the current table size
int getNextPrime(int currTableSize) {
int num = currTableSize * 2;
while (true){
bool hasFactors = false;
for (int i = 2; i <= (num / 2); i++)
{
// found a factor that isn't 1 or n, so number isn't prime
if (num % i == 0)
hasFactors = true;
}
if (hasFactors == false)
break;
else
num++;
}
return num;
}
// Rehash if load factor is greater than 1/2
void rehash(char type) {
if ((double) numUsedCells / tableSize > 0.5) {
// if rehash is needed, find the smallest number that is larger than double the table size
int newTableSize = getNextPrime(tableSize);
Word ** newTable = new Word * [newTableSize]();
// for each element in table that's not empty, move to newTable
for (int i = 0; i < tableSize; i++) {
if (table[i] != nullptr) {
if (type == 'l') {
// insert w at table[i] into newTable
int tableIndex = 0;
for (int j = 0; j < newTableSize; j++) {
// use Linear Probing to insert into new table
tableIndex = (table[i]->hashCode + j) % newTableSize;
if (newTable[tableIndex] == nullptr) {
newTable[tableIndex] = table[i];
break;
}
}
}
else if (type == 'q') {
// insert w at table[i] into newTable
int tableIndex = 0;
for (int j = 0; j < newTableSize; j++) {
// use Quadratic Probing to insert into new table
tableIndex = (table[i]->hashCode + (int) pow(j, 2)) % newTableSize;
if (newTable[tableIndex] == nullptr) {
newTable[tableIndex] = table[i];
break;
}
}
}
else if (type == 'd') {
unsigned int hash2 = 0;
for (int j = 0; j < table[i]->name.length(); j++)
hash2 = (37 * hash2) + (table[i]->name.at(j) * 47);
// insert w at table[i] into newTable
int tableIndex = 0;
for (int j = 0; j < newTableSize; j++) {
// use Double Hashing to insert into new table
tableIndex = (table[i]->hashCode + ((unsigned) j * hash2)) % newTableSize;
if (newTable[tableIndex] == nullptr) {
newTable[tableIndex] = table[i];
break;
}
}
}
}
}
// replace the old table with the new, larger table
table = newTable;
tableSize = newTableSize;
}
}
// used for converting integer to string in return of find functions
string intToStr(int num) {
ostringstream ss;
ss << num;
return ss.str();
}
// find word if table uses Linear Probing
string findLinearProbing(Word * w) {
bool success = false;
int investigated = 0;
string type = "";
string def = "";
int tableIndex = 0;
// if index from hashing doesn't contain the word, add one to the index until the word is found
for (int i = 0; i < tableSize; i++) {
investigated++;
tableIndex = (w->hashCode + i) % tableSize;
if (table[tableIndex] != nullptr && table[tableIndex]->name == w->name) {
success = true;
break;
}
}
if (success == true)
return "yes\t\t" + intToStr(investigated);
else
return "no\t\t" + intToStr(investigated);
}
// find word if table uses Quadratic Probing
string findQuadraticProbing(Word * w) {
bool success = false;
int investigated = 0;
string type = "";
string def = "";
int tableIndex = 0;
// if index from hashing doesn't contain the word, add one and square the index until the word is found
for (int i = 0; i < tableSize; i++) {
investigated++;
tableIndex = (w->hashCode + (int) pow(i, 2)) % tableSize;
if (table[tableIndex] != nullptr && table[tableIndex]->name == w->name) {
success = true;
break;
}
}
if (success == true)
return "yes\t\t" + intToStr(investigated);
else
return "no\t\t" + intToStr(investigated);
}
// find word if table uses Double Hashing
string findDoubleHashing(Word * w) {
bool success = false;
int investigated = 0;
string type = "";
string def = "";
unsigned int hash2 = secondHash(w);
int tableIndex = 0;
// if index from hashing doesn't contain the word, use a second hashing function
// and multiply the result of the second hashing function by the index until the
// word is found
for (int i = 0; i < tableSize; i++) {
investigated++;
tableIndex = (w->hashCode + ((unsigned) i * hash2)) % tableSize;
if (table[tableIndex] != nullptr && table[tableIndex]->name == w->name) {
success = true;
break;
}
}
if (success == true)
return "yes\t\t" + intToStr(investigated);
else
return "no\t\t" + intToStr(investigated);
}
};
class SeparateChaining {
public:
int tableSize, numUsedCells;
Node ** table;
// default constructor
SeparateChaining() {
tableSize = 13;
numUsedCells = 0;
table = new Node * [tableSize]();
}
// insert word into table
void insertSeparateChaining(Word * w) {
int tableIndex = w->hashCode % tableSize;
// if index in table is empty, place word at beginning
if (table[tableIndex] == nullptr)
table[tableIndex] = new Node(w);
// if index already contains words, place word at beginning of list of words
else {
Node * newNode = new Node(w);
newNode->next = table[tableIndex];
table[tableIndex] = newNode;
}
numUsedCells++;
rehash();
}
// get next prime number that is the smallest number that is larger than double the current table size
int getNextPrime(int currTableSize) {
int num = currTableSize * 2;
while (true){
bool hasFactors = false;
for (int i = 2; i <= (num / 2); i++)
{
// found a factor that isn't 1 or n, so number isn't prime
if (num % i == 0)
hasFactors = true;
}
if (hasFactors == false)
break;
else
num++;
}
return num;
}
// Rehash if load factor is greater than 1
void rehash() {
// rehash if load factor is greater than 1
if ((double) numUsedCells / tableSize > 1.0) {
// if rehash is needed, find the smallest number that is larger than double the table size
int newTableSize = getNextPrime(tableSize);
Node ** newTable = new Node * [newTableSize]();
for (int i = 0; i < tableSize; i++) {
// for each element in table that's not empty, move to newTable
if (table[i] != nullptr) {
// if only one element in index
if (table[i]->next == nullptr) {
int newTableIndex = table[i]->word->hashCode % newTableSize;
// use Separate Chaining to insert into new table
if (newTable[newTableIndex] == nullptr)
newTable[newTableIndex] = table[i];
else {
table[i]->next = newTable[newTableIndex];
newTable[newTableIndex] = table[i];
}
}
// if more than one element in index
else {
// move each element that's in index until index is empty
while (table[i] != nullptr) {
Node * temp = table[i]->next;
table[i]->next = nullptr;
int newTableIndex = table[i]->word->hashCode % newTableSize;
// use Separate Chaining to insert into new table
if (newTable[newTableIndex] == nullptr)
newTable[newTableIndex] = table[i];
else {
table[i]->next = newTable[newTableIndex];
newTable[newTableIndex] = table[i];
}
table[i] = temp;
}
}
}
}
// replace the old table with the new, larger table
table = newTable;
tableSize = newTableSize;
}
}
// used for converting integer to string in return of findSeparateChaining
string intToStr(int num) {
ostringstream ss;
ss << num;
return ss.str();
}
// find word in table
string findSeparateChaining(Word * w) {
bool success = false;
int investigated = 0;
string type = "";
string def = "";
int tableIndex = w->hashCode % tableSize;
// if index is empty, end search
if (table[tableIndex] == nullptr) {
investigated++;
}
else {
// if index isn't empty, look through each node until word is found
Node * n = table[tableIndex];
while (n != nullptr) {
investigated++;
if (n->word->name != w->name)
n = n->next;
else {
type = n->word->type;
def = n->word->definition;
success = true;
break;
}
}
}
if (success == true)
return type + "|" + def + "|yes\t\t" + intToStr(investigated);
else
return type + "|" + def + "|no\t\t" + intToStr(investigated);
}
};
int main() {
// Linear Probing
OpenAddressing * lp = new OpenAddressing();
// Quadratic Probing
OpenAddressing * qp = new OpenAddressing();
// Double Hashing
OpenAddressing * dh = new OpenAddressing();
// Separate Chaining
SeparateChaining * sc = new SeparateChaining();
// Total number of words in dictionary.txt
int numWords = 0;
// load dictionary into data structures
ifstream inFile("dictionary.txt");
if (inFile) {
string line;
while (inFile.eof() == false) {
getline(inFile, line);
string name, type, def;
// separate line from dictionary.txt into name, type, and definition
int pipe1 = line.find('|');
int pipe2 = line.substr(pipe1 + 1).find('|');
name = line.substr(0, pipe1);
type = line.substr(pipe1 + 1, pipe2);
def = line.substr(pipe1 + pipe2 + 2);
// create word object
Word * w = new Word(name, type, def);
// inset word into each data structure
lp->insertLinearProbing(w);
qp->insertQuadraticProbing(w);
dh->insertDoubleHashing(w);
sc->insertSeparateChaining(w);
numWords++;
}
}
inFile.close();
string input = " ";
while (true) {
cout << "Word to search for: ";
getline(cin, input);
// user can exit program by inputting nothing or -1
if (input != "-1" && input != "") {
Word * w = new Word(input);
// perform search for word in each data structure
string scResult = sc->findSeparateChaining(w);
string lpResult = lp->findLinearProbing(w);
string qpResult = qp->findQuadraticProbing(w);
string dhResult = dh->findDoubleHashing(w);
// if the word was found, print the name, type, and definition, and save the rest of the result
// only result from separate chaining find contains type and definition, because if the word was
// found in one data structure, it'll be found in the other three
// format of result is: type|definition|yes/no[tab]numberOfInvestigations
if (scResult.find('|') != 0) {
cout << input << " (" << scResult.substr(0, scResult.find('|')) << "): ";
scResult = scResult.substr(scResult.find('|') + 1);
cout << scResult.substr(0, scResult.find('|')) << "\n" << endl;
scResult = scResult.substr(scResult.find('|') + 1);
}
else
scResult = scResult.substr(2);
// round to 3 decimals for lambda
cout << fixed << setprecision(3);
cout << "Total words: " << numWords << endl;
cout << "Data Structure\t\tTable Size\tLambda\t\tSuccess\t\tItems Investigated" << endl;
cout << "Linear Probing\t\t" << lp->tableSize << "\t\t" << ((double) lp->numUsedCells / lp->tableSize) << "\t\t" << lpResult << endl;
cout << "Quadratic Probing\t" << qp->tableSize << "\t\t" << ((double) qp->numUsedCells / qp->tableSize) << "\t\t" << qpResult << endl;
cout << "Separate Chaining\t" << sc->tableSize << "\t\t" << ((double) sc->numUsedCells / sc->tableSize) << "\t\t" << scResult << endl;
cout << "Double Hashing\t\t" << dh->tableSize << "\t\t" << ((double) dh->numUsedCells / dh->tableSize) << "\t\t" << dhResult << "\n" << endl;
}
else
break;
}
return 0;
}
| true |
5bcc94eea28e9e4568727d863d98f45c0cc42220 | C++ | ivon99/Raster_Graphics_Project | /Pixel.cpp | UTF-8 | 1,090 | 3.5625 | 4 | [] | no_license | #include "Pixel.hpp"
#include <iostream>
using namespace std;
Pixel::Pixel(unsigned char R,unsigned char G,unsigned char B)
{
m_R=R;
m_G=G;
m_B=B;
}
Pixel& Pixel::operator=(const Pixel& other)
{
m_R=other.m_R;
m_G = other.m_G;
m_B= other.m_B;
return *this;
}
bool Pixel::isWhite() const
{
if((m_R==255)&&
(m_G==255)&&
(m_B==255))
{
return true;
}
else
{
return false;
}
}
bool Pixel::isGrey() const
{
if((m_R==m_G)&&(m_R==m_B)&&(m_B==m_G))
{
return true;
}
else
{
return false;
}
}
Pixel& Pixel::operator-(int value)
{
unsigned char old_R =m_R;
unsigned char old_G= m_G;
unsigned char old_B= m_B;
m_R=value-old_R;
m_G=value-old_G;
m_B=value-old_B;
return *this;
}
bool Pixel::operator>(int value)
{
if((m_R>value)&&
(m_G>value)&&
(m_B>value))
{
return true;
}
else
{
return false;
}
}
std::ostream& operator<<(std::ostream& out, Pixel& other)
{
out<<other.m_R<<other.m_G<<other.m_B;
return out;
}
| true |
9deeeccdec6f61b47309304ce1a459d53bba655d | C++ | mugisaku/liboat | /gramk/gramk_painter.hpp | UTF-8 | 2,120 | 2.59375 | 3 | [] | no_license | #ifndef GRAMK_PAINTER_HPP_INCLUDED
#define GRAMK_PAINTER_HPP_INCLUDED
#include"oat.hpp"
#include"gramk_card.hpp"
constexpr int number_of_colors = 8;
constexpr oat::Color
palette[number_of_colors] =
{
oat::Color(0x1F),
oat::Color(0x3F),
oat::Color(0x5F),
oat::Color(0x7F),
oat::Color(0x9F),
oat::Color(0xBF),
oat::Color(0xDF),
oat::Color(0xFF),
};
enum class
PaintingMode
{
draw_point,
draw_line,
draw_ellipse,
draw_rect,
fill_rect,
fill_area,
transform_area_frame,
paste,
layer,
};
using Callback = void (*)(Card* card);
class
Painter: public oat::Widget
{
static constexpr int pixel_size = 10;
Card* target;
Callback callback;
Card* copy_card;
Rect copy_rect;
oat::Point paste_point;
Card* tmp_card0;
Card* tmp_card1;
const Card* base_card;
bool hide_base_flag;
PaintingMode mode;
int selecting_state;
uint8_t current_color;
bool single_pointing_flag;
bool pointing_flag;
oat::Point point0;
oat::Point point1;
std::vector<oat::Point> point_buffer;
enum class Corner{
none,
top_left,
top_right,
bottom_left,
bottom_right,
} rect_corner;
Rect operating_rect;
Rect selecting_rect;
void draw_selecting_rect();
void fill_area(int color, int x, int y);
void paste(int x, int y, bool overwrite, bool rehearsal);
void make_pointing(int x, int y);
void move_corner(int x, int y);
public:
Painter(Callback cb);
void change_target(Card& card);
void change_base();
void change_hide_base_flag(bool v);
void change_current_color(uint8_t color);
void change_mode(PaintingMode mode_);
Card* get_target() const;
uint8_t get_current_color() const;
const Rect& get_operating_rect() const;
const Rect& get_selecting_rect() const;
void copy();
void clear_selection();
void clear_image();
void process_mouse(const oat::Mouse& mouse) override;
void render() override;
Widget* create_oper_widget();
Widget* create_mode_widget();
Widget* create_palette_widget();
};
#endif
| true |
7425f93c72176ee074bf4cd510ed275e2593de91 | C++ | jw2528783/WatermanJustin_CSC5_40717 | /Hmwk/Assignment2-3/Gaddis_7thEd_Chap3_Prob19/main.cpp | UTF-8 | 1,628 | 3.65625 | 4 | [] | no_license | /*
* File: main.cpp
* Author: Justin Waterman
* Created on January 14, 2015, 8:14 AM
* Purpose: Problem 19 How Many Pizzas?
* Number of pizzas needed for a party.
*/
#include <cstdlib>
#include <iostream>
#include <iomanip>
using namespace std;
const float PI=3.14159; //the value for Pi.
int main(int argc, char** argv) {
//Declare variables
float pizdiam; //diameter of the pizza
unsigned short numslic; //number of slices taken from the pizza
float pizarea; //area of the whole pizza
unsigned short numppl; //number of people at party
unsigned short numpizz; //number of pizzas to buy
float numslne;
//Display purpose and prompt for input.
cout<<"This program will calculate the number of pizzas to buy for a "
"party.\nPlease input the diameter of your pizzas, in inches."<<endl;
cin>>pizdiam;
cout<<"How many people will attend this party?"<<endl;
cin>>numppl;
//Calculations
pizarea=(pizdiam/2)*(pizdiam/2)*PI; //calculates the pizza's area
numslic=pizarea/14.125; //calculates the number of slices
cout<<fixed<<setprecision(1);
numslne=numppl*4;
numpizz=numslne/numslic+1; //calculates the number of pizzas needed to be bought.
//Display results
cout<<"The radius of your pizza = "<<pizdiam/2<<" inches"<<endl;
cout<<"the number of people at your party are "<<numppl<<endl;
cout<<"The pizza area = "<<pizarea<<endl;
cout<<"The number of slices that your pizza can be cut into are "<<
numslic<<endl;
cout<<"The number of pizzas you need to buy are "<<numpizz<<endl;
return 0;
}
| true |
caa51f1e35a92a1ebab47ecad956fc7b2d669244 | C++ | AlbertBartalis/Covid-Vaccination-Schedule | /Proiect final/main.cpp | UTF-8 | 1,436 | 3.09375 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include "queue.h"
#include "utils.h"
using namespace std;
pr_queue persoane;
void loadDatabase() {
ifstream in("input.txt");
while (!in.eof())
{
string n;
int a;
int s;
string c;
in >> n;
if (n.empty()) {
break;
}
in >> a;
in >> s;
in >> c;
persoane.enqueue(n, a, s, c);
}
cout << "Input data was read from file!" << endl;
}
void addPerson()
{
string n;
int a;
int s;
string c;
cout << "Give name: ";
cin >> n;
cout << "Age: ";
cin >> a;
cout << "Give sanitary condition: ";
cin >> s;
cout << "Give your city`s name: ";
cin >> c;
persoane.enqueue(n, a, s, c);
}
int main()
{
int cmd;
cmd = 9;
while (cmd != 0) {
printMenu();
cmd = getCommand();
switch (cmd) {
case 1: {
//initializeDataset();
loadDatabase();
break;
}
case 2: {
addPerson();
break;
}
case 3: {
persoane.dequeue();
break;
}
case 4:
for (int i = getDoses(); i > 0; i--)
persoane.dequeue();
break;
case 5:
persoane.display();
break;
default:
break;
}
}
return 0;
}
| true |
31ccaa8ef8e98b175c894f42cf01b55a7aeb785b | C++ | AmefuriTell/NN-GA | /GA/Individual.cpp | UTF-8 | 1,643 | 3.15625 | 3 | [] | no_license | #include "Individual.hpp"
#include "my_random.hpp"
//流用する際書き換えるポイント
/*
1. 染色体の型
2. 染色体の初期値
3. 染色体の突然変異
4. 評価値計算
*/
//コンストラクタ
Individual::Individual()
{
init(1000, 1000, 1, 1000, 0.1);
}
Individual::Individual(int gen_max, int pop_size, int elite, int chromo_size, long double mutate_prob)
{
init(gen_max, pop_size, elite, chromo_size, mutate_prob);
}
//デコンストラクタ
Individual::~Individual()
{
}
//個体を初期化(各個体1回しか発動させない)
void Individual::init(int gen_max, int pop_size, int elite, int chromo_size, long double mutate_prob)
{
srand((unsigned int)time(NULL));
GEN_MAX = gen_max;
POP_SIZE = pop_size;
ELIET = elite;
CHROMO_SIZE = chromo_size;
MUTATE_PROB = mutate_prob;
chromo.resize(CHROMO_SIZE);
score = 0.0L;
create_now_chromo();
}
//新種の個体を生成
void Individual::create_now_chromo()
{
for (int i = 0; i < CHROMO_SIZE; i++)
{
chromo[i] = rand_normal(0, 1.0);
}
}
//交叉
void Individual::crossover(Individual &father, Individual &mother)
{
//一様交叉
for (int i = 0; i < CHROMO_SIZE; i++)
{
chromo[i] = (rand() % 2) ? father.chromo[i] : mother.chromo[i];
}
}
//突然変異
void Individual::mutate()
{
for (int i = 0; i < CHROMO_SIZE; i++)
{
if((long double)rand() / RAND_MAX < MUTATE_PROB)
{
chromo[i] = rand_normal(0, 1.0);
}
}
}
//評価値を算出する(これは、コードごとに書き換える。)
void Individual::evaluate()
{
} | true |
b336bac67e5ed8e9430a9c02a2053d0358b6e416 | C++ | hannachoi24/Data_Structure | /Week7_List/includes/LineHnSLinkedList.h | UTF-8 | 3,719 | 4.09375 | 4 | [] | no_license | #pragma once
#include <iostream>
#include <string>
class line
{
protected:
std::string data;
public:
line(std::string line = "") { data = line; }
void read(std::istream *is = &std::cin)
{
std::getline(*is, data); // 한 줄씩 받음
}
void display(std::ostream *os = &std::cout)
{
*os << data << "\n";
}
bool hasData(std::string str) { return str == data; }
};
class node : public line
{
private:
node *next;
public:
node(std::string str = "") : line(str)
{
next = nullptr;
}
node *getLink() { return next; }
std::string getData() { return data; }
void setLink(node *target) { next = target; }
void insertNext(node *newnode)
{
if (newnode != nullptr)
{
newnode->next = next;
next = newnode;
}
} // 노드의 다음 자리에 새 노드를 넣는 연산
node *removeNext()
{
node *removed = next;
if (removed != nullptr)
next = removed->next;
return removed;
} // 노드의 다음 자리 노드를 지우는 연산
};
class l_hn_s_linked_list
{
protected:
node origin;
public:
l_hn_s_linked_list() : origin("head node") {} //생성자
~l_hn_s_linked_list() { clear(); } //소멸자
void clear(); // 리스트를 지우는 연산
node *getHead(); // 첫 노드를 부르는 연산
bool isEmpty(); // 공백 확인
node *getEntry(int pos); // 조회연산
void insert(int pos, node *n); // 삽입연산
node *remove(int pos); // 삭제연산
node *find(std::string value); // 검색연산 (value와 같은 값을 찾음)
void replace(int pos, node *n); // 치환연산
size_t size(); // 사이즈 구하기
void display(); // Linked List의 전체 내용 출력
};
void l_hn_s_linked_list::clear()
{
while (!isEmpty())
{
delete remove(0);
}
} // 리스트를 지우는 연산
node *l_hn_s_linked_list::getHead()
{
return origin.getLink();
} // 첫 노드를 부르는 연산
bool l_hn_s_linked_list::isEmpty()
{
return getHead() == nullptr;
} // 공백 확인
node *l_hn_s_linked_list::getEntry(int pos)
{
node *n = &origin;
for (int i = -1; i < pos; i++, n = n->getLink())
{
if (n == nullptr)
{
break;
}
}
return n;
} // 조회연산
void l_hn_s_linked_list::insert(int pos, node *n)
{
node *prev = getEntry(pos - 1);
if (prev != nullptr)
{
prev->insertNext(n);
}
} // 삽입연산
node *l_hn_s_linked_list::remove(int pos)
{
node *prev = getEntry(pos - 1);
return prev->removeNext();
} // 삭제연산
node *l_hn_s_linked_list::find(std::string value)
{
for (node *p = getHead(); p != NULL; p = p->getLink())
{
if (p->getData() == value)
{
return p;
}
}
return nullptr;
} // 검색연산 (value와 같은 값을 찾음). 가장 먼저 나오는 노드를 리턴
void l_hn_s_linked_list::replace(int pos, node *n)
{
node *prev = getEntry(pos - 1);
if (prev != nullptr)
{
delete prev->removeNext();
prev->insertNext(n);
}
} // 치환연산
size_t l_hn_s_linked_list::size()
{
int count = 0;
for (node *p = getHead(); p != nullptr; p = p->getLink())
{
count++;
}
return count;
} // 사이즈 구하기
void l_hn_s_linked_list::display()
{
std::cout << "전체 항목의 수: " << size() << ", ";
for (node *p = getHead(); p != nullptr; p = p->getLink())
{
std::cout << p->getData() << " ";
}
} // Linked List의 전체 내용 출력 | true |
a3338f230602f57fe1fe085acef7ae47bc6e1fd4 | C++ | KowalskiThomas/SemiNumericalAlgorithms | /cpp_large_integer_factorising/kroot.cpp | UTF-8 | 1,757 | 2.875 | 3 | [] | no_license | #include"kroot.h"
size_t get_size(const entier x)
{
return std::abs(x.get_mpz_t()->_mp_size);
}
entier power(entier a, int k)
{
if (k == 0)
return entier(1);
else if (k == 1)
return entier(a);
else if (k%2==0)
return power(a, k/2)* power(a,k/2);
else
return power(a, k/2) * power(a,k/2) * a;
}
entier sqrt_v2(entier a)
{
size_t n = get_size(a) ;
entier r = entier(a);
if (n > 2)
{
if (n % 2 == 1)
{
r = r >> ((n-1) * 64);
size_t j = get_size(r);
r = sqrt_v2(r) << (((n-1)) * 32);
}
else
{
r = r >> ((n-2) * 64);
size_t j = get_size(r);
r = sqrt_v2(r) << (((n-2)) * 32);
}
}
if (r == 0)
return 0;
int i = 0;
entier r_before = r + 1;
while (r < r_before)
{
r_before = r;
r = ( r + (a / r) ) / 2;
}
return r_before;
}
entier kroot_v2(entier a, int k)
{
size_t n = get_size(a);
entier r = entier(a);
if (n > k)
{
int i = 1;
while ((n-i)%k != 0)
{
i++;
}
r = r >> ((n-i) * 64);
r = kroot_v2(r, k) << ((n-i)/k * 64);
}
if (a==0)
return 0;
entier r_before = entier(r)+1;
while (r < r_before)
{
r_before = r;
r = ( (k-1) * r + (a / power(r,(k-1)))) / k;
}
return r_before;
}
unsigned long int log2(entier r)
{
if (r <= 1)
return 0;
unsigned long int i = (get_size(r) -1) * 64;
entier temp = r >> i;
while (temp > 0)
{
temp = temp >> 1;
i++;
}
return (i-1);
}
couple one_factor(entier a)
{
unsigned long int k = log2(a);
for (k; k>=2; k--)
{
entier r = kroot_v2(a, k);
if (power(r, k) == a)
{
couple c;
c.k = k;
c.r = r;
return c;
}
}
couple c;
c.k = 1;
c.r = a;
return c;
}
| true |
4a18cf259f1a40c3d9d60800d16d658f815fe5ab | C++ | RyanParker196/Zombie_Survival | /background.h | UTF-8 | 937 | 2.65625 | 3 | [] | no_license | //
// Created by Harry Makovsky on 5/2/19.
//
/*
This class is used ot create the city backgrouond city for the entire game. This class
also moves the background left to right as the man character moves away fromt the
zombies.
Constructor;
Background();
Method that draw the road, and the buildings
void draw();
void method that moves the background left
void moveLeft
void method that moves the background right
void moveRight
*/
#ifndef FINALPROJECT_DARKWHITE_BACKGROUND_H
#define FINALPROJECT_DARKWHITE_BACKGROUND_H
#include "shapes.h"
#include "graphics.h"
#include "rect.h"
#include "building.h"
#include <vector>
using namespace std;
class Background {
private:
double WIDTH;
Rect road,line1,line2;
vector<Building*> buildings;
public:
Background();
void draw();
void moveLeft();
void moveRight();
vector<Building*> getBuildings();
};
#endif //FINALPROJECT_DARKWHITE_BACKGROUND_H
| true |
090fca3b7c9b45d5864da06cde23e650adb7dff5 | C++ | teotwaki/latency-testruino | /latency-testruino.ino | UTF-8 | 3,745 | 2.515625 | 3 | [] | no_license | #include <LiquidCrystal.h>
#include <util/atomic.h>
#include "pin_config.hpp"
#include "config.hpp"
#include "typedefs.hpp"
#include "pressbutton.hpp"
#include "display.hpp"
#include "latencytest.hpp"
// Variables
TestResult test_result;
Display display(&test_result);
LatencyTest latency_test(&test_result);
PressButton start_stop_button(PIN_BUTTON_SS), reset_button(PIN_BUTTON_RS);
LiquidCrystal lcd(PIN_LCD_RS, PIN_LCD_EN, PIN_LCD_D4, PIN_LCD_D5, PIN_LCD_D6, PIN_LCD_D7);
void banner() {
lcd.clear();
lcd.setCursor(3, 0);
lcd.print(F("Back to the"));
lcd.setCursor(5, 1);
lcd.print(F("Future"));
led_on(Jack::A, Direction::TX);
delay(250);
led_on(Jack::B, Direction::RX);
delay(250);
led_on(Jack::A, Direction::RX);
delay(250);
led_on(Jack::B, Direction::TX);
delay(250);
lcd.clear();
lcd.setCursor(6, 0);
lcd.print(F("with"));
lcd.setCursor(6, 1);
lcd.print(F("Dixa"));
led_on(Jack::A, Direction::TX);
delay(250);
led_on(Jack::B, Direction::RX);
delay(250);
led_on(Jack::A, Direction::RX);
delay(250);
led_on(Jack::B, Direction::TX);
delay(250);
led_off();
lcd.clear();
}
void setup() {
// We are using 2 analog pins as outputs, to drive the microphone channels of the jacks.
pinMode(PIN_JACK_A_OUT, OUTPUT);
pinMode(PIN_JACK_B_OUT, OUTPUT);
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// display starting banner
banner();
adc_set_channel(Jack::B, Channel::LEFT);
}
void adc_set_channel(const Jack jack, const Channel channel) {
int8_t pin = 0;
if (jack == Jack::A) {
if (channel == Channel::LEFT) {
pin = PIN_JACK_A_IN_LEFT;
}
else {
pin = PIN_JACK_A_IN_RIGHT;
}
}
else {
if (channel == Channel::LEFT) {
pin = PIN_JACK_B_IN_LEFT;
}
else {
pin = PIN_JACK_B_IN_RIGHT;
}
}
// set pin
ADMUX = _BV(REFS0) // ref = AVCC
| _BV(ADLAR) // left adjust result
| pin; // input channel
// enable ADC
ADCSRB = 0; // free running mode
ADCSRA = _BV(ADEN) // enable
| _BV(ADSC) // start conversion
| _BV(ADATE) // auto trigger enable
| _BV(ADIF) // clear interrupt flag
| _BV(ADIE) // interrupt enable
| 7; // prescaler = 128
}
// Interrupt handler called each time an ADC reading is ready.
ISR(ADC_vect) {
// Read the ADC and convert to signed number.
int8_t sample = ADCH - 128;
// Update the phase of the local oscillator.
static uint16_t phase;
phase += PHASE_INC;
// Multiply the sample by square waves in quadrature.
int8_t x = sample;
if (((phase>>8) + 0x00) & 0x80) {
x = -1 - x;
}
int8_t y = sample;
if (((phase>>8) + 0x40) & 0x80) {
y = -1 - y;
}
// First order low-pass filter.
signal_I += x - (signal_I >> LOG_TAU);
signal_Q += y - (signal_Q >> LOG_TAU);
}
void led_on(const Jack jack, const Direction direction) {
int8_t pin = 0;
if (jack == Jack::A) {
if (direction == Direction::RX) {
pin = PIN_LED_A_RX;
}
else {
pin = PIN_LED_A_TX;
}
}
else {
if (direction == Direction::RX) {
pin = PIN_LED_B_RX;
}
else {
pin = PIN_LED_B_TX;
}
}
led_off();
digitalWrite(pin, HIGH);
}
void led_off() {
digitalWrite(PIN_LED_A_RX, LOW);
digitalWrite(PIN_LED_A_TX, LOW);
digitalWrite(PIN_LED_B_RX, LOW);
digitalWrite(PIN_LED_B_TX, LOW);
}
void loop() {
if (start_stop_button.pressed()) {
latency_test.startstop();
}
if (reset_button.pressed()) {
test_result.reset();
}
if (latency_test.running()) {
latency_test.run();
display.refresh(true);
}
else {
display.refresh(false);
}
}
| true |
c718215754df56bd8b3cb685c809feae8aeb9378 | C++ | luciedtigerhart/irrBoardGameEngine | /primevalion/PrimePlayState.cpp | UTF-8 | 103,101 | 2.71875 | 3 | [] | no_license | #include "PrimePlayState.h"
PrimePlayState::PrimePlayState() {};
PrimePlayState::~PrimePlayState() {};
void PrimePlayState::AgentACT(int ordering, IrrToken* token, IrrBoard* board)
{
//Set up animation
SetupAnimationAI(token, board, agent.move);
//Complete movement
if (ordering == 1) firstTokenMovedAI = true;
else if (ordering == 2) secondTokenMovedAI = true;
else if (ordering == 3) thirdTokenMovedAI = true;
tokenMovedAI = true;
}
void PrimePlayState::RessurrectTokenAI(IrrToken* token, IrrBoard* board, int i, int j)
{
//Re-activate token
token->setActive(true);
token->getBehavior(0)->setBool("isDead", false);
//Place token at the safe zone!
if (board->addToken(i, j, token))
{
//Make sure the token cannot move this turn
token->getBehavior(0)->setBool("isFinished", true);
//Increment AI token ressurrection counter
tokenRessurrectedAI++;
//Play position fitting sound
SFX->at(SFX_TOKEN_FIT)->getAudio()->setPlayOnceMode();
}
}
void PrimePlayState::SetupAnimationAI(IrrToken* token, IrrBoard* board, std::string move)
{
int iTarget, jTarget;
//Only animate tokens which have actually moved
if (move != "STAND")
{
//Simulate token selection
selectedToken = token;
token->getBehavior(0)->setBool("isSelected", true);
//Store adjacent positions
GetAdjacentTiles();
//Cross-shaped movement (includes Pushing)
if (move == "MOVE_N" || move == "MOVE_S" || move == "MOVE_W" || move == "MOVE_E")
{
//Set token's direction
if (move == "MOVE_N") selectedToken->getBehavior(0)->setInt("moveDir", NORTH);
else if (move == "MOVE_S") selectedToken->getBehavior(0)->setInt("moveDir", SOUTH);
else if (move == "MOVE_W") selectedToken->getBehavior(0)->setInt("moveDir", WEST);
else if (move == "MOVE_E") selectedToken->getBehavior(0)->setInt("moveDir", EAST);
//If target is a FREE tile...
if ((move == "MOVE_N" && board->board[iNorth][jNorth]->token == NULL)
|| (move == "MOVE_S" && board->board[iSouth][jSouth]->token == NULL)
|| (move == "MOVE_W" && board->board[iWest][jWest]->token == NULL)
|| (move == "MOVE_E" && board->board[iEast][jEast]->token == NULL))
{
//...And not a trap tile...
if ((move == "MOVE_N" && board->board[iNorth][jNorth]->inf != TRAP)
|| (move == "MOVE_S" && board->board[iSouth][jSouth]->inf != TRAP)
|| (move == "MOVE_W" && board->board[iWest][jWest]->inf != TRAP)
|| (move == "MOVE_E" && board->board[iEast][jEast]->inf != TRAP))
{
//...Neither an obstacle...
if ((move == "MOVE_N" && board->board[iNorth][jNorth]->inf != RUINS)
|| (move == "MOVE_S" && board->board[iSouth][jSouth]->inf != RUINS)
|| (move == "MOVE_W" && board->board[iWest][jWest]->inf != RUINS)
|| (move == "MOVE_E" && board->board[iEast][jEast]->inf != RUINS))
{
//Mark selected token for movement.
selectedToken->getBehavior(0)->setBool("isGonnaMove", true);
//Startup animation for selected token
selectedToken->getBehavior(0)->setBool("isAnimStarted", true);
//Execute move (start animations)
phase = ANIMATION_EXECUTION;
//Play token movement sound
SFX->at(SFX_TOKEN_DRAG)->getAudio()->setPlayOnceMode();
}
}
}
//If target is an occupied tile (PUSH move)...
else if ((move == "MOVE_N" && board->board[iNorth][jNorth]->token != NULL)
|| (move == "MOVE_S" && board->board[iSouth][jSouth]->token != NULL)
|| (move == "MOVE_W" && board->board[iWest][jWest]->token != NULL)
|| (move == "MOVE_E" && board->board[iEast][jEast]->token != NULL))
{
//Get position of target tile
if (move == "MOVE_N") { iTarget = iNorth; jTarget = jNorth; }
else if (move == "MOVE_S") { iTarget = iSouth; jTarget = jSouth; }
else if (move == "MOVE_W") { iTarget = iWest; jTarget = jWest; }
else if (move == "MOVE_E") { iTarget = iEast; jTarget = jEast; }
//If its a valid Push move...
if (PlayIsValid(PUSH, selectedToken->getBehavior(0)->getInt("moveDir"), board, iTarget, jTarget))
{
//Mark target token and the tokens behind it for pushing
tokensPushed = SetPushLine(CLICKED, selectedToken->getBehavior(0)->getInt("moveDir"), board, iTarget, jTarget);
//Mark selected token for movement
selectedToken->getBehavior(0)->setBool("isGonnaMove", true);
//Startup animation for selected token
selectedToken->getBehavior(0)->setBool("isAnimStarted", true);
//Execute move (start animations)
phase = ANIMATION_EXECUTION;
//Play token movement sound
SFX->at(SFX_TOKEN_DRAG)->getAudio()->setPlayOnceMode();
}
//Otherwise...
else
{
//Deselect token
selectedToken = NULL;
token->getBehavior(0)->setBool("isSelected", false);
}
}
}
//Diagonal movement (Attacking)
else if (move == "ATK_NW" || move == "ATK_NE" || move == "ATK_SW" || move == "ATK_SE")
{
//Set token's direction
if (move == "ATK_NW") selectedToken->getBehavior(0)->setInt("moveDir", NORTHWEST);
else if (move == "ATK_NE") selectedToken->getBehavior(0)->setInt("moveDir", NORTHEAST);
else if (move == "ATK_SW") selectedToken->getBehavior(0)->setInt("moveDir", SOUTHWEST);
else if (move == "ATK_SE") selectedToken->getBehavior(0)->setInt("moveDir", SOUTHEAST);
//Get position of target tile
if (move == "ATK_NW") { iTarget = iNorthwest; jTarget = jNorthwest; }
else if (move == "ATK_NE") { iTarget = iNortheast; jTarget = jNortheast; }
else if (move == "ATK_SW") { iTarget = iSouthwest; jTarget = jSouthwest; }
else if (move == "ATK_SE") { iTarget = iSoutheast; jTarget = jSoutheast; }
//If there's really a token at target position...
if (board->board[iTarget][jTarget]->token != NULL)
{
//...And its really an enemy...
if (board->board[iTarget][jTarget]->token->player != selectedToken->player)
{
//Mark enemy as attack target
board->board[iTarget][jTarget]->token->getBehavior(0)->setBool("isTargeted", true);
//Mark selected token for movement
selectedToken->getBehavior(0)->setBool("isGonnaMove", true);
//Startup animation for enemy and selected token
board->board[iTarget][jTarget]->token->getBehavior(0)->setBool("isAnimStarted", true);
selectedToken->getBehavior(0)->setBool("isAnimStarted", true);
//Execute move (start animations)
animAttackDeath = true;
phase = ANIMATION_EXECUTION;
}
}
}
}
}
void PrimePlayState::MoveTokenAI(IrrToken* token, IrrBoard* board, int ordering)
{
//Attempt to move a token based on agent FSM results
//First token of a team...
if (ordering == 1)
{
//If this token hasn't moved...
if (!firstTokenMovedAI && !tokenMovedAI)
{
//...Neither is already finished or dead...
if (!token->getBehavior(0)->getBool("isFinished") && !token->getBehavior(0)->getBool("isDead"))
{
//If token has attempted to move before...
if (firstTokenTryAgainAI)
{
//Try to move token a second time, making it "STAND" if still unable to move
if (agent.RunFSM(token, board, STAND_AS_DEFAULT))
{
//Act on the environment!
AgentACT(1, token, board);
}
}
//If this is the first attempt...
else
{
//Try to move token, doing nothing if it cannot move
if (agent.RunFSM(token, board, NO_DEFAULT))
{
//Act on the environment!
AgentACT(1, token, board);
}
else firstTokenTryAgainAI = true;
}
}
else firstTokenMovedAI = true;
}
}
//Second token of a team...
if (ordering == 2)
{
//If this token hasn't moved...
if (!secondTokenMovedAI && !tokenMovedAI)
{
//...Neither is already finished or dead...
if (!token->getBehavior(0)->getBool("isFinished") && !token->getBehavior(0)->getBool("isDead"))
{
//If token has attempted to move before...
if (secondTokenTryAgainAI)
{
//Try to move token a second time, making it "STAND" if still unable to move
if (agent.RunFSM(token, board, STAND_AS_DEFAULT))
{
//Act on the environment!
AgentACT(2, token, board);
}
}
//If this is the first attempt...
else
{
//Try to move token, doing nothing if it cannot move
if (agent.RunFSM(token, board, NO_DEFAULT))
{
//Act on the environment!
AgentACT(2, token, board);
}
else secondTokenTryAgainAI = true;
}
}
else secondTokenMovedAI = true;
}
}
//Third token of a team...
if (ordering == 3)
{
//If this token hasn't moved...
if (!thirdTokenMovedAI && !tokenMovedAI)
{
//...Neither is already finished or dead...
if (!token->getBehavior(0)->getBool("isFinished") && !token->getBehavior(0)->getBool("isDead"))
{
//If token has attempted to move before...
if (thirdTokenTryAgainAI)
{
//Try to move token a second time, making it "STAND" if still unable to move
if (agent.RunFSM(token, board, STAND_AS_DEFAULT))
{
//Act on the environment!
AgentACT(3, token, board);
}
}
//If this is the first attempt...
else
{
//Try to move token, doing nothing if it cannot move
if (agent.RunFSM(token, board, NO_DEFAULT))
{
//Act on the environment!
AgentACT(3, token, board);
}
else thirdTokenTryAgainAI = true;
}
}
else thirdTokenMovedAI = true;
}
}
}
void PrimePlayState::Initialize(IrrEngine* engine, int players, int tokens, int goal,
IrrParticleSystem* b, IrrParticleSystem* a,
IrrParticleSystem* rnw, IrrParticleSystem* rne,
IrrParticleSystem* rsw, IrrParticleSystem* rse,
PrimeTeam p1, PrimeTeam p2, PrimeTeam p3, PrimeTeam p4,
std::list<IrrToken*>* team1, std::list<IrrToken*>* team2,
std::list<IrrToken*>* team3, std::list<IrrToken*>* team4,
std::vector<IrrGameObject*>* music, std::vector<IrrGameObject*>* sound,
ICameraSceneNode* camera)
{
//Initialize agents
agent.Startup("log/Primevalion.csv");
AIPlay = false;
//Get input from engine
input = engine->getInput();
//Get particle systems from game state manager
bloodParticles = b; abilityParticles = a;
resourceParticlesNW = rnw; resourceParticlesNE = rne;
resourceParticlesSW = rsw; resourceParticlesSE = rse;
particlesOK = false; //Particles haven't been initialized yet
//Get audio lists from game state manager
BGM = music; SFX = sound;
//Get active camera from scene
activeCamera = camera;
//Create camera crosshair billboard
billboardCameraCrosshair = engine->getSceneManager()->addBillboardSceneNode(0, dimension2d<f32>(2.5f, 2.5f), activeCamera->getTarget());
billboardCameraCrosshair->getMaterial(0).setTexture(0, engine->getDriver()->getTexture("billboard/crosshair/billboard_crosshair.png"));
billboardCameraCrosshair->getMaterial(0).MaterialType = EMT_TRANSPARENT_ALPHA_CHANNEL;
billboardCameraCrosshair->getMaterial(0).Lighting = false;
//Crosshair is invisible by default
billboardCameraCrosshair->setVisible(false);
crosshairActive = false;
middleMousePressed = false;
//Initialize token lists
tokensTeam1 = new std::list<IrrToken*>();
tokensTeam2 = new std::list<IrrToken*>();
tokensTeam3 = new std::list<IrrToken*>();
tokensTeam4 = new std::list<IrrToken*>();
//Clone token lists
tokensActive = tokens;
if (p1.isActive) { for (t = team1->begin(); t != team1->end(); t++) tokensTeam1->push_back((*t)); }
if (p2.isActive) { for (t = team2->begin(); t != team2->end(); t++) tokensTeam2->push_back((*t)); }
if (p3.isActive) { for (t = team3->begin(); t != team3->end(); t++) tokensTeam3->push_back((*t)); }
if (p4.isActive) { for (t = team4->begin(); t != team4->end(); t++) tokensTeam4->push_back((*t)); }
//Clone player teams
playersActive = players;
//Player 1...
player1.idx = p1.idx;
player1.isAI = p1.isAI;
player1.isActive = p1.isActive;
player1.isVictorious = p1.isVictorious;
player1.assignedRace = p1.assignedRace;
player1.assignedTurn = p1.assignedTurn;
player1.primevalium = p1.primevalium;
//Player 2...
player2.idx = p2.idx;
player2.isAI = p2.isAI;
player2.isActive = p2.isActive;
player2.isVictorious = p2.isVictorious;
player2.assignedRace = p2.assignedRace;
player2.assignedTurn = p2.assignedTurn;
player2.primevalium = p2.primevalium;
//Player 3...
player3.idx = p3.idx;
player3.isAI = p3.isAI;
player3.isActive = p3.isActive;
player3.isVictorious = p3.isVictorious;
player3.assignedRace = p3.assignedRace;
player3.assignedTurn = p3.assignedTurn;
player3.primevalium = p3.primevalium;
//Player 4...
player4.idx = p4.idx;
player4.isAI = p4.isAI;
player4.isActive = p4.isActive;
player4.isVictorious = p4.isVictorious;
player4.assignedRace = p4.assignedRace;
player4.assignedTurn = p4.assignedTurn;
player4.primevalium = p4.primevalium;
//Initialize signals
signalEndTurn = signalEndMatch = signalButtonHover = false;
signalBackToTitle = signalVictoryBGM = false;
//Initialize match phase
phase = MATCH_START;
matchStart = matchOver = false;
turnBeginPhase = 0;
//Initialize goal
resourcesGoal = goal;
//Initialize auxiliary variables
tokenRessurrected = false;
resourcesVerified = false;
resourcesExtracted = false;
//Initialize selected token
selectedToken = NULL;
//Initialize "Wait" mini-engine
wait = 0.0f;
sleep = 0.0f;
awake = false;
then = IrrEngine::getInstance()->getDevice()->getTimer()->getTime();
//Initialize ressurrection skipping variables
skipRessurrection = skipRessurrectionAI = false;
deadTokensNotRevived = 0;
safeZoneTilesMax = 0;
safeZone1TilesOccupied = safeZone2TilesOccupied = 0;
safeZone3TilesOccupied = safeZone4TilesOccupied = 0;
safeZone1Full = safeZone2Full = safeZone3Full = safeZone4Full = false;
//Initialize animation variables
animSpeed = 0.0f;
fallCounter = 0.0f;
moveCounter = 0.0f;
tokensPushed = 0;
}
void PrimePlayState::Wait()
{
//----------------------
// "Wait" mini-engine:
//----------------------
//Calculate frame-independent time
now = IrrEngine::getInstance()->getDevice()->getTimer()->getTime();
deltaTime = (float)(now - then) / 1000.f;
then = now;
//If just woke up...
if (awake)
{
//Go back to sleep!
awake = false;
}
//If sleep has been set...
else if (sleep > 0.0f)
{
//Update wait
wait += 1.0f * deltaTime;
//When wait surpasses sleep time (in seconds)...
if (wait > sleep)
{
//...Reset wait and sleep.
sleep = wait = 0.0f;
//Wake up!
awake = true;
}
}
}
bool PrimePlayState::Wait(float seconds)
{
bool isAwake = false;
//Wait for "seconds" amount of time
if (!sleep && !awake) sleep = seconds;
else if (awake)
{
//Finally woke up, wait is over
isAwake = true;
}
return isAwake;
}
void PrimePlayState::InitParticles(IrrBoard* board)
{
//Set minimal and maximal emission rates
bloodMin = 10; bloodMax = 20;
abilityMin = 2; abilityMax = 5;
resourceMin = 2; resourceMax = 4;
//Create blood particles material
blood.Lighting = false; blood.ZWriteEnable = false;
blood.MaterialType = EMT_TRANSPARENT_VERTEX_ALPHA;
blood.setTexture(0, IrrEngine::getInstance()->getDriver()->getTexture("billboard/particle/particle_blood01.png"));
//Create ability particles material
ability.Lighting = false; ability.ZWriteEnable = false;
ability.MaterialType = EMT_TRANSPARENT_VERTEX_ALPHA;
ability.setTexture(0, IrrEngine::getInstance()->getDriver()->getTexture("billboard/particle/particle_light02.png"));
//Create resource particles material
resources.Lighting = false; resources.ZWriteEnable = false;
resources.MaterialType = EMT_TRANSPARENT_VERTEX_ALPHA;
resources.setTexture(0, IrrEngine::getInstance()->getDriver()->getTexture("billboard/particle/particle_light01.png"));
//Create blood particles emitter
IParticleEmitter* bEmitter = bloodParticles->createBoxEmitter(BLOOD, aabbox3d<f32>(-0.25f,-0.5f,-0.0f,0.75f,0.5f,1.0f), // emitter size
vector3df(0.0f,0.04f,0.0f), // direction and translation speed
0,0, // emit rate (zero by default)
SColor(0,255,255,255), // darkest color
SColor(0,255,255,255), // brightest color
2000,3000, // min and max age
10, //angle
dimension2df(0.1f,0.1f), // min size
dimension2df(0.4f,0.4f)); // max size
//Create ability particles emitter
IParticleEmitter* aEmitter = abilityParticles->createSphereEmitter(ABILITY, vector3df(0.0f,0.0f,0.0f), 1.0f, // emitter size
vector3df(0.0f,0.005f,0.0f), // direction and translation speed
0,0, // emit rate (zero by default)
SColor(0,255,255,255), // darkest color
SColor(0,255,255,255), // brightest color
2000,3000, // min and max age
10, //angle
dimension2df(0.4f,0.4f), // min size
dimension2df(0.8f,0.8f)); // max size
//Create resource particle emitters
CreateResourceEmitters();
//Set blood particle material
bloodParticles->node->getMaterial(0) = blood;
//Set ability particle material
abilityParticles->node->getMaterial(0) = ability;
//Set resource particle materials
resourceParticlesNW->node->getMaterial(0) = resources;
resourceParticlesNE->node->getMaterial(0) = resources;
resourceParticlesSW->node->getMaterial(0) = resources;
resourceParticlesSE->node->getMaterial(0) = resources;
//Create blood particle affectors
bloodParticles->addGravityAffector(1, vector3df(0.0f,-0.1f,0.0f));
bloodParticles->addFadeOutAffector(2, SColor(0,0,0,0), 4000); //The higher the value, the sooner they fade
//Create ability particle affectors
abilityParticles->addFadeOutAffector(3, SColor(0,0,0,0), 8000);
//Create resource particle fade out affectors
resourceParticlesNW->addFadeOutAffector(4, SColor(0,0,0,0), 12000);
resourceParticlesNE->addFadeOutAffector(5, SColor(0,0,0,0), 12000);
resourceParticlesSW->addFadeOutAffector(6, SColor(0,0,0,0), 12000);
resourceParticlesSE->addFadeOutAffector(7, SColor(0,0,0,0), 12000);
//Create resource particle rotation affectors
resourceParticlesNW->addRotationAffector(8, vector3df(0.0f, 15.0f, 0.0f), board->board[4][4]->node->getAbsolutePosition());
resourceParticlesNE->addRotationAffector(9, vector3df(0.0f, 15.0f, 0.0f), board->board[4][5]->node->getAbsolutePosition());
resourceParticlesSW->addRotationAffector(10, vector3df(0.0f, 15.0f, 0.0f), board->board[5][4]->node->getAbsolutePosition());
resourceParticlesSE->addRotationAffector(11, vector3df(0.0f, 15.0f, 0.0f), board->board[5][5]->node->getAbsolutePosition());
//Finish up particle initialization
particlesOK = true;
}
void PrimePlayState::CreateResourceEmitters(void)
{
//Create NORTHWEST resource particles emitter
IParticleEmitter* rnwEmitter = resourceParticlesNW->createRingEmitter(RESOURCES_NW, vector3df(0.0f,0.0f,0.0f), 0.6f, 0.1f, // emitter size
vector3df(0.0f,0.0005f,0.0f), // direction and translation speed
0,0, // emit rate (zero by default)
SColor(0,255,255,255), // darkest color
SColor(0,255,255,255), // brightest color
10000,12000, // min and max age
0, //angle
dimension2df(0.5f,0.5f), // min size
dimension2df(1.0f,1.0f)); // max size
//Create NORTHEAST resource particles emitter
IParticleEmitter* rneEmitter = resourceParticlesNE->createRingEmitter(RESOURCES_NE, vector3df(0.0f,0.0f,0.0f), 0.6f, 0.1f, // emitter size
vector3df(0.0f,0.0005f,0.0f), // direction and translation speed
0,0, // emit rate (zero by default)
SColor(0,255,255,255), // darkest color
SColor(0,255,255,255), // brightest color
10000,12000, // min and max age
0, //angle
dimension2df(0.5f,0.5f), // min size
dimension2df(1.0f,1.0f)); // max size
//Create SOUTHWEST resource particles emitter
IParticleEmitter* rswEmitter = resourceParticlesSW->createRingEmitter(RESOURCES_SW, vector3df(0.0f,0.0f,0.0f), 0.6f, 0.1f, // emitter size
vector3df(0.0f,0.0005f,0.0f), // direction and translation speed
0,0, // emit rate (zero by default)
SColor(0,255,255,255), // darkest color
SColor(0,255,255,255), // brightest color
10000,12000, // min and max age
0, //angle
dimension2df(0.5f,0.5f), // min size
dimension2df(1.0f,1.0f)); // max size
//Create NORTHWEST resource particles emitter
IParticleEmitter* rseEmitter = resourceParticlesSE->createRingEmitter(RESOURCES_SE, vector3df(0.0f,0.0f,0.0f), 0.6f, 0.1f, // emitter size
vector3df(0.0f,0.0005f,0.0f), // direction and translation speed
0,0, // emit rate (zero by default)
SColor(0,255,255,255), // darkest color
SColor(0,255,255,255), // brightest color
10000,12000, // min and max age
0, //angle
dimension2df(0.5f,0.5f), // min size
dimension2df(1.0f,1.0f)); // max size
}
void PrimePlayState::StartParticles(int particleSystemID, Vector* position)
{
//Find particle system with ID passed as parameter
if (particleSystemID == BLOOD)
{
//Restart emission
bloodParticles->node->getEmitter()->setMinParticlesPerSecond(bloodMin);
bloodParticles->node->getEmitter()->setMaxParticlesPerSecond(bloodMax);
//Re-position
bloodParticles->setPosition(position);
}
else if (particleSystemID == ABILITY)
{
//Restart emission
abilityParticles->node->getEmitter()->setMinParticlesPerSecond(abilityMin);
abilityParticles->node->getEmitter()->setMaxParticlesPerSecond(abilityMax);
//Re-position
abilityParticles->setPosition(position);
}
else if (particleSystemID == RESOURCES_NW)
{
//Restart emission
resourceParticlesNW->node->getEmitter()->setMinParticlesPerSecond(resourceMin);
resourceParticlesNW->node->getEmitter()->setMaxParticlesPerSecond(resourceMax);
//Re-position
resourceParticlesNW->setPosition(position);
}
else if (particleSystemID == RESOURCES_NE)
{
//Restart emission
resourceParticlesNE->node->getEmitter()->setMinParticlesPerSecond(resourceMin);
resourceParticlesNE->node->getEmitter()->setMaxParticlesPerSecond(resourceMax);
//Re-position
resourceParticlesNE->setPosition(position);
}
else if (particleSystemID == RESOURCES_SW)
{
//Restart emission
resourceParticlesSW->node->getEmitter()->setMinParticlesPerSecond(resourceMin);
resourceParticlesSW->node->getEmitter()->setMaxParticlesPerSecond(resourceMax);
//Re-position
resourceParticlesSW->setPosition(position);
}
else if (particleSystemID == RESOURCES_SE)
{
//Restart emission
resourceParticlesSE->node->getEmitter()->setMinParticlesPerSecond(resourceMin);
resourceParticlesSE->node->getEmitter()->setMaxParticlesPerSecond(resourceMax);
//Re-position
resourceParticlesSE->setPosition(position);
}
}
void PrimePlayState::StopParticles(int particleSystemID)
{
//Find particle system with ID passed as parameter
if (particleSystemID == BLOOD)
{
//Stop emission
bloodParticles->node->getEmitter()->setMinParticlesPerSecond(0);
bloodParticles->node->getEmitter()->setMaxParticlesPerSecond(0);
}
else if (particleSystemID == ABILITY)
{
//Stop emission
abilityParticles->node->getEmitter()->setMinParticlesPerSecond(0);
abilityParticles->node->getEmitter()->setMaxParticlesPerSecond(0);
}
else if (particleSystemID == RESOURCES_NW)
{
//Stop emission
resourceParticlesNW->node->getEmitter()->setMinParticlesPerSecond(0);
resourceParticlesNW->node->getEmitter()->setMaxParticlesPerSecond(0);
}
else if (particleSystemID == RESOURCES_NE)
{
//Stop emission
resourceParticlesNE->node->getEmitter()->setMinParticlesPerSecond(0);
resourceParticlesNE->node->getEmitter()->setMaxParticlesPerSecond(0);
}
else if (particleSystemID == RESOURCES_SW)
{
//Stop emission
resourceParticlesSW->node->getEmitter()->setMinParticlesPerSecond(0);
resourceParticlesSW->node->getEmitter()->setMaxParticlesPerSecond(0);
}
else if (particleSystemID == RESOURCES_SE)
{
//Stop emission
resourceParticlesSE->node->getEmitter()->setMinParticlesPerSecond(0);
resourceParticlesSE->node->getEmitter()->setMaxParticlesPerSecond(0);
}
}
void PrimePlayState::SetCrosshairPosition(void)
{
//Update crosshair position
billboardCameraCrosshair->setPosition(activeCamera->getTarget());
//When middle mouse button is released...
if (middleMousePressed && !input->getMouseState().middleButtonDown)
{
//Activate or deactivate crosshair
if (crosshairActive) crosshairActive = false;
else crosshairActive = true;
middleMousePressed = false;
}
//When middle mouse button is pressed...
if (input->getMouseState().middleButtonDown) middleMousePressed = true;
//Show crosshair if its active
if (crosshairActive) billboardCameraCrosshair->setVisible(true);
//Otherwise, hide crosshair
else billboardCameraCrosshair->setVisible(false);
}
void PrimePlayState::SetTurnPlayer(int turn)
{
int counter = 0;
//Iterate through turn count to find out if this
//is the first, second, third or fourth player's turn...
for (int iterator = 1; iterator <= turn; iterator++)
{
counter++;
if (counter > playersActive) counter = 1;
}
//Set "turnPlayer" as the current player
if (player1.assignedTurn == counter) turnPlayer = player1.idx;
else if (player2.assignedTurn == counter) turnPlayer = player2.idx;
else if (player3.assignedTurn == counter) turnPlayer = player3.idx;
else if (player4.assignedTurn == counter) turnPlayer = player4.idx;
}
int PrimePlayState::SetPushLine(bool clicked, int dir, IrrBoard* board, int iStart, int jStart)
{
bool breakScan = false;
int tokensToPush = 0;
int iTile = -1;
int jTile = -1;
int iAdd = -1;
int jAdd = -1;
int iBreak = -1;
int jBreak = -1;
//Configure search based on push direction
if (dir == WEST) { iBreak = -1; jBreak = 0; iAdd = 0; jAdd = -1; }
else if (dir == EAST) { iBreak = -1; jBreak = 9; iAdd = 0; jAdd = 1; }
else if (dir == NORTH) { iBreak = 0; jBreak = -1; iAdd = -1; jAdd = 0; }
else if (dir == SOUTH) { iBreak = 9; jBreak = -1; iAdd = 1; jAdd = 0; }
iTile = iStart;
jTile = jStart;
//Find tokens in a line, starting at token to be pushed
while (!breakScan)
{
//If a token has been found...
if (board->board[iTile][jTile]->token != NULL)
{
//If mouse button has been clicked and push move confirmed...
if (clicked)
{
//Mark this token for pushing
board->board[iTile][jTile]->token->getBehavior(0)->setBool("isGonnaBePushed", true);
board->board[iTile][jTile]->token->getBehavior(0)->setInt("moveDir", dir);
//Startup this token's animation
board->board[iTile][jTile]->token->getBehavior(0)->setBool("isAnimStarted", true);
tokensToPush++;
}
//Otherwise, if mouse is just hovering a pushable token...
else
{
//Highlight this token to show player which tokens will be pushed
board->board[iTile][jTile]->token->isHighlighted = true;
board->board[iTile][jTile]->token->highlight = PUSH_HOVER;
}
}
//If a free tile has been found, break scan
else if (board->board[iTile][jTile]->token == NULL) breakScan = true;
//If an obstacle has been found, break scan
else if (board->board[iTile][jTile]->inf == RUINS) breakScan = true;
//If "iBreak" or "jBreak" has been achieved, it means the board's
//border has been reached and the scan should be finished up
if (iTile == iBreak || jTile == jBreak) breakScan = true;
//Iterate scan
iTile += iAdd;
jTile += jAdd;
}
return tokensToPush;
}
bool PrimePlayState::PlayIsValid(int play, int dir, IrrBoard* board, int i, int j)
{
bool isValid = false;
bool breakScan = false;
int iTile = -1;
int jTile = -1;
int iAdd = -1;
int jAdd = -1;
int iBreak = -1;
int jBreak = -1;
int lastTileFound = 0;
int tilesChecked = 0;
int freeTiles = 0;
int heavyTokens = 0;
//Validate Push move
if (play == PUSH)
{
//Configure search based on push direction
if (dir == WEST) { iBreak = -1; jBreak = 0; iAdd = 0; jAdd = -1; }
else if (dir == EAST) { iBreak = -1; jBreak = 9; iAdd = 0; jAdd = 1; }
else if (dir == NORTH) { iBreak = 0; jBreak = -1; iAdd = -1; jAdd = 0; }
else if (dir == SOUTH) { iBreak = 9; jBreak = -1; iAdd = 1; jAdd = 0; }
iTile = i;
jTile = j;
//Find obstacles and tokens in a line, starting at token to be pushed
while (!breakScan)
{
//If an obstacle has been found...
if (board->board[iTile][jTile]->inf == RUINS)
{
//If last tile found was a token...
if (lastTileFound == TOKEN)
{
//If so far, only tokens have been found...
if (freeTiles == 0)
{
//Cannot push line of tokens past obstacles
isValid = false;
//Break "while" loop
breakScan = true;
}
//Else, if free tiles have been found...
else if (freeTiles > 0)
{
//If at least 1 free tile has been found
//between tokens, then they can be pushed
isValid = true;
//Break "while" loop
breakScan = true;
}
}
//Else, if last tile found was a
//free tile (trap or grass)...
else if (lastTileFound == FREE)
{
//If at least 1 free tile has been found
//between tokens, then they can be pushed
isValid = true;
//Break "while" loop
breakScan = true;
}
lastTileFound = RUINS;
}
//If a free tile has been found...
else if (board->board[iTile][jTile]->token == NULL)
{
lastTileFound = FREE;
freeTiles++;
//Free tiles inbetween heavy tokens enable pushing
if (heavyTokens > 0) --heavyTokens;
}
//If a token has been found...
else if (board->board[iTile][jTile]->token != NULL)
{
lastTileFound = TOKEN;
//If this token is a Troll with its ability activated,
//and its not in the current player's team...
if (board->board[iTile][jTile]->token->getBehavior(0)->getInt("race") == TROLL
&& board->board[iTile][jTile]->token->getBehavior(0)->getBool("isAbilityActive")
&& board->board[iTile][jTile]->token->player != turnPlayer)
{
heavyTokens++;
//If more than one of these have been found in a line...
if (heavyTokens >= 2 && freeTiles == 0)
{
//Cannot push 2 or more aligned Trolls
isValid = false;
//Break "while" loop
breakScan = true;
}
//If two of these have been found in a line, but there
//were free tiles before them, it shouldn't hamper movement.
else if (heavyTokens >= 2 && freeTiles > 0) heavyTokens = 0;
}
}
//If "iBreak" or "jBreak" has been achieved, it means the board's
//border has been reached and the scan should be finished up
if (iTile == iBreak || jTile == jBreak)
{
//If only tokens have been found...
if (freeTiles == 0)
{
//Cannot push line of tokens past border
isValid = false;
}
//Else, if free tiles have been found
//and no heavy tokens disallow movement...
else if (freeTiles > 0 && heavyTokens < 2)
{
//If at least 1 free tile has been found
//between tokens, then they can be pushed
isValid = true;
}
//Break "while" loop
breakScan = true;
}
//Iterate scan
iTile += iAdd;
jTile += jAdd;
}
}
//Validate Attack move
else if (play == ATTACK)
{
//If trying to attack someone from the same team...
if (board->board[i][j]->token->player == turnPlayer)
{
//Invalid move!
isValid = false;
}
//If trying to attack someone in a safe zone...
else if (board->board[i][j]->token->parentNode->inf == SAFE_ZONE_TEAM_1
|| board->board[i][j]->token->parentNode->inf == SAFE_ZONE_TEAM_2
|| board->board[i][j]->token->parentNode->inf == SAFE_ZONE_TEAM_3
|| board->board[i][j]->token->parentNode->inf == SAFE_ZONE_TEAM_4)
{
//Invalid move!
isValid = false;
}
//Otherwise, its a valid attack move!
else isValid = true;
}
//Return validation result
return isValid;
}
bool PrimePlayState::TokenHasTranslated(IrrToken* token, float speed)
{
bool destReached = false;
vector3df newRelativePosition;
float xDiff, yDiff, zDiff;
float xStep, yStep, zStep;
//Get token's translation vectors
Vector origin, destination;
origin.x = token->getBehavior(0)->getFloat("originPosition.x");
origin.y = token->getBehavior(0)->getFloat("originPosition.y");
origin.z = token->getBehavior(0)->getFloat("originPosition.z");
destination.x = token->getBehavior(0)->getFloat("destPosition.x");
destination.y = token->getBehavior(0)->getFloat("destPosition.y");
destination.z = token->getBehavior(0)->getFloat("destPosition.z");
//Get current distance between token and destination
xDiff = destination.x - token->node->getAbsolutePosition().X;
yDiff = destination.y - token->node->getAbsolutePosition().Y;
zDiff = destination.z - token->node->getAbsolutePosition().Z;
//Decreases speed the closer token gets to destination (trap fall only)
speed -= abs((destination.y - origin.y) - yDiff) * speed;
if (speed < 0.05f) speed = 0.05f; //Minimum speed
//If this is a movement animation running for less than 1 second,
//or a trap death animation running for less than 3 seconds...
if ((origin.y == destination.y && moveCounter < (0.73f * (tokensPushed + 1))) || (origin.y != destination.y && fallCounter < 2.3f))
{
//...Then destination hasn't been reached.
//Calculate next step offset
xStep = ((destination.x - origin.x) / 100) * speed;
yStep = ((destination.y - origin.y) / 100) * speed;
zStep = ((destination.z - origin.z) / 100) * speed;
//Calculate new position
newRelativePosition.X = token->node->getPosition().X + xStep;
newRelativePosition.Y = token->node->getPosition().Y + yStep;
newRelativePosition.Z = token->node->getPosition().Z + zStep;
//Move token closer to destination
token->node->setPosition(newRelativePosition);
//Increment trap falling counter
fallCounter += 1.0f * deltaTime;
//Increment movement counter
moveCounter += 1.0f * deltaTime;
}
//Otherwise, if this is an animation which has been running for too long...
else
{
//...Consider destination as reached.
destReached = true;
}
//Report whether destination is reached
return destReached;
}
void PrimePlayState::AnimateToken(IrrToken* token, IrrBoard* board, float speed)
{
//Pass animation states to another variable (decreases size of "if" statements below)
bool animStarted = token->getBehavior(0)->getBool("isAnimStarted");
bool animRunning = token->getBehavior(0)->getBool("isAnimRunning");
bool animFinished = token->getBehavior(0)->getBool("isAnimFinished");
//! IMPORTANT !
//---------------
//Animations happen in a specific order: 1st, attack death animation (tiles which
//were attacked diagonally). 2nd, simple movement animation (a token moves to an
//empty tile) and/or push movement animations (tokens get pushed by the selected token).
//3rd and last, trap death animation (token falls on a trap after being pushed).
//This order must always be respected, and an animation must never start before all
//animations that precede it are finished.
//----------------------------------------
// 1st Priority: ATTACK DEATH ANIMATION
//----------------------------------------
//If "isTargeted" is true, then this token is suffering an attack
//coming from a diagonal tile, where there's certainly an enemy token.
if (token->getBehavior(0)->getBool("isTargeted"))
{
animAttackDeath = true;
//If this token has been marked for animation, but hasn't started running it yet...
if (animStarted && !animRunning && !animFinished)
{
//Disable any active abilities
token->getBehavior(0)->setBool("isAbilityActive", false);
//Play attack death sound
if (token->getBehavior(0)->getInt("race") == KOBOLD) SFX->at(SFX_DIE_KOBOLD)->getAudio()->setPlayOnceMode();
if (token->getBehavior(0)->getInt("race") == GNOLL) SFX->at(SFX_DIE_GNOLL)->getAudio()->setPlayOnceMode();
if (token->getBehavior(0)->getInt("race") == TROLL) SFX->at(SFX_DIE_TROLL)->getAudio()->setPlayOnceMode();
if (token->getBehavior(0)->getInt("race") == HOG) SFX->at(SFX_DIE_HOG)->getAudio()->setPlayOnceMode();
//Start animation!
token->getBehavior(0)->setBool("isAnimRunning", true);
//Activate particle effect!
StartParticles(BLOOD, new Vector(token->node->getAbsolutePosition().X,
token->node->getAbsolutePosition().Y,
token->node->getAbsolutePosition().Z));
}
//If this token's animation is currently running...
else if (animStarted && animRunning && !animFinished)
{
// TEMPORARY ANIMATION
//-----------------------
if (Wait(1.75f))
{
token->getBehavior(0)->setBool("isAnimRunning", false);
token->getBehavior(0)->setBool("isAnimFinished", true);
}
//-----------------------
}
//If this token's animation is over...
else if (animStarted && !animRunning && animFinished)
{
//Terminate this token's animations
token->getBehavior(0)->setBool("isAnimClosed", true);
//Disable future moves for this token, in this turn
token->getBehavior(0)->setBool("isFinished", true);
//Kill token!
token->getBehavior(0)->setBool("isDead", true);
//Set this token as the "killed token"
killedToken = token;
//End particle effect
StopParticles(BLOOD);
}
//If animation is done, inform the other tokens
if (token->getBehavior(0)->getBool("isAnimClosed")) animAttackDeath = false;
}
//----------------------------------------
// 2nd Priority: MOVE/PUSH ANIMATION
//----------------------------------------
//If "isGonnaMove" is true, then this is the selected token.
//If "isGonnaBePushed" is true, then this token will be pushed by selected token.
//Either way, this token must be moved, but will only do so after all attack
//death animations are finished.
else if (!animAttackDeath && !token->getBehavior(0)->getBool("isAnimClosed") &&
(token->getBehavior(0)->getBool("isGonnaMove") || token->getBehavior(0)->getBool("isGonnaBePushed")))
{
if (token->getBehavior(0)->getBool("isGonnaMove")) animSimpleMove = true;
if (token->getBehavior(0)->getBool("isGonnaBePushed")) animPushMove = true;
//If this token has been marked for animation, but hasn't started running it yet...
if (animStarted && !animRunning && !animFinished)
{
//Get destination tile positions
iDest = GetDestinationTile(token->getBehavior(0)->getInt("moveDir"), token->parentNode->posi, token->parentNode->posj, I_TILE);
jDest = GetDestinationTile(token->getBehavior(0)->getInt("moveDir"), token->parentNode->posi, token->parentNode->posj, J_TILE);
//Pass destination tile positions to token
token->getBehavior(0)->setInt("iDest", iDest);
token->getBehavior(0)->setInt("jDest", jDest);
//Pass destination coordinates to token
token->getBehavior(0)->setFloat("destPosition.x", board->board[iDest][jDest]->node->getPosition().X);
token->getBehavior(0)->setFloat("destPosition.y", board->board[iDest][jDest]->node->getPosition().Y);
token->getBehavior(0)->setFloat("destPosition.z", board->board[iDest][jDest]->node->getPosition().Z);
//Pass origin coordinates to token
token->getBehavior(0)->setFloat("originPosition.x", token->node->getAbsolutePosition().X);
token->getBehavior(0)->setFloat("originPosition.y", token->node->getAbsolutePosition().Y);
token->getBehavior(0)->setFloat("originPosition.z", token->node->getAbsolutePosition().Z);
//If this token is being pushed, and its final destination is a trap...
if (token->getBehavior(0)->getBool("isGonnaBePushed"))
{
if (board->board[iDest][jDest]->inf == TRAP)
{
//Mark this token for the trap death animation
token->getBehavior(0)->setBool("isGonnaBeTrapped", true);
}
}
//Start animation!
token->getBehavior(0)->setBool("isAnimRunning", true);
}
//If this token's animation is currently running...
else if (animStarted && animRunning && !animFinished)
{
//Translate token, and when destination has been reached...
if (TokenHasTranslated(token, speed))
{
//Finish up animation
token->getBehavior(0)->setBool("isAnimRunning", false);
token->getBehavior(0)->setBool("isAnimFinished", true);
}
}
//If this is the selected token and the move animation is over...
else if (animStarted && !animRunning && animFinished
&& token->getBehavior(0)->getBool("isGonnaMove"))
{
//...And all pushed tokens have already moved...
if (PushedTokensSnapped(board))
{
//Reset relative position
token->node->setPosition(vector3df(0,0,0));
//If snap to new position has been successful...
if (board->moveToken(token->parentNode->posi, token->parentNode->posj,
token->getBehavior(0)->getInt("iDest"), token->getBehavior(0)->getInt("jDest")))
{
//Terminate move animation
token->getBehavior(0)->setBool("isAnimClosed", true);
//Inform other tokens that the selected token's movement has ended
animSimpleMove = false;
//Reset animation variables
fallCounter = 0.0f;
moveCounter = 0.0f;
tokensPushed = 0;
}
}
}
}
//----------------------------------------
// 3rd Priority: TRAP DEATH ANIMATION
//----------------------------------------
//If "isGonnaBeTrapped" is true, then this token will suffer a bloody death in a trap,
//but only after all attack death animations and movement animations are finished.
else if (!animAttackDeath && !animSimpleMove && !animPushMove &&
token->getBehavior(0)->getBool("isGonnaBeTrapped"))
{
animTrapDeath = true;
//If this token has been marked for animation, but hasn't started running it yet...
if (animStarted && !animRunning && !animFinished)
{
//Get tile height
//int trapHeight = board->tile_height;
//Pass destination coordinates to token (deeper into the trap hole)
token->getBehavior(0)->setFloat("destPosition.x", token->node->getAbsolutePosition().X);
token->getBehavior(0)->setFloat("destPosition.y", board->node->getAbsolutePosition().Y); //token->node->getAbsolutePosition().Y - trapHeight);
token->getBehavior(0)->setFloat("destPosition.z", token->node->getAbsolutePosition().Z);
//Pass origin coordinates to token (current position)
token->getBehavior(0)->setFloat("originPosition.x", token->node->getAbsolutePosition().X);
token->getBehavior(0)->setFloat("originPosition.y", token->node->getAbsolutePosition().Y);
token->getBehavior(0)->setFloat("originPosition.z", token->node->getAbsolutePosition().Z);
//Disable any active abilities
token->getBehavior(0)->setBool("isAbilityActive", false);
//Play trap death sound
if (token->getBehavior(0)->getInt("race") == KOBOLD) SFX->at(SFX_TRAP_KOBOLD)->getAudio()->setPlayOnceMode();
if (token->getBehavior(0)->getInt("race") == GNOLL) SFX->at(SFX_TRAP_GNOLL)->getAudio()->setPlayOnceMode();
if (token->getBehavior(0)->getInt("race") == TROLL) SFX->at(SFX_TRAP_TROLL)->getAudio()->setPlayOnceMode();
if (token->getBehavior(0)->getInt("race") == HOG) SFX->at(SFX_TRAP_HOG)->getAudio()->setPlayOnceMode();
//Start animation!
token->getBehavior(0)->setBool("isAnimRunning", true);
//Activate particle effect!
StartParticles(BLOOD, new Vector(token->node->getAbsolutePosition().X,
token->node->getAbsolutePosition().Y,
token->node->getAbsolutePosition().Z));
}
//If this token's animation is currently running...
else if (animStarted && animRunning && !animFinished)
{
//Translate token, and when destination has been reached...
if (TokenHasTranslated(token, speed * 0.6f))
{
//Finish up animation
token->getBehavior(0)->setBool("isAnimRunning", false);
token->getBehavior(0)->setBool("isAnimFinished", true);
}
}
//If this token's animation is over...
else if (animStarted && !animRunning && animFinished)
{
//Terminate this token's animations
token->getBehavior(0)->setBool("isAnimClosed", true);
//Disable future moves for this token, in this turn
token->getBehavior(0)->setBool("isFinished", true);
//Kill token!
token->getBehavior(0)->setBool("isDead", true);
//Set this token as the "killed token"
killedToken = token;
//End particle effect
StopParticles(BLOOD);
//Reset animation variables
fallCounter = 0.0f;
moveCounter = 0.0f;
tokensPushed = 0;
}
//If animation is done, inform the other tokens
if (token->getBehavior(0)->getBool("isAnimClosed")) animTrapDeath = false;
}
}
bool PrimePlayState::PushedTokensSnapped(IrrBoard* board)
{
IrrToken* tempToken;
bool everyTokenSnapped = false;
bool breakScan = false;
int foundTokens = 0, snappedTokens = 0;
int iStart = -1;
int jStart = -1;
int iTile = -1;
int jTile = -1;
int iAdd = -1;
int jAdd = -1;
int iBreak = -1;
int jBreak = -1;
int dir = selectedToken->getBehavior(0)->getInt("moveDir");
//If this is not a diagonal direction (which would mean this is an attack, not a push move)...
if (dir != NORTHWEST && dir != NORTHEAST && dir != SOUTHWEST && dir != SOUTHEAST)
{
//Configure search for a direction contrary to push direction, so tiles
//farthest to the selected token are moved first
if (dir == WEST) { iStart = selectedToken->parentNode->posi; jStart = 0;
iBreak = -1; jBreak = selectedToken->parentNode->posj; iAdd = 0; jAdd = 1; }
else if (dir == EAST) { iStart = selectedToken->parentNode->posi; jStart = 9;
iBreak = -1; jBreak = selectedToken->parentNode->posj; iAdd = 0; jAdd = -1; }
else if (dir == NORTH) { iStart = 0; jStart = selectedToken->parentNode->posj;
iBreak = selectedToken->parentNode->posi; jBreak = -1; iAdd = 1; jAdd = 0; }
else if (dir == SOUTH) { iStart = 9; jStart = selectedToken->parentNode->posj;
iBreak = selectedToken->parentNode->posi; jBreak = -1; iAdd = -1; jAdd = 0; }
iTile = iStart;
jTile = jStart;
//Find pushed tokens in a line, starting at opposite board border
while (!breakScan)
{
//If a token has been found...
if (board->board[iTile][jTile]->token != NULL)
{
//If this token has just been pushed and its animations haven't been terminated yet...
if (board->board[iTile][jTile]->token->getBehavior(0)->getBool("isGonnaBePushed")
&& !board->board[iTile][jTile]->token->getBehavior(0)->getBool("isAnimClosed"))
{
//A pushed token has been found
foundTokens++;
//If this token's translation animation has finished...
if (board->board[iTile][jTile]->token->getBehavior(0)->getBool("isAnimFinished"))
{
tempToken = board->board[iTile][jTile]->token;
//Reset relative position
tempToken->node->setPosition(vector3df(0,0,0));
//If snap to new position has been successful...
if (board->moveToken(tempToken->parentNode->posi, tempToken->parentNode->posj,
tempToken->getBehavior(0)->getInt("iDest"), tempToken->getBehavior(0)->getInt("jDest")))
{
//A pushed token has been snapped
snappedTokens++;
//If this token is marked for a painful trap death animation...
if (tempToken->getBehavior(0)->getBool("isGonnaBeTrapped"))
{
//Unmark push animation (it should be finished by now)
tempToken->getBehavior(0)->setBool("isGonnaBePushed", false);
//Reset a couple animation states
tempToken->getBehavior(0)->setBool("isAnimRunning", false);
tempToken->getBehavior(0)->setBool("isAnimFinished", false);
}
//Otherwise, if this token is still safe after being pushed
else
{
//Terminate all animations
tempToken->getBehavior(0)->setBool("isAnimClosed", true);
}
//Inform other tokens this one's push animation is over
animPushMove = false;
}
}
}
}
//If "iBreak" or "jBreak" has been achieved, it means the selected
//token has been reached and the scan should be finished up
if (iTile == iBreak || jTile == jBreak) breakScan = true;
//Iterate scan
iTile += iAdd;
jTile += jAdd;
}
}
//If all found tokens have been snapped, everything's good
if (foundTokens == snappedTokens) everyTokenSnapped = true;
return everyTokenSnapped;
}
bool PrimePlayState::EnemyTokenKilled(IrrBoard* board)
{
bool enemyWillDie = false;
//If a token was killed by an Attack or died by falling into a trap
if (killedToken != NULL)
{
//Only tokens of enemy teams are valid (killing allies doesn't count)
if (killedToken->player != turnPlayer) enemyWillDie = true;
}
return enemyWillDie;
}
bool PrimePlayState::TrollBesideMe(IrrToken* token, IrrBoard* board)
{
bool trollBesideMe = false;
//Grab adjacent tile positions
int up[2] = { token->parentNode->posi - 1, token->parentNode->posj };
int down[2] = { token->parentNode->posi + 1, token->parentNode->posj };
int left[2] = { token->parentNode->posi, token->parentNode->posj - 1 };
int right[2] = { token->parentNode->posi, token->parentNode->posj + 1 };
//Checking if adjacent tiles are valid and if there's a token on them
if (up[0] > -1 && up[0] < 10 && up[1] > -1 && up[1] < 10)
{
if (board->board[up[0]][up[1]]->token != NULL)
{
//If adjacent token is a Troll from the same team, which is not dying...
if (board->board[up[0]][up[1]]->token->getBehavior(0)->getInt("race") == TROLL
&& !board->board[up[0]][up[1]]->token->getBehavior(0)->getBool("isGonnaBeTrapped")
&& !board->board[up[0]][up[1]]->token->getBehavior(0)->getBool("isTargeted")
&& !board->board[up[0]][up[1]]->token->getBehavior(0)->getBool("isDead")
&& board->board[up[0]][up[1]]->token->player == token->player)
{
trollBesideMe = true;
}
}
}
if (down[0] > -1 && down[0] < 10 && down[1] > -1 && down[1] < 10)
{
if (board->board[down[0]][down[1]]->token != NULL)
{
//If adjacent token is a Troll from the same team, which is not dying...
if (board->board[down[0]][down[1]]->token->getBehavior(0)->getInt("race") == TROLL
&& !board->board[down[0]][down[1]]->token->getBehavior(0)->getBool("isGonnaBeTrapped")
&& !board->board[down[0]][down[1]]->token->getBehavior(0)->getBool("isTargeted")
&& !board->board[down[0]][down[1]]->token->getBehavior(0)->getBool("isDead")
&& board->board[down[0]][down[1]]->token->player == token->player)
{
trollBesideMe = true;
}
}
}
if (left[0] > -1 && left[0] < 10 && left[1] > -1 && left[1] < 10)
{
if (board->board[left[0]][left[1]]->token != NULL)
{
//If adjacent token is a Troll from the same team, which is not dying...
if (board->board[left[0]][left[1]]->token->getBehavior(0)->getInt("race") == TROLL
&& !board->board[left[0]][left[1]]->token->getBehavior(0)->getBool("isGonnaBeTrapped")
&& !board->board[left[0]][left[1]]->token->getBehavior(0)->getBool("isTargeted")
&& !board->board[left[0]][left[1]]->token->getBehavior(0)->getBool("isDead")
&& board->board[left[0]][left[1]]->token->player == token->player)
{
trollBesideMe = true;
}
}
}
if (right[0] > -1 && right[0] < 10 && right[1] > -1 && right[1] < 10)
{
if (board->board[right[0]][right[1]]->token != NULL)
{
//If adjacent token is a Troll from the same team, which is not dying...
if (board->board[right[0]][right[1]]->token->getBehavior(0)->getInt("race") == TROLL
&& !board->board[right[0]][right[1]]->token->getBehavior(0)->getBool("isGonnaBeTrapped")
&& !board->board[right[0]][right[1]]->token->getBehavior(0)->getBool("isTargeted")
&& !board->board[right[0]][right[1]]->token->getBehavior(0)->getBool("isDead")
&& board->board[right[0]][right[1]]->token->player == token->player)
{
trollBesideMe = true;
}
}
}
//Return whether there's a big, scary Troll beside me
return trollBesideMe;
}
void PrimePlayState::RessurrectToken(IrrToken* token, IrrBoard* board, int i, int j)
{
//If this token's team is the current playing team
if (token->player == turnPlayer)
{
//If this token is dead and the highlighted safe zone tile is empty
if (token->getBehavior(0)->getBool("isDead") && board->board[i][j]->token == NULL)
{
//Re-activate token
token->setActive(true);
token->getBehavior(0)->setBool("isDead", false);
//Place token at the safe zone!
if (board->addToken(i, j, token))
{
//Make sure the token cannot move this turn
token->getBehavior(0)->setBool("isFinished", true);
}
//Play position fitting sound
SFX->at(SFX_TOKEN_FIT)->getAudio()->setPlayOnceMode();
//Disable highlight on safe zone tiles momentarily
tokenRessurrected = true;
}
}
}
void PrimePlayState::VerifySafeZoneOccupation(IrrBoard* board)
{
int totalSafeZone1Tiles = 0;
//Clear ressurrection skipping variables
safeZone1TilesOccupied = safeZone2TilesOccupied = 0;
safeZone3TilesOccupied = safeZone4TilesOccupied = 0;
safeZone1Full = safeZone2Full = safeZone3Full = safeZone4Full = false;
skipRessurrection = false;
//Scan the whole board
for (int i=0; i < board->tile_i; i++)
{
for (int j=0; j < board->tile_j; j++)
{
//Count occupied tiles in all safe zones
if (board->board[i][j]->inf == SAFE_ZONE_TEAM_1 && board->board[i][j]->token != NULL) { safeZone1TilesOccupied++; }
else if (board->board[i][j]->inf == SAFE_ZONE_TEAM_2 && board->board[i][j]->token != NULL) { safeZone2TilesOccupied++; }
else if (board->board[i][j]->inf == SAFE_ZONE_TEAM_3 && board->board[i][j]->token != NULL) { safeZone3TilesOccupied++; }
else if (board->board[i][j]->inf == SAFE_ZONE_TEAM_4 && board->board[i][j]->token != NULL) { safeZone4TilesOccupied++; }
//If total amount of safe zone tiles hasn't been calculated yet...
if (safeZoneTilesMax == 0)
{
//Count team 1's safe zone tiles
if (board->board[i][j]->inf == SAFE_ZONE_TEAM_1) totalSafeZone1Tiles++;
}
}
}
//Determine total amount of safe zone tiles from team 1's tiles
if (safeZoneTilesMax == 0) safeZoneTilesMax = totalSafeZone1Tiles;
//If all safe zone tiles of a team are occupied, mark that safe zone as full
if (safeZone1TilesOccupied >= safeZoneTilesMax) safeZone1Full = true;
if (safeZone2TilesOccupied >= safeZoneTilesMax) safeZone2Full = true;
if (safeZone3TilesOccupied >= safeZoneTilesMax) safeZone3Full = true;
if (safeZone4TilesOccupied >= safeZoneTilesMax) safeZone4Full = true;
//If all safe zone tiles of the current player are occupied...
if ((turnPlayer == player1.idx && safeZone1Full) || (turnPlayer == player2.idx && safeZone2Full)
|| (turnPlayer == player3.idx && safeZone3Full) || (turnPlayer == player4.idx && safeZone4Full))
{
//This player is unable to ressurrect dead tokens
skipRessurrection = true;
}
}
void PrimePlayState::VerifyResourceExtraction(IrrBoard* board, bool effectVerification)
{
//Scan the whole board
for (int i=0; i < board->tile_i; i++)
{
for (int j=0; j < board->tile_j; j++)
{
//If a resource tile has a token on it...
if (board->board[i][j]->inf == RESOURCE && board->board[i][j]->token != NULL)
{
//Activate extraction effect...
if (effectVerification)
{
//Determine whether this tile is the Northwest, Northeast,
//Southwest or Southeast resource tile
//NORTHWEST...
if (i == 4 && j == 4)
{
//Begin particle emission
StartParticles(RESOURCES_NW, new Vector(board->board[i][j]->node->getAbsolutePosition().X,
board->board[i][j]->node->getAbsolutePosition().Y + 0.5f,
board->board[i][j]->node->getAbsolutePosition().Z));
}
//NORTHEAST...
else if (i == 4 && j == 5)
{
//Begin particle emission
StartParticles(RESOURCES_NE, new Vector(board->board[i][j]->node->getAbsolutePosition().X,
board->board[i][j]->node->getAbsolutePosition().Y + 0.5f,
board->board[i][j]->node->getAbsolutePosition().Z));
}
//SOUTHWEST...
else if (i == 5 && j == 4)
{
//Begin particle emission
StartParticles(RESOURCES_SW, new Vector(board->board[i][j]->node->getAbsolutePosition().X,
board->board[i][j]->node->getAbsolutePosition().Y + 0.5f,
board->board[i][j]->node->getAbsolutePosition().Z));
}
//SOUTHEAST...
else if (i == 5 && j == 5)
{
//Begin particle emission
StartParticles(RESOURCES_SE, new Vector(board->board[i][j]->node->getAbsolutePosition().X,
board->board[i][j]->node->getAbsolutePosition().Y + 0.5f,
board->board[i][j]->node->getAbsolutePosition().Z));
}
}
//...Or perform extraction!
else
{
//Activate this token's extraction state
board->board[i][j]->token->getBehavior(0)->setBool("isExtracting", true);
//Add Primevalium to this token's team
if (board->board[i][j]->token->player == player1.idx)
{
player1.primevalium += 100;
if (player1.assignedRace == KOBOLD) player1.primevalium += 60;
}
else if (board->board[i][j]->token->player == player2.idx)
{
player2.primevalium += 100;
if (player2.assignedRace == KOBOLD) player2.primevalium += 60;
}
else if (board->board[i][j]->token->player == player3.idx)
{
player3.primevalium += 100;
if (player3.assignedRace == KOBOLD) player3.primevalium += 60;
}
else if (board->board[i][j]->token->player == player4.idx)
{
player4.primevalium += 100;
if (player4.assignedRace == KOBOLD) player4.primevalium += 60;
}
resourcesExtracted = true;
}
}
//Otherwise, if there's no token on this resource tile...
else if (board->board[i][j]->inf == RESOURCE && board->board[i][j]->token == NULL)
{
//Deactivate extraction effect
if (effectVerification)
{
//Determine whether this tile is the Northwest, Northeast,
//Southwest or Southeast resource tile
//NORTHWEST...
if (i == 4 && j == 4) StopParticles(RESOURCES_NW);
//NORTHEAST...
else if (i == 4 && j == 5) StopParticles(RESOURCES_NE);
//SOUTHWEST...
else if (i == 5 && j == 4) StopParticles(RESOURCES_SW);
//SOUTHEAST...
else if (i == 5 && j == 5) StopParticles(RESOURCES_SE);
}
}
}
}
//If a player has reached the goal, set it as victorious
if (player1.primevalium >= resourcesGoal) player1.isVictorious = true;
if (player2.primevalium >= resourcesGoal) player2.isVictorious = true;
if (player3.primevalium >= resourcesGoal) player3.isVictorious = true;
if (player4.primevalium >= resourcesGoal) player4.isVictorious = true;
}
void PrimePlayState::ClearHighlights(IrrBoard* board)
{
//Scan the whole board
for (int i=0; i < board->tile_i; i++)
{
for (int j=0; j < board->tile_j; j++)
{
//Deactivate tile highlights
board->board[i][j]->isHighlighted = false;
board->board[i][j]->highlight = NONE;
//Deactivate token highlights
if (board->board[i][j]->token != NULL)
{
board->board[i][j]->token->isHighlighted = false;
board->board[i][j]->token->highlight = NONE;
}
}
}
}
void PrimePlayState::SwapPhase(IrrBoard* board)
{
int remainingTokens = 0, finishedTokens = 0;
//Begin the battle
if (phase == MATCH_START)
{
//Start match for real only after 2 seconds,
//during which "Sorting turn order" message is shown.
if (!matchStart && Wait(1.0f))
{
//Start playing match BGM
BGM->at(BGM_MATCH)->getAudio()->setLoopingStreamMode();
matchStart = true;
}
else if (matchStart && Wait(2.0f))
{
//Initialize particle systems
InitParticles(board);
phase = TURN_START;
matchStart = false;
}
}
//Show new turn messages and begin turn
else if (phase == TURN_START)
{
//Turn has begun!
if (turnBeginPhase == 0)
{
turnOver = false;
turnBeginPhase = NO_MESSAGE_AT_ONE;
}
//...Actually, it only really begins after 3 seconds,
//during which the "Player X Turn" message is shown.
else if (turnBeginPhase == NO_MESSAGE_AT_ONE && Wait(0.5f)) turnBeginPhase = TURN_MESSAGE_AT_TWO;
else if (turnBeginPhase == TURN_MESSAGE_AT_TWO && Wait(2.5f)) turnBeginPhase = NO_MESSAGE_AT_THREE;
else if (turnBeginPhase == NO_MESSAGE_AT_THREE && Wait(0.5f))
{
//Decrement ability cooldown for all units
UpdateCooldown();
//First step of a new turn is to ressurrect dead tokens
phase = RESSURRECTION_PLACEMENT;
//Reset AI token acting order variables
firstTokenMovedAI = secondTokenMovedAI = thirdTokenMovedAI = false;
firstTokenTryAgainAI = secondTokenTryAgainAI = thirdTokenTryAgainAI = false;
//Reset AI token ressurrection counter
tokenRessurrectedAI = 0;
turnBeginPhase = 0;
}
}
//Find dead tokens and decide whether ressurrection should be performed
if (phase == RESSURRECTION_PLACEMENT)
{
remainingTokens = GetRemainingTokens(DEAD_TOKENS, false, false);
//Check if there's at least 1 free safe zone tile
VerifySafeZoneOccupation(board);
//If AI has induced ressurrection phase skipping...
if (skipRessurrectionAI) skipRessurrection = true;
//Force ressurrection skipping if "End Match" button is pressed
if (signalEndMatch) skipRessurrection = true;
//If there are no dead tokens or ressurrection can't be performed
//because all safe zone tiles are occupied, go to next phase
if (!tokenRessurrected && (remainingTokens == 0 || skipRessurrection))
{
//Store how many dead tokens could not be revived, in case of skipping
if (skipRessurrection)
{
deadTokensNotRevived = remainingTokens;
skipRessurrection = false;
skipRessurrectionAI = false;
}
//Don't forget to reset action states
ResetTokenActionStates();
phase = PLAY_SELECTION;
}
}
//Find tokens which have moved and decide if turn is over
else if (phase == PLAY_SELECTION)
{
//If player has pressed the "End Turn" button...
if (signalEndTurn || signalEndMatch)
{
//Set all of current player's tokens as finished
FinishTokens();
}
//Count finished tokens
finishedTokens = GetRemainingTokens(false, FINISHED_TOKENS, false);
//If all tokens are finished, go to next phase
if (finishedTokens >= (tokensActive - deadTokensNotRevived))
{
//Wait for half a second
if (Wait(0.4f))
{
//Reset signal
signalEndTurn = false;
//Don't forget to reset action states
ResetTokenActionStates();
//Enable movement for all alive tokens in the next turn
for (t = tokensTeam1->begin(); t != tokensTeam1->end(); t++) (*t)->getBehavior(0)->setBool("isFinished", false);
for (t = tokensTeam2->begin(); t != tokensTeam2->end(); t++) (*t)->getBehavior(0)->setBool("isFinished", false);
for (t = tokensTeam3->begin(); t != tokensTeam3->end(); t++) (*t)->getBehavior(0)->setBool("isFinished", false);
for (t = tokensTeam4->begin(); t != tokensTeam4->end(); t++) (*t)->getBehavior(0)->setBool("isFinished", false);
//Dead tokens will stay dead
deadTokensNotRevived = 0;
//Time for resource extraction!
phase = TURN_END;
}
}
}
//Find tokens which animation hasn't finished yet
else if (phase == ANIMATION_EXECUTION)
{
remainingTokens = GetRemainingTokens(false, false, ANIMATED_TOKENS);
//If all tokens have finished their animations, go back to play selection
if (remainingTokens == 0)
{
//Disable future moves for selected token, in this turn
if (selectedToken->getBehavior(0)->getBool("isSelected"))
{
selectedToken->getBehavior(0)->setBool("isFinished", true);
selectedToken->getBehavior(0)->setBool("isSelected", false);
}
if (Wait(0.3f))
{
//Reset selected token and killed token
selectedToken = NULL;
killedToken = NULL;
//Don't forget to reset action states
ResetTokenActionStates();
phase = PLAY_SELECTION;
}
}
}
//Extract resources and check for a victory condition
else if (phase == TURN_END)
{
//If "End Match" button has been pressed...
if (signalEndMatch)
{
//Stop playing match BGM
BGM->at(BGM_MATCH)->getAudio()->stop(true, 1.0f);
//Advance straight to match end
phase = MATCH_END;
}
//Otherwise...
else
{
if (!resourcesVerified && Wait(0.8f))
{
//Perform resource extraction
VerifyResourceExtraction(board, false);
//Play resource extraction sound
if (resourcesExtracted) SFX->at(SFX_EXTRACTION)->getAudio()->setPlayOnceMode();
resourcesVerified = true;
}
else if (resourcesVerified && (!resourcesExtracted || (resourcesExtracted && Wait(2.0f))))
{
//Reset extraction state for all tokens
for (t = tokensTeam1->begin(); t != tokensTeam1->end(); t++) (*t)->getBehavior(0)->setBool("isExtracting", false);
for (t = tokensTeam2->begin(); t != tokensTeam2->end(); t++) (*t)->getBehavior(0)->setBool("isExtracting", false);
for (t = tokensTeam3->begin(); t != tokensTeam3->end(); t++) (*t)->getBehavior(0)->setBool("isExtracting", false);
for (t = tokensTeam4->begin(); t != tokensTeam4->end(); t++) (*t)->getBehavior(0)->setBool("isExtracting", false);
//Check for victory condition
if (player1.isVictorious || player2.isVictorious || player3.isVictorious || player4.isVictorious)
{
//Signal victory music
signalVictoryBGM = true;
//Stop playing match BGM
BGM->at(BGM_MATCH)->getAudio()->stop(true, 1.0f);
//End match if there's one or more victors
phase = MATCH_END;
}
//If no victors so far, go on with game...
else
{
//Current turn is over!
turnOver = true;
//Advance to next turn
phase = TURN_START;
}
//Reset auxiliary variables
resourcesVerified = false;
resourcesExtracted = false;
}
}
}
//Show victory messages and finish up match
else if (phase == MATCH_END)
{
//Wait until victory song is over,
//meanwhile displaying victory message.
if (!matchOver && Wait(1.0f))
{
matchOver = true;
//Play victory BGM, if there is a victorious player
if (signalVictoryBGM) BGM->at(BGM_VICTORY)->getAudio()->setPlayOnceMode();
}
//Once victory song has finished...
else if (matchOver && !signalBackToTitle && ((signalEndMatch && Wait(0.1f)) || (!signalEndMatch && Wait(6.0f))))
{
//Drop tokens which were dead by the end of match (still floating in limbo)
for (t = tokensTeam1->begin(); t != tokensTeam1->end(); t++) { if (!(*t)->isActive()) (*t)->node->drop(); }
for (t = tokensTeam2->begin(); t != tokensTeam2->end(); t++) { if (!(*t)->isActive()) (*t)->node->drop(); }
for (t = tokensTeam3->begin(); t != tokensTeam3->end(); t++) { if (!(*t)->isActive()) (*t)->node->drop(); }
for (t = tokensTeam4->begin(); t != tokensTeam4->end(); t++) { if (!(*t)->isActive()) (*t)->node->drop(); }
//Reset signal
signalEndMatch = false;
//Inform game state manager the match is over
signalBackToTitle = true;
//Stop playing victory BGM
BGM->at(BGM_VICTORY)->getAudio()->stop();
//Remove camera crosshair billboard
billboardCameraCrosshair->remove();
}
}
}
void PrimePlayState::SwapPhaseAI(IrrBoard* board)
{
//The agent senses its surroundings and determines a theoretical action for itself.
//This method will take that "imaginary" action and make it real.
//Move tokens based on agent decisions, not highlighted tiles
if (phase == PLAY_SELECTION)
{
//Enable new move by resetting previous move
tokenMovedAI = false;
//Team 1...
if (turnPlayer == 1 && player1.isAI)
{
AIPlay = true;
//Attempt to move tokens in order (2, 1, 3)
t = tokensTeam1->begin(); t++; MoveTokenAI((*t), board, 2);
--t; MoveTokenAI((*t), board, 1);
t++; t++; MoveTokenAI((*t), board, 3);
//If all tokens have moved, signal turn end
if (firstTokenMovedAI && secondTokenMovedAI && thirdTokenMovedAI && !signalEndTurn)
{
//This also forces Finished state onto "standing" tokens!
signalEndTurn = true;
}
}
//Team 2...
else if (turnPlayer == 2 && player2.isAI)
{
AIPlay = true;
//Attempt to move tokens in order (2, 3, 1)
t = tokensTeam2->begin(); t++; MoveTokenAI((*t), board, 2);
t++; MoveTokenAI((*t), board, 3);
--t; --t; MoveTokenAI((*t), board, 1);
//If all tokens have moved, signal turn end
if (firstTokenMovedAI && secondTokenMovedAI && thirdTokenMovedAI && !signalEndTurn)
{
//This also forces Finished state onto "standing" tokens!
signalEndTurn = true;
}
}
//Team 3...
else if (turnPlayer == 3 && player3.isAI)
{
AIPlay = true;
//Attempt to move tokens in order (2, 3, 1)
t = tokensTeam3->begin(); t++; MoveTokenAI((*t), board, 2);
t++; MoveTokenAI((*t), board, 3);
--t; --t; MoveTokenAI((*t), board, 1);
//If all tokens have moved, signal turn end
if (firstTokenMovedAI && secondTokenMovedAI && thirdTokenMovedAI && !signalEndTurn)
{
//This also forces Finished state onto "standing" tokens!
signalEndTurn = true;
}
}
//Team 4...
else if (turnPlayer == 4 && player4.isAI)
{
AIPlay = true;
//Attempt to move tokens in order (2, 1, 3)
t = tokensTeam4->begin(); t++; MoveTokenAI((*t), board, 2);
--t; MoveTokenAI((*t), board, 1);
t++; t++; MoveTokenAI((*t), board, 3);
//If all tokens have moved, signal turn end
if (firstTokenMovedAI && secondTokenMovedAI && thirdTokenMovedAI && !signalEndTurn)
{
//This also forces Finished state onto "standing" tokens!
signalEndTurn = true;
}
}
//No AI team is playing
else AIPlay = false;
}
//Ressurrection happens automatically, in pre-defined tiles
else if (phase == RESSURRECTION_PLACEMENT)
{
//Team 1...
if (turnPlayer == 1 && player1.isAI)
{
for (t = tokensTeam1->begin(); t != tokensTeam1->end(); t++)
{
//If token is dead...
if ((*t)->getBehavior(0)->getBool("isDead"))
{
if (board->board[4][0]->token == NULL) RessurrectTokenAI((*t), board, 4, 0); //1st Priority position
else if (board->board[5][0]->token == NULL) RessurrectTokenAI((*t), board, 5, 0); //2nd Priority position
else if (board->board[3][0]->token == NULL) RessurrectTokenAI((*t), board, 3, 0); //3rd Priority position
else skipRessurrectionAI = true; //All pre-defined positions occupied, skip ressurrection.
}
}
}
//Team 2...
else if (turnPlayer == 2 && player2.isAI)
{
for (t = tokensTeam2->begin(); t != tokensTeam2->end(); t++)
{
//If token is dead...
if ((*t)->getBehavior(0)->getBool("isDead"))
{
if (board->board[5][9]->token == NULL) RessurrectTokenAI((*t), board, 5, 9); //1st Priority position
else if (board->board[4][9]->token == NULL) RessurrectTokenAI((*t), board, 4, 9); //2nd Priority position
else if (board->board[6][9]->token == NULL) RessurrectTokenAI((*t), board, 6, 9); //3rd Priority position
else skipRessurrectionAI = true; //All pre-defined positions occupied, skip ressurrection.
}
}
}
//Team 3...
else if (turnPlayer == 3 && player3.isAI)
{
for (t = tokensTeam3->begin(); t != tokensTeam3->end(); t++)
{
//If token is dead...
if ((*t)->getBehavior(0)->getBool("isDead"))
{
if (board->board[0][5]->token == NULL) RessurrectTokenAI((*t), board, 0, 5); //1st Priority position
else if (board->board[0][4]->token == NULL) RessurrectTokenAI((*t), board, 0, 4); //2nd Priority position
else if (board->board[0][6]->token == NULL) RessurrectTokenAI((*t), board, 0, 6); //3rd Priority position
else skipRessurrectionAI = true; //All pre-defined positions occupied, skip ressurrection.
}
}
}
//Team 4...
else if (turnPlayer == 4 && player4.isAI)
{
for (t = tokensTeam4->begin(); t != tokensTeam4->end(); t++)
{
//If token is dead...
if ((*t)->getBehavior(0)->getBool("isDead"))
{
if (board->board[9][4]->token == NULL) RessurrectTokenAI((*t), board, 9, 4); //1st Priority position
else if (board->board[9][5]->token == NULL) RessurrectTokenAI((*t), board, 9, 5); //2nd Priority position
else if (board->board[9][3]->token == NULL) RessurrectTokenAI((*t), board, 9, 3); //3rd Priority position
else skipRessurrectionAI = true; //All pre-defined positions occupied, skip ressurrection.
}
}
}
//No AI team is playing
else AIPlay = false;
}
}
void PrimePlayState::SwapPhaseOnClick(IrrBoard* board, int i, int j)
{
//Verify which is the clicked token/tile's type of highlight
//(MOVE, MOVE_HOVER, PUSH_HOVER, etc.) and act accordingly!
//If the current phase involves selecting and moving tokens...
if (phase == PLAY_SELECTION)
{
//If mouse is hovering an empty tile...
if (board->board[i][j]->token == NULL)
{
//...And a token has already been selected...
if (selectedToken != NULL)
{
//...Mark selected token for movement.
selectedToken->getBehavior(0)->setBool("isGonnaMove", true);
//Startup animation for selected token
selectedToken->getBehavior(0)->setBool("isAnimStarted", true);
//Execute move (start animations)
phase = ANIMATION_EXECUTION;
//Play token movement sound
SFX->at(SFX_TOKEN_DRAG)->getAudio()->setPlayOnceMode();
}
}
//Otherwise, if mouse is above an occupied tile...
else if (board->board[i][j]->token != NULL)
{
//If a token hasn't been selected yet
if (selectedToken == NULL)
{
//Select the hovered token
selectedToken = board->getToken(i,j);
board->board[i][j]->token->getBehavior(0)->setBool("isSelected", true);
//Play token selection sound
SFX->at(SFX_TOKEN_SELECT_LIGHT)->getAudio()->setPlayOnceMode();
}
//Otherwise, if a token has already been selected...
else if (selectedToken != NULL)
{
//If mouse is above a token that's highlighted for pushing...
if (board->board[i][j]->token->highlight == PUSH_HOVER)
{
//Mark this token and the tokens behind it for pushing
tokensPushed = SetPushLine(CLICKED, selectedToken->getBehavior(0)->getInt("moveDir"), board, i, j);
//Mark selected token for movement
selectedToken->getBehavior(0)->setBool("isGonnaMove", true);
//Startup animation for selected token
selectedToken->getBehavior(0)->setBool("isAnimStarted", true);
//Execute move (start animations)
phase = ANIMATION_EXECUTION;
//Play token movement sound
SFX->at(SFX_TOKEN_DRAG)->getAudio()->setPlayOnceMode();
}
//Otherwise...
else
{
//...If mouse is over an allied token, which is not the selected token...
if (board->board[i][j]->token->player == turnPlayer)
{
//Unselect previous token
selectedToken->getBehavior(0)->setBool("isSelected", false);
//Select new token
selectedToken = board->getToken(i,j);
board->board[i][j]->token->getBehavior(0)->setBool("isSelected", true);
//Play token selection sound
SFX->at(SFX_TOKEN_SELECT_LIGHT)->getAudio()->setPlayOnceMode();
}
//...If mouse is over an enemy token...
else
{
//Mark enemy as attack target
board->board[i][j]->token->getBehavior(0)->setBool("isTargeted", true);
//Mark selected token for movement
selectedToken->getBehavior(0)->setBool("isGonnaMove", true);
//Startup animation for enemy and selected token
board->board[i][j]->token->getBehavior(0)->setBool("isAnimStarted", true);
selectedToken->getBehavior(0)->setBool("isAnimStarted", true);
//Execute move (start animations)
animAttackDeath = true;
phase = ANIMATION_EXECUTION;
}
}
}
}
}
//If the current phase involves reviving dead tokens...
else if (phase == RESSURRECTION_PLACEMENT)
{
if (!tokenRessurrected)
{
//Iterate through all players' token lists, reviving dead tokens
for (t = tokensTeam1->begin(); t != tokensTeam1->end(); t++) RessurrectToken((*t), board, i, j);
for (t = tokensTeam2->begin(); t != tokensTeam2->end(); t++) RessurrectToken((*t), board, i, j);
for (t = tokensTeam3->begin(); t != tokensTeam3->end(); t++) RessurrectToken((*t), board, i, j);
for (t = tokensTeam4->begin(); t != tokensTeam4->end(); t++) RessurrectToken((*t), board, i, j);
}
}
}
void PrimePlayState::GetAdjacentTiles()
{
//Get adjacent tile positions
iNorth = selectedToken->parentNode->posi - 1;
jNorth = selectedToken->parentNode->posj ;
iSouth = selectedToken->parentNode->posi + 1;
jSouth = selectedToken->parentNode->posj;
iWest = selectedToken->parentNode->posi;
jWest = selectedToken->parentNode->posj - 1;
iEast = selectedToken->parentNode->posi;
jEast = selectedToken->parentNode->posj + 1;
//Get diagonal tile positions
iNorthwest = selectedToken->parentNode->posi - 1;
jNorthwest = selectedToken->parentNode->posj - 1;
iNortheast = selectedToken->parentNode->posi - 1;
jNortheast = selectedToken->parentNode->posj + 1;
iSouthwest = selectedToken->parentNode->posi + 1;
jSouthwest = selectedToken->parentNode->posj - 1;
iSoutheast = selectedToken->parentNode->posi + 1;
jSoutheast = selectedToken->parentNode->posj + 1;
}
int PrimePlayState::GetDestinationTile(int dir, int i, int j, bool iTile)
{
int dest = -1;
//If "iTile" is true, get the destination "i" tile (Row)
if (iTile)
{
if (dir == NORTH || dir == NORTHEAST || dir == NORTHWEST) dest = i - 1;
else if (dir == SOUTH || dir == SOUTHEAST || dir == SOUTHWEST) dest = i + 1;
else if (dir == EAST || dir == WEST) dest = i;
}
//Otherwise, get the destination "j" tile (Column)
else
{
if (dir == NORTH || dir == SOUTH) dest = j;
else if (dir == EAST || dir == NORTHEAST || dir == SOUTHEAST) dest = j + 1;
else if (dir == WEST || dir == NORTHWEST || dir == SOUTHWEST) dest = j - 1;
}
//Return destination
return dest;
}
int PrimePlayState::GetRemainingTokens(bool dead, bool finished, bool animated)
{
int remainingTokens = 0;
//Look for tokens which animation hasn't finished
if (animated)
{
//If "isAnimClosed" is false, then the token's animation hasn't been terminated by play state
for (t = tokensTeam1->begin(); t != tokensTeam1->end(); t++)
{
if ((*t)->getBehavior(0)->getBool("isAnimStarted") && !(*t)->getBehavior(0)->getBool("isAnimClosed"))
remainingTokens++;
}
for (t = tokensTeam2->begin(); t != tokensTeam2->end(); t++)
{
if ((*t)->getBehavior(0)->getBool("isAnimStarted") && !(*t)->getBehavior(0)->getBool("isAnimClosed"))
remainingTokens++;
}
for (t = tokensTeam3->begin(); t != tokensTeam3->end(); t++)
{
if ((*t)->getBehavior(0)->getBool("isAnimStarted") && !(*t)->getBehavior(0)->getBool("isAnimClosed"))
remainingTokens++;
}
for (t = tokensTeam4->begin(); t != tokensTeam4->end(); t++)
{
if ((*t)->getBehavior(0)->getBool("isAnimStarted") && !(*t)->getBehavior(0)->getBool("isAnimClosed"))
remainingTokens++;
}
}
//Otherwise, search for dead or finished tokens
else
{
//Find out which player this turn belongs to,
//and if that player has any dead tokens
if (player1.isActive && turnPlayer == player1.idx)
{
//Search team 1's tokens
for (t = tokensTeam1->begin(); t != tokensTeam1->end(); t++)
{
//Look for dead tokens or tokens which have already moved
if (dead) { if ((*t)->getBehavior(0)->getBool("isDead")) remainingTokens++; }
else if (finished) { if ((*t)->getBehavior(0)->getBool("isFinished")) remainingTokens++; }
}
}
else if (player2.isActive && turnPlayer == player2.idx)
{
//Search for dead tokens among team 2's tokens
for (t = tokensTeam2->begin(); t != tokensTeam2->end(); t++)
{
//Look for dead tokens or tokens which have already moved
if (dead) { if ((*t)->getBehavior(0)->getBool("isDead")) remainingTokens++; }
else if (finished) { if ((*t)->getBehavior(0)->getBool("isFinished")) remainingTokens++; }
}
}
else if (player3.isActive && turnPlayer == player3.idx)
{
//Search for dead tokens among team 3's tokens
for (t = tokensTeam3->begin(); t != tokensTeam3->end(); t++)
{
//Look for dead tokens or tokens which have already moved
if (dead) { if ((*t)->getBehavior(0)->getBool("isDead")) remainingTokens++; }
else if (finished) { if ((*t)->getBehavior(0)->getBool("isFinished")) remainingTokens++; }
}
}
else if (player4.isActive && turnPlayer == player4.idx)
{
//Search for dead tokens among team 4's tokens
for (t = tokensTeam4->begin(); t != tokensTeam4->end(); t++)
{
//Look for dead tokens or tokens which have already moved
if (dead) { if ((*t)->getBehavior(0)->getBool("isDead")) remainingTokens++; }
else if (finished) { if ((*t)->getBehavior(0)->getBool("isFinished")) remainingTokens++; }
}
}
}
//Return amout of dead or finished tokens
return remainingTokens;
}
void PrimePlayState::UpdateCooldown()
{
int currentCooldown = -1;
//Decrease cooldown time for all units
for (t = tokensTeam1->begin(); t != tokensTeam1->end(); t++)
{
currentCooldown = (*t)->getBehavior(0)->getInt("abilityCooldown");
if (currentCooldown > 0) (*t)->getBehavior(0)->setInt("abilityCooldown", currentCooldown - 1);
}
for (t = tokensTeam2->begin(); t != tokensTeam2->end(); t++)
{
currentCooldown = (*t)->getBehavior(0)->getInt("abilityCooldown");
if (currentCooldown > 0) (*t)->getBehavior(0)->setInt("abilityCooldown", currentCooldown - 1);
}
for (t = tokensTeam3->begin(); t != tokensTeam3->end(); t++)
{
currentCooldown = (*t)->getBehavior(0)->getInt("abilityCooldown");
if (currentCooldown > 0) (*t)->getBehavior(0)->setInt("abilityCooldown", currentCooldown - 1);
}
for (t = tokensTeam4->begin(); t != tokensTeam4->end(); t++)
{
currentCooldown = (*t)->getBehavior(0)->getInt("abilityCooldown");
if (currentCooldown > 0) (*t)->getBehavior(0)->setInt("abilityCooldown", currentCooldown - 1);
}
}
void PrimePlayState::FinishTokens()
{
//Find current player and end its turn by manually finishing all token moves
if (turnPlayer == player1.idx)
{
for (t = tokensTeam1->begin(); t != tokensTeam1->end(); t++) (*t)->getBehavior(0)->setBool("isFinished", true);
}
else if (turnPlayer == player2.idx)
{
for (t = tokensTeam2->begin(); t != tokensTeam2->end(); t++) (*t)->getBehavior(0)->setBool("isFinished", true);
}
else if (turnPlayer == player3.idx)
{
for (t = tokensTeam3->begin(); t != tokensTeam3->end(); t++) (*t)->getBehavior(0)->setBool("isFinished", true);
}
else if (turnPlayer == player4.idx)
{
for (t = tokensTeam4->begin(); t != tokensTeam4->end(); t++) (*t)->getBehavior(0)->setBool("isFinished", true);
}
}
void PrimePlayState::ResetTokenActionStates()
{
//Reset action states for all tokens of all teams
for (t = tokensTeam1->begin(); t != tokensTeam1->end(); t++) (*t)->getBehavior(0)->reset();
for (t = tokensTeam2->begin(); t != tokensTeam2->end(); t++) (*t)->getBehavior(0)->reset();
for (t = tokensTeam3->begin(); t != tokensTeam3->end(); t++) (*t)->getBehavior(0)->reset();
for (t = tokensTeam4->begin(); t != tokensTeam4->end(); t++) (*t)->getBehavior(0)->reset();
}
void PrimePlayState::ManageRaceAbilities(IrrToken* token, IrrBoard* board)
{
//Activate or deactivate abilities, when conditions are met!
//KOBOLDs...
if (token->getBehavior(0)->getInt("race") == KOBOLD)
{
//ADVANCED PROSPECTION activates when a Kobold unit is placed on an extraction tile...
if (board->board[token->parentNode->posi][token->parentNode->posj]->inf == RESOURCE)
{
//...As long as its not dead nor dying.
if (!token->getBehavior(0)->getBool("isAbilityActive")
&& !token->getBehavior(0)->getBool("isDead")
&& !token->getBehavior(0)->getBool("isTargeted")
&& !token->getBehavior(0)->getBool("isGonnaBeTrapped"))
{
//Activate ability and show special effect
token->getBehavior(0)->setBool("isAbilityActive", true);
StartParticles(ABILITY, new Vector(token->parentNode->node->getAbsolutePosition().X,
token->parentNode->node->getAbsolutePosition().Y + 1.0f,
token->parentNode->node->getAbsolutePosition().Z));
//Play ability activation sound
SFX->at(SFX_ABILITY)->getAudio()->setPlayOnceMode();
}
}
else token->getBehavior(0)->setBool("isAbilityActive", false);
}
//GNOLLs...
else if (token->getBehavior(0)->getInt("race") == GNOLL)
{
//RECOVERY RUSH activates when a dead Gnoll unit is placed back on the field
if (((AIPlay && tokenRessurrectedAI > 0) || (!AIPlay && tokenRessurrected))
&& !token->getBehavior(0)->getBool("isDead") && token->getBehavior(0)->getBool("isFinished"))
{
if (!token->getBehavior(0)->getBool("isAbilityActive"))
{
//Activate ability and show special effect
token->getBehavior(0)->setBool("isAbilityActive", true);
token->getBehavior(0)->setBool("isFinished", false);
StartParticles(ABILITY, new Vector(token->parentNode->node->getAbsolutePosition().X,
token->parentNode->node->getAbsolutePosition().Y + 1.0f,
token->parentNode->node->getAbsolutePosition().Z));
//Play ability activation sound
SFX->at(SFX_ABILITY)->getAudio()->setPlayOnceMode();
//Decrement AI token ressurrection counter
if (tokenRessurrectedAI > 0) tokenRessurrectedAI -= 1;
}
}
else if (!tokenRessurrected && token->getBehavior(0)->getBool("isFinished"))
{
token->getBehavior(0)->setBool("isAbilityActive", false);
}
}
//TROLLs...
else if (token->getBehavior(0)->getInt("race") == TROLL)
{
//HEAVYWEIGHT activates when there's 2 or more trolls beside one another...
if (TrollBesideMe(token, board))
{
//...As long as neither of them is dying.
if (!token->getBehavior(0)->getBool("isGonnaBeTrapped")
&& !token->getBehavior(0)->getBool("isTargeted")
&& !token->getBehavior(0)->getBool("isDead"))
{
if (!token->getBehavior(0)->getBool("isAbilityActive"))
{
//Activate ability and show special effect
token->getBehavior(0)->setBool("isAbilityActive", true);
StartParticles(ABILITY, new Vector(token->parentNode->node->getAbsolutePosition().X,
token->parentNode->node->getAbsolutePosition().Y + 1.0f,
token->parentNode->node->getAbsolutePosition().Z));
//Play ability activation sound
SFX->at(SFX_ABILITY)->getAudio()->setPlayOnceMode();
}
}
}
else token->getBehavior(0)->setBool("isAbilityActive", false);
}
//HOGs...
else if (token->getBehavior(0)->getInt("race") == HOG)
{
//If this is the selected token and its animation has finished...
if (token == selectedToken && token->getBehavior(0)->getBool("isAnimClosed"))
{
if (token->getBehavior(0)->getBool("isFinished") && token->getBehavior(0)->getInt("abilityCooldown") == 0)
{
//KILL RUSH activates when a Hog unit kills an enemy unit
if (EnemyTokenKilled(board))
{
if (!token->getBehavior(0)->getBool("isAbilityActive"))
{
//Activate ability and show special effect
token->getBehavior(0)->setBool("isAbilityActive", true);
token->getBehavior(0)->setBool("isFinished", false);
StartParticles(ABILITY, new Vector(token->parentNode->node->getAbsolutePosition().X,
token->parentNode->node->getAbsolutePosition().Y + 1.0f,
token->parentNode->node->getAbsolutePosition().Z));
//Play ability activation sound
SFX->at(SFX_ABILITY)->getAudio()->setPlayOnceMode();
//This ability cannot be activated again for 3 rounds
token->getBehavior(0)->setInt("abilityCooldown", (3 * playersActive));
//If this is an AI turn...
if (AIPlay)
{
//Attempt to move Hog AI tokens one more time
firstTokenMovedAI = secondTokenMovedAI = thirdTokenMovedAI = false;
firstTokenTryAgainAI = secondTokenTryAgainAI = thirdTokenTryAgainAI = false;
}
}
}
}
}
else if (token->getBehavior(0)->getBool("isFinished"))
{
token->getBehavior(0)->setBool("isAbilityActive", false);
}
}
}
void PrimePlayState::ManageRessurrection(IrrBoard* board, int i, int j)
{
bool tileMarked = false;
int iTile = -1;
int jTile = -1;
if (turnPlayer == player1.idx)
{
//If this tile is this team's safe zone, and there's no token on it...
if (board->board[i][j]->inf == SAFE_ZONE_TEAM_1 && board->board[i][j]->token == NULL)
{
//Mark this tile's position for highlighting
iTile = i; jTile = j; tileMarked = true;
}
}
else if (turnPlayer == player2.idx)
{
//If this tile is this team's safe zone, and there's no token on it...
if (board->board[i][j]->inf == SAFE_ZONE_TEAM_2 && board->board[i][j]->token == NULL)
{
//Mark this tile's position for highlighting
iTile = i; jTile = j; tileMarked = true;
}
}
else if (turnPlayer == player3.idx)
{
//If this tile is this team's safe zone, and there's no token on it...
if (board->board[i][j]->inf == SAFE_ZONE_TEAM_3 && board->board[i][j]->token == NULL)
{
//Mark this tile's position for highlighting
iTile = i; jTile = j; tileMarked = true;
}
}
else if (turnPlayer == player4.idx)
{
//If this tile is this team's safe zone, and there's no token on it...
if (board->board[i][j]->inf == SAFE_ZONE_TEAM_4 && board->board[i][j]->token == NULL)
{
//Mark this tile's position for highlighting
iTile = i; jTile = j; tileMarked = true;
}
}
//If a tile has been marked for highlighting...
if (tileMarked)
{
//Highlight the tile
board->board[iTile][jTile]->isHighlighted = true;
if (board->board[iTile][jTile]->isMouseHover)
board->board[iTile][jTile]->highlight = RESSURRECT_HOVER;
else board->board[iTile][jTile]->highlight = RESSURRECT;
}
}
void PrimePlayState::ManageTokenSelection(IrrBoard* board, int i, int j)
{
//If the tile at (i,j) has a token
if (board->board[i][j]->token != NULL)
{
//If the token belongs to the current player
if (board->board[i][j]->token->player == turnPlayer)
{
//If this token isn't selected, neither dead and hasn't moved yet...
if (!board->board[i][j]->token->getBehavior(0)->getBool("isSelected")
&& !board->board[i][j]->token->getBehavior(0)->getBool("isDead")
&& !board->board[i][j]->token->getBehavior(0)->getBool("isFinished"))
{
//Highlight tile
board->board[i][j]->isHighlighted = true;
if (board->board[i][j]->isMouseHover || board->board[i][j]->token->isMouseHover)
board->board[i][j]->highlight = MOVE_HOVER;
else board->board[i][j]->highlight = MOVE;
//Check if token isn't already highlighted
//by something else (like a Push move)
if (!board->board[i][j]->token->isHighlighted)
{
//Highlight token
board->board[i][j]->token->isHighlighted = true;
board->board[i][j]->token->highlight = MOVE_HOVER;
}
}
}
}
}
void PrimePlayState::ManageMoveSelection(IrrBoard* board, int i, int j)
{
int dir = -1;
//Grab adjacent directions
GetAdjacentTiles();
//If this is not a trap or obstacle tile...
if (board->board[i][j]->inf != TRAP && board->board[i][j]->inf != RUINS)
{
//Find out this tile's direction relative to selected token
if (i == iNorth && j == jNorth) dir = NORTH;
else if (i == iSouth && j == jSouth) dir = SOUTH;
else if (i == iWest && j == jWest) dir = WEST;
else if (i == iEast && j == jEast) dir = EAST;
else if (i == iNorthwest && j == jNorthwest) dir = NORTHWEST;
else if (i == iNortheast && j == jNortheast) dir = NORTHEAST;
else if (i == iSouthwest && j == jSouthwest) dir = SOUTHWEST;
else if (i == iSoutheast && j == jSoutheast) dir = SOUTHEAST;
//If this is the North, South, West or East tile...
if (dir == NORTH || dir == SOUTH || dir == WEST || dir == EAST)
{
//If there's NOT a token on this tile...
if (board->board[i][j]->token == NULL)
{
//Highlight tile for Movement
board->board[i][j]->isHighlighted = true;
if (board->board[i][j]->isMouseHover)
board->board[i][j]->highlight = MOVE_HOVER;
else board->board[i][j]->highlight = MOVE;
//Set move direction for selected token
selectedToken->getBehavior(0)->setInt("moveDir", dir);
}
//Else, if there's a token on this tile...
else if (board->board[i][j]->token != NULL)
{
//If its a valid Push move...
if (PlayIsValid(PUSH,dir,board,i,j))
{
//Highlight tile for Push
board->board[i][j]->isHighlighted = true;
if (board->board[i][j]->isMouseHover || board->board[i][j]->token->isMouseHover)
{
board->board[i][j]->highlight = PUSH_HOVER;
//Highlight token for Push
board->board[i][j]->token->isHighlighted = true;
board->board[i][j]->token->highlight = PUSH_HOVER;
//Highlight other tokens in the Push line
SetPushLine(ONLY_HIGHLIGHT, dir,board,i,j);
//Set move direction for selected token
selectedToken->getBehavior(0)->setInt("moveDir", dir);
}
else if (!board->board[i][j]->isMouseHover && !board->board[i][j]->token->isMouseHover)
{
board->board[i][j]->highlight = PUSH;
}
}
}
}
//If this is the Northeast, Northwest, Southeast or Southwest tile...
else if (dir == NORTHEAST || dir == NORTHWEST || dir == SOUTHEAST || dir == SOUTHWEST)
{
//If there's a token on this tile...
if (board->board[i][j]->token != NULL)
{
//If its a valid Attack move...
if (PlayIsValid(ATTACK,0,board,i,j))
{
//Highlight tile for Attack
board->board[i][j]->isHighlighted = true;
if (board->board[i][j]->isMouseHover || board->board[i][j]->token->isMouseHover)
{
board->board[i][j]->highlight = ATTACK_HOVER;
//Highlight token for Attack
board->board[i][j]->token->isHighlighted = true;
board->board[i][j]->token->highlight = ATTACK_HOVER;
//Set move direction for selected token
selectedToken->getBehavior(0)->setInt("moveDir", dir);
}
else if (!board->board[i][j]->isMouseHover && !board->board[i][j]->token->isMouseHover)
{
board->board[i][j]->highlight = ATTACK;
}
}
}
}
}
}
void PrimePlayState::UpdateTurnPhases(IrrBoard* board)
{
bool tileSelected = false;
bool tokenSelected = false;
bool mouseClickedOnHighlight = false;
//Manage camera crosshair
SetCrosshairPosition();
//Advance phases when conditions are met
SwapPhase(board);
//AI: Make intelligent agent think
SwapPhaseAI(board);
//Activate or deactivate resource extraction effects
if (particlesOK) VerifyResourceExtraction(board, true);
//By default, tiles and tokens are not highlighted
ClearHighlights(board);
//Scan the whole board
for (int i=0; i < board->tile_i; i++)
{
for (int j=0; j < board->tile_j; j++)
{
//If this is not an AI player's turn...
if ((turnPlayer == 1 && !player1.isAI) || (turnPlayer == 2 && !player2.isAI)
|| (turnPlayer == 3 && !player3.isAI) || (turnPlayer == 4 && !player4.isAI))
{
//No token or tile is selected by default
tileSelected = false;
tokenSelected = false;
//If a token has been selected...
if (selectedToken != NULL)
{
//...But its animation hasn't begun...
if (!selectedToken->getBehavior(0)->getBool("isAnimStarted"))
{
//...Reset its move direction.
selectedToken->getBehavior(0)->setInt("moveDir", -1);
}
}
//Highlight tiles and tokens according to phase
//-------------------------------------------
//-------- RESSURRECTION PLACEMENT ----------
//-------------------------------------------
if (phase == RESSURRECTION_PLACEMENT)
{
if (!tokenRessurrected) ManageRessurrection(board,i,j);
else if (tokenRessurrected)
{
if (Wait(0.3f)) tokenRessurrected = false;
}
}
//-------------------------------------------
//------------ PLAY SELECTION ---------------
//-------------------------------------------
else if (phase == PLAY_SELECTION)
{
ManageTokenSelection(board,i,j);
if (selectedToken != NULL)
{
ManageMoveSelection(board,i,j);
}
}
//-------------------------------------------
//---------- INPUT VERIFICATION -------------
//-------------------------------------------
//Check for mouse position over a tile which can be interacted with
if (board->board[i][j]->isMouseHover && board->board[i][j]->isHighlighted)
{
tileSelected = true;
}
//Check for mouse position over a token which can be interacted with
if (board->board[i][j]->token != NULL)
{
if (board->board[i][j]->token->isMouseHover && board->board[i][j]->token->isHighlighted)
{
tokenSelected = true;
}
}
//If mouse button is pressed, and it isn't hovering a match button...
if (input->getMouseState().leftButtonDown && !signalButtonHover)
{
//If mouse cursor is above a highlighted tile or token...
if (tileSelected || tokenSelected)
{
//Mouse has been clicked atop a highlighted object
mouseClickedOnHighlight = true;
//Select another token or advance phase
SwapPhaseOnClick(board, i, j);
}
}
}
}
}
//Enable board interaction again
signalButtonHover = false;
//-------------------------------------------
//-------- RACE ABILITY MANAGEMENT ----------
//-------------------------------------------
//By default, there's no ability activation special effect
if (particlesOK) StopParticles(ABILITY);
//Activate or deactivate abilities when necessary
for (t = tokensTeam1->begin(); t != tokensTeam1->end(); t++) ManageRaceAbilities((*t), board);
for (t = tokensTeam2->begin(); t != tokensTeam2->end(); t++) ManageRaceAbilities((*t), board);
for (t = tokensTeam3->begin(); t != tokensTeam3->end(); t++) ManageRaceAbilities((*t), board);
for (t = tokensTeam4->begin(); t != tokensTeam4->end(); t++) ManageRaceAbilities((*t), board);
//-------------------------------------------
//--------- ANIMATION EXECUTION -------------
//-------------------------------------------
//Set animation speed
animSpeed = 620.0f * deltaTime;
if (phase == ANIMATION_EXECUTION)
{
//Reset some animation control variables
animSimpleMove = animPushMove = animTrapDeath = false;
//Iterate through all players' token lists and animate them
for (t = tokensTeam1->begin(); t != tokensTeam1->end(); t++) AnimateToken((*t), board, animSpeed);
for (t = tokensTeam2->begin(); t != tokensTeam2->end(); t++) AnimateToken((*t), board, animSpeed);
for (t = tokensTeam3->begin(); t != tokensTeam3->end(); t++) AnimateToken((*t), board, animSpeed);
for (t = tokensTeam4->begin(); t != tokensTeam4->end(); t++) AnimateToken((*t), board, animSpeed);
}
//-------------------------------------------
//--- VERIFICATION FOR TOKEN DESELECTION ----
//-------------------------------------------
//If this is not an AI player's turn...
if ((turnPlayer == 1 && !player1.isAI) || (turnPlayer == 2 && !player2.isAI)
|| (turnPlayer == 3 && !player3.isAI) || (turnPlayer == 4 && !player4.isAI))
{
if (input->getMouseState().leftButtonDown)
{
//If mouse has been clicked somewhere without interaction...
if (!mouseClickedOnHighlight)
{
//If a token has already been selected...
if (phase == PLAY_SELECTION && selectedToken != NULL)
{
//If neither selected token nor its tile are below mouse
if (!selectedToken->isMouseHover && !selectedToken->parentNode->isMouseHover)
{
//Unselect token!
selectedToken->getBehavior(0)->setBool("isSelected", false);
selectedToken = NULL;
}
}
}
}
}
};
void PrimePlayState::Update(IrrBoard* board, int turn)
{
Wait(); //Update "Wait" mini-engine
//Update match
SetTurnPlayer(turn);
UpdateTurnPhases(board);
}; | true |