Skip to content

Commit

Permalink
Added tasks
Browse files Browse the repository at this point in the history
  • Loading branch information
svenar-nl committed Sep 28, 2016
1 parent c9055ee commit abcaf1c
Show file tree
Hide file tree
Showing 2 changed files with 118 additions and 0 deletions.
71 changes: 71 additions & 0 deletions Java/src/me/winspeednl/libz/tasks/Task.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package me.winspeednl.libz.tasks;

public class Task {

private String name = "";
private int ticks = 0, interval = 0, executedCount = 0, maxExecutes = 0;
private boolean repeat = false, isAlive = true, isRunning = false;

public Task(String name, int interval, boolean repeat) {
this(name, interval, repeat, false);
}

public Task(String name, int interval, boolean repeat, boolean forceStart) {
this.name = name;
this.interval = interval;
this.repeat = repeat;
this.isRunning = forceStart;
}

public boolean update() {
if (isRunning) {
if (!repeat && executedCount > 0) isAlive = false;
if (maxExecutes != 0 && executedCount > maxExecutes) isAlive = false;
if (interval <= ticks) {
ticks = 0;
executedCount++;
return true;
} else ticks++;
return false;
} else return false;
}

public void start() {
isRunning = true;
}

public void stop() {
isRunning = false;
}

public boolean isAlive() {
return isAlive;
}

public boolean isRunning() {
return isRunning;
}

public String getName() {
return name;
}

public int executedCount() {
return executedCount;
}

public void dieAfterNumExecutes(int count) {
maxExecutes = count;
}

public void setInterval(int interval) {
this.interval = interval;
}

public void reset() {
ticks = 0;
executedCount = 0;
isAlive = true;
isRunning = false;
}
}
47 changes: 47 additions & 0 deletions Java/src/me/winspeednl/libz/tasks/TaskContainer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package me.winspeednl.libz.tasks;

import java.util.ArrayList;

import me.winspeednl.libz.entities.LibZ_Entity;

public class TaskContainer {
private ArrayList<Task> tasks = new ArrayList<Task>();
private LibZ_Entity entity;

public TaskContainer(LibZ_Entity entity) {
this.entity = entity;
}

public void addTask(Task task) {
tasks.add(task);
}

public void update() {
ArrayList<Task> deadTasks = null;

for (Task task : tasks) {
if (task.isAlive()) {
if (task.update())
entity.taskTriggered(task.getName());
}
else {
if (deadTasks == null) deadTasks = new ArrayList<Task>();
deadTasks.add(task);
}
}

if (deadTasks != null)
for (Task deadTask : deadTasks)
tasks.remove(deadTask);
}

public int activeTasks() {
int activeTasks = 0;
for (Task task : tasks) if (task.isAlive() && task.isRunning()) activeTasks++;
return activeTasks;
}

public ArrayList<Task> getTasks() {
return tasks;
}
}

0 comments on commit abcaf1c

Please sign in to comment.