Bukkit countdown timer starts counting down infinite (2,1,-1,-2 etc) - minecraft

So i got this problem when one - two+ players are online the countdown timer goes in minus like this 4,3,2,1,0 -1,-2,-3 etc.
Does anyone know how i can fix this, been struggling with it for quite a long time now :P
Here is my countdown class:
#Override
public void run() {
if (timeUntilStart == 0) {
if (!Game.canStart()) {
if(Bukkit.getOnlinePlayers().size() <= 2) {
plugin.restartCountdown();
ChatUtilities.broadcast(ChatColor.RED + "Not enough players to start. Countdown will");
ChatUtilities.broadcast(ChatColor.RED + "restart.");
for (Player p : Bukkit.getOnlinePlayers()) p.playSound(p.getLocation(), Sound.ENDERDRAGON_WINGS, 5, 1);
return;
}else{
if(Game.canStart()) {
if(Bukkit.getOnlinePlayers().size() >= 2) {
Game.start();
}
}
}
}
}
boolean broadcast = false;
for (Player p : Bukkit.getOnlinePlayers()) {
p.setLevel(timeUntilStart);
if (timeUntilStart < 11 || timeUntilStart == 120 ||timeUntilStart == 60 || timeUntilStart == 30) {
p.playSound(p.getLocation(), Sound.ORB_PICKUP, 5, 0);
if (timeUntilStart == 1) p.playSound(p.getLocation(), Sound.ORB_PICKUP, 5, 1);
broadcast = true;
}
}
if (broadcast) ChatUtilities.broadcast(String.valueOf(timeUntilStart) + " ยง6Seconds until the game starts!");{
}
{
timeUntilStart -= 1;
}
}
}

The only case in which your method returns and timeUtilStart is not decremented is
timeUntilStart == 0 && !Game.canStart() && Bukkit.getOnlinePlayers().size() <= 2
As defined by the first three if blocks in your code.
This explains why your countdown does not stop when you have 3 or more players around.
I believe this mistake happened because of messy {} blocks and indentation. Take a step back and closely read the code you wrote again and fix brackets as well as indentation.
Good formatting is not a pointless chore, it's an essential tool to help yourself understand what you already wrote.

Have you tried using the bukkit scheduler? People tend to forget that bukkit's API can handle countdowns very well. Just call the scheduler with this
myInteger = Bukkit's.getScheduler.scheduleSyncRepeatingTask(plugin, new runnable(), 0L, 20L)
Put your JavaPlugin extension class in as plugin, use runnable adding unimplemented methods, 0L is ticks before first run, 20L is ticks between each run.
Cancel the countdown like this
Bukkit's.getScheduler.cancelTask(myInteger)

Related

Null pointer Exception at the end of draw processing3

I get a Null Pointer Exception, and the trace tells me it is inside a function that I have. This function runs every frame and does some calculations and stuff. Anyway, the problem is that when I go to debug, stepping through each line, the function runs fine, and the error only comes up at the end of the draw loop.
This error only recently came up, and the changes I made don't have much to do with the function in question so...
The function mentioned in the trace detects if the object touches something, and acts on it.
Also, the trace gives a line number that does not exist, I'm guessing that's because of the Processing compiling.
I am using Processing 4 if that matters.
Here's the trace:
java.lang.NullPointerException
at ants$Ant.sense(ants.java:190)
at ants$Ant.go(ants.java:220)
at ants.draw(ants.java:44)
at processing.core.PApplet.handleDraw(PApplet.java:2201)
at processing.awt.PSurfaceAWT$10.callDraw(PSurfaceAWT.java:1422)
at processing.core.PSurfaceNone$AnimationThread.run(PSurfaceNone.java:354)
Thanks!
Edit:
More info: This is an ant simulator, and it crashes at food pickup. This used to work and broke while adding (seemingly) unrelated stuff. It crashes at food pickup, which is managed by the sense() function. The Food class only has a position and a render function.
Here is some code:
void sense() { // The problematic function
if (!detectFood && !carryFood) {
float closest = viewRadius;
Food selected = null;
for (Food fd : foods){
float foodDist = position.dist(fd.position);
if(foodDist <= viewRadius) {
if(foodDist < closest) {
selected = fd;
closest = foodDist;
}
}
}
if (selected != null){
detectFood = true;
foodFocused = selected;
}
} else {
if(position.dist(foodFocused.position) < 2*r) {
takeFood();
detectFood = false;
}
}
}
void draw() { // draw loop
background(51);
for (Food food : foods) {
food.render();
}
for (Ant ant : ants) {
ant.go();
}
for (int i=0; i < trails.size(); i++) {
Trail trail = trails.get(i);
if (trail.strenght <= 0)
trails.remove(trail);
else
trail.go();
}
}
The problem is not the trail, as it still crashes without it,

