Browse Source

Hallo

main
pascalhain 11 months ago
parent
commit
ec38213982

+ 87
- 0
src/Bot/Bot.java View File

package Bot;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.InetSocketAddress;

public abstract class Bot {

// Ein Bot ist ein Programm, das sich mit einem Server verbindet und
// mit diesem kommuniziert. Der Server sendet dem Bot eine Zeichenkette,
// die das Spielfeld repräsentiert. Der Bot sendet dem Server ein Zeichen,
// das die nächste Bewegung des Bots repräsentiert.


private final String host; // Hostname oder IP-Adresse des Servers
private final int port; // Port des Servers

protected Bot(String[] args) {
host = args.length > 0 ? args[0] : "localhost";
port = args.length > 1 ? Integer.parseInt(args[1]) : 63187;
}

// Diese Methode stellt die Verbindung zum Server her und startet die
// Kommunikation mit dem Server. Die Methode wird von der main-Methode
// aufgerufen.
protected void run() {
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(host, port));
OutputStream out = socket.getOutputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
View view = new View();
while (true) {
view.read(in);
view.print();
try {
char ch = nextMove(view);
out.write(ch);
}
catch (Exception e) { break; }
}
socket.close();
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}

// Diese Methode ermittelt den nächsten Zug des Bots. Sie wird von der
// run-Methode aufgerufen, nachdem der Server das Spielfeld gesendet hat.
// Subklassen müssen diese Methode implementieren.
abstract protected char nextMove(View view) throws Exception;

// Diese Klasse repräsentiert das Spielfeld. Sie wird von der run-Methode
// verwendet, um das Spielfeld zu lesen und auszugeben.
// Subklassen können diese Klasse verwenden, um das Spielfeld zu analysieren.
public static class View {
protected String data;
protected int width;

// Diese Methode liest das Spielfeld vom Server.
private void read(BufferedReader in) throws IOException {
StringBuilder sb = new StringBuilder();
data = in.readLine();
if (data == null) {
return;
}
sb.append(data);
width = data.length();
for (int i = 1; i < width; ++i) {
sb.append(in.readLine());
}
data = sb.toString();
}

// Diese Methode gibt das Spielfeld aus.
protected void print() {
if (data == null || width < 1) {
return;
}
for (int i = 0, len = data.length(); i < len; i += width) {
System.out.println(data.substring(i, i + width));
}
}
}
}

+ 90
- 0
src/Bot/EscapeBot.java View File

package Bot;
import java.io.IOException;

public class EscapeBot extends Bot {

private boolean rocketFound = false;
private int counter=0;


public EscapeBot(String[] args) {
super(args);
}

@Override
protected char nextMove(View view) throws IOException {
counter++;
System.out.println(counter);
if (view.data.contains("o")) {
System.out.println("rocket found");

return moveToRocket(view);
}else {
return findRocket();
}

}


// Wenn die Rakete nicht gefunden wurde oder bereits gefunden wurde,
// mache einen zufälligen Schritt.



private char findRocket(){
if(counter==1||counter==6||counter==11||counter==21||counter==31||counter==46||counter==61||counter==81||counter==101||counter==126||counter==151||counter==181||counter==211||counter==246||counter==271){
System.out.println("ich dreh mich");

return '>';

}
System.out.println("ich geh gerade aus");
return '^';
}
private char moveToRocket(View view) {
int zeroIndex = view.data.indexOf("o");

// Berechne die x- und y-Koordinaten der "0" im Sichtfeld
int zeroX = zeroIndex % view.width;
int zeroY = zeroIndex / view.width;

// Berechne die x- und y-Koordinaten der aktuellen Position des Bots
int botX = view.width / 2;
int botY = view.width / 2;
System.out.println(zeroX);
System.out.println(zeroY);
System.out.println(botX);
System.out.println(botY);

if(zeroY<botY){
System.out.println("ich suche das ziehl");
return '^';

}else if(zeroY>botY){
return'v';
}else if(zeroY==botY){
if(zeroX<botX){
System.out.println("suche:Ich dreh mich nach links ");
return '<';
}else {
System.out.println("ziel:ich dreh mich nach rechts");
return '>';
}
}else
return 'q';


}




public static void main(String[] args) {
EscapeBot escapeBot = new EscapeBot(args);
escapeBot.run();
}
}





