cocos2dx : Change Array to Vector - arrays

I need to change Array to Vector as it is being depracted in cocos2dx.
Earlier it was running but after deprecation its giving error.
As I am quite new to cocos2dx I am not able to resolve this issue.
Here is my code:
int BaseScene::generateRandom()
{
//int rn = arc4random()%6+1;
int rn = rand() % 6 + 1;
Array * balls = (Array*)this->getChildren();
Array * ballsTypeLeft = Array::create();
// if(balls->count() <= 7)
{
for (int j=0; j<balls->count(); j++)
{
Node * a = (Node*)balls->objectAtIndex(j);
if(a->getTag() >= Tag_Ball_Start)
{
Ball * currentBall = (Ball*)balls->objectAtIndex(j);
bool alreadyHas = false;
for(int k=0;k<ballsTypeLeft->count();k++)
{
if(strcmp(((String*)ballsTypeLeft->objectAtIndex(k))->getCString(), (String::createWithFormat("%d",currentBall->type))->getCString()) == 0)
{
alreadyHas = true;
}
}
if(alreadyHas)
{
}
else
{
ballsTypeLeft->addObject(String::createWithFormat("%d",currentBall->type));
}
}
}
}
// CCLog("%d",ballsTypeLeft->count());
if(ballsTypeLeft->count() <=2)
{
// int tmp = arc4random()%ballsTypeLeft->count();
int tmp = rand() % ballsTypeLeft->count();
return ((String*)ballsTypeLeft->objectAtIndex(tmp))->intValue();
}
return rn;
}
How can I make this method working?
Please convert this method using Vector.
Thanks

To change cocos2d::Array to cocos2d::Vector, you must first understand it. cocos2d::Vector is implemented to mimick std::vector. std::vector is part of the STL in c++. cocos2d::Vector is built specifically to handle cocos2d::Ref. Whenever you add a Ref type to Vector it automatically retained and then released on cleanup.
Now to change Array to Vector in your code:
Store children this way:
Vector <Node*> balls = this->getChildren();
Access ball at index i this way:
Ball* ball = (Ball*)balls.at (i);
Add elements to vector this way:
balls.pushBack (myNewBall);
EDIT -
From what I understand, you want to get a random ball from the scene/layer. You can perform this by simply returning the Ball object:
Ball* BaseScene::generateRandom()
{
Vector <Node*> nodeList = this->getChildren();
Vector <Ball*> ballList;
for (int i = 0; i<nodeList.size(); i++)
{
if (ball->getTag() >= Tag_Ball_Start)
{
Ball * ball = (Ball*)nodeList.at(i);
ballList.pushBack(ball);
}
}
if (ballList.size() > 0)
{
return ballList[rand() % ballList.size()];
}
return nullptr;
}
If there is no ball it will return NULL which you can check when you call the function. The code you have linked below seems to make use of Arrays outside the function. You need to make the changes to accommodate that. I suggest studying the documentation for Vector.

Related

Combining a set of expressions

