Merge pull request #50 from TiagoRG/dev-tiagorg

[LSD] pratica06 guide added
[LSD] pratica06 part1 added (with enable and direction selector included)

[LABI] tema04 xml reader added

[POO] aula07 ex3 added (not fully working, check TODO.md for more)
This commit is contained in:
Tiago Garcia 2023-04-04 14:41:05 +01:00 committed by GitHub
commit 78b3c6de13
Signed by untrusted user who does not match committer: TiagoRG
GPG Key ID: DFCD48E3F420DB42
12 changed files with 546 additions and 0 deletions

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8" ?>
<conf>
<interval>1</interval>
<output>
<csv active="true" separator="," />
<xml active="false" />
</output>
<monitor>
<cpu active="true" />
<network active="true" />
<ram active="false" />
</monitor>
</conf>

View File

@ -0,0 +1,7 @@
time,cpu,ram,network
1679769801.7018511,20.0,,38943828
1679769802.702516,28.0,,38946821
1679769803.7031012,7.4,,38948575
1679769804.7034643,11.8,,38949179
1679769805.7041101,8.0,,38951189
1679769806.704759,7.1,,38951668
1 time cpu ram network
2 1679769801.7018511 20.0 38943828
3 1679769802.702516 28.0 38946821
4 1679769803.7031012 7.4 38948575
5 1679769804.7034643 11.8 38949179
6 1679769805.7041101 8.0 38951189
7 1679769806.704759 7.1 38951668

View File

@ -0,0 +1,30 @@
import csv
import time
import psutil
from lxml import etree
def main(args=None):
xml = etree.parse('../datafiles/conf.xml')
root = xml.getroot()
delimiter = root.findall("./output/csv")[0].attrib["separator"]
monitor_cpu = root.findall("./monitor/cpu")[0].attrib["active"]
monitor_ram = root.findall("./monitor/ram")[0].attrib["active"]
monitor_network = root.findall("./monitor/network")[0].attrib["active"]
with open("../datafiles/monitor.csv", "w") as f:
writer = csv.DictWriter(f, delimiter=delimiter, fieldnames=["time", "cpu", "ram", "network"])
writer.writeheader()
while True:
cpu = psutil.cpu_percent() if monitor_cpu == "true" else ""
ram = psutil.virtual_memory().percent if monitor_ram == "true" else ""
network = psutil.net_io_counters().bytes_sent if monitor_network == "true" else ""
writer.writerow({"time": time.time(), "cpu": cpu, "ram": ram, "network": network})
time.sleep(1)
if __name__ == '__main__':
main()

View File

@ -0,0 +1,18 @@
from lxml import etree
def main(args=None):
xml = etree.parse('../datafiles/conf.xml')
root = xml.getroot()
print(root.tag)
print_childs(root)
def print_childs(root):
for child in root:
print(child.tag, child.attrib, child.text)
print_childs(child)
if __name__ == '__main__':
main()

View File

@ -0,0 +1,22 @@
package aula07.ex3;
public class Ball extends MovableObject {
private String color;
public Ball(double initialX, double initialY, String color) {
super(initialX, initialY);
setColor(color);
}
public Ball(String color) {
this(0, 0, color);
}
public String getColor() {
return this.color;
}
public void setColor(String color) {
this.color = color;
}
}

View File

