Bukkit countdown message sends message 4 times - bukkit

I just created a countdown method in Java, but i have a problem when the countdowner broadcasts the messages: 60(and down) seconds until the game starts!
The broadcast gets sent *4. Does anyone know any solution to this?
Here is my code:
Main plugin;
public StartCountdown(Main pl) {
plugin = pl;
}
public static int timeUntilStart;
#Override
public void run() {
for(Player p1 : Bukkit.getOnlinePlayers()){
if(timeUntilStart == 0) {
if(!Game.canStart()) {
plugin.restartCountdown();
ChatUtilities.broadcast(ChatColor.RED + "Not enough players to start. Countdown will");
ChatUtilities.broadcast(ChatColor.RED + "restart.");
p1.playSound(p1.getLocation(), Sound.ENDERDRAGON_WINGS, 5, 1);
return;
}
Game.start();
}
for(Player p : Bukkit.getOnlinePlayers()){
p.setLevel(timeUntilStart);
if(timeUntilStart < 11 || 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);
}
ChatUtilities.broadcast(String.valueOf(timeUntilStart)
+ " §6Seconds until the game starts!");
}
}
}
timeUntilStart -= 1;
}
}

You are broadcasting for every player that is online. You need to move any code that you don't want to run for every player outside of the for loop.
#Override
public void run() {
if (timeUntilStart == 0) {
if (!Game.canStart()) {
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;
}
Game.start();
}
boolean broadcast;
for (Player p : Bukkit.getOnlinePlayers()) {
p.setLevel(timeUntilStart);
if (timeUntilStart < 11 || 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;
}

as Tanner Little said above
You are broadcasting for every player that is online. You need to move any code that you don't want to run for every player outside of the for loop.
You need to make sure as well that you are cancelling the task. I would recommend using the inbuilt scheduler. You can access the scheduler in this way
private int countDownTimer
private int countDownTime
public void runCountDown() {
countDownTimer = Bukkit.getScheduler.scheduleSyncDelayedTask(plugin, new runnable() {
public void run {
if (countDownTime <= 0) {
//do your bradcasting here
for (Player ingame : Bukkit.getOnlinePlayers()) {
//Do your player specific stuff here
}
Bukkit.getScheduler.cancelTask(countDownTimer);
}
if (countDownTime % 10 == 0) { //You can pick whaterver times u want this is just for an example
//Do periodic broadcasting
}
countDownTime -= 1;
}
}, 0L, 20L); //This means that it would wait 0 ticks to start the countdown and do the task every 20 ticks ie) 1 second.
}
Hopefully this helps you.

Related

How i make function like void loop and void setup in arduino?

I want make function like void loop or void setup like arduino main function which that function can input another execution code.
unsigned long NOW;
void setup() {
}
void loop() {
void doEvery(2){ //do Every 2 second
//Put Code that Execute every 2 second
}
void doEvery(4){ //do Every 4 second
//Put Code that Execute every 4 second
}
}
How to declare/define function doEvery?
i think that function must contain
if(millis()-NOW>=EVERY){
NOW=millis();
//THE LINE CODE
}
Taking THIS as initial idea:
unsigned long previousMillis2 = 0, previousMillis100 = 0;
void setup() {
}
void loop() {
unsigned long currentMillis = millis();
//doEvery 2
if (currentMillis - previousMillis2 >= 2) {
previousMillis2 = currentMillis; //stores last execution's timestamp
//CODE EVERY 2 millis
}
//doEvery 100
if (currentMillis - previousMillis100 >= 100) {
previousMillis100 = currentMillis; //stores last execution's timestamp
//CODE EVERY 100 millis
}
}
With this, you will use millis() to ask for how many millis passed since initialization of Arduino. Then you store last time you executed your code and compare how many time passed since it.
It's not a dynamic function for defining new intervals but if you only need a pair of it, you can code it easily.
EDIT:
If you need something more dynamic, you should use anonymous functions. SEE THIS or THIS The point here is function as parameter.
I've made an animation library out of this for the WS2812 ledstrip:
https://github.com/laurijssen/ledstripanimator/blob/master/ledanim.c
The timing stuff that jabujavi describes happens in the UpdateFrame function where every animation in the list advances to the next frame after it's configured milliseconds.
class AnimList
{
Animation *first = NULL;
Adafruit_NeoPixel strip;
public:
AnimList(int nleds) : strip(nleds, 9, NEO_GRB + NEO_KHZ800)
{
strip.begin();
}
void UpdateFrame()
{
strip.clear();
Animation **anim = &first;
while (*anim)
{
if (millis() - (*anim)->last >= (*anim)->ms)
{
if (!(*anim)->UpdateFrame(strip))
{
*anim = (*anim)->next;
}
else
{
(*anim)->last = millis();
anim = &(*anim)->next;
}
}
}
}
};
Now you just call AnimList::UpdateFrame as fast as possible inside loop()
void loop() {
list->UpdateFrame();
list->Render();
if (!list->Find(&r1))
{
r1 = Rain (rand() % NUMLEDS, rand() % NUMLEDS, {BRIGHTNESS, 0, 15 }) ;
list->AddFirst(&r1);
}
}
edit
So if you want to execute code every 2 seconds you create a class which inherits from Animation and override Updateframe. Then put ms variable at the time you want to pass between frames.
Of course remove all Adafruit and animation references if you just want a task based lib.
class TaskA : public Task
{
public:
TaskA() { ms = 2000; }
bool UpdateFrame()
{
Serial.println("2 seconds passed");
return true;
}
};
TaskA t;
void setup()
{
list->AddTask(&t);
}
void loop()
{
list->UpdateTasks();
}

Stop arduino loop when a condition is active

I need my code to stop in the loop, i have tried to put in a break but the method sendToGCM() continues. I only want the method to be executed once, the stop while the condition
void loop()
{
// Other code here giving temp a value
if (temp > 22)
{
status = false;
value["status"] = status;
while (temp > 22)
{
sendToGCM(); // Sends push notification
break;
}
}
else
{
status = true;
value["status"] = status;
}
}
So if I understood you correctly, if the temperature goes 22 degrees you want to send a message, but only the first time. If you break the loop, you still enter it if you the loop() function is executed again.
In order to achieve what you want to do, you code will need to look something like this
boolean message_sent;
void loop() {
...
if(temperature > 22 && !message_sent) {
sendToGCM();
message_sent = true;
}
}
If you want to send a message every time the temperature rises over 22 degrees you would need something like this
boolean message_sent;
boolean was_under_22;
void setup() {
...
was_under_22 = function_that_checks_if_temp_is_under_22();
...
}
void loop() {
...
if(temperature > 22 && was_under_22) {
if(!message_sent) {
sendToGCM();
message_sent = true;
was_under_22 = false;
}
} else {
was_under_22 = true;
message_sent = false;
}
}
EDIT: slightly adapted the code in response to Patrick Trentin's comment. The code assumes you only want to capture if the temperature rises above 22 degrees and that if the Arduino starts with over 22 degrees then no message is sent.
Your problem is that you are setting temp, then entering the loop that checks that value. A simple solution would be to update the temp value inside the while loop, to give the application a chance to break out of the while loop.
Example:
void loop()
{
// Other code here giving temp a value
if (temp > 22)
{
status = false;
value["status"] = status;
while (temp > 22)
{
sendToGCM(); // Sends push notification
//Additional code to set the value of temp, allowing the value to
//be greater than 22.
}
}
else
{
status = true;
value["status"] = status;
}
}
Please note that the above example is intended to continuously send the push notification while the temp value is over 22. If that's not the intention, just remove the sendToGCM() from the while loop. You will still only send it if the temp is greater than 22, since you have the if check.

calling if statement and not updating it until it's finished

How can I call an if statement (or any other function) without calling it again, until it's finished executing? I have an update function that calls another function (in another class) but because it executes every update, the user doesn't get the time to actually complete the IF statements (the if statements rely on user input) so therefor it returns nothing or only the first part.
Code (where the update is):
public void Update(){
if(Mouse.isButtonDown(0)){
changeTile();
}
while(Keyboard.next()){
if(Keyboard.getEventKey() == Keyboard.KEY_RIGHT && Keyboard.getEventKeyState()){
moveIndex();
}
if(Keyboard.getEventKey() == Keyboard.KEY_LEFT && Keyboard.getEventKeyState()){
moveIndexBack();
}
}
}
changeTile function:
public void changeTile(){
boolean start = true;
if(start){
while(Mouse.next()){
if(Mouse.getEventButton() == 0 && Mouse.getEventButtonState()){
//system uses tileTypes because player textures are tiletypes itself, so in the end we can let them swim by changing tiletypes
int xCoord = (int) Math.floor(Mouse.getX() / 64);
int yCoord = (int) Math.floor((HEIGHT - Mouse.getY() - 1) / 64);
tileType tile1 = map[xCoord][yCoord].getType();
System.out.println("first tile is set to:" + tile1);
start = false;
}
}
}
if(!start){
while(Mouse.next()){
if(Mouse.getEventButton() == 0 && Mouse.getEventButtonState()){
int xCoord2 = (int) Math.floor(Mouse.getX() / 64);
int yCoord2 = (int) Math.floor((HEIGHT - Mouse.getY() - 1) / 64);
tileType tile2 = map[xCoord2][yCoord2].getType();
System.out.println("second tile is set to:" + tile2);
}
}
}

Pops / clicks when stopping and starting DirectX sound synth in C++ / MFC

I have made a soft synthesizer in Visual Studio 2012 with C++, MFC and DirectX. Despite having added code to rapidly fade out the sound I am experiencing popping / clicking when stopping playback (also when starting).
I copied the DirectX code from this project: http://www.codeproject.com/Articles/7474/Sound-Generator-How-to-create-alien-sounds-using-m
I'm not sure if I'm allowed to cut and paste all the code from the Code Project. Basically I use the Player class from that project as is, the instance of this class is called m_player in my code. The Stop member function in that class calls the Stop function of LPDIRECTSOUNDBUFFER:
void Player::Stop()
{
DWORD status;
if (m_lpDSBuffer == NULL)
return;
HRESULT hres = m_lpDSBuffer->GetStatus(&status);
if (FAILED(hres))
EXCEP(DirectSoundErr::GetErrDesc(hres), "Player::Stop GetStatus");
if ((status & DSBSTATUS_PLAYING) == DSBSTATUS_PLAYING)
{
hres = m_lpDSBuffer->Stop();
if (FAILED(hres))
EXCEP(DirectSoundErr::GetErrDesc(hres), "Player::Stop Stop");
}
}
Here is the notification code (with some supporting code) in my project that fills the sound buffer. Note that the rend function always returns a double between -1 to 1, m_ev_smps = 441, m_n_evs = 3 and m_ev_sz = 882. subInit is called from OnInitDialog:
#define FD_STEP 0.0005
#define SC_NOT_PLYD 0
#define SC_PLYNG 1
#define SC_FD_OUT 2
#define SC_FD_IN 3
#define SC_STPNG 4
#define SC_STPD 5
bool CMainDlg::subInit()
// initialises various variables and the sound player
{
Player *pPlayer;
SOUNDFORMAT format;
std::vector<DWORD> events;
int t, buf_sz;
try
{
pPlayer = new Player();
pPlayer->SetHWnd(m_hWnd);
m_player = pPlayer;
m_player->Init();
format.NbBitsPerSample = 16;
format.NbChannels = 1;
format.SamplingRate = 44100;
m_ev_smps = 441;
m_n_evs = 3;
m_smps = new short[m_ev_smps];
m_smp_scale = (int)pow(2, format.NbBitsPerSample - 1);
m_max_tm = (int)((double)m_ev_smps / (double)(format.SamplingRate * 1000));
m_ev_sz = m_ev_smps * format.NbBitsPerSample/8;
buf_sz = m_ev_sz * m_n_evs;
m_player->CreateSoundBuffer(format, buf_sz, 0);
m_player->SetSoundEventListener(this);
for(t = 0; t < m_n_evs; t++)
events.push_back((int)((t + 1)*m_ev_sz - m_ev_sz * 0.95));
m_player->CreateEventReadNotification(events);
m_status = SC_NOT_PLYD;
}
catch(MATExceptions &e)
{
MessageBox(e.getAllExceptionStr().c_str(), "Error initializing the sound player");
EndDialog(IDCANCEL);
return FALSE;
}
return TRUE;
}
void CMainDlg::Stop()
// stop playing
{
m_player->Stop();
m_status = SC_STPD;
}
void CMainDlg::OnBnClickedStop()
// causes fade out
{
m_status = SC_FD_OUT;
}
void CMainDlg::OnSoundPlayerNotify(int ev_num)
// render some sound samples and check for errors
{
ScopeGuardMutex guard(&m_mutex);
int s, end, begin, elapsed;
if (m_status != SC_STPNG)
{
begin = GetTickCount();
try
{
for(s = 0; s < m_ev_smps; s++)
{
m_smps[s] = (int)(m_synth->rend() * 32768 * m_fade);
if (m_status == SC_FD_IN)
{
m_fade += FD_STEP;
if (m_fade > 1)
{
m_fade = 1;
m_status = SC_PLYNG;
}
}
else if (m_status == SC_FD_OUT)
{
m_fade -= FD_STEP;
if (m_fade < 0)
{
m_fade = 0;
m_status = SC_STPNG;
}
}
}
}
catch(MATExceptions &e)
{
OutputDebugString(e.getAllExceptionStr().c_str());
}
try
{
m_player->Write(((ev_num + 1) % m_n_evs)*m_ev_sz, (unsigned char*)m_smps, m_ev_sz);
}
catch(MATExceptions &e)
{
OutputDebugString(e.getAllExceptionStr().c_str());
}
end = GetTickCount();
elapsed = end - begin;
if(elapsed > m_max_tm)
m_warn_msg.Format(_T("Warning! compute time: %dms"), elapsed);
else
m_warn_msg.Format(_T("compute time: %dms"), elapsed);
}
if (m_status == SC_STPNG)
Stop();
}
It seems like the buffer is not always sounding out when the stop button is clicked. I don't have any specific code for waiting for the sound buffer to finish playing before the DirectX Stop is called. Other than that the sound playback is working just fine, so at least I am initialising the player correctly and notification code is working in that respect.
Try replacing 32768 with 32767. Not by any means sure this is your issue, but it could overflow the positive short int range (assuming your audio is 16-bit) and cause a "pop".
I got rid of the pops / clicks when stopping playback, by filling the buffer with zeros after the fade out. However I still get pops when re-starting playback, despite filling with zeros and then fading back in (it is frustrating).

Arduino can't get my boolean to work

I cant get my boolean to work I don't know what I'm doing wrong with it. Could anyone take a look at the code and give me a hint on what is wrong with it? I have tested different ways to write it but without success. The only time the boolean worked was when I put the code under void loop. But I can't use it there.
#include <RemoteReceiver.h>
boolean statusLed1 = false;
void setup() {
Serial.begin(115200);
// Initialize receiver on interrupt 0 (= digital pin 2), calls the callback "showCode"
// after 3 identical codes have been received in a row. (thus, keep the button pressed
// for a moment)
//
// See the interrupt-parameter of attachInterrupt for possible values (and pins)
// to connect the receiver.
RemoteReceiver::init(0, 3, showCode);
}
void loop() {
}
// Callback function is called only when a valid code is received.
void showCode(unsigned long receivedCode, unsigned int period) {
// Note: interrupts are disabled. You can re-enable them if needed.
// Print the received code.
Serial.print("Code: ");
Serial.print(receivedCode);
Serial.print(", period duration: ");
Serial.print(period);
Serial.println("us.");
if (receivedCode == 353805)
{
statusLed1 = true;
}
if (receivedCode == 352829)
{
statusLed1 = false;
}
if (statusLed1 = true) {
Serial.print("on");
}
if (statusLed1 = false){
Serial.print("off");
}
}
if (statusLed1 = true) {
Oldest gotcha in the book. = is assignment, == is equality comparison.
Also, don't compare against a boolean like this regardless.
if (statusLed1) {
change
if (statusLed1 = true) {
Serial.print("on");
}
if (statusLed1 = false){
Serial.print("off");
}
}
to
if (statusLed1 == true) {
Serial.print("on");
}
if (statusLed1 == false){
Serial.print("off");
}
}
or
if (statusLed1) {
Serial.print("on");
}
if (!statusLed1){
Serial.print("off");
}
}