+ 46
- 0
src/Bot/ManualBot.java View File

package Bot;

import java.io.IOException;
import java.util.Scanner;


public class ManualBot extends Bot {

public ManualBot(String[] args) {
super(args);
}

@Override
protected char nextMove(View view) throws IOException {
System.out.println(" (w: Forward, s: Backward, a: Left, d: Right, q: Quit): ");
Scanner scan= new Scanner(System.in);
//BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// String input = reader.readLine().trim();

String command = scan.nextLine();

switch (command) {
case "w":
return '^';
case "s":
return 'v';
case "a":
return '<';
case "d":
return '>';
case "q":
System.out.println("Connection terminated by user.");
throw new IOException("Connection terminated by user.");
default:
System.out.println("Invalid command. Try again.");

}
return 'q';
}


public static void main(String[] args) {
ManualBot manualBot = new ManualBot(args);
manualBot.run();
}
}

+ 46
- 0
src/Bot/Rumblebot.java View File

package Bot;

import java.io.IOException;
import java.util.Scanner;


public class Rumblebot extends Bot {

public Rumblebot(String[] args) {
super(args);
}

@Override
protected char nextMove(View view) throws IOException {
System.out.println(" (w: Forward, s: Backward, a: Left, d: Right, q: Quit): ");
Scanner scan= new Scanner(System.in);
//BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// String input = reader.readLine().trim();

String command = scan.nextLine();

switch (command) {
case "w":
return '^';
case "s":
return 'v';
case "a":
return '<';
case "d":
return '>';
case "q":
System.out.println("Connection terminated by user.");
throw new IOException("Connection terminated by user.");
default:
System.out.println("Invalid command. Try again.");

}
return 'q';
}


public static void main(String[] args) {
Rumblebot rumblebot = new Rumblebot(args);
rumblebot.run();
}
}

+ 143
- 0
src/Bot/SnakeBot.java View File

package Bot;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;


public class SnakeBot extends Bot {

public SnakeBot(String[] args) {
super(args);
}

int counter=0;

@Override
protected char nextMove(View view) throws IOException {
int wagenIndex = view.data.indexOf("*");

// Berechne die x- und y-Koordinaten der "0" im Sichtfeld
int wagenX = wagenIndex % view.width;
int wagenY = wagenIndex / view.width;
//Berechen die x- und y-Koordinate der @ im Sichtfeld


// Berechne die x- und y-Koordinaten der aktuellen Position des Bots
int botX = view.width / 2;
int botY = view.width / 2;

System.out.println("wagen"+wagenX+" ,"+wagenY);
System.out.println("bot"+botX+", "+botY);
if((wagenY+1)==botY){
System.out.println("ich dreh mich ");
return '>';
}else {
return search(view);
}

}

private char search(View view){


if(view.data.contains("@")){
return moveToRocket(view);
}
else {
System.out.println("ich laufe");
counter++;
if(counter>40){
counter=0;
return '>';
}
return '^';
}
}


private char moveToRocket(View view) {

int wagenIndex = view.data.indexOf("*");

// Berechne die x- und y-Koordinaten der "0" im Sichtfeld
int wagenX = wagenIndex % view.width;
int wagenY = wagenIndex / view.width;


int botX = view.width / 2;
int botY = view.width / 2;

// Finde alle '@'-Symbole im Sichtfeld
List<Integer> targetIndices = new ArrayList<>();
for (int i = 0; i < view.data.length(); i++) {
if (view.data.charAt(i) == '@') {
targetIndices.add(i);
}
}

if (targetIndices.isEmpty()) {
// Keine Ziele vorhanden, laufe weiter
System.out.println("Ich laufe weiter");
return '^';
}

// Finde das am nächsten liegende Ziel
int nearestTargetIndex = findNearestTarget(botX, botY, targetIndices, view.width);

// Berechne die x- und y-Koordinaten des nächsten Ziels
int targetX = nearestTargetIndex % view.width;
int targetY = nearestTargetIndex / view.width;

// Bewege dich in Richtung des nächsten Ziels
if (targetY < botY) {
System.out.println("Ich bewege mich nach oben");
return '^';
} else if (targetY > botY) {
if((wagenY+1)==botY){
System.out.println("ich dreh mich ");
return '>';
}else {


System.out.println("Ich bewege mich nach unten");
return 'v';}
} else {
if (targetX < botX) {
System.out.println("Ich drehe mich nach links");
return '<';
} else if (targetX > botX) {
System.out.println("Ich drehe mich nach rechts");
return '>';
}
}

// Default-Rückgabewert, sollte nicht erreicht werden
return 'q';
}

private int findNearestTarget(int botX, int botY, List<Integer> targetIndices, int width) {
int nearestTargetIndex = -1;
int minDistance = Integer.MAX_VALUE;

for (int targetIndex : targetIndices) {
int targetX = targetIndex % width;
int targetY = targetIndex / width;

int distance = Math.abs(targetX - botX) + Math.abs(targetY - botY);

if (distance < minDistance) {
minDistance = distance;
nearestTargetIndex = targetIndex;
}
}

return nearestTargetIndex;
}

public static void main(String[] args) {
SnakeBot snakebot= new SnakeBot(args);
snakebot.run();
}
}

