Actionscript 3: How to make movieclip variables work with variables on stage (Healthbar Help) - variables

I am totally new at this whole programming thing, and I really need help. So basically, I'm trying to make a healthbar that will increase or decrease depending on what button is clicked. I made a healthbar movieclip with 101 frames (I included zero) and put this in the actionscript layer of the movieclip:
var health:Number = 0;
if(health == 0)
{
gotoAndStop("1")
}
if(health == 1)
{
gotoAndStop("2")
}
if(health == 2)
{
gotoAndStop("3")
}
and on and on like so. Basically, on the stage itself, I have a button called fortyfiveup_btn that is commanded to do this:
var health:Number = 0;
fortyfiveup_btn.addEventListener(MouseEvent.CLICK, fortyfiveupClick);
function fortyfiveupClick(event:MouseEvent):void{
health = health+45
}
I quickly realized that both health variables, the one for the button and the one for the healthbar will not interact. How can I make it so if the button is clicked, the health goes to the relevant frame or percentage?
Thanks for any answers, and I appreciate all the help I can get :)

If the answer == yes to my comment you should do this:
You need to give the movieclip an instancename (perhaps lifebar) and from stage you can access the health inside the "lifebar" with lifebar.health.
So you need this inside your stage:
//You can delete the var health:Number = 0;
fortyfiveup_btn.addEventListener(MouseEvent.CLICK, fortyfiveupClick);
function fortyfiveupClick(event:MouseEvent):void{
//You can write this, too: lifebar.health += 45;
lifebar.health = lifebar.health+45;
}
You can even optimize your lifebar script, don't use 101 times the if(health == x) you can use this, too:
gotoAndStop(health + 1);
(I think this is inside an ENTER_FRAME event?)
EDIT:
Some error countermeasures:
//Don't let health decrease below 0
if(health < 0) health = 0;
//And don't above 100
else if(health > 100) health = 100;
gotoAndStop(health + 1);
Use int instead of Number when you don't use decimal numbers and uint when you don't use negative integers (this bugs when the number can drop under 0, so for your health we take int):
health:int = 0;

Related

TListView Caption-Cell of last row doesn't get colored

I have been working with VCL for a couple months now, and could solve all my problems by googling, but this one got me stuck.
I want to color a row in a TListView whenever the subItem at index 7 of that row does not contain a certain text (see code below). It all works well, except that the caption-cell (furthest to the left) of the last row does not get colored. I tried a couple hacks (e.g. enabling and then disbaling the ListView when drawing an item), but I didn't find one that doesn't break other stuff on the form (e.g. timers).
Also, after I click on the cell, it does get colored...
I'm using XE7 (C++Builder) on Windows 7.
All suggestions are appreciated ;)
void __fastcall TBackupManagerForm::OverviewListViewCustomDrawItem(TCustomListView *Sender, TListItem *Item, TRect &Rect, TOwnerDrawState State)
{
if ((*Item->SubItems)[7] != "someText") {
Sender->Canvas->Brush->Color = clRed;
}
else {
Sender->Canvas->Brush->Color = clWindow;
}
TRect r, rt;
r = Item->DisplayRect(drBounds);
Sender->Canvas->FillRect(Rect);
r.Right = r.Left + (*OverviewListView->Columns)[0]->Width;
rt = r;
rt.Left += 5;
rt.Top += 1;
UnicodeString s = Item->Caption;
Sender->Canvas->TextRect(rt, s, TTextFormat()<<tfSingleLine<<tfEndEllipsis);
for (int i = 0; i < Item->SubItems->Count; i++) {
ListView_GetSubItemRect(Sender->Handle, Item->Index, i+1, LVIR_BOUNDS,&rt);
s = (*Item->SubItems)[i];
Sender->Canvas->TextRect(rt, s, TTextFormat()<<tfSingleLine<<tfEndEllipsis);
}
}
EDIT
(Answering comments here because not enough rep :P)
#PaulMcCarthy Yeah, that seemed weird to me too...
#RemyLebeau Thanks for the suggestions, I implemented them.
Also, I managed to get it drawn properly by making an extra call to OverviewListView->Refresh() from outside CustomDrwaItem, but it still bugs me that it didn't work without it (pun somewhat intended).

Adding aging to boids simulation