@ -0,0 +1,80 @@
package aula07.ex3;
public class Game {
private final Team team1;
private final Team team2;
private int team1Goals;
private int team2Goals;
private final Ball ball;
private final double gameDuration;
private double timeElapsed;
public Game(Team team1, Team team2, Ball ball, double gameDuration) {
this.team1 = team1;
this.team2 = team2;
this.ball = ball;
this.gameDuration = gameDuration * 60;
this.timeElapsed = 0;
}
public double getGameDuration() {
return this.gameDuration;
}
public double getTimeElapsed() {
return this.timeElapsed;
}
public Team getTeam1() {
return this.team1;
}
public Team getTeam2() {
return this.team2;
}
public void start() {
new Thread(() -> {
while (this.timeElapsed < this.gameDuration) {
this.timeElapsed += 0.1;
if (this.timeElapsed % 60 == 0)
System.out.printf("Tempo: %d minutos", (int) this.timeElapsed / 60);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
public void moveBall(double newX, double newY) {
this.ball.move(newX, newY);
}
public void moveRobot(int robotId, double newX, double newY) {
for (Robot r : this.team1.getRobots())
if (r.getId() == robotId)
r.move(newX, newY);
for (Robot r : this.team2.getRobots())
if (r.getId() == robotId)
r.move(newX, newY);
}
public void addGoal(Team team, int scorerId) {
if (team == this.team1) {
this.team1Goals++;
this.team1.increaseGoalsScored(scorerId);
this.team2.increaseGoalsTaken();
} else {
this.team2Goals++;
this.team2.increaseGoalsScored(scorerId);
this.team1.increaseGoalsTaken();
}
}
@Override
public String toString() {
return this.team1.getName() + " vs " + this.team2.getName() + ": " + this.team1Goals + "-" + this.team2Goals + "\nBola: " + this.ball.getColor();
}
}

View File

@ -0,0 +1,187 @@
package aula07.ex3;
import java.util.Scanner;
public class Main {
public static final Scanner sin = new Scanner(System.in);
public static Team[] teams;
public static Game[] games;
public static void main(String[] args) {
while (true) {
int option = menu();
switch (option) {
case 0 -> {
sin.close();
System.exit(0);
}
case 1 -> createTeam();
case 2 -> listTeams();
case 3 -> listRobots();
case 4 -> createGame();
case 5 -> listGames();
default -> System.out.println("Opção inválida!");
}
}
}
private static void listGames() {
for (Game g : games)
System.out.println(g);
}
private static void createGame() {
if (teams == null || teams.length < 2) {
System.out.println("Não existem equipas suficientes para criar um jogo!");
return;
}
System.out.println("Equipas:");
for (int i = 0; i < teams.length; i++)
System.out.println((i+1) + " - " + teams[i].getName());
System.out.print("Escolha a equipa 1: ");
int team1Id = Integer.parseInt(sin.nextLine());
System.out.print("Escolha a equipa 2: ");
int team2Id = Integer.parseInt(sin.nextLine());
Team team1 = teams[team1Id-1];
Team team2 = teams[team2Id-1];
System.out.println("Bola para o jogo:");
System.out.print("Cor da bola: ");
String color = sin.nextLine();
System.out.print("X inicial: ");
String xString = sin.nextLine();
double ballX = Double.parseDouble(xString.equals("") ? "0" : xString);
System.out.print("Y inicial: ");
String yString = sin.nextLine();
double ballY = Double.parseDouble(yString.equals("") ? "0" : yString);
Ball ball = new Ball(ballX, ballY, color);
System.out.println("Duração do jogo (minutos): ");
String durationString = sin.nextLine();
double duration = Double.parseDouble(durationString.equals("") ? "90" : durationString);
Game game = new Game(team1, team2, ball, duration);
if (games == null)
games = new Game[] { game };
else {
Game[] newGames = new Game[games.length+1];
System.arraycopy(games, 0, newGames, 0, games.length);
newGames[games.length] = game;
games = newGames;
}
game.start();
new Thread(() -> {
while (game.getTimeElapsed() < game.getGameDuration()) {
System.out.println("1 - Mover bola");
System.out.println("2 - Mover robot");
System.out.println("3 - Adicionar golo");
System.out.print("Opção: ");
int option = Integer.parseInt(sin.nextLine());
swit : switch (option) {
case 1 -> {
System.out.print("Novo X: ");
double x = Double.parseDouble(sin.nextLine());
System.out.print("Novo Y: ");
double y = Double.parseDouble(sin.nextLine());
ball.move(x, y);
}
case 2 -> {
System.out.println("Robots:");
for (Robot r : game.getTeam1().getRobots())
System.out.println(r);
for (Robot r : game.getTeam2().getRobots())
System.out.println(r);
System.out.print("Escolha o ID do robot: ");
int robotId = Integer.parseInt(sin.nextLine());
System.out.print("Novo X: ");
double x = Double.parseDouble(sin.nextLine());
System.out.print("Novo Y: ");
double y = Double.parseDouble(sin.nextLine());
game.moveRobot(robotId, x, y);
}
case 3 -> {
System.out.println("Robots:");
System.out.println(game.getTeam1());
System.out.println(game.getTeam2());
System.out.print("Escolha o ID do robot que marcou: ");
int robotId = Integer.parseInt(sin.nextLine());
for (Robot r : game.getTeam1().getRobots())
if (r.getId() == robotId) {
game.addGoal(game.getTeam1(), robotId);
break swit;
}
for (Robot r : game.getTeam2().getRobots())
if (r.getId() == robotId) {
game.addGoal(game.getTeam2(), robotId);
break swit;
}
}
default -> System.out.println("Opção inválida!");
}
}
});
}
private static void listRobots() {
if (teams == null || teams.length == 0) {
System.out.println("Não existem equipas!");
return;
}
for (Team t : teams) {
System.out.println("Equipa " + t.getName());
for (Robot r : t.getRobots())
System.out.println(r);
}
}
private static void listTeams() {
if (teams == null || teams.length == 0) {
System.out.println("Não existem equipas!");
return;
}
for (Team t : teams)
System.out.println(t);
}
private static void createTeam() {
System.out.print("Nome da equipa: ");
String name = sin.nextLine();
System.out.print("Treinador: ");
String coach = sin.nextLine();
System.out.print("Número de robots: ");
int nRobots = Integer.parseInt(sin.nextLine());
Robot[] robots = new Robot[nRobots];
for (int i = 0; i < nRobots; i++) {
System.out.println("Robot " + (i+1));
System.out.print("\n1 - GoalKeeper\n2 - Defender\n3 - Midfielder\n4 - Striker\nPosição: ");
PlayerPosition position = PlayerPosition.getPositionById(Integer.parseInt(sin.nextLine()));
System.out.print("X inicial: ");
String xString = sin.nextLine();
double x = Double.parseDouble(xString.equals("") ? "0" : xString);
System.out.print("Y inicial: ");
String yString = sin.nextLine();
double y = Double.parseDouble(yString.equals("") ? "0" : yString);
robots[i] = new Robot(x, y, position);
}
Team team = new Team(name, coach, robots);
if (teams == null)
teams = new Team[] {team};
else {
Team[] newTeams = new Team[teams.length+1];
System.arraycopy(teams, 0, newTeams, 0, teams.length);
newTeams[teams.length] = team;
teams = newTeams;
}
}
private static int menu() {
System.out.println("1. Criar equipa");
System.out.println("2. Listar equipas");
System.out.println("3. Listar robots");
System.out.println("4. Criar jogo");
System.out.println("5. Listar jogos");
System.out.println("0. Sair");
System.out.print("> ");
return Integer.parseInt(sin.nextLine());
}
}

View File

@ -0,0 +1,31 @@
package aula07.ex3;
public class MovableObject {
protected double x;
protected double y;
protected double distanceTravelled;
protected MovableObject(double initialX, double initialY) {
this.x = initialX;
this.y = initialY;
this.distanceTravelled = 0;
}
protected MovableObject() {
this(0, 0);
}
protected void move(double newX, double newY) {
increaseDistanceTravelled(calculateDistanceTravelled(newX, newY));
this.x = newX;
this.y = newY;
}
protected void increaseDistanceTravelled(double distance) {
this.distanceTravelled += distance;
}
private double calculateDistanceTravelled(double newX, double newY) {
return Math.sqrt(Math.pow((this.x - newX), 2) + Math.pow(this.y - newY, 2));
}
}

View File

@ -0,0 +1,27 @@
package aula07.ex3;
public enum PlayerPosition {
GoalKeeper,
Striker,
Defender,
MidFielder;
public static PlayerPosition getPositionById(int id) {
return switch (id) {
case 1 -> GoalKeeper;
case 2 -> Striker;
case 3 -> Defender;
case 4 -> MidFielder;
default -> null;
};
}
public String toString() {
return switch (this) {
case GoalKeeper -> "GoalKeeper";
case Striker -> "Striker";
case Defender -> "Defender";
case MidFielder -> "MidFielder";
};
}
}

View File

@ -0,0 +1,42 @@
package aula07.ex3;
public class Robot extends MovableObject {
public static int currentID = 0;
private final int id;
private PlayerPosition playerPosition;
private int goalsScored = 0;
public Robot(double initialX, double initialY, PlayerPosition playerPosition) {
super(initialX, initialY);
this.id = ++Robot.currentID;
setPlayerPosition(playerPosition);
}
public Robot(PlayerPosition playerPosition) {
this(0, 0, playerPosition);
}
public int getId() {
return this.id;
}
public PlayerPosition getPlayerPosition() {
return this.playerPosition;
}
public void setPlayerPosition(PlayerPosition playerPosition) {
this.playerPosition = playerPosition;
}
public int getGoalsScored() {
return this.goalsScored;
}
public void increaseGoalsScored() {
this.goalsScored++;
}
@Override
public String toString() {
return String.format("Robot %d (%s) at (%.2f, %.2f) with %.2f travelled distance and %d goals scored",
this.id, this.playerPosition, this.x, this.y, this.distanceTravelled, this.goalsScored);
}
}

View File

@ -0,0 +1,4 @@
# TODO's
- [ ] Fix the timer (not working asynchronically)
- [ ] Properly test the program to find out what actually needs to be done :skull:

View File

@ -0,0 +1,85 @@
package aula07.ex3;
public class Team {
private final String name;
private String coach;
private int goalsScored = 0;
private int goalsTaken = 0;
private Robot[] robots;
public Team(String name, String coach, Robot[] robots) {
this.name = name;
this.coach = coach;
this.setRobots(robots);
}
public String getName() {
return this.name;
}
public String getCoach() {
return this.coach;
}
public void setCoach(String coach) {
this.coach = coach;
}
public int getGoalsScored() {
return this.goalsScored;
}
public void increaseGoalsScored(int scorerId) {
for (Robot r : this.robots)
if (r.getId() == scorerId)
r.increaseGoalsScored();
this.goalsScored++;
}
public int getGoalsTaken() {
return this.goalsTaken;
}
public void increaseGoalsTaken() {
this.goalsTaken++;
}
public Robot[] getRobots() {
return this.robots;
}
public void setRobots(Robot[] robots) {
this.robots = robots;
}
public void addRobot(Robot robot) {
if (this.robots == null)
this.setRobots(new Robot[] {robot});
else {
Robot[] newRobots = new Robot[this.robots.length+1];
System.arraycopy(this.robots, 0, newRobots, 0, this.robots.length);
newRobots[newRobots.length-1] = robot;
this.setRobots(newRobots);
}
}
public void removeRobot(Robot robot) {
Robot[] newRobots = new Robot[this.robots.length-1];
int index = 0;
for (Robot r : this.robots)
if (r.getId() != robot.getId()) {
newRobots[index] = r;
index++;
}
this.setRobots(newRobots);
}
@Override
public String toString() {
StringBuilder robotsString = new StringBuilder();
for (Robot r : this.robots)
robotsString.append("\n\t\t").append(r.toString());
return String.format("Team %s\n\tCoach: %s\n\tGoals Scored: %d\n\tGoals Taken: %d\n\tRobots:%s",
this.name, this.coach, this.goalsScored, this.goalsTaken, robotsString);
}
}