+ 8
- 0
src/HelloWorld/ErrorWriter.java View File

package HelloWorld;

public class ErrorWriter implements IHelloWorldWriter {
@Override
public void writeHelloWorld(){
System.err.println("Hello World");
}
}

+ 24
- 0
src/HelloWorld/Executor.java View File

package HelloWorld;

public class Executor{



public static void main(String[] args) {

printwriteHelloWorld(new OutWriter(), new ErrorWriter(), true);
printwriteHelloWorld(new OutWriter(), new ErrorWriter(), false);
}

public static void printwriteHelloWorld(IHelloWorldWriter writer1, IHelloWorldWriter writer2, boolean second) {


if(second){
writer2.writeHelloWorld();
}else {
writer1.writeHelloWorld();
}


}
}

+ 9
- 0
src/HelloWorld/IHelloWorldWriter.java View File

package HelloWorld;


public interface IHelloWorldWriter {

void writeHelloWorld();
}



+ 9
- 0
src/HelloWorld/OutWriter.java View File

package HelloWorld;

public class OutWriter implements IHelloWorldWriter {
@Override
public void writeHelloWorld(){
System.out.println("Hello Wolrd");
}

}

+ 1
- 1
src/Praktikum1/Teilerdurch5.java View File

package Praktikum1;
package praktikum1;