I am trying to perform a sequence of operations on a 2D array (where dimensions are equal on both sides), where the sequence of operations is random. For each operation, it is a function which represents a transformation of a point to another point, which is represented as an expression. Is it possible to combine different expressions together without knowing their run time values?
For instance, to transform a point 1000 times, 1000 function calls would need to be done. However, since the same transformation would be applied to all points, is it possible to generalize these 1000 calls into a single call for the sake of this transformation?
The following is a simplified example of what I am trying to achieve.
int MoveRightIndex(int offset, int index)
{
return index + offset;
}
int MoveLeftIndex(int offset, int index)
{
return index - offset;
}
int MultIndex(int mult, int index)
{
return index*mult;
}
int main()
{
int index = 0;
index = MoveRightIndex(5, index); // index + 5
index = MultIndex(3, index); // index * 3
index = MoveLeftIndex(2, index); // index - 2
printf("index is: %i\n", index);
// Is there a way to generalize this "net" operation for the next point without calling the same functions again?
//e.g. I know now for the next index the transformation is (index + 5)*3 -2 -> 3*index + 13
//How can I apply 3*index + 13 to index2 without doing the above 3 function calls?
}
You could write a function to do the composition at compile time:
static inline int composite(int roffset, int mult, int loffset, int index)
{
return MoveLeftIndex(loffset, MultIndex(mult, MoveRightIndex(roffset, index)));
}
and, the compiler may be able to do an astonishingly good job of optimizing that. You'd invoke:
index = composite(5, 3, 2, index);
to get the job done 'all at once'. This gives you no runtime flexibility, though.
An alternative is to define a structure defining operations and an array of the structure that can be initialized (with care) at runtime, along the lines of:
typedef int (*Transformer)(int value, int index);
typedef struct
{
const char *t_name;
Transformer t_func;
int t_value;
} TransformStep;
static TransformStep steps[] =
{
{ "MoveRightIndex", NULL, 5 },
{ "MultIndex", NULL, 3 },
{ "MoveLeftIndex", NULL, 2 },
};
enum { NUM_STEPS = sizeof(steps) / sizeof(steps[0]) };
typedef struct
{
const char *t_name;
Transformer t_func;
} NameToPointerMapping;
/* If the list of mappings gets big, sort the array and use search */
static const NameToPointerMapping mappings[] =
{
{ "MoveLeftIndex", MoveLeftIndex },
{ "MoveRightIndex", MoveRightIndex },
{ "MultIndex", MultIndex },
};
enum { NUM_MAPPINGS = sizeof(mappings) / sizeof(mappings[0]) };
static int MapFunctionNamesToPointers(size_t nsteps, TransformSteps *steps)
{
if (nsteps == 0 || steps == NULL)
return -1;
for (size_t i = 0; i < nsteps; i++)
{
if (steps[i].t_func == NULL)
{
for (size_t j = 0; j < NUM_MAPPINGS; j++)
{
if (strcmp(steps[i].t_name, mappings[j].t_name) == 0)
{
steps[i].t_func = mappings[j].t_func;
break;
}
}
if (steps[i].t_func == NULL)
{
…report error - named transformer not found…
return -1;
}
}
}
return 0;
}
static int ApplyTransform(size_t nsteps, TransformStep *steps, int *pindex)
{
if (nsteps == 0 || steps == NULL)
return -1; // Report error
if (steps[0].t_func == NULL && MapFunctionNamesToPointers(nsteps, steps) != 0)
return -1; // Report error
int index = *pindex;
for (size_t i = 0; i < nsteps; i++)
index = (*steps[i].t_func(steps[i].t_value, index);
*pindex = index;
return 0; // Report success
}
No compiler has been consulted about the accuracy of the conceptual code above.
There's nothing to stop you from creating the array dynamically with the function names and the values read from a file or standard input, and then mapping the names accordingly. The first time an array is used, the function names are mapped to the corresponding function pointers. Thereafter, the code simply cycles through the series of function calls.
There are endless optimizations and refactorings that could be applied, but the basic idea is that function names are mapped to corresponding function pointers, and then the array of transformation steps can be applied to the
data. One change would be to do the mapping outside the ApplyTransform() function; another would be to factor the linear search into another small, separate (inline?) function and use that. The list continues. With care, you could build the list of functions and their pointers dynamically so that you can load shared libraries containing new transformations.
This design forces you to have one 'value' per function call. There are ways to allow multiple values instead, but that's rapidly getting more complex.

Trouble iterating through Array and sorting into conditional to check for each Array item

I want to iterate through each of the declared arrays all_sprites_x_coordinates[], all_sprites_width[], all_sprites_height[] and substitute them into the if statement accordingly (i've shown you as an example below). Basically this function is to make sure the player in my game safely spawns, so it must check if there are no sprites within a 6 pixel distance to the left and right of the car. Each sprite within the Arrays are other sprites that exist in the game. I'm having trouble with syntax and problem solving in general, as I am VERY new to C so succinct explanations would really help me understand. I also think that the if statement should be in the for loop.
bool determineSafeSpawn(sprite_id sprite1, sprite_id sprite2){
int car_x = sprite_x(player_car);
int all_sprites_x_coordinates[] = { sprite_x(rock), sprite_x(zombie), sprite_x(bat), sprite_x(tree), sprite_x(hill), sprite_x(bush), sprite_x(house_one), sprite_x(fuel_station)};
int all_sprites_width[] = { ROCK_WIDTH, ZOMBIE_WIDTH, BAT_WIDTH, TREE_WIDTH, HILL_WIDTH, BUSH_WIDTH, HOUSE_ONE_WIDTH, FUEL_STATION_WIDTH};
int all_sprites_height[] = { ROCK_HEIGHT, ZOMBIE_HEIGHT, BAT_HEIGHT, TREE_HEIGHT, HILL_HEIGHT, BUSH_HEIGHT, HOUSE_ONE_HEIGHT, FUEL_STATION_HEIGHT};
bool flag = false;
for (size_t i = 0; i < sizeof(all_sprites) / sizeof(sprite) && !flag; ++i) {
//flag &&= overlaps(all_sprites[i], your_target_sprite);
// check if any sprite within array is within 6 pixels of car
if ((((car_x < all_sprites_x_coordinates[] + all_sprites_width[] + 6) && (car_x > all_sprites_x_coordinates[] + all_sprites_width[])) || ((car_x + CAR_WIDTH > all_sprites_x_coordinates[] - 6) && (car_x + CAR_WIDTH < all_sprites_x_coordinates[])) && speed == 0)) {
// move left or right and search again
} else {
// it is safe to spawn
return true;
}
}
}

Transform an array to another array by shifting value to adjacent element

I am given 2 arrays, Input and Output Array. The goal is to transform the input array to output array by performing shifting of 1 value in a given step to its adjacent element. Eg: Input array is [0,0,8,0,0] and Output array is [2,0,4,0,2]. Here 1st step would be [0,1,7,0,0] and 2nd step would be [0,1,6,1,0] and so on.
What can be the algorithm to do this efficiently? I was thinking of performing BFS but then we have to do BFS from each element and this can be exponential. Can anyone suggest solution for this problem?
I think you can do this simply by scanning in each direction tracking the cumulative value (in that direction) in the current array and the desired output array and pushing values along ahead of you as necessary:
scan from the left looking for first cell where
cumulative value > cumulative value in desired output
while that holds move 1 from that cell to the next cell to the right
scan from the right looking for first cell where
cumulative value > cumulative value in desired output
while that holds move 1 from that cell to the next cell to the left
For your example the steps would be:
FWD:
[0,0,8,0,0]
[0,0,7,1,0]
[0,0,6,2,0]
[0,0,6,1,1]
[0,0,6,0,2]
REV:
[0,1,5,0,2]
[0,2,4,0,2]
[1,1,4,0,2]
[2,0,4,0,2]
i think BFS could actually work.
notice that n*O(n+m) = O(n^2+nm) and therefore not exponential.
also you could use: Floyd-Warshall algorithm and Johnson’s algorithm, with a weight of 1 for a "flat" graph, or even connect the vertices in a new way by their actual distance and potentially save some iterations.
hope it helped :)
void transform(int[] in, int[] out, int size)
{
int[] state = in.clone();
report(state);
while (true)
{
int minPressure = 0;
int indexOfMinPressure = 0;
int maxPressure = 0;
int indexOfMaxPressure = 0;
int pressureSum = 0;
for (int index = 0; index < size - 1; ++index)
{
int lhsDiff = state[index] - out[index];
int rhsDiff = state[index + 1] - out[index + 1];
int pressure = lhsDiff - rhsDiff;
if (pressure < minPressure)
{
minPressure = pressure;
indexOfMinPressure = index;
}
if (pressure > maxPressure)
{
maxPressure = pressure;
indexOfMaxPressure = index;
}
pressureSum += pressure;
}
if (minPressure == 0 && maxPressure == 0)
{
break;
}
boolean shiftLeft;
if (Math.abs(minPressure) > Math.abs(maxPressure))
{
shiftLeft = true;
}
else if (Math.abs(minPressure) < Math.abs(maxPressure))
{
shiftLeft = false;
}
else
{
shiftLeft = (pressureSum < 0);
}
if (shiftLeft)
{
++state[indexOfMinPressure];
--state[indexOfMinPressure + 1];
}
else
{
--state[indexOfMaxPressure];
++state[indexOfMaxPressure + 1];
}
report(state);
}
}
A simple greedy algorithm will work and do the job in minimum number of steps. The function returns the total numbers of steps required for the task.
int shift(std::vector<int>& a,std::vector<int>& b){
int n = a.size();
int sum1=0,sum2=0;
for (int i = 0; i < n; ++i){
sum1+=a[i];
sum2+=b[i];
}
if (sum1!=sum2)
{
return -1;
}
int operations=0;
int j=0;
for (int i = 0; i < n;)
{
if (a[i]<b[i])
{
while(j<n and a[j]==0){
j++;
}
if(a[j]<b[i]-a[i]){
operations+=(j-i)*a[j];
a[i]+=a[j];
a[j]=0;
}else{
operations+=(j-i)*(b[i]-a[i]);
a[j]-=(b[i]-a[i]);
a[i]=b[i];
}
}else if (a[i]>b[i])
{
a[i+1]+=(a[i]-b[i]);
operations+=(a[i]-b[i]);
a[i]=b[i];
}else{
i++;
}
}
return operations;
}
Here -1 is a special value meaning that given array cannot be converted to desired one.
Time Complexity: O(n).

MQL4 array creating variables

I'm trying to make this function create X number of variables using an array. I know that this is technically wrong because I need a constant as my array's value (currently 'x'), but excluding that, what am I missing? Looked at so many code samples and can't figure it out, but I know it's got to be simple...
void variables()
{
int i;
int bars = 10;
int x = 1;
for (i = 1; i <= bars+1; i++)
{
int variables[bars] = { x };
x++;
if (i >= bars+1)
{
break;
}
}
void variables()
{
int bars = 10;
if(bars >= Bars) bars = Bars - 1;
// to be able to set array size based on variable,
// make a dynamically sized array
double highvalues[];
ArrayResize(highvalues, bars);
for (int i = 0 /*Note: Array index is zero-based, 0 is first*/; i <= bars; i++)
{
highvalues[i] = iHigh(NULL, 0, i);
// or
highvalues[i] = High[i];
}
}
It is hard to tell what do you want to achieve.
If you want to fill an array with a value ArrayFill() fill help you.

Array of text don't fade out until the last one is appended

I want to make a group of array fade out until the last array in this group was appended. for example, I use append to create zoog[0], zoog[1], zoog[2], and I want these three objects not fadeout until zoog[2] is created and wait for a second, the same situation with zoog[3], zoog[4],zoog[5], these three objects don't fadeout until zoog[5] is created. But now what I can do is make each object fadeout as soon as it is created.
Zoog[]zoog = new Zoog[1];
float count=0;
int xpos =0;
int ypos =0;
String message="haha";
int ntextsize = 20;
int nopacity =200;
int thistime = 0;
int thiscount = 0;
//Zoog zoog;
void setup() {
size(400, 400);
xpos = int(random(width/2-200, width/2+40));
ypos = int(random(height/2, height/2-40));
zoog[0] = new Zoog(xpos,ypos,message,nopacity);
}
void draw(){
background(255,255,255);
for(int i=0; i<zoog.length; i++){
// if(millis()-thistime>4000){
// zoog[i].disappear();
// }
zoog[i].jiggle();
zoog[i].display();
}
}
void mousePressed(){
count = count + 1;
// int thiscount = 0;
if(count%3 ==0){
xpos=int(random(30, width-30));
ypos=int(random(10, height-10));
}
else{
ypos = ypos+50;
// thiscount = thiscount +1;
// thistime = millis();
// }
}
nopacity = int(random(100,255));
// text(message, xpos, ypos);
Zoog b = new Zoog(xpos,ypos,message,nopacity);
zoog =(Zoog[]) append(zoog,b);
}
Zoog class
class Zoog {
int x;
int y;
String thatmessage;
int opaci =0;
Zoog(int xpo, int ypo, String thismessage, int opa) {
x = xpo;
y = ypo;
thatmessage = thismessage;
opaci = opa;
}
void jiggle() {
x = x+int(random(-2, 2));
y = y+int(random(-2, 2));
}
void display() {
fill(0, opaci);
text(thatmessage, x, y);
print("x position is "+ x);
print("y position is "+y);
}
void disappear() {
for (int j=0; j<255; j++) {
opaci = opaci -j;
}
}
}
If I understand correctly you want to make 3 zoogs and then start fading those three out until they're gone. If this is correct there are a couple of ways I'd go about doing this.
First, I wouldn't use an array especially if you're dynamically updating the amount inside it. If you want to do that I'd use, arraylists. Here's the javadocs reference. Basically you'd initialize an arraylist of Zoogs and put the zoog.add(new Zoog...) in the mousepressed. The good thing about arraylists is that they have a number of member functions that can help you manipulate them. For instance, you can check the size of the arraylist in your draw function instead of the time. Once you're above 3 start fading the first 3 out until they're dead (using a Zoog member function to say they're dead). You can check that "isDead" member function in your draw loop and remove the correct dead Zoog while in your for loop.
Here's a rough implementation, assuming you created an isDead function in your Zoog class that just returns whether the opacity is greater than 0:
void Draw()
{
for (Zoog zoog : zoogs) //for each statement simplifying the code -
//says for each Zoog in zoogs do
{
zoog.jiggle();
zoog.display();
}
if(zoogs.size() >= 3) {
for(int i = 0; i < 3; i++) {
zoogs.get(i).disappear();
}
}
if (zoogs.get(0).isDead() && zoogs.get(1).isDead() && zoogs.get(2).isDead()) {
zoogs.remove(2);
zoogs.remove(1);
zoogs.remove(0);
}
}
This is by no means a perfect example but it shows how to remove 3 zoogs at a time by lessening their opacity and checking whether they are dead. If you're clicking a million times then it will take a while for each chain of three to die.

Resources