Gamemaker - destroy a specific instance without collision event

I've just started using gamemaker studio 2 and I've been scratching my head over this one for a while.
I need to be able to destroy a specific instance of my enemy object without using the collision event. Here is my current code:
In my player object:
if (sprite_index = spr_player_attack_left) {
if (obj_enemy.x > x - 25 && obj_enemy.x < x) {
obj_enemy.hp--;
}
}
//detect right
if (sprite_index = spr_player_attack_right) {
if (obj_enemy.x < x + 25 && obj_enemy.x > x) {
obj_enemy.hp--;
}
}
//detect up
if (sprite_index = spr_player_attack_up) {
if (obj_enemy.y > y - 25 && obj_enemy.y < y) {
obj_enemy.hp--;
}
}
//detect down
if (sprite_index = spr_player_attack_up) {
if (obj_enemy.y < y + 25 && obj_enemy.y > y) {
obj_enemy.hp--;
}
}
And in my enemy object:
if (hp <= 0) {
var attacked = instance_find(obj_enemy, this.id);
instance_destroy(attacked);
}
Currently there is only one instance of the enemy in the room that registers an attack, and when I attack that instance, all instances are destroyed, while I only want one to be destroyed.
Thanks in advance for any help!
The reason this is happening is because you are using the object index, and not an index of a specific instance. When you do:
<object_index>.<object_property> eg. obj_enemy.hp
Two things can happen:
If there is one instance currently active in the game, then that
instance's variable will be referenced.
If there are two or more instances, then GameMaker can't tell which one you want to reference.
The offending code here are the if statements:
if (obj_enemy.x > x - 25 && obj_enemy.x < x) {
obj_enemy.hp--;
}
The way you can rewrite them is:
with (obj_enemy) {
if (x > other.x - 25 && x < other.x) hp--;
}
The same goes for all of the other if statements as well. The with keyword acts as a loop here. You can read it as "go through each instance of obj_enemy and do the code between { ... }". To reference the instance outside the with statement we use other(in this example, other will be the player).
And for the code in the enemy object, you don't have to use instance_find at all. Actually the this.id part is completely invalid, unless you define this as an instance variable before that code runs.
Anyways, the correct version would be:
if (hp <= 0) {
instance_destroy();
}
The instance_destroy function destroys the instance that is currently in scope(in GMS2 or GMS1 Early Access, you can pass it an additional id of the instance you wish to destroy).

How can i change background color in a while loop - processing