public class Teilerdurch5 { public class Teilerdurch5 {



+ 1
- 2
src/Praktikum1/Zahlenfilter.java View File

package Praktikum1;
package praktikum1;


import java.util.Scanner;


public class Zahlenfilter { public class Zahlenfilter {
public static void main(String[] args) { public static void main(String[] args) {

+ 0
- 0
src/Praktikum4/BetterPhilospher.java View File


+ 45
- 0
src/Praktikum4/Fork.java View File

package Praktikum4;

public class Fork {

private boolean inUse=false;
private final int id;

public Fork(int id){
this.id=id;
}

public int getId(){
return id;
}


public boolean take(){
try {
//kurz warten
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

synchronized (this) {
if (!inUse) {
inUse=true;
return true;
} else {
//System.out.println("Keine Gabel frei");
return false;
}
}
}

public void put(){
synchronized (this) {
inUse = false;
}
}

public boolean isInUse() {
return inUse;
}
}

+ 59
- 0
src/Praktikum4/Philosopher.java View File

package Praktikum4;

import java.util.concurrent.Semaphore;

class Philosopher implements Runnable{

protected int id;
protected final Fork left;
protected final Fork right;

public Philosopher(int id,Fork left,Fork rigth){
this.id=id;
this.left=left;
this.right=rigth;
}
private void tryToGetFork(Fork fork, String forkType) {

System.out.println("Philosopher " + id + " is trying to get " + forkType + " fork " + fork.getId());
while (!fork.take()) {
Thread.yield(); // Busy wait, um die CPU zu entlasten
}
System.out.println("Philosopher " + id + " got " + forkType + " fork " + fork.getId());
}

@Override
public void run() {
try {
Fork firstFork;
Fork secondFork;

if (left.getId() < right.getId()) {
firstFork = left;
secondFork = right;
} else {
firstFork = right;
secondFork = left;
}


tryToGetFork(firstFork, "first");


tryToGetFork(secondFork, "second");
System.out.println("Philosopher " + id + " is eating");


Thread.sleep(2000);


left.put();
right.put();


System.out.println("Philosopher " + id + " finished eating");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

+ 58
- 0
src/Praktikum4/SorterClient.java View File

package Praktikum4;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class SorterClient {

public static void main(String[] args) {
SorterClient client = new SorterClient();
client.run();
}

private void run() {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.isEmpty())
break;
line = sort(line);
System.out.println(line);
}
scanner.close();
}

private static final String SERVER_ADDRESS = "localhost";
private static final int SERVER_PORT = 12345;

private String sort(String line)
{

InetSocketAddress adress = new InetSocketAddress(SERVER_ADDRESS, SERVER_PORT);
try ( Socket socket = new Socket()) {
socket.connect(adress);
sendLine(socket, line);
String answer = receiveLine(socket);
return answer;
} catch (IOException e) {
e.printStackTrace();
return "Error: Unable to communicate with the server.";
}
}

public static String receiveLine(Socket socket) throws IOException {
InputStream in = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
return reader.readLine();
}

public static void sendLine(Socket socket, String line) throws IOException {
OutputStream out = socket.getOutputStream();
PrintWriter writer = new PrintWriter(out);
writer.println(line);
writer.flush();
}
}

+ 80
- 0
src/Praktikum4/SorterServer.java View File

package Praktikum4;


import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class SorterServer implements Runnable {
public static void main(String[] args) {
final int port = 12345;
try (ServerSocket socket = new ServerSocket(port)) {
while (true) {
Socket client = socket.accept();
Thread thread = new Thread(new SorterServer(client));
thread.start();
}
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}

private Socket socket;

private SorterServer(Socket socket) {
this.socket = socket;
}

@Override
public void run() {
try {
String msg = receiveLine(this.socket);
String ausgabe=sortAndCount(msg);
sendLine(socket,ausgabe );
}
catch (Exception e) {};
}


public static String receiveLine(Socket socket) throws IOException {
InputStream in = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
return reader.readLine();
}

public static void sendLine(Socket socket, String line) throws IOException {
OutputStream out = socket.getOutputStream();
PrintWriter writer = new PrintWriter(out);
writer.println(line);
writer.flush();
}

public static String sortAndCount(String input) {

Map<Character, Integer> charCountMap = new HashMap<>();


for (char c : input.toCharArray()) {
charCountMap.put(c, charCountMap.getOrDefault(c, 0) + 1);
}


StringBuilder sortedString = new StringBuilder();


for (char c = 'a'; c <= 'z'; c++) {

if (charCountMap.containsKey(c)) {
int count = charCountMap.get(c);
for (int i = 0; i < count; i++) {
sortedString.append(c);
}
}
}

// Rückgabe der sortierten Zeichenkette
return sortedString.toString();
}
}

+ 11
- 0
src/Praktikum4/Table.java View File

package Praktikum4;

public class Table {
public static void main(String[] args) {
Fork[] forks = { new Fork(0), new Fork(1), new Fork(2),
new Fork(3), new Fork(4)}; Philosopher[] philosophers = {
new Philosopher(0, forks[0], forks[1]), new Philosopher(1, forks[1], forks[2]), new Philosopher(2, forks[2], forks[3]), new Philosopher(3, forks[3], forks[4]), new Philosopher(4, forks[4], forks[0])
};
for (Philosopher philosopher : philosophers) { Thread t = new Thread(philosopher); t.start();
} }
}

+ 0
- 2
src/test.java View File

public class test {
}

+ 33
- 0
test/HelloWorld/ExecutorTest.java View File

/*package HelloWorld;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;


class ExecutorTest {

@Test
void printwriteHelloWorld() {


//Mock-Objekte werden erzeugt
IHelloWorldWriter outMock =mock(OutWriter.class);
IHelloWorldWriter errMock =mock(OutWriter.class);

Executor.printwriteHelloWorld(outMock,errMock,true);

verify(outMock,times(1)).writeHelloWorld();
verify(errMock,times(0)).writeHelloWorld();

}
}


//writeHelloWorld wird einmal für outMock aufgerufen und keinmal für errMock, weil second auf false gesetzt wurde

// Mock -Objekte ermöglichen, Verhalten von Abhängigkeiten zu testen. Bei unserem Fall können wir nun die Methode aufrufen ohen das tatsächlich was geprintet wurde

// Bei fehlerhaftem Verhalten würde der Test fehlschlagen -- Die Methode hat also nicht die erwarteten Aufrufe

*/

+ 33
- 0
test/Praktikum4/ForkTest.java View File

package Praktikum4;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

class ForkTest {

@Test
void getId() {
Fork fork = new Fork(1);
assertEquals(1, fork.getId());
}

@Test
void take() {
Fork fork = new Fork(2);
assertTrue(fork.take());// sollte nicht in Gebrauch sein



}


@Test
void put() {
Fork fork = new Fork(3);
fork.put();



}
}

+ 37
- 0
test/praktikum1/TriangleCheckerTest.java View File

package praktikum1;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

class TriangleCheckerTest {

@Test
void checkEquilateralTriangle() {
//Gleichseitig
assertEquals(TriangleChecker.TriangleType.EQUILATERAL,TriangleChecker.checkTriangle(5,5,5));
}
@Test
void checkIsoscelesTriangle(){
//Gleichschenklich
assertEquals(TriangleChecker.TriangleType.ISOSCELES, TriangleChecker.checkTriangle(5,5,3));
assertEquals(TriangleChecker.TriangleType.ISOSCELES, TriangleChecker.checkTriangle(3,5,5));
assertEquals(TriangleChecker.TriangleType.ISOSCELES, TriangleChecker.checkTriangle(5,3,5));
}

@Test
void checkNormalTrianlge(){
assertEquals(TriangleChecker.TriangleType.NORMAL,TriangleChecker.checkTriangle(3,5,7));
}
@Test
void chechNoneTrianlge(){
assertEquals(TriangleChecker.TriangleType.NONE,TriangleChecker.checkTriangle(100,10,1));
assertEquals(TriangleChecker.TriangleType.NONE,TriangleChecker.checkTriangle(10,100,1));
assertEquals(TriangleChecker.TriangleType.NONE,TriangleChecker.checkTriangle(1,10,100));
assertEquals(TriangleChecker.TriangleType.NONE,TriangleChecker.checkTriangle(-2,2,3));
assertEquals(TriangleChecker.TriangleType.NONE,TriangleChecker.checkTriangle(2,-2,3));
assertEquals(TriangleChecker.TriangleType.NONE,TriangleChecker.checkTriangle(2,2,-3));


}
}

+ 32
- 0
test/praktikum1/ZahlenfilterTest.java View File

package praktikum1;

import com.sun.org.apache.xpath.internal.objects.XNumber;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Test;

class ZahlenfilterTest {

@org.junit.jupiter.api.Test
void istdurch5teilbar() {

assertFalse(Zahlenfilter.istdurch5teilbar(12));
assertTrue(Zahlenfilter.istdurch5teilbar(10));

}

@org.junit.jupiter.api.Test
void auf9endet() {
assertTrue(Zahlenfilter.auf9endet(89));
assertFalse(Zahlenfilter.auf9endet(65));
}

@org.junit.jupiter.api.Test
void addiertunddurch3() {
assertTrue(Zahlenfilter.addiertunddurch3(9,6));

}
}

Loading…
Cancel
Save