I am working on expanding this sketch: http://www.openprocessing.org/sketch/11045
Trying to add aging to boids agents using frameCount.
I initialise ArrayList with age inbuilt:
boids = new ArrayList();
for (int i = 0; i < boidNum; i++) {
Agent boid = new Agent(random(width), random(height), 1, round(frameCount + random(300, 400)));
boids.add(boid);
}
Then retrieve it :
Agent(float posX, float posY, int t, int a) {
mass = 5.0;
location = new PVector(posX, posY);
vel = new PVector(random(-5,5), random(-5, 5));
acc = new PVector();
type = t;
wdelta = 0.0;
action = 0;
age = a;
}
I want to use something like this for the living cycle :
if (frameCount != age) {
age = age - 1;
}
if (frameCount == age) {
boids.remove(this);
}
But I'm not sure where in the code I should put it.
Also is this the best way to do it, or am I overcomplicating things?
Update:
I wrote a new method:
void boid(ArrayList boids) {
for (int i = 0; i < boids.size(); i++) {
if (frameCount >= age) {
boids.remove(this);
}
}
}
which is being called from:
void steer(ArrayList boids, ArrayList predators, ArrayList landscape) {
if (type == 1) boid(boids); ...
It sounds like you would want to put that code in the Agent class, after you do the updating and drawing of the Agent- taking a quick look at the code, that's probably the run() function in the Agent class.
But I'm not totally sure why you're comparing each Agent's age with the frameCount. The frameCount variable just tells you how long the sketch has been running. You if statement kills any birds that have the same age as the sketch, which doesn't make any sense.
Instead, you need to have two variables in your Agent class: the age variable that starts at 0 and increments by one each frame, and a maxAge variable that stores the age at which the Agent should be removed.
If you want some friendly advice though, I'd really recommend starting over from scratch with your own code instead of trying to modify an existing one, especially if you aren't really sure how the code works yet. It might seem like you're saving time by using existing code, but if you don't really know how code works yet, you'll definitely save yourself a bunch of headaches by writing it yourself. Up to you though.

game maker random cave generation

I want to make a cave explorer game in game maker 8.0.
I've made a block object and an generator But I'm stuck. Here is my code for the generator
var r;
r = random_range(0, 1);
repeat(room_width/16) {
repeat(room_height/16) {
if (r == 1) {
instance_create(x, y, obj_block)
}
y += 16;
}
x += 16;
}
now i always get a blank frame
You need to use irandom(1) so you get an integer. You also should put it inside the loop so it generates a new value each time.
In the second statement, you are generating a random real value and storing it in r. What you actually require is choosing one of the two values. I recommend that you use the function choose(...) for this. Here goes the corrected statement:
r = choose(0,1); //Choose either 0 or 1 and store it in r
Also, move the above statement to the inner loop. (Because you want to decide whether you want to place a block at the said (x,y) location at every spot, right?)
Also, I recommend that you substitute sprite_width and sprite_height instead of using the value 16 directly, so that any changes you make to the sprite will adjust the resulting layout of the blocks accordingly.
Here is the code with corrections:
var r;
repeat(room_width/sprite_width) {
repeat(room_height/sprite_height) {
r = choose(0, 1);
if (r == 1)
instance_create(x, y, obj_block);
y += sprite_height;
}
x += sprite_width;
}
That should work. I hope that helps!
Looks like you are only creating a instance if r==1. Shouldn't you create a instance every time?
Variable assignment r = random_range(0, 1); is outside the loop. Therefore performed only once before starting the loop.
random_range(0, 1) returns a random real number between 0 and 1 (not integer!). But you have if (r == 1) - the probability of getting 1 is a very small.
as example:
repeat(room_width/16) {
repeat(room_height/16) {
if (irandom(1)) {
instance_create(x, y, obj_block)
}
y += 16;
}
x += 16;
}
Here's a possible, maybe even better solution:
length = room_width/16;
height = room_height/16;
for(xx = 0; xx < length; xx+=1)
{
for(yy = 0; yy < height; yy+=1)
{
if choose(0, 1) = 1 {
instance_create(xx*16, yy*16, obj_block); }
}
}
if you want random caves, you should probably delete random sections of those blocks,
not just single ones.
For bonus points, you could use a seed value for the random cave generation. You can also have a pathway random generation that will have a guaranteed path to the finish with random openings and fake paths that generate randomly from that path. Then you can fill in the extra spaces with other random pieces.
But in regards to your code, you must redefine the random number each time you are placing a block, which is why all of them are the same. It should be called inside of the loops, and should be an integer instead of a decimal value.
Problem is on the first line, you need to put r = something in the for cycle

Looping with iterator vs temp object gives different result graphically (Libgdx/Java)

I've got a particle "engine" whom I've implementing a Pool system to and I've tested two different ways of rendering every Particle in a list. Please note that the Pooling really doesn't have anything with the problem to do. I just followed a tutorial and tried to use the second method when I noticed that they behaved differently.
The first way:
for (int i = 0; i < particleList.size(); i++) {
Iterator<Particle> it = particleList.iterator();
while (it.hasNext()) {
Particle p = it.next();
if (p.isDead()){
it.remove();
}
p.render(batch, delta);
}
}
Which works just fine. My particles are sharp and they move with the correct speed.
The second way:
Particle p;
for (int i = 0; i < particleList.size(); i++) {
p = particleList.get(i);
p.render(batch, delta);
if (p.isDead()) {
particleList.remove(i);
bulletPool.free(p);
}
}
Which makes all my particles blurry and moving really slow!
The render method for my particles look like this:
public void render(SpriteBatch batch, float delta) {
sprite.setX(sprite.getX() + (dx * speed) * delta * Assets.FPS);
sprite.setY(sprite.getY() + (dy * speed) * delta * Assets.FPS);
ttl--;
sprite.setScale(sprite.getScaleX() - 0.002f);
if (ttl <= 0 || sprite.getScaleX() <= 0)
isDead = true;
sprite.draw(batch);
}
Why do the different rendering methods provide different results?
Thanks in advance
You are mutating (removing elements from) a list while iterating over it. This is a classic way to make a mess.
The Iterator must have code to handle the delete case correctly. But your index-based for loop does not. Specifically when you call particleList.remove(i) the i is now "out of sync" with the content of the list. Consider what happens when you remove the element at index 3: 'i' will increment to 4, but the old element 4 got shuffled down into index 3, so it will get skipped.
I assume you're avoiding the Iterator to avoid memory allocations. So, one way to side-step this issue is to reverse the loop (go from particleList.size() down to 0). Alternatively, you can only increment i for non-dead particles.

How to run two loops at the same time?

I have been developing a very simple text game using Objective C and Xcode. It is almost done but I am having a problem, the scanf method stops the loop and asks for user input while I need the computer to be running the rest of the loop, the solution I came up with was running two while loops at the same time, one being the logic loop and another being a loop for user input.
I have been doing my research and it looks like using threads are the way to go, I just have not found a tutorial that will break it down for a n00b in Objective C (I am decent in java, I just have never worked with threads). If anybody could explain them or link me to a very broken down tutorial that would be great. Or if anybody has another idea I am open to anything else.
Necessary Code (The scanf I am having a problem with has asterisks on the line):
while(running != 0)
{
if(gameState == 1)
{
if(timeToGenerateNum == true)
{
while(randNumber < 10000000)
{
randNumber = arc4random() % 100000000;
}
NSLog(#"%i", randNumber);
timeToGenerateNum = false;
}
else
{
while(time <= 2500)
{
NSLog(#"Testing");
time++;
******************scanf("%i", &userNum);************************
if(userNum == randNumber)
{
score += time;
time = 0;
timeToGenerateNum = true;
}
}
NSLog(#"Game Over! Your score was %i!", score);
running = 0;
}
}
else if(gameState == 2)
{
NSLog(#"To play, simply type in the number that appears on the screen.");
NSLog(#"But be careful, you only have a short amount of time before GAME OVER!");
NSLog(#"The quicker you type in the number the more score you get!");
NSLog(#"Are you ready to start, if so type '1' and press enter!");
scanf("%i", &gameState);
}
}
You're going to have to learn a bit about BSD (Unix, Linux) input/output to pull this off: replace your call to scanf with a non-blocking function you write to acquire input from the user's keyboard.
This function should immediately return whatever the user typed, or immediately return with a zero character count if she didn't type anything.
Read up on the select(2) system call, and keep in mind that keyboard input (standard input) is the first file descriptor, file descriptor zero.