I'm new to processing and trying to make a very simple program where i have an arduino that produces a seriel input (according to an analogue read value). The idea is a Processing window will open with a block color shown for 30 seconds. In this time all the readings from the arduino will be summed and averaged - creating an average for that color.
After 30 seconds the colour will change and a new average (for the next color) will start being calculated. This is the code i have started to write (for now focusing on just one 30 second period of green).
I realise there are likely problems with the reading/summing and averaging (i havent researched these yet so i'll put that to one side) - but my main question is why isn't the background green? When i run this program i expect the background to be green for 30 seconds - where as what happens is it is white for 30 seconds then changes to green. Can't figure out why! Thanks for any help!
import processing.serial.*;
Serial myPort;
float gsrAverage;
float greenAverage;
int gsrValue;
int greenTotal = 0;
int greenCount = 1;
int timeSinceStart = 0;
int timeAtStart;
int count=0;
color green = color(118,236,0);
void setup () {
size(900, 450);
// List all the available serial ports
//println(Serial.list());
myPort = new Serial(this, Serial.list()[0], 9600);
}
void draw () {
while (timeSinceStart < 30000) {
background(green);
greenTotal = greenTotal + gsrValue;
greenCount = greenCount + 1;
delay(500);
timeSinceStart = millis()-timeAtStart;
//println(timeSinceStart); for de bugging
}
greenAverage = greenTotal/greenCount;
//println(greenAverage); for de bugging
}
void serialEvent (Serial myPort) {
int inByte=myPort.read();
//0-255
gsrValue=inByte;
}
What I like to do for timers, is use IF statements and use millis() or a constantly updated variable 'm' right inside the condition:
int timeSinceStart;
int m;
void setup(){
timeSinceStart = millis(); // initialize here so it only happens once
}
void draw(){
m = millis(); // constantly update the variable
if(timeSinceStart + 30000 < m){
greenAverage = greenTotal/greenCount; // or whatever is outside while loop
timeSinceStart = millis();
}
//Anything that went inside the while loop can go here, or above the IF
}
This makes it so around every 30 seconds, the background will change once, and you just re-update the timeSinceStart variable in there too. This way, it will only update when you want it to update and not constantly update and break the code.
I tend not to use while loops in processing as they usually cause headaches. Hope my example helps.
May have found a way round this using an IF statement. I perhaps looked over the fact the draw function is itself a loop, so i was able to use a variation of
if (timeSinceStart < 5000) {
background(green);
}
within draw.
When dealing with timed events in Processing you should not use while loops inside the draw() function. The draw() function itself is a while loop which updates the "screen" each frame.
So, what you should do is create a timer and let it do a switch for you inside the draw() function. In your case, if you want to start with a green screen, you do that in the setup() function, and then create a method for altering according to a timer in your draw() function.
This is a suggestion on how you could solve your particular problem. Just change the cycle variable according to your need. In your case it would be 30000.
boolean isGreen = true;
int startTime = 0;
int lastTime = 0;
int cycle = 1000; //the cycle you need
void setup() {
size(200, 200);
background(0, 255, 0); //green
}
void draw() {
startTime = millis();
if (startTime > lastTime + cycle) {
if (isGreen) {
background(255); //white
isGreen = !isGreen;
} else {
background(0, 255, 0); //green
isGreen = !isGreen;
}
lastTime = millis();
}
}

local variables arent working Xna when assigned

Im needing to use local variables but when i use them for a timer (decreases time until conditions are met) it doesnt work
for (int i = 0; i < Weapons.Count; i++)
{
if (Weapons[i].ItemType == 6)
{
if (standard.IsKeyDown(Keys.G))
{
Cannons.Add(new CannonFire(this));
}
}
else if (Weapons[i].ItemType == 7)
{
float Recharge = Weapons[i].Laser.Rate;
Recharge -= (float)gametime.ElapsedGameTime.Seconds;
if (standard.IsKeyDown(Keys.G) && Recharge < 0)
{
laser.Add(new LaserFire(this, new Vector3(Weapons[i].Laser.range, 1, 1) ));
Recharge = Weapons[i].Laser.Rate;
}
}
}
other relevant code is where im getting the rate from
public class LaserItem
{
float Damage;
float Range;
float Last;
float RechargeRate;
public float damage
{
get { return Damage; }
set { Damage = value; }
}
public float Rate
{
get { return RechargeRate; }
set { RechargeRate = value; }
}
public float Life
{
get { return Last; }
set { Last = value; }
}
it works without the timer but i cant have it like that because i dont want 300 lasers to be built every time someone hits the key. as far as i can tell the timer is set to the laser rate every frame so it never reaches 0 (this section it in the update function)
for this piece of code its fine but when i need it in a loop i have to use local variables;
From what I can understand, what you are doing in the code is that you're creating a new local variable with the value set to the recharge rate of the laser every single update, firing it when the time from the last update is longer than the recharge rate - this would occur only on a very slow update.
Taking into account the automatic Update (the main loop one) calling of XNA, what would help you is setting some class variable for the Weapon, e.g. RemainingRecharge and when you fire, set it to the recharge rate and substract the elapsed time every update until it reaches zero or less. The only difference from your code is that the recharge is moved to the class instance and thus preserved between updates.
Recharge isn't a reference or a pointer; it's a copy (as float and double are immutable types). So, assigning a value to Recharge at the end of the if() block does absolutely nothing. (I'd bet that it even gets removed by the compiler).
Try this:
else if (Weapons[i].ItemType == 7)
{
float recharge = Weapons[i].Laser.Rate;
recharge -= (float)gametime.ElapsedGameTime.Seconds;
if (standard.IsKeyDown(Keys.G) && recharge < 0)
{
laser.Add(new LaserFire(this, new Vector3(Weapons[i].Laser.range, 1,1)));
/// changed the the next line:
Weapons[i].Laster.Rate = recharge;
}
}
i figured it out, XNA has a TimeSpan thing you can use its easier to work with and you can tell it if it reaches a number reset and do what you want

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

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;