file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
Reading.java
/FileExtraction/Java_unseen/xuhyacinth_MusicPlayer/src/com/xu/music/player/config/Reading.java
package com.xu.music.player.config; import com.xu.music.player.system.Constant; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.HashSet; public class Reading { public HashSet<String> read() { File file = new File(Constant.MUSIC_PLAYER_SONG_LISTS_FULL_PATH); if (file.exists() && file.isFile()) { HashSet<String> songs = new HashSet<String>(); Constant.MUSIC_PLAYER_SONGS_LIST.clear(); InputStreamReader fReader = null; BufferedReader bReader = null; String song; try (FileInputStream stream = new FileInputStream(file)) { fReader = new InputStreamReader(stream, StandardCharsets.UTF_8); bReader = new BufferedReader(fReader); while ((song = bReader.readLine()) != null) { songs.add(song); Constant.MUSIC_PLAYER_SONGS_LIST.add(song); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (fReader != null) { fReader.close(); } if (bReader != null) { bReader.close(); } } catch (Exception e) { e.printStackTrace(); } } return songs; } else { return null; } } public boolean empty(String k) { return k == null || k.length() <= 0; } }
1,685
Java
.java
xuhyacinth/MusicPlayer
9
0
0
2020-12-13T04:23:25Z
2022-03-15T03:58:12Z
SongChoiceWindow.java
/FileExtraction/Java_unseen/xuhyacinth_MusicPlayer/src/com/xu/music/player/config/SongChoiceWindow.java
package com.xu.music.player.config; import com.xu.music.player.system.Constant; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableItem; import java.io.File; import java.util.LinkedList; public class SongChoiceWindow { public static void updateSongList(Table table, LinkedList<String> lists) { table.removeAll(); TableItem tableItem; for (int i = 0, len = lists.size(); i < len; i++) { tableItem = new TableItem(table, SWT.NONE); tableItem.setText(new String[]{(i + 1) + "", lists.get(i).split(Constant.MUSIC_PLAYER_SYSTEM_SPLIT)[1]}); } } public LinkedList<String> openChoiseWindows(Shell shell) { FileDialog dialog = new FileDialog(shell, SWT.OPEN | SWT.MULTI); dialog.setFilterNames(new String[]{"*.mp3", "*.MP3", "*.wav", "*.WAV", "*.flac", "*.FLAC", "*.pcm", "*.PCM"}); dialog.open(); String[] lists = dialog.getFileNames(); String paths; Constant.MUSIC_PLAYER_SONGS_TEMP_LIST.clear(); for (int i = 0, len = lists.length; i < len; i++) { paths = lists[i]; if (paths.toLowerCase().endsWith(".mp3") || paths.toLowerCase().endsWith(".flac") || paths.toLowerCase().endsWith(".wav") || paths.toLowerCase().endsWith(".pcm")) { paths = dialog.getFilterPath() + File.separator + lists[i]; paths = paths + Constant.MUSIC_PLAYER_SYSTEM_SPLIT + haveLyric(paths); Constant.MUSIC_PLAYER_SONGS_TEMP_LIST.add(paths); } } new Writing().write(Constant.MUSIC_PLAYER_SONGS_TEMP_LIST); return Constant.MUSIC_PLAYER_SONGS_TEMP_LIST; } private String haveLyric(String path) { path = path.substring(0, path.lastIndexOf(".")); path += ".lrc"; if (!(new File(path).exists())) { return "N"; } else { return "Y"; } } }
2,044
Java
.java
xuhyacinth/MusicPlayer
9
0
0
2020-12-13T04:23:25Z
2022-03-15T03:58:12Z
Writing.java
/FileExtraction/Java_unseen/xuhyacinth_MusicPlayer/src/com/xu/music/player/config/Writing.java
package com.xu.music.player.config; import com.xu.music.player.system.Constant; import org.jaudiotagger.audio.AudioFile; import org.jaudiotagger.audio.AudioFileIO; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Objects; public class Writing { public static void main(String[] args) { Writing writing = new Writing(); List<String> list = new ArrayList<String>(); list.add("F:\\KuGou\\丸子呦 - 广寒宫.mp3<-->Y"); writing.write(list); for (String l : Constant.MUSIC_PLAYER_SONGS_LIST) { System.out.println(l); } } public boolean write(List<String> lists) { File file = new File(Constant.MUSIC_PLAYER_SONG_LISTS_FULL_PATH); HashSet<String> songs = new HashSet<String>(); if (file.exists()) { songs = new Reading().read(); String content; String[] splits; for (String list : lists) { splits = list.split(Constant.MUSIC_PLAYER_SYSTEM_SPLIT); content = splits[0]; try { content += Constant.MUSIC_PLAYER_SYSTEM_SPLIT + getSongName(splits[0]); content += Constant.MUSIC_PLAYER_SYSTEM_SPLIT + getSongName(splits[0]); content += Constant.MUSIC_PLAYER_SYSTEM_SPLIT + getSongLength(splits[0]); content += Constant.MUSIC_PLAYER_SYSTEM_SPLIT + splits[1]; } catch (Exception e1) { e1.printStackTrace(); } songs.add(content); } } else { try { new File(Constant.MUSIC_PLAYER_SONG_LISTS_PATH).mkdirs(); file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } String content; String[] splits; for (String list : lists) { splits = list.split(Constant.MUSIC_PLAYER_SYSTEM_SPLIT); content = splits[0]; try { content += Constant.MUSIC_PLAYER_SYSTEM_SPLIT + getSongName(splits[0]); content += Constant.MUSIC_PLAYER_SYSTEM_SPLIT + getSongName(splits[0]); content += Constant.MUSIC_PLAYER_SYSTEM_SPLIT + getSongLength(splits[0]); content += Constant.MUSIC_PLAYER_SYSTEM_SPLIT + splits[1]; } catch (Exception e1) { e1.printStackTrace(); } songs.add(content); } } FileWriter fWriter = null; BufferedWriter bWriter; try { fWriter = new FileWriter(new File(Constant.MUSIC_PLAYER_SONG_LISTS_FULL_PATH)); bWriter = new BufferedWriter(fWriter); Constant.MUSIC_PLAYER_SONGS_LIST.clear(); for (String song : songs) { bWriter.write(song); Constant.MUSIC_PLAYER_SONGS_LIST.add(song); bWriter.newLine(); } bWriter.flush(); bWriter.close(); } catch (Exception e) { e.printStackTrace(); return false; } finally { try { if (fWriter != null) { fWriter.close(); } } catch (Exception e) { e.printStackTrace(); } } return true; } private String getSongName(String song) { song = song.replace("/", "\\"); return song.substring(song.lastIndexOf("\\") + 1, song.lastIndexOf(".")); } private int getSongLength(String path) { File file = new File(path); AudioFile mp3 = null; try { mp3 = AudioFileIO.read(file); } catch (Exception e) { e.printStackTrace(); } return Objects.requireNonNull(mp3).getAudioHeader().getTrackLength(); } }
4,086
Java
.java
xuhyacinth/MusicPlayer
9
0
0
2020-12-13T04:23:25Z
2022-03-15T03:58:12Z
Asynchronous.java
/FileExtraction/Java_unseen/xuhyacinth_MusicPlayer/src/com/xu/music/player/download/Asynchronous.java
package com.xu.music.player.download; import com.xu.music.player.system.Constant; import java.io.BufferedInputStream; import java.io.File; import java.io.RandomAccessFile; import java.net.HttpURLConnection; import java.net.URL; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class Asynchronous { private long length = 0; private int index = 1; public static void main(String[] args) throws InterruptedException { new Asynchronous().download(object -> { }, "http://localhost:8080/WEB/a/a.pdf", "kk"); } public void download(DownloadNotify notify, String url) { String name = url.substring(url.lastIndexOf("/") + 1); HttpURLConnection connection; String newname; try { connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("HEAD"); connection.connect(); length = connection.getContentLengthLong(); File file = new File(Constant.MUSIC_PLAYER_DOWNLOAD_PATH + name); while (file.exists()) { newname = name.substring(0, name.lastIndexOf(".")) + "[" + index + "]" + name.substring(name.lastIndexOf(".")); file = new File(Constant.MUSIC_PLAYER_DOWNLOAD_PATH + newname); index++; name = newname; } RandomAccessFile raf = new RandomAccessFile(Constant.MUSIC_PLAYER_DOWNLOAD_PATH + name, "rw"); raf.setLength(length); raf.close(); connection.disconnect(); task(notify, url, Constant.MUSIC_PLAYER_DOWNLOAD_PATH + name, length); } catch (Exception e) { e.printStackTrace(); } } public void download(DownloadNotify notify, String url, String name) { name += url.substring(url.lastIndexOf(".")); String newname; HttpURLConnection connection; try { connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("HEAD"); connection.connect(); length = connection.getContentLengthLong(); File file = new File(Constant.MUSIC_PLAYER_DOWNLOAD_PATH + name); while (file.exists()) { newname = name.substring(0, name.lastIndexOf(".")) + "[" + index + "]" + name.substring(name.lastIndexOf(".")); file = new File(Constant.MUSIC_PLAYER_DOWNLOAD_PATH + newname); index++; name = newname; } RandomAccessFile raf = new RandomAccessFile(Constant.MUSIC_PLAYER_DOWNLOAD_PATH + name, "rw"); raf.setLength(length); raf.close(); connection.disconnect(); task(notify, url, Constant.MUSIC_PLAYER_DOWNLOAD_PATH + name, length); } catch (Exception e) { e.printStackTrace(); } } public void task(DownloadNotify notify, String url, String path, long length) { ThreadPoolExecutor executor = new ThreadPoolExecutor(Constant.MUSIC_PLAYER_DOWNLOAD_CORE_POOL_SIZE, Constant.MUSIC_PLAYER_DOWNLOAD_MAX_POOL_SIZE, 10, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(5), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy()); if (length <= 10 * 1024 * 1024) { executor.execute(new DownLoadTask(notify, url, path, 0, length)); } else { for (long i = 0, len = length / Constant.MUSIC_PLAYER_DOWNLOAD_FILE_SIZE_PER_THREAD; i <= len; i++) { if (i == len && i > 0) { System.out.println("A-->" + length + "\t" + i * Constant.MUSIC_PLAYER_DOWNLOAD_FILE_SIZE_PER_THREAD + "--" + i + "--" + length); executor.execute(new DownLoadTask(notify, url, path, i * Constant.MUSIC_PLAYER_DOWNLOAD_FILE_SIZE_PER_THREAD, length)); } else { System.out.println("B-->" + length + "\t" + i * Constant.MUSIC_PLAYER_DOWNLOAD_FILE_SIZE_PER_THREAD + "--" + i + "--" + ((i + 1) * Constant.MUSIC_PLAYER_DOWNLOAD_FILE_SIZE_PER_THREAD - 1)); executor.execute(new DownLoadTask(notify, url, path, i * Constant.MUSIC_PLAYER_DOWNLOAD_FILE_SIZE_PER_THREAD, (i + 1) * Constant.MUSIC_PLAYER_DOWNLOAD_FILE_SIZE_PER_THREAD - 1)); } } } executor.shutdown(); } } class DownLoadTask implements Runnable { private DownloadNotify notify; private String url; private String path; private long start; private long end; public DownLoadTask(DownloadNotify notify, String url, String path, long start, long end) { this.notify = notify; this.url = url; this.path = path; this.start = start; this.end = end; } @Override public void run() { BufferedInputStream stream = null; RandomAccessFile access = null; HttpURLConnection connection = null; try { access = new RandomAccessFile(path, "rw"); connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Range", "bytes=" + this.start + "-" + this.end); access.seek(this.start); stream = new BufferedInputStream(connection.getInputStream()); byte[] bt = new byte[10 * 1024]; int length; while ((length = stream.read(bt, 0, bt.length)) != -1) { access.write(bt, 0, length); if (notify != null) { synchronized (this) { this.notify.result(length); } } } } catch (Exception e) { e.printStackTrace(); } finally { if (stream != null) { try { stream.close(); } catch (Exception e) { e.printStackTrace(); } } if (access != null) { try { access.close(); } catch (Exception e) { e.printStackTrace(); } } if (connection != null) { connection.disconnect(); } } } }
6,459
Java
.java
xuhyacinth/MusicPlayer
9
0
0
2020-12-13T04:23:25Z
2022-03-15T03:58:12Z
DownloadNotify.java
/FileExtraction/Java_unseen/xuhyacinth_MusicPlayer/src/com/xu/music/player/download/DownloadNotify.java
package com.xu.music.player.download; /** * Java MusicPlayer 歌词线程通知 * * @Author: hyacinth * @ClassName: LyricyNotify * @Description: TODO * @Date: 2020年5月18日22:32:59 * @Copyright: hyacinth */ public interface DownloadNotify { void result(Object object); }
289
Java
.java
xuhyacinth/MusicPlayer
9
0
0
2020-12-13T04:23:25Z
2022-03-15T03:58:12Z
PlayerEntity.java
/FileExtraction/Java_unseen/xuhyacinth_MusicPlayer/src/com/xu/music/player/entity/PlayerEntity.java
package com.xu.music.player.entity; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.ProgressBar; import org.eclipse.swt.widgets.Table; public class PlayerEntity { private static Table table; private static org.eclipse.swt.widgets.Label text; private static ProgressBar bar; private static String song; private static Composite spectrum; public static Composite getSpectrum() { return spectrum; } public static void setSpectrum(Composite spectrum) { PlayerEntity.spectrum = spectrum; } public static Table getTable() { return table; } public static void setTable(Table table) { PlayerEntity.table = table; } public static org.eclipse.swt.widgets.Label getText() { return text; } public static void setText(org.eclipse.swt.widgets.Label text) { PlayerEntity.text = text; } public static ProgressBar getBar() { return bar; } public static void setBar(ProgressBar bar) { PlayerEntity.bar = bar; } public static String getSong() { return song; } public static void setSong(String song) { PlayerEntity.song = song; } }
1,233
Java
.java
xuhyacinth/MusicPlayer
9
0
0
2020-12-13T04:23:25Z
2022-03-15T03:58:12Z
Constant.java
/FileExtraction/Java_unseen/xuhyacinth_MusicPlayer/src/com/xu/music/player/system/Constant.java
package com.xu.music.player.system; import java.awt.*; import java.io.File; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class Constant { /** * 用户文件夹 */ public static final String SYSTEM_USER_HOME = System.getProperties().getProperty("user.home");// 用户文件夹 /** * 用户文件名称 */ public static final String SYSTEM_USER_NAME = System.getProperties().getProperty("user.name");// 用户文件名称 /** * 歌单存放文件名 */ public static final String MUSIC_PLAYER_SONG_LISTS_NAME = "MusicPlayer.song";// 歌单存放文件名 /** * 歌单存放路径 */ public static final String MUSIC_PLAYER_SONG_LISTS_PATH = SYSTEM_USER_HOME + File.separator + ".MusicPlayer" + File.separator;// 歌单存放路径 /** * 歌单存放文件 */ public static final String MUSIC_PLAYER_SONG_LISTS_FULL_PATH = MUSIC_PLAYER_SONG_LISTS_PATH + MUSIC_PLAYER_SONG_LISTS_NAME;// 歌单存放文件 /** * 播放器日志 */ public static final String MUSIC_PLAYER_LOG = "Log.log";// 播放器日志 /** * 分割符 */ public static final String MUSIC_PLAYER_SYSTEM_SPLIT = "<-->";// 分割符 /** * 文件下载路径 */ public static final String MUSIC_PLAYER_DOWNLOAD_PATH = SYSTEM_USER_HOME + File.separator + ".MusicPlayer" + File.separator + "download" + File.separator;// 文件下载路径 /** * 播放器颜色 */ public static List<Color> MUSIC_PLAYER_COLORS = new ArrayList<Color>();//播放器颜色 /** * 播放列表 */ public static LinkedList<String> MUSIC_PLAYER_SONGS_LIST = new LinkedList<String>();// 播放列表 /** * 临时播放列表 * * @date 2020年1月10日12:54:08 */ public static LinkedList<String> MUSIC_PLAYER_SONGS_TEMP_LIST = new LinkedList<String>();// 临时播放列表 /** * 歌词 * * @date 2020年1月10日12:54:08 */ public static LinkedList<String> PLAYING_SONG_LYRIC = new LinkedList<String>();// 歌词 /** * 是否有歌词 */ public static volatile boolean PLAYING_SONG_HAVE_LYRIC = false;// 是否有歌词 /** * 是否开启歌词 */ public static volatile boolean MUSIC_PLAYER_SYSTEM_START_LYRIC = true;// 是否开启歌词 /** * 是否开启频谱 */ public static volatile boolean MUSIC_PLAYER_SYSTEM_START_SPECTRUM = true;// 是否开启频谱 /** * 正在播放歌曲索引 */ public static int PLAYING_SONG_INDEX = 0;// 正在播放歌曲索引 /** * 正在播放歌曲播放时长 */ public static int PLAYING_SONG_LENGTH = 0;// 正在播放歌曲播放时长 /** * 正在播放歌曲 */ public static String PLAYING_SONG_NAME = "";// 正在播放歌曲 /** * 是否正在播放 */ public static boolean MUSIC_PLAYER_PLAYING_STATE = true;// 是否正在播放 /** * 频谱 背景颜色 */ public static volatile Color SPECTRUM_BACKGROUND_COLOR = Color.WHITE;// 频谱 背景颜色 /** * 频谱 前景颜色 */ public static volatile Color SPECTRUM_FOREGROUND_COLOR = Color.BLUE;// 频谱 前景颜色 /** * 频谱 整个频谱的宽度 */ public static volatile int SPECTRUM_TOTAL_WIDTH = 0;// 频谱 整个频谱的宽度 /** * 频谱 整个频谱的高度 */ public static volatile int SPECTRUM_TOTAL_HEIGHT = 0;// 频谱 整个频谱的高度 /** * 频谱 显示的频谱的数量 */ public static volatile int SPECTRUM_TOTAL_NUMBER = 0;// 频谱 显示的频谱的数量 /** * 频谱 存储大小 */ public static volatile int SPECTRUM_SAVE_INIT_SIZE = 50;// 频谱 存储大小 /** * 频谱 样式 0 条形 1方块 */ public static volatile int SPECTRUM_STYLE = 0;// 频谱 样式 0 条形 1方块 /** * 频谱 FFT */ public static volatile boolean SPECTRUM_REAL_FFT = false;// 频谱 FFT /** * 频谱 刷新时间间隔 */ public static volatile long SPECTRUM_REFLASH_TIME = 100;// 频谱 刷新时间间隔 /** * 频谱 宽度 */ public static volatile int SPECTRUM_SPLIT_WIDTH = 5;// 频谱 宽度 /** * 文件下载 核心池大小 */ public static volatile int MUSIC_PLAYER_DOWNLOAD_CORE_POOL_SIZE = 10;// 文件下载 核心池大小 /** * 文件下载 最大池 */ public static volatile int MUSIC_PLAYER_DOWNLOAD_MAX_POOL_SIZE = 15;// 文件下载 最大池 /** * 文件下载 每个线程下载10M */ public static volatile long MUSIC_PLAYER_DOWNLOAD_FILE_SIZE_PER_THREAD = 10 * 1024 * 1024;// 文件下载 每个线程下载10M }
4,853
Java
.java
xuhyacinth/MusicPlayer
9
0
0
2020-12-13T04:23:25Z
2022-03-15T03:58:12Z
ControllerServer.java
/FileExtraction/Java_unseen/xuhyacinth_MusicPlayer/src/com/xu/music/player/modle/ControllerServer.java
package com.xu.music.player.modle; import com.xu.music.player.entity.PlayerEntity; /** * Java MusocPlayer 被观察者 * * @Author: hyacinth * @ClassName: LyricyServer * @Description: TODO * @Date: 2019年12月26日 下午8:03:42 * @Copyright: hyacinth */ public class ControllerServer implements Observed { @Override public void startLyricPlayer(Observer observer, PlayerEntity entity) { observer.start(entity); } @Override public void startSpectrumPlayer(Observer observer, PlayerEntity entity) { observer.start(entity); } @Override public void endLyricPlayer(Observer observer) { observer.end(); } @Override public void endSpectrumPlayer(Observer observer) { observer.end(); } @Override public void stopLyricPlayer(Observer observer) { observer.stop(); } @Override public void stopSpectrumPlayer(Observer observer) { observer.stop(); } }
979
Java
.java
xuhyacinth/MusicPlayer
9
0
0
2020-12-13T04:23:25Z
2022-03-15T03:58:12Z
Observer.java
/FileExtraction/Java_unseen/xuhyacinth_MusicPlayer/src/com/xu/music/player/modle/Observer.java
package com.xu.music.player.modle; import com.xu.music.player.entity.PlayerEntity; /** * Java MusocPlayer 抽象 观察者 接口 * * @Author: hyacinth * @ClassName: Observer * @Description: TODO * @Date: 2019年12月26日 下午8:02:58 * @Copyright: hyacinth */ public interface Observer { void start(PlayerEntity entity); void stop(); void end(); }
378
Java
.java
xuhyacinth/MusicPlayer
9
0
0
2020-12-13T04:23:25Z
2022-03-15T03:58:12Z
Observed.java
/FileExtraction/Java_unseen/xuhyacinth_MusicPlayer/src/com/xu/music/player/modle/Observed.java
package com.xu.music.player.modle; import com.xu.music.player.entity.PlayerEntity; /** * Java MusicPlayer 抽象 被观察者 接口 * * @Author: hyacinth * @ClassName: Observed * @Description: TODO * @Date: 2019年12月26日 下午8:02:38 * @Copyright: hyacinth */ public interface Observed { void startLyricPlayer(Observer observer, PlayerEntity entity); void startSpectrumPlayer(Observer observer, PlayerEntity entity); void endLyricPlayer(Observer observer); void endSpectrumPlayer(Observer observer); void stopLyricPlayer(Observer observer); void stopSpectrumPlayer(Observer observer); }
635
Java
.java
xuhyacinth/MusicPlayer
9
0
0
2020-12-13T04:23:25Z
2022-03-15T03:58:12Z
Controller.java
/FileExtraction/Java_unseen/xuhyacinth_MusicPlayer/src/com/xu/music/player/modle/Controller.java
package com.xu.music.player.modle; import com.xu.music.player.entity.PlayerEntity; import com.xu.music.player.lyric.LyricyNotify; import com.xu.music.player.system.Constant; import com.xu.music.player.thread.LyricyThread; import com.xu.music.player.thread.SpectrumThread; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.TableItem; import org.eclipse.wb.swt.SWTResourceManager; /** * Java MusicPlayer 观察者 * * @Author: hyacinth * @ClassName: LyricPlayer * @Description: TODO * @Date: 2019年12月26日 下午8:04:08 * @Copyright: hyacinth */ @SuppressWarnings(value = "all") public class Controller implements Observer { private static LyricyThread lyricy = null;// 歌词 private static SpectrumThread spectrum = null;// 频谱 private int merchant = 0; private int remainder = 0; private String format = ""; @Override public void start(PlayerEntity entity) { if (Constant.PLAYING_SONG_HAVE_LYRIC && Constant.MUSIC_PLAYER_SYSTEM_START_LYRIC) { startLyricPlayer(entity); } if (Constant.MUSIC_PLAYER_SYSTEM_START_SPECTRUM) { startSpectrumPlayer(entity); } } private String format(int time) { merchant = time / 60; remainder = time % 60; if (time < 10) { format = "00:0" + time; } else if (time < 60) { format = "00:" + time; } else { if (merchant < 10 && remainder < 10) { format = "0" + merchant + ":0" + remainder; } else if (merchant < 10 && remainder < 60) { format = "0" + merchant + ":" + remainder; } else if (merchant >= 10 && remainder < 10) { format = merchant + ":0" + remainder; } else if (merchant >= 10 && remainder < 60) { format = merchant + ":0" + remainder; } } return format; } @Override public void end() { if (Constant.PLAYING_SONG_HAVE_LYRIC && Constant.MUSIC_PLAYER_SYSTEM_START_LYRIC) { System.out.println("观察者 结束所有 歌词线程"); endLyricPlayer(); } if (Constant.MUSIC_PLAYER_SYSTEM_START_SPECTRUM) { System.out.println("观察者 结束所有 频谱线程"); endSpectrumPlayer(); } System.gc(); } @Override public void stop() { stopLyricPlayer(); stopSpectrumPlayer(); } public void startLyricPlayer(PlayerEntity entity) { int length = Integer.parseInt(Constant.PLAYING_SONG_NAME.split(Constant.MUSIC_PLAYER_SYSTEM_SPLIT)[3]); PlayerEntity.getBar().setMaximum(length); PlayerEntity.getBar().setSelection(0); if (lyricy != null) { //TODO: } else { lyricy = new LyricyThread(new LyricyNotify() { @Override public void lyric(double lrc, double pro) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { TableItem[] items = PlayerEntity.getTable().getItems(); for (int i = 0, len = items.length; i < len; i++) { if (i == lrc) { items[i].setBackground(SWTResourceManager.getColor(SWT.COLOR_GRAY));//将选中的行的颜色变为蓝色 if (i > 7) { PlayerEntity.getTable().setTopIndex(i - 7); } } else { items[i].setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));//将选中的行的颜色变为蓝色 } } PlayerEntity.getBar().setSelection((int) pro); PlayerEntity.getText().setText(format((int) pro)); } }); } }); lyricy.setDaemon(true); lyricy.start(); } } public void startSpectrumPlayer(PlayerEntity entity) { if (Constant.SPECTRUM_TOTAL_HEIGHT == 0) { Constant.SPECTRUM_TOTAL_HEIGHT = PlayerEntity.getSpectrum().getClientArea().height; Constant.SPECTRUM_TOTAL_WIDTH = PlayerEntity.getSpectrum().getClientArea().width; if (Constant.SPECTRUM_STYLE == 0) { Constant.SPECTRUM_TOTAL_NUMBER = PlayerEntity.getSpectrum().getClientArea().width / 5; Constant.SPECTRUM_SPLIT_WIDTH = 5; } else if (Constant.SPECTRUM_STYLE == 1) { Constant.SPECTRUM_TOTAL_NUMBER = PlayerEntity.getSpectrum().getClientArea().width / 20; Constant.SPECTRUM_SPLIT_WIDTH = 20; } Constant.SPECTRUM_SAVE_INIT_SIZE = Constant.SPECTRUM_TOTAL_NUMBER; } if (spectrum == null) { spectrum = new SpectrumThread(PlayerEntity.getSpectrum()); spectrum.setDaemon(true); spectrum.start(); } } public void endLyricPlayer() { if (lyricy != null) { lyricy.stop(); lyricy = null; } } public void endSpectrumPlayer() { if (spectrum != null) { spectrum.stop(); spectrum = null; } } public void stopLyricPlayer() { if (lyricy != null) { try { lyricy.wait(0); } catch (InterruptedException e) { e.printStackTrace(); } } } public void stopSpectrumPlayer() { if (spectrum != null) { try { spectrum.wait(0); } catch (InterruptedException e) { e.printStackTrace(); } } } }
5,984
Java
.java
xuhyacinth/MusicPlayer
9
0
0
2020-12-13T04:23:25Z
2022-03-15T03:58:12Z
MusicPlayerTray.java
/FileExtraction/Java_unseen/xuhyacinth_MusicPlayer/src/com/xu/music/player/tray/MusicPlayerTray.java
package com.xu.music.player.tray; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.widgets.*; import org.eclipse.wb.swt.SWTResourceManager; /** * Java MusicPlayer 观察者 * * @Author: hyacinth * @ClassName: LyricPlayer * @Description: TODO * @Date: 2020年5月18日22:21:21 * @Copyright: hyacinth */ public class MusicPlayerTray { private Shell shell; private Tray tray; private Menu menu; public MusicPlayerTray(Shell shell, Tray tray) { super(); this.shell = shell; this.tray = tray; } public void tray() { if (tray == null) { MessageDialog.openError(shell, "错误提示", "您的系统不支持托盘图标"); } else { TrayItem item = new TrayItem(tray, SWT.NONE); item.setToolTipText("登录"); item.setImage(SWTResourceManager.getImage(MusicPlayerTray.class, "/com/xu/music/player/image/main.png")); menu = new Menu(shell, SWT.POP_UP); item.addListener(SWT.MenuDetect, arg0 -> menu.setVisible(true)); // 放大 // MenuItem max = new MenuItem(menu, SWT.PUSH); // max.setText("放大"); // max.addSelectionListener(new SelectionAdapter() { // public void widgetSelected(SelectionEvent arg0) { // shell.setVisible(true); // shell.setMaximized(true); // } // }); // 缩小 MenuItem mini = new MenuItem(menu, SWT.PUSH); mini.setText("缩小"); mini.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { shell.setMaximized(true); } }); // 关闭 new MenuItem(menu, SWT.SEPARATOR);//横线 MenuItem close = new MenuItem(menu, SWT.PUSH); close.setText("关闭"); close.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { tray.dispose(); shell.dispose(); System.exit(0); } }); } } }
2,426
Java
.java
xuhyacinth/MusicPlayer
9
0
0
2020-12-13T04:23:25Z
2022-03-15T03:58:12Z
LyricyThread.java
/FileExtraction/Java_unseen/xuhyacinth_MusicPlayer/src/com/xu/music/player/thread/LyricyThread.java
package com.xu.music.player.thread; import com.xu.music.player.lyric.LyricyNotify; import com.xu.music.player.player.XMusic; import com.xu.music.player.system.Constant; /** * Java MusicPlayer 歌词线程 * * @Author: hyacinth * @ClassName: LyricyThread * @Description: TODO * @Date: 2019年12月26日 下午8:00:13 * @Copyright: hyacinth */ public class LyricyThread extends Thread { private LyricyNotify notify; private long time = 0; private int index = 0; private int length = 0; private long merchant = 0; private long remainder = 0; private String format = ""; private boolean add = true; public LyricyThread(LyricyNotify notify) { this.notify = notify; } @Override public void run() { length = Constant.PLAYING_SONG_LYRIC.size(); while (XMusic.isPlaying() && index <= length) { for (int i = 0, len = Constant.PLAYING_SONG_LYRIC.size(); i < len; i++) { String secounds = Constant.PLAYING_SONG_LYRIC.get(i).split(Constant.MUSIC_PLAYER_SYSTEM_SPLIT)[0]; if (secounds.startsWith("0")) { secounds = secounds.substring(0, secounds.lastIndexOf(".")); if (secounds.equalsIgnoreCase(formatTime(time))) { index = i; add = false; } else { if (add) { index++; } } } } this.notify.lyric(index, time); time++; try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } /** * 时间转换 * * @param time * @return * @date 2020年5月18日22:23:14 */ private String formatTime(long time) { merchant = time / 60; remainder = time % 60; if (time < 10) { format = "00:0" + time; } else if (time < 60) { format = "00:" + time; } else { if (merchant < 10 && remainder < 10) { format = "0" + merchant + ":0" + remainder; } else //noinspection ConstantConditions if (merchant < 10 && remainder < 60) { format = "0" + merchant + ":" + remainder; } else //noinspection ConstantConditions if (merchant >= 10 && remainder < 10) { format = merchant + ":0" + remainder; } else //noinspection ConstantConditions,ConstantConditions if (merchant >= 10 && remainder < 60) { format = merchant + ":0" + remainder; } } return format; } }
2,861
Java
.java
xuhyacinth/MusicPlayer
9
0
0
2020-12-13T04:23:25Z
2022-03-15T03:58:12Z
SpectrumThread.java
/FileExtraction/Java_unseen/xuhyacinth_MusicPlayer/src/com/xu/music/player/thread/SpectrumThread.java
package com.xu.music.player.thread; import com.xu.music.player.fft.Complex; import com.xu.music.player.fft.FFT; import com.xu.music.player.player.XMusic; import com.xu.music.player.system.Constant; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; /** * Java MusicPlayer 音频线程 * * @Author: hyacinth * @ClassName: SpectrumThread * @Description: TODO * @Date: 2019年12月26日 下午7:58:50 * @Copyright: hyacinth */ public class SpectrumThread extends Thread { private Composite spectrum;//频谱面板 private int twidth;// 频谱总高读 private int theight;// 频谱总宽度 private int sheight;// 频谱高度 public SpectrumThread(Composite spectrum) { this.spectrum = spectrum; twidth = Constant.SPECTRUM_TOTAL_WIDTH; theight = Constant.SPECTRUM_TOTAL_HEIGHT; } @Override public void run() { while (XMusic.isPlaying()) { Display.getDefault().asyncExec(() -> { twidth = Constant.SPECTRUM_TOTAL_WIDTH; theight = Constant.SPECTRUM_TOTAL_HEIGHT; draw(1, twidth, theight); }); try { Thread.sleep(Constant.SPECTRUM_REFLASH_TIME); } catch (InterruptedException e) { e.printStackTrace(); } } } public void draw(int style, int width, int height) { InputStream inputStream = null; ByteArrayOutputStream stream = null; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = image.createGraphics(); //image = graphics.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT); //graphics.dispose(); //graphics = image.createGraphics(); graphics.setBackground(Constant.SPECTRUM_BACKGROUND_COLOR); graphics.clearRect(0, 0, width, height); graphics.setColor(Constant.SPECTRUM_FOREGROUND_COLOR); graphics.setStroke(new BasicStroke(1f)); if (Constant.SPECTRUM_STYLE == 0) {//直接打印 PCM 或 FFT if (Constant.SPECTRUM_REAL_FFT) {//使用快速傅里叶变换(FFT)解码音频 PCM 默认不使用FFT(Constant.SPECTRUM_REAL_FFT = false) if (XMusic.deque.size() >= Constant.SPECTRUM_SAVE_INIT_SIZE) { Double[] data = list2array(XMusic.deque); for (int i = 0, length = data.length; i < length; i++) { sheight = (int) Math.abs(data[i]); graphics.fillRect(i * Constant.SPECTRUM_SPLIT_WIDTH, height - sheight, Constant.SPECTRUM_SPLIT_WIDTH, sheight); } } } else {//直接打印 PCM if (XMusic.deque.size() >= Constant.SPECTRUM_SAVE_INIT_SIZE) { for (int i = 0, len = XMusic.deque.size(); i < Constant.SPECTRUM_TOTAL_NUMBER; i++) { try { if (i < len) { sheight = (int) Math.abs(Double.parseDouble(XMusic.deque.get(i) + "")); sheight = Math.min(sheight, height); } } catch (Exception e) { sheight = 0; } graphics.fillRect(i * Constant.SPECTRUM_SPLIT_WIDTH, height - sheight, Constant.SPECTRUM_SPLIT_WIDTH, sheight); //graphics.fillRect(i*5, height/2-spectrum_height, 5, -spectrum_height);//双谱 } } } stream = new ByteArrayOutputStream(); try { ImageIO.write(image, "png", stream); } catch (IOException e) { throw new RuntimeException(e.getMessage()); } inputStream = new ByteArrayInputStream(stream.toByteArray()); spectrum.setBackgroundImage(new Image(null, new ImageData(inputStream).scaledTo(width, height))); try { inputStream.close(); } catch (IOException e) { throw new RuntimeException(e.getMessage()); } } else if (Constant.SPECTRUM_STYLE == 1) {//直接打印 PCM int indexs = 0; if (XMusic.deque.size() >= Constant.SPECTRUM_SAVE_INIT_SIZE) { for (int i = 0, len = XMusic.deque.size(); i < Constant.SPECTRUM_TOTAL_NUMBER; i++) { try { if (i < len) { sheight = Math.abs(Integer.parseInt(XMusic.deque.get(i) + "")); sheight = Math.min(sheight, height); } } catch (Exception e) { sheight = 0; } int indexc = 10; for (int j = 0; j < sheight; j = indexc) { graphics.fillRect(indexs, height - indexc, Constant.SPECTRUM_SPLIT_WIDTH, 5); indexc += 7; } indexs += 22; } } stream = new ByteArrayOutputStream(); try { ImageIO.write(image, "png", stream); } catch (IOException e) { throw new RuntimeException(e.getMessage()); } inputStream = new ByteArrayInputStream(stream.toByteArray()); spectrum.setBackgroundImage(new Image(null, new ImageData(inputStream).scaledTo(width, height))); } try { stream.close(); } catch (IOException e) { throw new RuntimeException(e.getMessage()); } try { inputStream.close(); } catch (IOException e) { throw new RuntimeException(e.getMessage()); } graphics.dispose(); } private Double[] list2array(List<Double> lists) { //Double[] c = Stream.of(lists).map(a->a.toString()).collect(Collectors.toList()).stream().map(b->Double.parseDouble(b)).toArray(Double[]::new); Double[] c = new Double[lists.size()]; synchronized (lists) { for (int i = 0; i < lists.size(); i++) { try { c[i] = Double.valueOf((lists.get(i) == null ? "0.0" : lists.get(i).toString())); } catch (Exception e) { c[i] = 0.0; } } } Complex[] x = new Complex[c.length]; for (int i = 0; i < x.length; i++) { try { x[i] = new Complex(c[i], 0); } catch (Exception e) { x[i] = new Complex(0, 0); } } return FFT.array(x); } }
7,138
Java
.java
xuhyacinth/MusicPlayer
9
0
0
2020-12-13T04:23:25Z
2022-03-15T03:58:12Z
FFT.java
/FileExtraction/Java_unseen/xuhyacinth_MusicPlayer/src/com/xu/music/player/fft/FFT.java
package com.xu.music.player.fft; import java.util.stream.Stream; /************************************************************************* * Compilation: javac FFT.java Execution: java FFT N Dependencies: Complex.java * * Compute the FFT and inverse FFT of a length N complex sequence. Bare bones * implementation that runs in O(N log N) time. Our goal is to optimize the * clarity of the code, rather than performance. * * Limitations ----------- - assumes N is a power of 2 * * - not the most memory efficient algorithm (because it uses an object type for * representing complex numbers and because it re-allocates memory for the * subarray, instead of doing in-place or reusing a single temporary array) * *************************************************************************/ public class FFT { /** * compute the FFT of x[], assuming its length is a power of 2 * * @param x * @return */ public static Complex[] fft(Complex[] x) { int n = x.length; // base case if (n == 1) { return new Complex[]{x[0]}; } // radix 2 Cooley-Tukey FFT if (n % 2 != 0) { throw new RuntimeException("N is not a power of 2"); } // fft of even terms Complex[] even = new Complex[n / 2]; for (int k = 0; k < n / 2; k++) { even[k] = x[2 * k]; } Complex[] q = fft(even); // fft of odd terms Complex[] odd = even; // reuse the array for (int k = 0; k < n / 2; k++) { odd[k] = x[2 * k + 1]; } Complex[] r = fft(odd); // combine Complex[] y = new Complex[n]; for (int k = 0; k < n / 2; k++) { double kth = -2 * k * Math.PI / n; Complex wk = new Complex(Math.cos(kth), Math.sin(kth)); y[k] = q[k].plus(wk.times(r[k])); y[k + n / 2] = q[k].minus(wk.times(r[k])); } return y; } /** * compute the inverse FFT of x[], assuming its length is a power of 2 * * @param x * @return */ public static Complex[] ifft(Complex[] x) { int n = x.length; Complex[] y = new Complex[n]; // take conjugate for (int i = 0; i < n; i++) { y[i] = x[i].conjugate(); } // compute forward FFT y = fft(y); // take conjugate again for (int i = 0; i < n; i++) { y[i] = y[i].conjugate(); } // divide by N for (int i = 0; i < n; i++) { y[i] = y[i].scale(1.0 / n); } return y; } /** * compute the circular convolution of x and y * * @param x * @param y * @return */ public static Complex[] cconvolve(Complex[] x, Complex[] y) { // should probably pad x and y with 0s so that they have same length and are powers of 2 if (x.length != y.length) { throw new RuntimeException("Dimensions don't agree"); } int n = x.length; // compute FFT of each sequence,求值 Complex[] a = fft(x); Complex[] b = fft(y); // point-wise multiply,点值乘法 Complex[] c = new Complex[n]; for (int i = 0; i < n; i++) { c[i] = a[i].times(b[i]); } // compute inverse FFT,插值 return ifft(c); } /** * compute the linear convolution of x and y * * @param x * @param y * @return */ public static Complex[] convolve(Complex[] x, Complex[] y) { Complex zero = new Complex(0, 0); // 2n次数界,高阶系数为0. Complex[] a = new Complex[2 * x.length]; for (int i = 0; i < x.length; i++) { a[i] = x[i]; } for (int i = x.length; i < 2 * x.length; i++) { a[i] = zero; } Complex[] b = new Complex[2 * y.length]; for (int i = 0; i < y.length; i++) { b[i] = y[i]; } for (int i = y.length; i < 2 * y.length; i++) { b[i] = zero; } return cconvolve(a, b); } /** * Complex[] to double array for MusicPlayer * * @param x * @return */ public static Double[] array(Complex[] x) {//for MusicPlayer int len = x.length;//修正幅过小 输出幅值 * 2 / length * 50 return Stream.of(x).map(a -> a.abs() * 2 / len * 50).toArray(Double[]::new); } /** * display an array of Complex numbers to standard output * * @param x * @param title */ public static void show(Double[] x, String... title) { for (String s : title) { System.out.print(s); } System.out.println(); System.out.println("-------------------"); for (int i = 0, len = x.length; i < len; i++) { System.out.println(x[i]); } System.out.println(); } /** * display an array of Complex numbers to standard output * * @param x * @param title */ public static void show(Complex[] x, String title) { System.out.println(title); System.out.println("-------------------"); for (int i = 0, len = x.length; i < len; i++) { // 输出幅值需要 * 2 / length System.out.println(x[i].abs() * 2 / len); } System.out.println(); } /** * 将数组数据重组成2的幂次方输出 * * @param data * @return */ public static Double[] pow2DoubleArr(Double[] data) { // 创建新数组 Double[] newData = null; int dataLength = data.length; int sumNum = 2; while (sumNum < dataLength) { sumNum = sumNum * 2; } int addLength = sumNum - dataLength; if (addLength != 0) { newData = new Double[sumNum]; System.arraycopy(data, 0, newData, 0, dataLength); for (int i = dataLength; i < sumNum; i++) { newData[i] = 0d; } } else { newData = data; } return newData; } /** * 去偏移量 * * @param originalArr 原数组 * @return 目标数组 */ public static Double[] deskew(Double[] originalArr) { // 过滤不正确的参数 if (originalArr == null || originalArr.length <= 0) { return null; } // 定义目标数组 Double[] resArr = new Double[originalArr.length]; // 求数组总和 Double sum = 0D; for (int i = 0; i < originalArr.length; i++) { sum += originalArr[i]; } // 求数组平均值 Double aver = sum / originalArr.length; // 去除偏移值 for (int i = 0; i < originalArr.length; i++) { resArr[i] = originalArr[i] - aver; } return resArr; } }
6,990
Java
.java
xuhyacinth/MusicPlayer
9
0
0
2020-12-13T04:23:25Z
2022-03-15T03:58:12Z
Complex.java
/FileExtraction/Java_unseen/xuhyacinth_MusicPlayer/src/com/xu/music/player/fft/Complex.java
package com.xu.music.player.fft; /****************************************************************************** * Compilation: javac Complex.java * Execution: java Complex * * Data type for complex numbers. * * The data type is "immutable" so once you create and initialize * a Complex object, you cannot change it. The "final" keyword * when declaring re and im enforces this rule, making it a * compile-time error to change the .re or .im instance variables after * they've been initialized. * * % java Complex * a = 5.0 + 6.0i * b = -3.0 + 4.0i * Re(a) = 5.0 * Im(a) = 6.0 * b + a = 2.0 + 10.0i * a - b = 8.0 + 2.0i * a * b = -39.0 + 2.0i * b * a = -39.0 + 2.0i * a / b = 0.36 - 1.52i * (a / b) * b = 5.0 + 6.0i * conj(a) = 5.0 - 6.0i * |a| = 7.810249675906654 * tan(a) = -6.685231390246571E-6 + 1.0000103108981198i * ******************************************************************************/ import java.util.Objects; public class Complex { private final double re; // the real part private final double im; // the imaginary part // create a new object with the given real and imaginary parts public Complex(double real, double imag) { re = real; im = imag; } // a static version of plus public static Complex plus(Complex a, Complex b) { double real = a.re + b.re; double imag = a.im + b.im; Complex sum = new Complex(real, imag); return sum; } // sample client for testing public static void main(String[] args) { Complex a = new Complex(3.0, 4.0); Complex b = new Complex(-3.0, 4.0); System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("Re(a) = " + a.re()); System.out.println("Im(a) = " + a.im()); System.out.println("b + a = " + b.plus(a)); System.out.println("a - b = " + a.minus(b)); System.out.println("a * b = " + a.times(b)); System.out.println("b * a = " + b.times(a)); System.out.println("a / b = " + a.divides(b)); System.out.println("(a / b) * b = " + a.divides(b).times(b)); System.out.println("conj(a) = " + a.conjugate()); System.out.println("|a| = " + a.abs()); System.out.println("tan(a) = " + a.tan()); } // return a string representation of the invoking Complex object @Override public String toString() { if (im == 0) { return re + ""; } if (re == 0) { return im + "i"; } if (im < 0) { return re + " - " + (-im) + "i"; } return re + " + " + im + "i"; } // return abs/modulus/magnitude public double abs() { return Math.hypot(re, im); } // return angle/phase/argument, normalized to be between -pi and pi public double phase() { return Math.atan2(im, re); } // return a new Complex object whose value is (this + b) public Complex plus(Complex b) { Complex a = this; // invoking object double real = a.re + b.re; double imag = a.im + b.im; return new Complex(real, imag); } // return a new Complex object whose value is (this - b) public Complex minus(Complex b) { Complex a = this; double real = a.re - b.re; double imag = a.im - b.im; return new Complex(real, imag); } // return a new Complex object whose value is (this * b) public Complex times(Complex b) { Complex a = this; double real = a.re * b.re - a.im * b.im; double imag = a.re * b.im + a.im * b.re; return new Complex(real, imag); } // return a new object whose value is (this * alpha) public Complex scale(double alpha) { return new Complex(alpha * re, alpha * im); } // return a new Complex object whose value is the conjugate of this public Complex conjugate() { return new Complex(re, -im); } // return a new Complex object whose value is the reciprocal of this public Complex reciprocal() { double scale = re * re + im * im; return new Complex(re / scale, -im / scale); } // return the real or imaginary part public double re() { return re; } public double im() { return im; } // return a / b public Complex divides(Complex b) { Complex a = this; return a.times(b.reciprocal()); } // return a new Complex object whose value is the complex exponential of // this public Complex exp() { return new Complex(Math.exp(re) * Math.cos(im), Math.exp(re) * Math.sin(im)); } // return a new Complex object whose value is the complex sine of this public Complex sin() { return new Complex(Math.sin(re) * Math.cosh(im), Math.cos(re) * Math.sinh(im)); } // return a new Complex object whose value is the complex cosine of this public Complex cos() { return new Complex(Math.cos(re) * Math.cosh(im), -Math.sin(re) * Math.sinh(im)); } // return a new Complex object whose value is the complex tangent of this public Complex tan() { return sin().divides(cos()); } // See Section 3.3. @Override public boolean equals(Object x) { if (x == null) { return false; } if (this.getClass() != x.getClass()) { return false; } Complex that = (Complex) x; return (this.re == that.re) && (this.im == that.im); } // See Section 3.3. @Override public int hashCode() { return Objects.hash(re, im); } }
5,882
Java
.java
xuhyacinth/MusicPlayer
9
0
0
2020-12-13T04:23:25Z
2022-03-15T03:58:12Z
APISearchTipsEntity.java
/FileExtraction/Java_unseen/xuhyacinth_MusicPlayer/src/com/xu/music/player/search/APISearchTipsEntity.java
package com.xu.music.player.search; public class APISearchTipsEntity { private String srctype; private String bitrate; private String source; private String rp_type; private String songname_original; private String audio_id; private String othername; private String price; private String mvhash; private String feetype; private String extname; private String pay_type_sq; private String group; private String rp_publish; private String fold_type; private String othername_original; private String songname; private String pkg_price_320; private String sqprivilege; private String sqfilesize; private String filename; private String m4afilesize; private String topic; private String pkg_price; private String album_id; private String s320hash; private String pkg_price_sq; private String hash; private String singername; private String fail_process_320; private String fail_process_sq; private String fail_process; private String sqhash; private String filesize; private String privilege; private String isnew; private String price_sq; private String duration; private String ownercount; private String pay_type_320; private String album_name; private String old_cpy; private String album_audio_id; private String pay_type; private String s320filesize; private String Accompany; private String sourceid; private String s320privilege; private String isoriginal; private String topic_url; private String price_320; public String getSrctype() { return srctype; } public void setSrctype(String srctype) { this.srctype = srctype; } public String getBitrate() { return bitrate; } public void setBitrate(String bitrate) { this.bitrate = bitrate; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } public String getRp_type() { return rp_type; } public void setRp_type(String rp_type) { this.rp_type = rp_type; } public String getSongname_original() { return songname_original; } public void setSongname_original(String songname_original) { this.songname_original = songname_original; } public String getAudio_id() { return audio_id; } public void setAudio_id(String audio_id) { this.audio_id = audio_id; } public String getOthername() { return othername; } public void setOthername(String othername) { this.othername = othername; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getMvhash() { return mvhash; } public void setMvhash(String mvhash) { this.mvhash = mvhash; } public String getFeetype() { return feetype; } public void setFeetype(String feetype) { this.feetype = feetype; } public String getExtname() { return extname; } public void setExtname(String extname) { this.extname = extname; } public String getPay_type_sq() { return pay_type_sq; } public void setPay_type_sq(String pay_type_sq) { this.pay_type_sq = pay_type_sq; } public String getGroup() { return group; } public void setGroup(String group) { this.group = group; } public String getRp_publish() { return rp_publish; } public void setRp_publish(String rp_publish) { this.rp_publish = rp_publish; } public String getFold_type() { return fold_type; } public void setFold_type(String fold_type) { this.fold_type = fold_type; } public String getOthername_original() { return othername_original; } public void setOthername_original(String othername_original) { this.othername_original = othername_original; } public String getSongname() { return songname; } public void setSongname(String songname) { this.songname = songname; } public String getPkg_price_320() { return pkg_price_320; } public void setPkg_price_320(String pkg_price_320) { this.pkg_price_320 = pkg_price_320; } public String getSqprivilege() { return sqprivilege; } public void setSqprivilege(String sqprivilege) { this.sqprivilege = sqprivilege; } public String getSqfilesize() { return sqfilesize; } public void setSqfilesize(String sqfilesize) { this.sqfilesize = sqfilesize; } public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } public String getM4afilesize() { return m4afilesize; } public void setM4afilesize(String m4afilesize) { this.m4afilesize = m4afilesize; } public String getTopic() { return topic; } public void setTopic(String topic) { this.topic = topic; } public String getPkg_price() { return pkg_price; } public void setPkg_price(String pkg_price) { this.pkg_price = pkg_price; } public String getAlbum_id() { return album_id; } public void setAlbum_id(String album_id) { this.album_id = album_id; } public String getS320hash() { return s320hash; } public void setS320hash(String s320hash) { this.s320hash = s320hash; } public String getPkg_price_sq() { return pkg_price_sq; } public void setPkg_price_sq(String pkg_price_sq) { this.pkg_price_sq = pkg_price_sq; } public String getHash() { return hash; } public void setHash(String hash) { this.hash = hash; } public String getSingername() { return singername; } public void setSingername(String singername) { this.singername = singername; } public String getFail_process_320() { return fail_process_320; } public void setFail_process_320(String fail_process_320) { this.fail_process_320 = fail_process_320; } public String getFail_process_sq() { return fail_process_sq; } public void setFail_process_sq(String fail_process_sq) { this.fail_process_sq = fail_process_sq; } public String getFail_process() { return fail_process; } public void setFail_process(String fail_process) { this.fail_process = fail_process; } public String getSqhash() { return sqhash; } public void setSqhash(String sqhash) { this.sqhash = sqhash; } public String getFilesize() { return filesize; } public void setFilesize(String filesize) { this.filesize = filesize; } public String getPrivilege() { return privilege; } public void setPrivilege(String privilege) { this.privilege = privilege; } public String getIsnew() { return isnew; } public void setIsnew(String isnew) { this.isnew = isnew; } public String getPrice_sq() { return price_sq; } public void setPrice_sq(String price_sq) { this.price_sq = price_sq; } public String getDuration() { return duration; } public void setDuration(String duration) { this.duration = duration; } public String getOwnercount() { return ownercount; } public void setOwnercount(String ownercount) { this.ownercount = ownercount; } public String getPay_type_320() { return pay_type_320; } public void setPay_type_320(String pay_type_320) { this.pay_type_320 = pay_type_320; } public String getAlbum_name() { return album_name; } public void setAlbum_name(String album_name) { this.album_name = album_name; } public String getOld_cpy() { return old_cpy; } public void setOld_cpy(String old_cpy) { this.old_cpy = old_cpy; } public String getAlbum_audio_id() { return album_audio_id; } public void setAlbum_audio_id(String album_audio_id) { this.album_audio_id = album_audio_id; } public String getPay_type() { return pay_type; } public void setPay_type(String pay_type) { this.pay_type = pay_type; } public String getS320filesize() { return s320filesize; } public void setS320filesize(String s320filesize) { this.s320filesize = s320filesize; } public String getAccompany() { return Accompany; } public void setAccompany(String accompany) { Accompany = accompany; } public String getSourceid() { return sourceid; } public void setSourceid(String sourceid) { this.sourceid = sourceid; } public String getS320privilege() { return s320privilege; } public void setS320privilege(String s320privilege) { this.s320privilege = s320privilege; } public String getIsoriginal() { return isoriginal; } public void setIsoriginal(String isoriginal) { this.isoriginal = isoriginal; } public String getTopic_url() { return topic_url; } public void setTopic_url(String topic_url) { this.topic_url = topic_url; } public String getPrice_320() { return price_320; } public void setPrice_320(String price_320) { this.price_320 = price_320; } @Override public String toString() { return "APISearchTipsEntity [srctype=" + srctype + ", bitrate=" + bitrate + ", source=" + source + ", rp_type=" + rp_type + ", songname_original=" + songname_original + ", audio_id=" + audio_id + ", othername=" + othername + ", price=" + price + ", mvhash=" + mvhash + ", feetype=" + feetype + ", extname=" + extname + ", pay_type_sq=" + pay_type_sq + ", group=" + group + ", rp_publish=" + rp_publish + ", fold_type=" + fold_type + ", othername_original=" + othername_original + ", songname=" + songname + ", pkg_price_320=" + pkg_price_320 + ", sqprivilege=" + sqprivilege + ", sqfilesize=" + sqfilesize + ", filename=" + filename + ", m4afilesize=" + m4afilesize + ", topic=" + topic + ", pkg_price=" + pkg_price + ", album_id=" + album_id + ", s320hash=" + s320hash + ", pkg_price_sq=" + pkg_price_sq + ", hash=" + hash + ", singername=" + singername + ", fail_process_320=" + fail_process_320 + ", fail_process_sq=" + fail_process_sq + ", fail_process=" + fail_process + ", sqhash=" + sqhash + ", filesize=" + filesize + ", privilege=" + privilege + ", isnew=" + isnew + ", price_sq=" + price_sq + ", duration=" + duration + ", ownercount=" + ownercount + ", pay_type_320=" + pay_type_320 + ", album_name=" + album_name + ", old_cpy=" + old_cpy + ", album_audio_id=" + album_audio_id + ", pay_type=" + pay_type + ", s320filesize=" + s320filesize + ", Accompany=" + Accompany + ", sourceid=" + sourceid + ", s320privilege=" + s320privilege + ", isoriginal=" + isoriginal + ", topic_url=" + topic_url + ", price_320=" + price_320 + "]"; } }
11,706
Java
.java
xuhyacinth/MusicPlayer
9
0
0
2020-12-13T04:23:25Z
2022-03-15T03:58:12Z
Search.java
/FileExtraction/Java_unseen/xuhyacinth_MusicPlayer/src/com/xu/music/player/search/Search.java
package com.xu.music.player.search; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Random; @SuppressWarnings(value = "all") public class Search { private static String json = ""; private static String url = ""; public static void main(String[] args) throws MalformedURLException, IOException { List<APISearchTipsEntity> songs = Search.search("不醉不", "API"); //for (APISearchTipsEntity song:songs) { //System.out.println(song.toString()); //} songs = downloads(songs.get(0)); download(songs.get(0)); } public static void download(APISearchTipsEntity entitys) { String url = "http://www.kugou.com/yy/index.php?r=play/getdata&hash=" + entitys.getHash(); String content = ""; try { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); InputStreamReader reader = new InputStreamReader(connection.getInputStream()); BufferedReader breader = new BufferedReader(reader); while ((content = breader.readLine()) != null) { json += content; } System.out.println(json); } catch (IOException e) { e.printStackTrace(); } } public static <T> List<T> downloads(APISearchTipsEntity entitys) { List<T> songs = new ArrayList<T>(); String url = "http://www.kugou.com/yy/index.php?r=play/getdata&hash=" + (empty(entitys.getS320hash()) ? entitys.getHash() : entitys.getS320hash()); String content = ""; try { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); InputStreamReader reader = new InputStreamReader(connection.getInputStream()); BufferedReader breader = new BufferedReader(reader); while ((content = breader.readLine()) != null) { json += content; } json = json.substring(0, json.lastIndexOf("errcode") + 11); JSONObject ojsons = JSONObject.parseObject(json); ojsons = JSONObject.parseObject(ojsons.getString("data")); JSONArray array = JSONArray.parseArray(ojsons.getString("info")); for (int i = 0; i < array.size(); i++) { APISearchTipsEntity entity = JSON.toJavaObject(JSONObject.parseObject(array.get(i).toString()), APISearchTipsEntity.class); entity.setS320hash(JSON.parseObject(array.get(i).toString()).get("320hash").toString()); entity.setS320filesize(JSON.parseObject(array.get(i).toString()).get("320filesize").toString()); entity.setS320privilege(JSON.parseObject(array.get(i).toString()).get("320privilege").toString()); songs.add((T) entity); } } catch (IOException e) { e.printStackTrace(); } return songs; } public static <T> List<T> search(String name, String type) { List<T> songs = new ArrayList<T>(); if ("API".equalsIgnoreCase(type)) { url = "http://mobilecdn.kugou.com/api/v3/search/song?format=json&keyword=" + name + "&page=1&pagesize=20&showtype=1"; } else if ("WEB".equalsIgnoreCase(type)) { url = "http://searchtip.kugou.com/getSearchTip?MusicTipCount=5&MVTipCount=2&albumcount=2&keyword=" + name + "&callback=jQuery180014477266089871377_1523886180659&_=1523886" + RandomCode(); } try { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); InputStreamReader reader = new InputStreamReader(connection.getInputStream()); BufferedReader breader = new BufferedReader(reader); json = breader.readLine(); } catch (IOException e) { e.printStackTrace(); } if ("API".equalsIgnoreCase(type)) { JSONObject ojsons = JSONObject.parseObject(json); ojsons = JSONObject.parseObject(ojsons.getString("data")); JSONArray array = JSONArray.parseArray(ojsons.getString("info")); for (int i = 0; i < array.size(); i++) { APISearchTipsEntity entity = JSON.toJavaObject(JSONObject.parseObject(array.get(i).toString()), APISearchTipsEntity.class); entity.setS320hash(JSON.parseObject(array.get(i).toString()).get("320hash").toString()); entity.setS320filesize(JSON.parseObject(array.get(i).toString()).get("320filesize").toString()); entity.setS320privilege(JSON.parseObject(array.get(i).toString()).get("320privilege").toString()); songs.add((T) entity); } } else if ("WEB".equalsIgnoreCase(type)) { json = json.substring(json.indexOf("(") + 1, json.lastIndexOf(")")); JSONObject ojsons = JSONObject.parseObject(json); JSONArray arrays = JSONArray.parseArray(ojsons.getString("data")); for (int i = 0; i < arrays.size(); i++) { ojsons = JSONObject.parseObject(JSONObject.parseObject(arrays.get(i).toString()).toJSONString()); JSONArray array = JSONArray.parseArray(ojsons.getString("RecordDatas")); for (int j = 0; j < array.size(); j++) { WEBSearchTipsEntity entity = JSON.toJavaObject(JSONObject.parseObject(array.get(j).toString()), WEBSearchTipsEntity.class); songs.add((T) entity); } } } return songs; } private static String RandomCode() { String code = ""; for (int i = 0; i < 6; i++) { code += new Random().nextInt(10) + ""; } return code; } private static boolean empty(String val) { if (val == null || val.length() <= 0) { return true; } else { return false; } } }
6,204
Java
.java
xuhyacinth/MusicPlayer
9
0
0
2020-12-13T04:23:25Z
2022-03-15T03:58:12Z
WEBSearchTipsEntity.java
/FileExtraction/Java_unseen/xuhyacinth_MusicPlayer/src/com/xu/music/player/search/WEBSearchTipsEntity.java
package com.xu.music.player.search; public class WEBSearchTipsEntity { private String hintInfo; private String matchCount; private String hot; public String getHintInfo() { return hintInfo; } public void setHintInfo(String hintInfo) { this.hintInfo = hintInfo; } public String getMatchCount() { return matchCount; } public void setMatchCount(String matchCount) { this.matchCount = matchCount; } public String getHot() { return hot; } public void setHot(String hot) { this.hot = hot; } @Override public String toString() { return "WEBSearchTipsEntity [hintInfo=" + hintInfo + ", matchCount=" + matchCount + ", hot=" + hot + "]"; } }
770
Java
.java
xuhyacinth/MusicPlayer
9
0
0
2020-12-13T04:23:25Z
2022-03-15T03:58:12Z
Player.java
/FileExtraction/Java_unseen/xuhyacinth_MusicPlayer/src/com/xu/music/player/player/Player.java
package com.xu.music.player.player; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioFormat.Encoding; import javax.sound.sampled.AudioInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; public interface Player { /** * Java Music 加载音频 * * @param url 音频文件url地址 * @return boolean 是否加载成功 * @Title: load * @Description: Java Music 加载音频 * @date 2019年10月31日19:06:39 */ void load(URL url); /** * Java Music 加载音频 * * @param file 音频文件 * @return boolean 是否加载成功 * @Title: load * @Description: Java Music 加载音频 * @date 2019年10月31日19:06:39 */ void load(File file); /** * Java Music 加载音频 * * @return boolean 是否加载成功 * @Title: load * @Description: Java Music 加载音频 * @date 2019年10月31日19:06:39 */ void load(String path); /** * Java Music 加载音频 * * @param stream 音频文件输入流 * @return boolean 是否加载成功 * @Title: load * @Description: Java Music 加载音频 * @date 2019年10月31日19:06:39 */ void load(InputStream stream); /** * Java Music 加载音频 * * @param encoding Encoding * @param stream AudioInputStream * @return boolean 是否加载成功 * @Title: load * @Description: Java Music 加载音频 * @date 2019年10月31日19:06:39 */ void load(Encoding encoding, AudioInputStream stream); /** * Java Music 加载音频 * * @param stream AudioFormat * @param stream AudioInputStream * @return boolean 是否加载成功 * @Title: load * @Description: Java Music 加载音频 * @date 2019年10月31日19:06:39 */ void load(AudioFormat format, AudioInputStream stream); /** * Java Music 结束播放 * * @throws IOException * @Title: end * @Description: Java Music 结束播放 * @date 2019年10月31日19:06:39 */ void end() throws IOException; /** * Java Music 暂停播放 * * @Title: stop * @Description: Java Music 结束播放 * @date 2019年10月31日19:06:39 */ void stop(); /** * Java Music 开始播放 * * @throws Exception * @Title: start * @Description: Java Music 结束播放 * @date 2019年10月31日19:06:39 */ void start() throws Exception; /** * Java Music 是否打开 * * @return 是否打开 * @Title: isOpen * @Description: Java Music 是否打开 * @date 2019年10月31日19:06:39 */ boolean isOpen(); /** * Java Music 是否运行 * * @return 是否运行 * @Title: isAlive * @Description: Java Music 是否运行 * @date 2019年10月31日19:06:39 */ boolean isAlive(); /** * Java Music 是否正在播放 * * @return 是否正在播放 * @Title: isRuning * @Description: Java Music 是否正在播放 * @date 2019年10月31日19:06:39 */ boolean isRuning(); /** * Java Music 音频信息 * * @return 音频信息 * @Title: info * @Description: Java Music 音频信息 * @date 2019年10月31日19:06:39 */ String info(); /** * Java Music 音频播放时长 * * @return 音频播放时长 * @Title: length * @Description: Java Music 音频播放时长 * @date 2019年10月31日19:06:39 */ double length(); }
3,702
Java
.java
xuhyacinth/MusicPlayer
9
0
0
2020-12-13T04:23:25Z
2022-03-15T03:58:12Z
XMusic.java
/FileExtraction/Java_unseen/xuhyacinth_MusicPlayer/src/com/xu/music/player/player/XMusic.java
package com.xu.music.player.player; import com.xu.music.player.modle.Controller; import com.xu.music.player.modle.ControllerServer; import com.xu.music.player.system.Constant; import javazoom.spi.mpeg.sampled.file.MpegAudioFileReader; import javax.sound.sampled.*; import javax.sound.sampled.AudioFormat.Encoding; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.LinkedList; public class XMusic implements Player { public static volatile LinkedList<Double> deque = new LinkedList<Double>(); private static DataLine.Info info = null; private static AudioFormat format = null; private static SourceDataLine data = null; private static AudioInputStream stream = null; private static volatile boolean playing = false; private static Thread thread = null; private XMusic() { } /** * 静态内部内模式 创建播放器实例 * * @return 播放器实例 */ public static XMusic player() { return Music.modle; } public static boolean isPlaying() { return playing; } @Override public void load(URL url) { try { end(); } catch (IOException e) { throw new RuntimeException(e.getMessage()); } try { stream = AudioSystem.getAudioInputStream(url); format = stream.getFormat(); if (format.getEncoding().toString().toLowerCase().contains("mpeg")) {//mp3 MpegAudioFileReader mp = new MpegAudioFileReader(); stream = mp.getAudioInputStream(url); format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, format.getSampleRate(), 16, format.getChannels(), format.getChannels() * 2, format.getSampleRate(), false); stream = AudioSystem.getAudioInputStream(format, stream); } else if (format.getEncoding().toString().toLowerCase().contains("flac")) {//flac format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, format.getSampleRate(), 16, format.getChannels(), format.getChannels() * 2, format.getSampleRate(), false); stream = AudioSystem.getAudioInputStream(format, stream); } info = new DataLine.Info(SourceDataLine.class, format, AudioSystem.NOT_SPECIFIED); data = (SourceDataLine) AudioSystem.getLine(info); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } } @Override public void load(File file) { try { end(); } catch (IOException e) { e.printStackTrace(); } try { stream = AudioSystem.getAudioInputStream(file); format = stream.getFormat(); if (format.getEncoding().toString().toLowerCase().contains("mpeg")) {//mp3 MpegAudioFileReader mp = new MpegAudioFileReader(); stream = mp.getAudioInputStream(file); format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, format.getSampleRate(), 16, format.getChannels(), format.getChannels() * 2, format.getSampleRate(), false); stream = AudioSystem.getAudioInputStream(format, stream); } else if (format.getEncoding().toString().toLowerCase().contains("flac")) { format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, format.getSampleRate(), 16, format.getChannels(), format.getChannels() * 2, format.getSampleRate(), false); stream = AudioSystem.getAudioInputStream(format, stream); } info = new DataLine.Info(SourceDataLine.class, format, AudioSystem.NOT_SPECIFIED); data = (SourceDataLine) AudioSystem.getLine(info); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } } @Override public void load(InputStream streams) { try { end(); } catch (IOException e) { throw new RuntimeException(e.getMessage()); } try { stream = AudioSystem.getAudioInputStream(streams); format = stream.getFormat(); if (format.getEncoding().toString().toLowerCase().contains("mpeg")) {//mp3 MpegAudioFileReader mp = new MpegAudioFileReader(); stream = mp.getAudioInputStream(streams); format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, format.getSampleRate(), 16, format.getChannels(), format.getChannels() * 2, format.getSampleRate(), false); stream = AudioSystem.getAudioInputStream(format, stream); } else if (format.getEncoding().toString().toLowerCase().contains("flac")) { format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, format.getSampleRate(), 16, format.getChannels(), format.getChannels() * 2, format.getSampleRate(), false); stream = AudioSystem.getAudioInputStream(format, stream); } info = new DataLine.Info(SourceDataLine.class, format, AudioSystem.NOT_SPECIFIED); data = (SourceDataLine) AudioSystem.getLine(info); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } } @Override public void load(String path) { try { end(); } catch (IOException e) { e.printStackTrace(); } File file = new File(path); load(file); } @Override public void stop() { if (data != null && data.isOpen()) { data.stop(); synchronized (thread) { try { thread.wait(0); } catch (InterruptedException e) { throw new RuntimeException(e.getMessage()); } } playing = false; } } @Override public void load(Encoding encoding, AudioInputStream stream) { // TODO Auto-generated method stub } @Override public void load(AudioFormat format, AudioInputStream stream) { } @SuppressWarnings("deprecation") @Override public void end() throws IOException { if (data != null) { data.stop(); data.drain(); stream.close(); if (thread != null) { thread.stop(); thread = null; } deque.clear(); } playing = false; } @Override public void start() { if (thread != null) { synchronized (thread) { thread.notify(); data.start(); playing = true; } } else { playing = true; thread = new Thread(() -> { try { if (info != null) { data.open(format); data.start(); byte[] buf = new byte[4]; int channels = stream.getFormat().getChannels(); float rate = stream.getFormat().getSampleRate(); while (stream.read(buf) != -1 && playing) { if (channels == 2) {//立体声 if (rate == 16) { put((double) ((buf[1] << 8) | buf[0]));//左声道 //put((double) ((buf[3] << 8) | buf[2]));//右声道 } else { put((double) buf[1]);//左声道 put((double) buf[3]);//左声道 //put((double) buf[2]);//右声道 //put((double) buf[4]);//右声道 } } else {//单声道 if (rate == 16) { put((double) ((buf[1] << 8) | buf[0])); put((double) ((buf[3] << 8) | buf[2])); } else { put((double) buf[0]); put((double) buf[1]); put((double) buf[2]); put((double) buf[3]); } } data.write(buf, 0, 4); } new ControllerServer().endLyricPlayer(new Controller());// 结束歌词和频谱 System.out.println("解码器 结束歌词和频谱"); end();// 结束播放流 System.out.println("解码器 结束播放流"); } } catch (Exception e) { throw new RuntimeException(e.getMessage()); } }); thread.setDaemon(true); thread.start(); } } @Override public double length() { return Integer.parseInt(Constant.PLAYING_SONG_NAME.split(Constant.MUSIC_PLAYER_SYSTEM_SPLIT)[3]); } @Override public boolean isOpen() { return data.isOpen(); } @Override public boolean isAlive() { if (data != null && data.isOpen()) { return data.isActive(); } else { return false; } } @Override public boolean isRuning() { if (data != null && data.isOpen()) { return data.isRunning(); } else { return false; } } @Override public String info() { if (stream != null) { return stream.getFormat().toString(); } else { return ""; } } public void put(Double v) { synchronized (deque) { deque.add(v); if (deque.size() > Constant.SPECTRUM_TOTAL_NUMBER) { deque.removeFirst(); } } } private static class Music { private static XMusic modle = new XMusic(); } }
10,161
Java
.java
xuhyacinth/MusicPlayer
9
0
0
2020-12-13T04:23:25Z
2022-03-15T03:58:12Z
Test.java
/FileExtraction/Java_unseen/xuhyacinth_MusicPlayer/src/com/xu/music/player/player/Test.java
package com.xu.music.player.player; public class Test { public static void main(String[] args) throws Exception { Player player = XMusic.player(); player.load("C:\\Users\\Administrator\\Desktop\\梦涵 - 加减乘除.mp3"); System.out.println(player.info()); player.start(); System.out.println(123); } }
355
Java
.java
xuhyacinth/MusicPlayer
9
0
0
2020-12-13T04:23:25Z
2022-03-15T03:58:12Z
TestUtilities.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/test/java/dk/aau/cs/ds306e18/tournament/TestUtilities.java
package dk.aau.cs.ds306e18.tournament; import dk.aau.cs.ds306e18.tournament.model.*; import dk.aau.cs.ds306e18.tournament.model.match.Series; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import static java.time.Instant.now; public class TestUtilities { public static final String[] TEST_BOT_CONFIG_FILES = { "src/test/bots/alpha.cfg", "src/test/bots/bravo.cfg", "src/test/bots/charlie.cfg", "src/test/bots/delta.cfg", "src/test/bots/echo.cfg", "src/test/bots/foxtrot.cfg", "src/test/bots/golf.cfg", "src/test/bots/hotel.cfg", "src/test/bots/india.cfg", "src/test/bots/juliet.cfg", "src/test/bots/kilo.cfg", "src/test/bots/lima.cfg", "src/test/bots/mike.cfg", "src/test/bots/november.cfg", }; public static final String[] TEAM_NAMES = {"Complexity", "FlipSid3", "Fnatic", "Method", "Dignitas", "Team Secret", "We Dem Girlz", "Allegiance", "Cloud9", "Evil Geniuses", "G2", "Ghost Gaming", "NRG", "Rogue", "The Muffin Men", "FC Barcelona", "Team SoloMid", "The Bricks", "Baguette Squad", "Frontline", "Exalty", "ARG", "Echo Zulu", "Ghost", "Triple Commit", "The D00ds", "Plot Twist", "Gadget", "Firecrackers", "My Little Pwners", "Avalanche", "ChronoRetreat", "Dala's Warriors"}; private static final Random rand = new Random(); /** * Returns the given amount of bots from test configs. Each bot will be unique. */ public static List<BotFromConfig> getTestConfigBots(int count) { if (0 < count && count < TEST_BOT_CONFIG_FILES.length) throw new AssertionError("Only 0-" + TEST_BOT_CONFIG_FILES.length + " test bots are supported."); return Arrays.stream(TEST_BOT_CONFIG_FILES) .limit(count) .map(BotFromConfig::new) .collect(Collectors.toList()); } /** * Returns a random bot from a test config. Only use it when the randomness does not affect the test. */ private static BotFromConfig randomBotFromConfig() { int i = rand.nextInt(TEST_BOT_CONFIG_FILES.length); return new BotFromConfig(TEST_BOT_CONFIG_FILES[i]); } /** * Returns the given amount of teams. The teams are seeded and each team is unique due to team name and seed. * Note that the bots are chosen randomly. */ public static List<Team> getTestTeams(int count, int teamSize) { if (count < 0 || TEAM_NAMES.length <= count) throw new AssertionError("Only 0-" + TEAM_NAMES.length + " test teams are supported."); return IntStream.range(1, count + 1) .mapToObj(seed -> new Team( TEAM_NAMES[seed], Stream.generate(() -> (Bot) randomBotFromConfig()) .limit(teamSize) .collect(Collectors.toList()), seed, "Team description")) .collect(Collectors.toList()); } /** * Generates a tournament with the given number of teams with the given number of bots per team. Note that * the bots are randomly chosen, but team are unique due to team names. */ public static Tournament generateTournamentWithTeams(int teamCount, int botsPerTeam) { Tournament tournament = new Tournament(); tournament.setName("DatTestTournament"); List<Team> teams = getTestTeams(teamCount, botsPerTeam); tournament.addTeams(teams); return tournament; } /** * Sets all matches in the given list to have been played. The best seeded team wins. */ public static void setAllMatchesToPlayed(List<Series> series) { for (Series serie : series) { Team teamOne = serie.getTeamOne(); Team teamTwo = serie.getTeamTwo(); if (teamOne.getInitialSeedValue() < teamTwo.getInitialSeedValue()) { serie.setScores(1, 0, 0); } else { serie.setScores(0, 1, 0); } serie.setHasBeenPlayed(true); } } }
4,362
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
FileOperationsTest.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/test/java/dk/aau/cs/ds306e18/tournament/utility/FileOperationsTest.java
package dk.aau.cs.ds306e18.tournament.utility; import org.junit.Test; import java.io.File; import static org.junit.Assert.assertEquals; public class FileOperationsTest { @Test public void checkFilename01() { assertEquals("txt", FileOperations.getFileExtension(new File("filename.txt"))); assertEquals("obj", FileOperations.getFileExtension(new File("filename.obj"))); } @Test public void checkFilename02() { assertEquals("", FileOperations.getFileExtension(new File("folder/no-extension-file"))); } @Test public void checkFilename03() { assertEquals("", FileOperations.getFileExtension(new File("fol.der/no-extension-file"))); } }
705
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
AutoNamingTest.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/test/java/dk/aau/cs/ds306e18/tournament/utility/AutoNamingTest.java
package dk.aau.cs.ds306e18.tournament.utility; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Set; import static org.junit.Assert.assertEquals; public class AutoNamingTest { @RunWith(Parameterized.class) static public class GetNameTest { private String result; private String expectedResult; public GetNameTest(String[] botNames, String expectedResult) { this.result = AutoNaming.getName(Arrays.asList(botNames)); this.expectedResult = expectedResult; } @Parameterized.Parameters public static Collection parameters() { return Arrays.asList(new Object[][]{ {new String[0], "Team"}, {new String[]{"ReliefBot", "Beast from the East"}, "Relief-Beast"}, {new String[]{"Air Bud", "Skybot"}, "Air-Sky"}, {new String[]{"Botimus Prime", "Gas Gas Gas"}, "Botimus-Gas"}, {new String[]{"Self-driving car", "Diablo"}, "Self-driving-Diablo"}, {new String[]{"Gosling", "Self-driving car"}, "Gosling-Self-driving"}, {new String[]{"NV Derevo", "AdversityBot"}, "NV-Adversity"}, {new String[]{"Wildfire V2", "Boolean Algebra Calf"}, "Wildfire-Boolean"}, {new String[]{"Psyonix Allstar", "Zoomelette"}, "Allstar-Zoomelette"}, {new String[]{"Kamael", "Kamael"}, "Kamael"}, }); } @Test public void getNameTest() { assertEquals(expectedResult, result); } } @RunWith(Parameterized.class) static public class UniquifyTest { private String result; private String expectedResult; public UniquifyTest(String teamName, String[] otherTeams, String expectedResult) { this.result = AutoNaming.uniquify(teamName, new HashSet<>(Arrays.asList(otherTeams))); this.expectedResult = expectedResult; } @Parameterized.Parameters public static Collection parameters() { return Arrays.asList(new Object[][]{ { "TSM", new String[]{"NRG", "C9"}, "TSM"}, { "Team", new String[]{"Team", "AnotherTeam"}, "Team (2)"}, { "Team", new String[]{"Team (1)", "Team (2)"}, "Team"}, { "Team", new String[]{"Team", "Team (2)"}, "Team (3)"}, { "", new String[]{"", "Another Team"}, " (2)"}, }); } @Test public void uniquifyTest() { assertEquals(expectedResult, result); } } }
2,781
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
SerializerTest.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/test/java/dk/aau/cs/ds306e18/tournament/utility/SerializerTest.java
package dk.aau.cs.ds306e18.tournament.utility; import dk.aau.cs.ds306e18.tournament.model.Stage; import dk.aau.cs.ds306e18.tournament.model.Tournament; import dk.aau.cs.ds306e18.tournament.model.format.DoubleEliminationFormat; import dk.aau.cs.ds306e18.tournament.model.format.RoundRobinFormat; import dk.aau.cs.ds306e18.tournament.model.format.SingleEliminationFormat; import dk.aau.cs.ds306e18.tournament.model.format.SwissFormat; import dk.aau.cs.ds306e18.tournament.serialization.Serializer; import org.junit.Test; import static dk.aau.cs.ds306e18.tournament.TestUtilities.*; import static org.junit.Assert.assertEquals; public class SerializerTest { /** * Test for serialising a Tournament object, serializes it to a JSON-string, deserializes it to * a Tournament object, and checks equality between the original object and the resuscitated object. * The tournament does not have any stages. */ @Test public void serializingPrimitiveTournamentConcurrencyTest() { Tournament tournament = generateTournamentWithTeams(4, 1); String jsonObject = Serializer.serialize(tournament); Tournament deserializedTournament = Serializer.deserialize(jsonObject); assertEquals(tournament, deserializedTournament); } /** * Test for serialising a Round Robin Tournament object, serializes it to a JSON-string, deserializes it to * a Tournament object, and checks equality between the original object and the resuscitated object */ @Test public void serializingRoundRobinConcurrencyTest() { Tournament tournament = generateTournamentWithTeams(4, 1); tournament.addStage(new Stage("Round Robin Stage", new RoundRobinFormat())); tournament.start(); String jsonObject = Serializer.serialize(tournament); Tournament deserializedTournament = Serializer.deserialize(jsonObject); assertEquals(tournament, deserializedTournament); } /** * Test for serialising a Single Elimination Tournament object, serializes it to a JSON-string, deserializes it * to a Tournament object, and checks equality between the original object and the resuscitated object */ @Test public void serializingSingleEliminationConcurrencyTest() { Tournament tournament = generateTournamentWithTeams(4, 1); tournament.addStage(new Stage("Single Elimination Stage", new SingleEliminationFormat())); tournament.start(); String jsonObject = Serializer.serialize(tournament); Tournament deserializedTournament = Serializer.deserialize(jsonObject); assertEquals(tournament, deserializedTournament); } /** * Test for serialising a Swiss Tournament object, serializes it to a JSON-string, deserializes it to * a Tournament object, and checks equality between the original object and the resuscitated object */ @Test public void serializingSwissConcurrencyTest() { Tournament tournament = generateTournamentWithTeams(4, 1); tournament.addStage(new Stage("Swiss Stage", new SwissFormat())); tournament.start(); String jsonObject = Serializer.serialize(tournament); Tournament deserializedTournament = Serializer.deserialize(jsonObject); assertEquals(tournament, deserializedTournament); } /** * Test for serialising a Double Elimination Tournament object, serializes it to a JSON-string, deserializes it to * a Tournament object, and checks equality between the original object and the resuscitated object */ @Test public void serializingDoubleEliminationConcurrencyTest() { Tournament tournament = generateTournamentWithTeams(4, 1); tournament.addStage(new Stage("Double Elimination Stage", new DoubleEliminationFormat())); tournament.start(); String jsonObject = Serializer.serialize(tournament); Tournament deserializedTournament = Serializer.deserialize(jsonObject); assertEquals(tournament, deserializedTournament); } }
4,065
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
ConfigFileTest.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/test/java/dk/aau/cs/ds306e18/tournament/rlbot/configuration/ConfigFileTest.java
package dk.aau.cs.ds306e18.tournament.rlbot.configuration; import org.junit.Test; import java.io.File; import java.io.IOException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class ConfigFileTest { private final static String TEST_DIR = "src/test/"; private final static String TEST_CONFIG = "config_format_test.cfg"; private final static String TEST_CONFIG_OUT = "_out_config_format_test.cfg"; @Test public void setAndGetString01() { ConfigFile config = new ConfigFile(); config.set("Section", "key", "value"); assertEquals("value", config.getString("Section", "key", null)); } @Test public void setAndGetString02() { ConfigFile config = new ConfigFile(); config.set("Some Section", "Some key", "some value"); assertEquals("some value", config.getString("Some Section", "Some key", null)); } @Test public void setAndGetString03() { ConfigFile config = new ConfigFile(); config.set("Section", "key", "value"); // Section does not exist assertEquals("default value", config.getString("Some other Section", "key", "default value")); } @Test public void setAndGetString04() { ConfigFile config = new ConfigFile(); config.set("Section", "key", "value"); // Key does not exist assertEquals("default value", config.getString("Section", "some other key", "default value")); } @Test public void setAndGetInt01() { ConfigFile config = new ConfigFile(); config.set("Section", "key", 42); assertEquals(42, config.getInt("Section", "key", -1)); } @Test public void setAndGetFloat01() { ConfigFile config = new ConfigFile(); config.set("Section", "key", 0.5f); assertEquals(0.5f, config.getFloat("Section", "key", -1f), 1e-10f); } @Test public void setAndGetDouble01() { ConfigFile config = new ConfigFile(); config.set("Section", "key", 1.23); assertEquals(1.23, config.getDouble("Section", "key", 0.0), 1e-10); } @Test public void setAndGetBoolean01() { ConfigFile config = new ConfigFile(); config.set("Section", "key", true); assertTrue(config.getBoolean("Section", "key", false)); } @Test public void load01() throws IOException { ConfigFile testConfig = new ConfigFile(new File(TEST_DIR, TEST_CONFIG)); assertTrue(testConfig.hasSection("Apples")); assertEquals("red", testConfig.getString("Apples", "color", null)); assertEquals(20, testConfig.getInt("Apples", "count", -1)); assertTrue(testConfig.hasSection("Bananas")); assertEquals("they taste pretty good", testConfig.getString("Bananas", "multiline property", null)); assertEquals("", testConfig.getString("Bananas", "no value", null)); assertTrue(testConfig.getBoolean("Bananas", "other delimiter", false)); assertTrue(testConfig.hasSection("Empty")); } @Test public void write01() throws IOException { ConfigFile testConfig = new ConfigFile(new File(TEST_DIR, TEST_CONFIG)); testConfig.write(new File(TEST_DIR, TEST_CONFIG_OUT)); // Load again to make sure output was readable and didn't modify any values testConfig = new ConfigFile(new File(TEST_DIR, TEST_CONFIG)); assertTrue(testConfig.hasSection("Apples")); assertEquals("red", testConfig.getString("Apples", "color", null)); assertEquals(20, testConfig.getInt("Apples", "count", -1)); assertTrue(testConfig.hasSection("Bananas")); assertEquals("they taste pretty good", testConfig.getString("Bananas", "multiline property", null)); assertEquals("", testConfig.getString("Bananas", "no value", null)); assertTrue(testConfig.getBoolean("Bananas", "other delimiter", false)); assertTrue(testConfig.hasSection("Empty")); } }
4,008
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
BotConfigTest.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/test/java/dk/aau/cs/ds306e18/tournament/rlbot/configuration/BotConfigTest.java
package dk.aau.cs.ds306e18.tournament.rlbot.configuration; import org.junit.Test; import java.io.File; import java.io.IOException; import static org.junit.Assert.assertEquals; public class BotConfigTest { private static final String TEST_BOT_CONFIG_FILE = "src/test/bots/alpha.cfg"; @Test public void constructor01() throws IOException { BotConfig bot = new BotConfig(new File(TEST_BOT_CONFIG_FILE)); assertEquals(new File(TEST_BOT_CONFIG_FILE), bot.getConfigFile()); assertEquals("Alpha Bot", bot.getName()); assertEquals(new File("bot.py"), bot.getPythonFile()); assertEquals(new File("./appearance.cfg"), bot.getLooksConfig()); assertEquals("Alpha Developer", bot.getDeveloper()); assertEquals("This is a short description of the Alpha Bot", bot.getDescription()); assertEquals("This is a fun fact about the Alpha Bot", bot.getFunFact()); assertEquals("https://github.com/developer/Alpha-repo", bot.getGithub()); assertEquals("Alpha language", bot.getLanguage()); } }
1,076
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
MatchConfigTest.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/test/java/dk/aau/cs/ds306e18/tournament/rlbot/configuration/MatchConfigTest.java
package dk.aau.cs.ds306e18.tournament.rlbot.configuration; import org.junit.Test; import java.io.File; import java.io.IOException; import java.util.List; import static dk.aau.cs.ds306e18.tournament.rlbot.configuration.MatchConfigOptions.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; public class MatchConfigTest { private static final String MATCH_CONFIG_FILE = "src/test/rlbot.cfg"; private static final String MATCH_CONFIG_FILE_OUT = "src/test/_out_rlbot.cfg"; @Test public void read01() throws IOException { MatchConfig config = new MatchConfig(new File(MATCH_CONFIG_FILE)); // Match settings assertEquals(GameMap.MANNFIELD, config.getGameMap()); assertEquals(GameMode.SOCCER, config.getGameMode()); assertFalse(config.isSkipReplays()); assertFalse(config.isInstantStart()); // Mutators assertEquals(MatchLength.UNLIMITED, config.getMatchLength()); assertEquals(MaxScore.UNLIMITED, config.getMaxScore()); assertEquals(Overtime.UNLIMITED, config.getOvertime()); assertEquals(BallMaxSpeed.DEFAULT, config.getBallMaxSpeed()); assertEquals(GameSpeed.DEFAULT, config.getGameSpeed()); assertEquals(BallType.DEFAULT, config.getBallType()); assertEquals(BallWeight.DEFAULT, config.getBallWeight()); assertEquals(BallSize.DEFAULT, config.getBallSize()); assertEquals(BallBounciness.DEFAULT, config.getBallBounciness()); assertEquals(BoostAmount.DEFAULT, config.getBoostAmount()); assertEquals(BoostStrength.TIMES_ONE, config.getBoostStrength()); assertEquals(RumblePowers.NONE, config.getRumblePowers()); assertEquals(Gravity.DEFAULT, config.getGravity()); assertEquals(Demolish.DEFAULT, config.getDemolish()); assertEquals(RespawnTime.THREE_SECONDS, config.getRespawnTime()); // Participants // We won't test the BotConfigs here, only the other stuff in ParticipantInfo List<ParticipantInfo> participants = config.getParticipants(); assertEquals(2, participants.size()); assertEquals(BotSkill.ALLSTAR, participants.get(0).getSkill()); assertEquals(BotType.RLBOT, participants.get(0).getType()); assertEquals(TeamColor.BLUE, participants.get(0).getTeam()); assertEquals(BotSkill.ALLSTAR, participants.get(1).getSkill()); assertEquals(BotType.RLBOT, participants.get(1).getType()); assertEquals(TeamColor.BLUE, participants.get(1).getTeam()); } @Test public void readWrite01() throws IOException { MatchConfig config = new MatchConfig(new File(MATCH_CONFIG_FILE)); config.clearParticipants(); // Clear since the bot configs are irrelevant config.write(new File(MATCH_CONFIG_FILE_OUT)); // Load same file again and compare before and after MatchConfig config2 = new MatchConfig(new File(MATCH_CONFIG_FILE_OUT)); assertEquals(config, config2); } }
3,032
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
TieBreakerTest.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/test/java/dk/aau/cs/ds306e18/tournament/model/TieBreakerTest.java
package dk.aau.cs.ds306e18.tournament.model; import dk.aau.cs.ds306e18.tournament.TestUtilities; import dk.aau.cs.ds306e18.tournament.model.match.Series; import org.junit.Test; import java.util.Arrays; import java.util.HashMap; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; public class TieBreakerTest { @Test public void goalDiff01() { List<Team> teams = TestUtilities.getTestTeams(6, 1); Series seriesOne = new Series(teams.get(0), teams.get(1)); Series seriesTwo = new Series(teams.get(2), teams.get(3)); Series seriesThree = new Series(teams.get(4), teams.get(5)); List<Series> series = Arrays.asList(seriesOne, seriesTwo, seriesThree); seriesOne.setScores(9, 5, 0); seriesOne.setHasBeenPlayed(true); seriesTwo.setScores(4, 0, 0); seriesTwo.setHasBeenPlayed(true); seriesThree.setScores(4, 3, 0); seriesThree.setHasBeenPlayed(true); for (Team team : teams) { team.getStatsManager().trackAllSeries(null, series); } List<Team> ordered = TieBreaker.GOAL_DIFF.compareAll(teams, null); assertSame(ordered.get(0), teams.get(0)); // goal diff of 4, goals scored of 9 assertSame(ordered.get(1), teams.get(2)); // goal diff of 4, goals scored of 4 assertSame(ordered.get(2), teams.get(4)); // goal diff of 1, goals scored of 4 assertSame(ordered.get(3), teams.get(5)); // goal diff of -1, goals scored of 3 assertSame(ordered.get(4), teams.get(1)); // goal diff of -4, goals scored of 5 assertSame(ordered.get(5), teams.get(3)); // goal diff of -4, goals scored of 0 } @Test public void goalScored01() { List<Team> teams = TestUtilities.getTestTeams(4, 1); Series seriesOne = new Series(teams.get(0), teams.get(1)); Series seriesTwo = new Series(teams.get(2), teams.get(3)); List<Series> series = Arrays.asList(seriesOne, seriesTwo); seriesOne.setScores(5, 1, 0); seriesOne.setHasBeenPlayed(true); seriesTwo.setScores(4, 2, 0); seriesTwo.setHasBeenPlayed(true); for (Team team : teams) { team.getStatsManager().trackAllSeries(null, series); } List<Team> ordered = TieBreaker.GOALS_SCORED.compareAll(teams, null); assertSame(ordered.get(0), teams.get(0)); // goals scored of 5 assertSame(ordered.get(1), teams.get(2)); // goals scored of 4 assertSame(ordered.get(2), teams.get(3)); // goals scored of 2 assertSame(ordered.get(3), teams.get(1)); // goals scored of 1 } @Test public void bySeed01() { List<Team> teams = TestUtilities.getTestTeams(4, 1); Series seriesOne = new Series(teams.get(0), teams.get(1)); Series seriesTwo = new Series(teams.get(2), teams.get(3)); List<Series> series = Arrays.asList(seriesOne, seriesTwo); // Scores shouldn't matter seriesOne.setScores(2, 3, 0); seriesOne.setHasBeenPlayed(true); seriesTwo.setScores(4, 1, 0); seriesTwo.setHasBeenPlayed(true); for (Team team : teams) { team.getStatsManager().trackAllSeries(null, series); } List<Team> ordered = TieBreaker.SEED.compareAll(teams, null); assertSame(ordered.get(0), teams.get(0)); // seed 1 assertSame(ordered.get(1), teams.get(1)); // seed 2 assertSame(ordered.get(2), teams.get(2)); // seed 3 assertSame(ordered.get(3), teams.get(3)); // seed 4 } @Test public void compareWithPoints01() { List<Team> teams = TestUtilities.getTestTeams(6, 1); Series seriesOne = new Series(teams.get(0), teams.get(1)); Series seriesTwo = new Series(teams.get(2), teams.get(3)); Series seriesThree = new Series(teams.get(4), teams.get(5)); List<Series> series = Arrays.asList(seriesOne, seriesTwo, seriesThree); seriesOne.setScores(2, 3, 0); seriesOne.setHasBeenPlayed(true); seriesTwo.setScores(4, 2, 0); seriesTwo.setHasBeenPlayed(true); seriesThree.setScores(3, 4, 0); seriesThree.setHasBeenPlayed(true); for (Team team : teams) { team.getStatsManager().trackAllSeries(null, series); } // Team 0 and team 3 both have 2 goals, but team 0 has one point // Team 1 and team 4 both have 3 goals, but team 4 has one point // Team 2 and team 5 both have 4 goals, but team 2 has one point HashMap<Team, Integer> pointsMap = new HashMap<>(); pointsMap.put(teams.get(0), 1); pointsMap.put(teams.get(1), 0); pointsMap.put(teams.get(2), 1); pointsMap.put(teams.get(3), 0); pointsMap.put(teams.get(4), 1); pointsMap.put(teams.get(5), 0); List<Team> best = TieBreaker.GOALS_SCORED.compareWithPoints(teams, pointsMap, null); assertSame(teams.get(2), best.get(0)); assertSame(teams.get(4), best.get(1)); assertSame(teams.get(0), best.get(2)); assertSame(teams.get(5), best.get(3)); assertSame(teams.get(1), best.get(4)); assertSame(teams.get(3), best.get(5)); } @Test public void compareWithPoints02() { List<Team> teams = TestUtilities.getTestTeams(6, 1); Series seriesOne = new Series(teams.get(0), teams.get(1)); Series seriesTwo = new Series(teams.get(2), teams.get(3)); Series seriesThree = new Series(teams.get(4), teams.get(5)); List<Series> series = Arrays.asList(seriesOne, seriesTwo, seriesThree); seriesOne.setScores(1, 3, 0); seriesOne.setHasBeenPlayed(true); seriesTwo.setScores(2, 5, 0); seriesTwo.setHasBeenPlayed(true); seriesThree.setScores(4, 0, 0); seriesThree.setHasBeenPlayed(true); for (Team team : teams) { team.getStatsManager().trackAllSeries(null, series); } // Teams with points should be ahead, but their goals decide the order next HashMap<Team, Integer> pointsMap = new HashMap<>(); pointsMap.put(teams.get(0), 0); pointsMap.put(teams.get(1), 0); pointsMap.put(teams.get(2), 1); pointsMap.put(teams.get(3), 0); pointsMap.put(teams.get(4), 1); pointsMap.put(teams.get(5), 1); List<Team> best = TieBreaker.GOALS_SCORED.compareWithPoints(teams, pointsMap, null); assertSame(teams.get(4), best.get(0)); assertSame(teams.get(2), best.get(1)); assertSame(teams.get(5), best.get(2)); assertSame(teams.get(3), best.get(3)); assertSame(teams.get(1), best.get(4)); assertSame(teams.get(0), best.get(5)); } }
6,769
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
TeamTest.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/test/java/dk/aau/cs/ds306e18/tournament/model/TeamTest.java
package dk.aau.cs.ds306e18.tournament.model; import org.junit.Test; import java.util.ArrayList; import static org.junit.Assert.*; public class TeamTest { }
162
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
SeriesTest.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/test/java/dk/aau/cs/ds306e18/tournament/model/SeriesTest.java
package dk.aau.cs.ds306e18.tournament.model; import dk.aau.cs.ds306e18.tournament.model.match.Series; import dk.aau.cs.ds306e18.tournament.model.match.MatchResultDependencyException; import org.junit.Test; import java.util.List; import static org.junit.Assert.*; public class SeriesTest { @Test public void isReadyToPlay01() { Series series = new Series(new Team("A", null, 0, "a"), new Team("B", null, 0, "b")); assertTrue(series.isReadyToPlay()); } @Test public void isReadyToPlay02() { Series firstSeries = new Series(new Team("A", null, 0, "a"), new Team("B", null, 0, "b")); Series secondSeries = new Series().setTeamOne(new Team("C", null, 0, "c")).setTeamTwoToWinnerOf(firstSeries); secondSeries.setTeamTwoToWinnerOf(firstSeries); assertFalse(secondSeries.isReadyToPlay()); firstSeries.setScores(4, 2, 0); firstSeries.setHasBeenPlayed(true); assertTrue(secondSeries.isReadyToPlay()); } @Test public void getWinnerAndLoser01() { // team one wins Team expectedWinner = new Team("A", null, 0, "a"); Team expectedLoser = new Team("B", null, 0, "b"); Series series = new Series(expectedWinner, expectedLoser); series.setScores(3, 2, 0); series.setHasBeenPlayed(true); assertSame(series.getWinner(), expectedWinner); assertSame(series.getLoser(), expectedLoser); } @Test public void getWinnerAndLoser02() { // team two wins Team expectedWinner = new Team("A", null, 0, "a"); Team expectedLoser = new Team("B", null, 0, "b"); Series series = new Series(expectedLoser, expectedWinner); series.setScores(3, 5, 0); series.setHasBeenPlayed(true); assertSame(series.getWinner(), expectedWinner); assertSame(series.getLoser(), expectedLoser); } @Test(expected = IllegalStateException.class) public void getWinnerAndLoser03() { Series series = new Series(new Team("A", null, 0, "a"), new Team("B", null, 0, "b")); series.setScores(3, 5, 0); // note: match is not finished series.getWinner(); } @Test(expected = IllegalStateException.class) public void getWinnerAndLoser04() { Series series = new Series(new Team("A", null, 0, "a"), new Team("B", null, 0, "b")); series.setScores(3, 5, 0); // note: match is not finished series.getLoser(); } @Test public void getStatus01() { Series firstSeries = new Series(new Team("A", null, 0, "a"), new Team("B", null, 0, "b")); Series secondSeries = new Series().setTeamOne(new Team("C", null, 0, "c")).setTeamTwoToWinnerOf(firstSeries); assertSame(secondSeries.getStatus(), Series.Status.NOT_PLAYABLE); } @Test public void getStatus02() { Series firstSeries = new Series(new Team("A", null, 0, "a"), new Team("B", null, 0, "b")); Series secondSeries = new Series().setTeamOne(new Team("C", null, 0, "c")).setTeamTwoToWinnerOf(firstSeries); firstSeries.setScores(0, 2, 0); firstSeries.setHasBeenPlayed(true); assertSame(secondSeries.getStatus(), Series.Status.READY_TO_BE_PLAYED); } @Test public void getStatus03() { Series series = new Series(new Team("A", null, 0, "a"), new Team("B", null, 0, "b")); series.setScores(0, 0, 0); series.setHasBeenPlayed(true); assertSame(series.getOutcome(), Series.Outcome.DRAW); } @Test public void getStatus04() { Series series = new Series(new Team("A", null, 0, "a"), new Team("B", null, 0, "b")); series.setScores(2, 0, 0); series.setHasBeenPlayed(true); assertSame(series.getOutcome(), Series.Outcome.TEAM_ONE_WINS); } @Test public void getStatus05() { Series series = new Series(new Team("A", null, 0, "a"), new Team("B", null, 0, "b")); series.setScores(0, 2, 0); series.setHasBeenPlayed(true); assertSame(series.getOutcome(), Series.Outcome.TEAM_TWO_WINS); } @Test public void dependsOn01() { Series firstSeries = new Series(new Team("A", null, 0, "a"), new Team("B", null, 0, "b")); Series secondSeries = new Series().setTeamOne(new Team("C", null, 0, "c")).setTeamTwoToWinnerOf(firstSeries); assertTrue(secondSeries.dependsOn(firstSeries)); } @Test public void dependsOn02() { Series firstSeries = new Series(new Team("A", null, 0, "a"), new Team("B", null, 0, "b")); Series secondSeries = new Series().setTeamOne(new Team("C", null, 0, "c")).setTeamTwoToLoserOf(firstSeries); assertTrue(secondSeries.dependsOn(firstSeries)); } @Test public void dependsOn03() { Series firstSeries = new Series(new Team("A", null, 0, "a"), new Team("B", null, 0, "b")); Series secondSeries = new Series().setTeamOne(new Team("C", null, 0, "c")).setTeamTwoToWinnerOf(firstSeries); assertFalse(firstSeries.dependsOn(secondSeries)); } @Test public void dependsOn04() { Series firstSeries = new Series(new Team("A", null, 0, "a"), new Team("B", null, 0, "b")); Series secondSeries = new Series().setTeamOne(new Team("C", null, 0, "c")).setTeamTwoToLoserOf(firstSeries); assertFalse(firstSeries.dependsOn(secondSeries)); } @Test public void dependsOn05() { Series firstSeries = new Series(new Team("A", null, 0, "a"), new Team("B", null, 0, "b")); Series secondSeries = new Series(new Team("C", null, 0, "c"), new Team("D", null, 0, "d")); Series thirdSeries = new Series().setTeamOneToWinnerOf(firstSeries).setTeamTwoToLoserOf(secondSeries); assertFalse(firstSeries.dependsOn(secondSeries)); assertFalse(secondSeries.dependsOn(firstSeries)); assertTrue(thirdSeries.dependsOn(firstSeries)); assertTrue(thirdSeries.dependsOn(secondSeries)); } @Test public void getTreeAsListBFS01() { Series firstSeries = new Series(new Team("A", null, 0, "a"), new Team("B", null, 0, "b")); Series secondSeries = new Series(new Team("C", null, 0, "c"), new Team("D", null, 0, "d")); Series thirdSeries = new Series(new Team("E", null, 0, "e"), new Team("F", null, 0, "f")); Series fourthSeries = new Series(new Team("G", null, 0, "g"), new Team("H", null, 0, "h")); Series firstSemiFinal = new Series().setTeamOneToWinnerOf(firstSeries).setTeamTwoToWinnerOf(secondSeries); Series secondSemiFinal = new Series().setTeamOneToWinnerOf(thirdSeries).setTeamTwoToWinnerOf(fourthSeries); Series finalSeries = new Series().setTeamOneToWinnerOf(firstSemiFinal).setTeamTwoToWinnerOf(secondSemiFinal); List<Series> bfs = finalSeries.getTreeAsListBFS(); assertSame(finalSeries, bfs.get(0)); assertSame(secondSemiFinal, bfs.get(1)); assertSame(firstSemiFinal, bfs.get(2)); assertSame(fourthSeries, bfs.get(3)); assertSame(thirdSeries, bfs.get(4)); assertSame(secondSeries, bfs.get(5)); assertSame(firstSeries, bfs.get(6)); } @Test public void getTreeAsListBFS02() { Series firstSeries = new Series(new Team("A", null, 0, "a"), new Team("B", null, 0, "b")); Series secondSeries = new Series().setTeamOneToWinnerOf(firstSeries).setTeamTwo(new Team("C", null, 0, "c")); Series thirdSeries = new Series().setTeamOneToWinnerOf(secondSeries).setTeamTwo(new Team("D", null, 0, "d")); List<Series> bfs = thirdSeries.getTreeAsListBFS(); assertSame(thirdSeries, bfs.get(0)); assertSame(secondSeries, bfs.get(1)); assertSame(firstSeries, bfs.get(2)); assertEquals(3, bfs.size()); } @Test public void reconnect01() { Team expectedWinner = new Team("A", null, 0, "a"); Series seriesOne = new Series(expectedWinner, new Team("B", null, 0, "b")); Series seriesTwo = new Series().setTeamOne(new Team("C", null, 0, "c")).setTeamTwoToWinnerOf(seriesOne); seriesOne.setScores(4, 2, 0); seriesOne.setHasBeenPlayed(true); assertSame(expectedWinner, seriesTwo.getTeamTwo()); // change match one winner now goes to third match instead Series seriesThree = new Series().setTeamOne(new Team("D", null, 0, "d")).setTeamTwoToWinnerOf(seriesOne); assertFalse(seriesTwo.dependsOn(seriesOne)); assertNull(seriesTwo.getTeamTwo()); assertSame(expectedWinner, seriesThree.getTeamTwo()); } @Test public void reconnect02() { Team expectedWinner = new Team("A", null, 0, "a"); Series seriesOne = new Series(expectedWinner, new Team("B", null, 0, "b")); Series seriesTwo = new Series().setTeamOne(new Team("C", null, 0, "c")).setTeamTwoToWinnerOf(seriesOne); seriesOne.setScores(4, 2, 0); seriesOne.setHasBeenPlayed(true); assertSame(expectedWinner, seriesTwo.getTeamTwo()); // change match two's team two to be winner of match three Series seriesThree = new Series(new Team("D", null, 0, "d"), new Team("E", null, 0, "e")); seriesTwo.setTeamTwoToWinnerOf(seriesThree); assertFalse(seriesTwo.dependsOn(seriesOne)); assertTrue(seriesTwo.dependsOn(seriesThree)); assertNull(seriesTwo.getTeamTwo()); } @Test public void reconnect03() { Team expectedLoser = new Team("A", null, 0, "a"); Series seriesOne = new Series(expectedLoser, new Team("B", null, 0, "b")); Series seriesTwo = new Series().setTeamOne(new Team("C", null, 0, "c")).setTeamTwoToLoserOf(seriesOne); seriesOne.setScores(0, 3, 0); seriesOne.setHasBeenPlayed(true); assertSame(expectedLoser, seriesTwo.getTeamTwo()); // change match one loser now goes to third match instead Series seriesThree = new Series().setTeamOne(new Team("D", null, 0, "d")).setTeamTwoToLoserOf(seriesOne); assertFalse(seriesTwo.dependsOn(seriesOne)); assertNull(seriesTwo.getTeamTwo()); assertSame(expectedLoser, seriesThree.getTeamTwo()); } @Test public void reconnect04() { Team expectedLoser = new Team("A", null, 0, "a"); Series seriesOne = new Series(expectedLoser, new Team("B", null, 0, "b")); Series seriesTwo = new Series().setTeamOne(new Team("C", null, 0, "c")).setTeamTwoToLoserOf(seriesOne); seriesOne.setScores(0, 3, 0); seriesOne.setHasBeenPlayed(true); assertSame(expectedLoser, seriesTwo.getTeamTwo()); // change match two's team two to be loser of match three Series seriesThree = new Series(new Team("D", null, 0, "d"), new Team("E", null, 0, "e")); seriesTwo.setTeamTwoToLoserOf(seriesThree); assertFalse(seriesTwo.dependsOn(seriesOne)); assertTrue(seriesTwo.dependsOn(seriesThree)); assertNull(seriesTwo.getTeamTwo()); } @Test public void setScores01(){ Team teamOne = new Team("A", null, 1, null); Team teamTwo = new Team("B", null, 1, null); Series series = new Series(teamOne, teamTwo); int teamOneScore = 5; int teamTwoScore = 2; series.setScores(teamOneScore, teamTwoScore, 0); series.setHasBeenPlayed(true); assertEquals(teamOneScore, (int) series.getTeamOneScore(0).get()); assertEquals(teamTwoScore, (int) series.getTeamTwoScore(0).get()); } @Test public void setScores02(){ Team teamOne = new Team(null, null, 1, null); Team teamTwo = new Team(null, null, 1, null); Series series = new Series(teamOne, teamTwo); int teamOneScore1 = 5; int teamTwoScore1 = 2; int teamOneScore2 = 2; int teamTwoScore2 = 2; series.setScores(teamOneScore1, teamTwoScore1, 0); series.setHasBeenPlayed(true); series.setScores(teamOneScore2, teamTwoScore2, 0); series.setHasBeenPlayed(true); assertEquals(teamOneScore2, (int) series.getTeamOneScore(0).get()); assertEquals(teamTwoScore2, (int) series.getTeamTwoScore(0).get()); } @Test public void reconnectAfterPlay01() { Team tA = new Team("A", null, 0, "a"); Team tE = new Team("E", null, 0, "e"); Series seriesOne = new Series(tA, new Team("B", null, 0, "b")); Series seriesTwo = new Series().setTeamOne(new Team("C", null, 0, "c")).setTeamTwoToWinnerOf(seriesOne); Series seriesThree = new Series(tE, new Team("D", null, 0, "d")); // Team A and E wins seriesOne.setScores(1, 0, 0); seriesOne.setHasBeenPlayed(true); seriesThree.setScores(1, 0, 0); seriesThree.setHasBeenPlayed(true); // Match two's team two should be A assertSame(tA, seriesTwo.getTeamTwo()); // Match two's team two should be E, if we change it to be winner of match three seriesTwo.setTeamTwoToWinnerOf(seriesThree); assertSame(tE, seriesTwo.getTeamTwo()); } @Test public void reset01() { Team teamA = new Team("A", null, 0, "a"); Team teamB = new Team("B", null, 0, "b"); Team teamC = new Team("C", null, 0, "c"); Series seriesOne = new Series(teamA, teamB); Series seriesTwo = new Series().setTeamOne(teamC).setTeamTwoToWinnerOf(seriesOne); seriesOne.setScores(2, 1, 0); seriesOne.setHasBeenPlayed(true); seriesTwo.setScores(4, 3, 0); assertEquals(2, (int) seriesOne.getTeamOneScore(0).get()); assertEquals(1, (int) seriesOne.getTeamTwoScore(0).get()); assertEquals(4, (int) seriesTwo.getTeamOneScore(0).get()); assertEquals(3, (int) seriesTwo.getTeamTwoScore(0).get()); // This forced reset should remove all scores. Also in match two that has not been played seriesOne.forceReset(); assertFalse(seriesOne.getTeamOneScore(0).isPresent()); assertFalse(seriesOne.getTeamTwoScore(0).isPresent()); assertFalse(seriesTwo.getTeamOneScore(0).isPresent()); assertFalse(seriesTwo.getTeamTwoScore(0).isPresent()); } @Test(expected = MatchResultDependencyException.class) public void reset02() { Team teamA = new Team("A", null, 0, "a"); Team teamB = new Team("B", null, 0, "b"); Team teamC = new Team("C", null, 0, "c"); Series seriesOne = new Series(teamA, teamB); Series seriesTwo = new Series().setTeamOne(teamC).setTeamTwoToWinnerOf(seriesOne); seriesOne.setScores(2, 1, 0); seriesOne.setHasBeenPlayed(true); seriesTwo.setScores(4, 3, 0); assertEquals(2, (int) seriesOne.getTeamOneScore(0).get()); assertEquals(1, (int) seriesOne.getTeamTwoScore(0).get()); assertEquals(4, (int) seriesTwo.getTeamOneScore(0).get()); assertEquals(3, (int) seriesTwo.getTeamTwoScore(0).get()); // This reset should not be legal as match two has entered scores seriesOne.softReset(); } @Test(expected = MatchResultDependencyException.class) public void reset03() { Team teamA = new Team("A", null, 0, "a"); Team teamB = new Team("B", null, 0, "b"); Team teamC = new Team("C", null, 0, "c"); Series seriesOne = new Series(teamA, teamB); Series seriesTwo = new Series().setTeamOne(teamC).setTeamTwoToWinnerOf(seriesOne); seriesOne.setScores(2, 1, 0); seriesOne.setHasBeenPlayed(true); seriesTwo.setScores(4, 3, 0); seriesTwo.setHasBeenPlayed(true); assertEquals(2, (int) seriesOne.getTeamOneScore(0).get()); assertEquals(1, (int) seriesOne.getTeamTwoScore(0).get()); assertEquals(4, (int) seriesTwo.getTeamOneScore(0).get()); assertEquals(3, (int) seriesTwo.getTeamTwoScore(0).get()); // This reset should not be legal as match two has been played seriesOne.softReset(); } @Test public void reset04() { Team teamA = new Team("A", null, 0, "a"); Team teamB = new Team("B", null, 0, "b"); Team teamC = new Team("C", null, 0, "c"); Series seriesOne = new Series(teamA, teamB); Series seriesTwo = new Series().setTeamOne(teamC).setTeamTwoToWinnerOf(seriesOne); seriesOne.setScores(2, 1, 0); seriesOne.setHasBeenPlayed(true); seriesTwo.setScores(4, 3, 0); assertEquals(2, (int) seriesOne.getTeamOneScore(0).get()); assertEquals(1, (int) seriesOne.getTeamTwoScore(0).get()); assertEquals(4, (int) seriesTwo.getTeamOneScore(0).get()); assertEquals(3, (int) seriesTwo.getTeamTwoScore(0).get()); // This should be legal as it doesn't change the outcome of match one seriesOne.setScores(4, 2, 0); assertEquals(4, (int) seriesOne.getTeamOneScore(0).get()); assertEquals(2, (int) seriesOne.getTeamTwoScore(0).get()); assertEquals(4, (int) seriesTwo.getTeamOneScore(0).get()); assertEquals(3, (int) seriesTwo.getTeamTwoScore(0).get()); } @Test public void reset05() { Team teamA = new Team("A", null, 0, "a"); Team teamB = new Team("B", null, 0, "b"); Team teamC = new Team("C", null, 0, "c"); Series seriesOne = new Series(teamA, teamB); Series seriesTwo = new Series().setTeamOne(teamC).setTeamTwoToWinnerOf(seriesOne); seriesOne.setScores(2, 1, 0); seriesOne.setHasBeenPlayed(true); seriesTwo.setScores(4, 3, 0); seriesTwo.setHasBeenPlayed(true); assertEquals(2, (int) seriesOne.getTeamOneScore(0).get()); assertEquals(1, (int) seriesOne.getTeamTwoScore(0).get()); assertEquals(4, (int) seriesTwo.getTeamOneScore(0).get()); assertEquals(3, (int) seriesTwo.getTeamTwoScore(0).get()); // This reset should be legal as it doesn't change the outcome of match one, even when match two has been played seriesOne.setScores(4, 2, 0); assertEquals(4, (int) seriesOne.getTeamOneScore(0).get()); assertEquals(2, (int) seriesOne.getTeamTwoScore(0).get()); assertEquals(4, (int) seriesTwo.getTeamOneScore(0).get()); assertEquals(3, (int) seriesTwo.getTeamTwoScore(0).get()); } @Test public void identifier01() { Team teamA = new Team("A", null, 0, "a"); Team teamB = new Team("B", null, 0, "b"); Team teamC = new Team("C", null, 0, "c"); Team teamD = new Team("D", null, 0, "d"); Series seriesOne = new Series(teamA, teamB); Series seriesTwo = new Series().setTeamOne(teamC).setTeamTwoToWinnerOf(seriesOne); Series seriesThree = new Series().setTeamTwo(teamD).setTeamOneToLoserOf(seriesOne); seriesOne.setIdentifier(1); seriesTwo.setIdentifier(2); seriesThree.setIdentifier(3); assertEquals("Winner of 1", seriesTwo.getTeamTwoAsString()); assertEquals("C", seriesTwo.getTeamOneAsString()); assertEquals("Loser of 1", seriesThree.getTeamOneAsString()); assertEquals("D", seriesThree.getTeamTwoAsString()); } @Test public void switchingColors01() { Team teamA = new Team("A", null, 0, "a"); Team teamB = new Team("B", null, 0, "b"); Series series = new Series(teamA, teamB); assertSame(teamA, series.getTeamOne()); assertSame(teamB, series.getTeamTwo()); assertSame(teamA, series.getBlueTeam()); assertSame(teamB, series.getOrangeTeam()); series.setTeamOneToBlue(false); assertSame(teamA, series.getTeamOne()); assertSame(teamB, series.getTeamTwo()); assertSame(teamB, series.getBlueTeam()); assertSame(teamA, series.getOrangeTeam()); } @Test public void switchingColors02() { Team teamA = new Team("A", null, 0, "a"); Team teamB = new Team("B", null, 0, "b"); Series series = new Series(teamA, teamB); series.setScores(2, 0, 0); series.setHasBeenPlayed(true); assertEquals(2, (int) series.getTeamOneScore(0).get()); assertEquals(0, (int) series.getTeamTwoScore(0).get()); assertEquals(2, (int) series.getBlueScore(0).get()); assertEquals(0, (int) series.getOrangeScore(0).get()); series.setTeamOneToBlue(false); assertEquals(2, (int) series.getTeamOneScore(0).get()); assertEquals(0, (int) series.getTeamTwoScore(0).get()); assertEquals(0, (int) series.getBlueScore(0).get()); assertEquals(2, (int) series.getOrangeScore(0).get()); } @Test public void switchingColors03() { Team teamA = new Team("A", null, 0, "a"); Team teamB = new Team("B", null, 0, "b"); Series series = new Series(teamA, teamB); series.setScores(2, 0, 0); series.setHasBeenPlayed(true); assertEquals("A", series.getTeamOneAsString()); assertEquals("B", series.getTeamTwoAsString()); assertEquals("A", series.getBlueTeamAsString()); assertEquals("B", series.getOrangeTeamAsString()); series.setTeamOneToBlue(false); assertEquals("A", series.getTeamOneAsString()); assertEquals("B", series.getTeamTwoAsString()); assertEquals("B", series.getBlueTeamAsString()); assertEquals("A", series.getOrangeTeamAsString()); } }
21,409
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
StatsTest.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/test/java/dk/aau/cs/ds306e18/tournament/model/stats/StatsTest.java
package dk.aau.cs.ds306e18.tournament.model.stats; import dk.aau.cs.ds306e18.tournament.model.Team; import dk.aau.cs.ds306e18.tournament.model.format.Format; import dk.aau.cs.ds306e18.tournament.model.match.Series; import org.junit.Test; import static org.junit.Assert.*; public class StatsTest { // Test class contains tests for both Stats, StatsTracker, StatsChangeListener, // and StatsManager as those classes are very tightly connected @Test public void stats01() { Team teamA = new Team("A", null, 1, "a"); Team teamB = new Team("B", null, 2, "b"); Stats statsA = teamA.getStatsManager().getGlobalStats(); // Same Stats instance all way through assertEquals(0, statsA.getWins()); assertEquals(0, statsA.getLoses()); assertEquals(0, statsA.getGoals()); assertEquals(0, statsA.getGoalsConceded()); Series series = new Series(teamA, teamB); teamA.getStatsManager().trackSeries(null, series); series.setScores(3, 2, 0); series.setHasBeenPlayed(true); // Stats are added now that a match is tracked assertEquals(1, statsA.getWins()); assertEquals(0, statsA.getLoses()); assertEquals(3, statsA.getGoals()); assertEquals(2, statsA.getGoalsConceded()); } @Test public void stats02() { Team teamA = new Team("A", null, 0, "a"); Team teamB = new Team("B", null, 0, "b"); Series series = new Series(teamA, teamB); teamA.getStatsManager().trackSeries(null, series); teamB.getStatsManager().trackSeries(null, series); series.setScores(1, 3, 0); // Match not over assertStats(teamA, null, 0, 0, 1, 3); assertStats(teamB, null, 0, 0, 3, 1); } @Test public void stats03() { Team teamA = new Team("A", null, 0, "a"); Team teamB = new Team("B", null, 0, "b"); Series series = new Series(teamA, teamB); teamA.getStatsManager().trackSeries(null, series); teamB.getStatsManager().trackSeries(null, series); series.setScores(5, 2, 0); series.setHasBeenPlayed(true); assertStats(teamA, null, 1, 0, 5, 2); assertStats(teamB, null, 0, 1, 2, 5); } @Test public void stats04() { Team teamA = new Team("A", null, 0, "a"); Team teamB = new Team("B", null, 0, "b"); Team teamC = new Team("C", null, 0, "c"); Series seriesOne = new Series(teamA, teamB); Series seriesTwo = new Series().setTeamOne(teamC).setTeamTwoToWinnerOf(seriesOne); seriesOne.setScores(2, 1, 0); seriesOne.setHasBeenPlayed(true); seriesTwo.setScores(4, 3, 0); seriesTwo.setHasBeenPlayed(true); for (Team team : new Team[]{teamA, teamB, teamC}) { team.getStatsManager().trackSeries(null, seriesOne); team.getStatsManager().trackSeries(null, seriesTwo); } assertStats(teamA, null, 1, 1, 5, 5); assertStats(teamB, null, 0, 1, 1, 2); assertStats(teamC, null, 1, 0, 4, 3); } public static void assertStats(Team team, Format format, int wins, int loses, int goals, int goalsConceded) { Stats stats = format == null ? team.getStatsManager().getGlobalStats() : team.getStatsManager().getStats(format); assertEquals(wins, stats.getWins()); assertEquals(loses, stats.getLoses()); assertEquals(goals, stats.getGoals()); assertEquals(goalsConceded, stats.getGoalsConceded()); } }
3,569
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
SwissFormatTest.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/test/java/dk/aau/cs/ds306e18/tournament/model/format/SwissFormatTest.java
package dk.aau.cs.ds306e18.tournament.model.format; import dk.aau.cs.ds306e18.tournament.TestUtilities; import dk.aau.cs.ds306e18.tournament.model.Team; import dk.aau.cs.ds306e18.tournament.model.TieBreaker; import dk.aau.cs.ds306e18.tournament.model.match.Series; import dk.aau.cs.ds306e18.tournament.model.stats.StatsTest; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static dk.aau.cs.ds306e18.tournament.TestUtilities.*; import static org.junit.Assert.*; public class SwissFormatTest { //Even number of teams @Test public void calculateMaxRounds01(){ int numberOfTeams = 4; int teamSize = 2; SwissFormat sw = new SwissFormat(); sw.start(getTestTeams(numberOfTeams, teamSize), true); assertEquals(numberOfTeams - 1, sw.getMaxRoundsPossible()); } //Odd number of teams @Test public void calculateMaxRounds02(){ int numberOfTeams = 5; int teamSize = 2; SwissFormat sw = new SwissFormat(); sw.start(getTestTeams(numberOfTeams, teamSize), true); assertEquals(numberOfTeams, sw.getMaxRoundsPossible()); } //No teams @Test public void calculateMaxRounds03(){ int numberOfTeams = 0; int teamSize = 2; SwissFormat sw = new SwissFormat(); sw.start(getTestTeams(numberOfTeams, teamSize), true); assertEquals(numberOfTeams, sw.getMaxRoundsPossible()); } //more than 0 matches // one round @Test public void getAllMatches01(){ int numberOfTeams = 4; int teamSize = 2; SwissFormat sw = new SwissFormat(); sw.start(getTestTeams(numberOfTeams, teamSize), true); List<Series> allSeries = sw.getAllSeries(); assertEquals(numberOfTeams/2, allSeries.size()); } //0 matches // one round @Test public void getAllMatches02(){ int numberOfTeams = 0; int teamSize = 0; SwissFormat sw = new SwissFormat(); sw.start(getTestTeams(numberOfTeams, teamSize), true); List<Series> allSeries = sw.getAllSeries(); assertEquals(0, allSeries.size()); } //more than 0 matches // more round @Test public void getAllMatches03(){ int numberOfTeams = 12; int teamSize = 2; SwissFormat sw = new SwissFormat(); sw.start(getTestTeams(numberOfTeams, teamSize), true); //The first round. assertEquals(numberOfTeams/2, sw.getAllSeries().size()); //Fill in scores List<Series> series = sw.getLatestRound(); for(Series serie : series){ serie.setScores(5, 2, 0); serie.setHasBeenPlayed(true); } sw.startNextRound(); assertEquals((numberOfTeams/2) * 2, sw.getAllSeries().size()); } @Test public void getPendingMatches01(){ int numberOfTeams = 4; int teamSize = 2; SwissFormat sw = new SwissFormat(); sw.start(getTestTeams(numberOfTeams, teamSize), true); List<Series> unplayedSeries = sw.getPendingMatches(); assertEquals(0, unplayedSeries.size()); } //0 matches @Test public void getPendingMatches02(){ int numberOfTeams = 0; int teamSize = 0; SwissFormat sw = new SwissFormat(); sw.start(getTestTeams(numberOfTeams, teamSize), true); List<Series> unplayedSeries = sw.getPendingMatches(); assertEquals(0, unplayedSeries.size()); } @Test public void getPendingMatches03(){ int numberOfTeams = 4; int teamSize = 2; SwissFormat sw = new SwissFormat(); sw.start(getTestTeams(numberOfTeams, teamSize), true); //All has to be played setAllMatchesToPlayed(sw.getUpcomingMatches()); assertEquals(0 , sw.getPendingMatches().size()); } @Test public void getUpcomingMatches01(){ int numberOfTeams = 4; int teamSize = 2; SwissFormat sw = new SwissFormat(); sw.start(getTestTeams(numberOfTeams, teamSize), true); assertEquals(numberOfTeams/2 , sw.getUpcomingMatches().size()); } @Test public void getUpcomingMatches02(){ int numberOfTeams = 16; int teamSize = 2; SwissFormat sw = new SwissFormat(); sw.start(getTestTeams(numberOfTeams, teamSize), true); assertEquals(numberOfTeams/2 , sw.getUpcomingMatches().size()); } @Test public void getUpcomingMatches03(){ int numberOfTeams = 1; int teamSize = 2; SwissFormat sw = new SwissFormat(); sw.start(getTestTeams(numberOfTeams, teamSize), true); assertEquals(0 , sw.getUpcomingMatches().size()); } @Test public void getCompletedMatches01(){ int numberOfTeams = 4; int teamSize = 2; SwissFormat sw = new SwissFormat(); sw.start(getTestTeams(numberOfTeams, teamSize), true); assertEquals(0 , sw.getCompletedMatches().size()); } @Test public void getCompletedMatches02(){ int numberOfTeams = 4; int teamSize = 2; SwissFormat sw = new SwissFormat(); sw.start(getTestTeams(numberOfTeams, teamSize), true); setAllMatchesToPlayed(sw.getUpcomingMatches()); assertEquals(sw.getAllSeries().size() , sw.getCompletedMatches().size()); } //Create round is legal @Test public void createNewRound01(){ int numberOfTeams = 4; int teamSize = 2; SwissFormat sw = new SwissFormat(); sw.start(getTestTeams(numberOfTeams, teamSize), true); //All has to be played setAllMatchesToPlayed(sw.getUpcomingMatches()); assertTrue(sw.startNextRound()); } //Create round is illegal: max rounds has been created. @Test public void createNewRound02(){ int numberOfTeams = 2; int teamSize = 2; SwissFormat sw = new SwissFormat(); sw.start(getTestTeams(numberOfTeams, teamSize), true); //All has to be played setAllMatchesToPlayed(sw.getUpcomingMatches()); assertFalse(sw.startNextRound()); } //Create new round is illegal: no matches has been played @Test public void createNewRound03(){ int numberOfTeams = 4; int teamSize = 2; SwissFormat sw = new SwissFormat(); sw.start(getTestTeams(numberOfTeams, teamSize), true); assertFalse(sw.startNextRound()); } //No team can play each other more than once @Test public void createNewRound04(){ //Create a list of unique teams. List<Team> teams = getTestTeams(7, 1); //Create the sw with the teams SwissFormat sw = new SwissFormat(); sw.start(teams, true); //Generate all rounds and fill result do{ List<Series> series = sw.getUpcomingMatches(); for(Series serie : series) { serie.setScores(1, 0, 0); serie.setHasBeenPlayed(true); } sw.startNextRound(); }while(!sw.hasUnstartedRounds()); List<Series> allSeries = sw.getAllSeries(); //Check if no teams has played each other more than once for(int i = 0; i < allSeries.size(); i++){ for(int j = i + 1; j < allSeries.size(); j++){ Series series1 = allSeries.get(i); Series series2 = allSeries.get(j); //System.out.println("Match Comp 1: Match1B: " + match1.getTeamOne().getTeamName() + " Match1O " + match1.getTeamTwo().getTeamName() // + " Match2B " + match2.getTeamOne().getTeamName() + " Match2O " + match2.getTeamTwo().getTeamName()); assertFalse(series1.getTeamOne().getTeamName().equals(series2.getTeamOne().getTeamName()) && series1.getTeamTwo().getTeamName().equals(series2.getTeamTwo().getTeamName())); assertFalse(series1.getTeamOne().getTeamName().equals(series2.getTeamTwo().getTeamName()) && series1.getTeamTwo().getTeamName().equals(series2.getTeamOne().getTeamName())); } } } //Create round is illegal: only one team. @Test public void createNewRound05(){ int numberOfTeams = 1; int teamSize = 2; SwissFormat sw = new SwissFormat(); sw.start(getTestTeams(numberOfTeams, teamSize), true); //All has to be played setAllMatchesToPlayed(sw.getUpcomingMatches()); assertFalse(sw.startNextRound()); } @Test public void hasUnstartedRounds01(){ int numberOfTeams = 2; int teamSize = 2; SwissFormat sw = new SwissFormat(); sw.start(getTestTeams(numberOfTeams, teamSize), true); assertFalse(sw.hasUnstartedRounds()); } @Test public void hasUnstartedRounds02(){ int numberOfTeams = 4; int teamSize = 2; SwissFormat sw = new SwissFormat(); sw.start(getTestTeams(numberOfTeams, teamSize), true); assertTrue(sw.hasUnstartedRounds()); } @Test public void hasUnstartedRounds03(){ int numberOfTeams = 12; int teamSize = 2; SwissFormat sw = new SwissFormat(); sw.setRoundCount(1); sw.start(getTestTeams(numberOfTeams, teamSize), true); assertFalse(sw.hasUnstartedRounds()); } @Test public void setRoundCount01() { int numberOfTeams = 12; int teamSize = 2; SwissFormat sw = new SwissFormat(); sw.setRoundCount(3); sw.start(getTestTeams(numberOfTeams, teamSize), true); assertTrue(sw.hasUnstartedRounds()); assertEquals(3, sw.getRoundCount()); } @Test public void setRoundCount02() { int numberOfTeams = 8; int teamSize = 2; SwissFormat sw = new SwissFormat(); sw.setRoundCount(44444); sw.start(getTestTeams(numberOfTeams, teamSize), true); assertTrue(sw.hasUnstartedRounds()); assertEquals(7, sw.getRoundCount()); } @Test(expected = IllegalArgumentException.class) public void setRoundCount03() { SwissFormat sw = new SwissFormat(); sw.setRoundCount(-2); } @Test(expected = IllegalStateException.class) public void setRoundCount04() { int numberOfTeams = 8; int teamSize = 2; SwissFormat sw = new SwissFormat(); sw.setRoundCount(3); sw.start(getTestTeams(numberOfTeams, teamSize), true); sw.setRoundCount(2); } @Test public void getStatus01(){ //Pending SwissFormat sw = new SwissFormat(); assertEquals(StageStatus.PENDING, sw.getStatus()); } @Test public void getStatus02(){ //Running SwissFormat sw = new SwissFormat(); sw.start(getTestTeams(4, 2), true); sw.startNextRound(); assertEquals(StageStatus.RUNNING, sw.getStatus()); } @Test public void getStatus03(){ //Concluded // max number of rounds and all played SwissFormat sw = new SwissFormat(); sw.start(getTestTeams(2,2), true); sw.startNextRound(); //Set all matches to played setAllMatchesToPlayed(sw.getUpcomingMatches()); assertEquals(StageStatus.CONCLUDED, sw.getStatus()); } @Test public void getStatus04(){ //Concluded //max number of round but not played SwissFormat sw = new SwissFormat(); sw.start(getTestTeams(2,2), true); sw.startNextRound(); assertNotEquals(StageStatus.CONCLUDED, sw.getStatus()); } @Test public void getTopTeams01(){ //No teams SwissFormat sw = new SwissFormat(); sw.start(new ArrayList<>(), true); assertEquals(0, sw.getTopTeams(0, TieBreaker.SEED).size()); } @Test public void getTopTeams02(){ SwissFormat sw = new SwissFormat(); List<Team> inputTeams = getTestTeams(4, 2); sw.start(inputTeams, true); setAllMatchesToPlayed(sw.getUpcomingMatches()); //All teams now have the same amount of points. ArrayList<Team> top3Teams = new ArrayList<>(sw.getTopTeams(3, TieBreaker.SEED)); //The top teams should be the ones with the lowest seeds //Sort the input teams by seed Team teamWithWorstSeed = inputTeams.get(0); //Find team with highest seed for(Team team : inputTeams){ if(team.getInitialSeedValue() > teamWithWorstSeed.getInitialSeedValue()){ teamWithWorstSeed = team; } } //Make sure that that team is not a part of the top 3 for(Team team : top3Teams) assertNotSame(team, teamWithWorstSeed); } @Test public void stats01() { SwissFormat sw = new SwissFormat(); List<Team> teams = TestUtilities.getTestTeams(4, 1); sw.start(teams, true); // Play all matches. The highest seeded team wins 1-0 while (sw.getStatus() == StageStatus.RUNNING) { List<Series> latestRound = sw.getLatestRound(); for (Series series : latestRound) { if (series.getTeamOne().getInitialSeedValue() < series.getTeamTwo().getInitialSeedValue()) { series.setScores(1, 0, 0); } else { series.setScores(0, 1, 0); } series.setHasBeenPlayed(true); } sw.startNextRound(); } // Check if stats are as expected StatsTest.assertStats(teams.get(0), sw, 3, 0, 3, 0); StatsTest.assertStats(teams.get(1), sw, 2, 1, 2, 1); StatsTest.assertStats(teams.get(2), sw, 1, 2, 1, 2); StatsTest.assertStats(teams.get(3), sw, 0, 3, 0, 3); } }
13,853
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
DoubleEliminationFormatTest.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/test/java/dk/aau/cs/ds306e18/tournament/model/format/DoubleEliminationFormatTest.java
package dk.aau.cs.ds306e18.tournament.model.format; import dk.aau.cs.ds306e18.tournament.TestUtilities; import dk.aau.cs.ds306e18.tournament.model.Team; import dk.aau.cs.ds306e18.tournament.model.TieBreaker; import dk.aau.cs.ds306e18.tournament.model.match.Series; import dk.aau.cs.ds306e18.tournament.model.stats.StatsTest; import org.junit.Test; import java.util.HashMap; import java.util.List; import static org.junit.Assert.*; public class DoubleEliminationFormatTest { @Test public void amountOfMatches01() { DoubleEliminationFormat de = new DoubleEliminationFormat(); de.start(TestUtilities.getTestTeams(8, 1), true); assertEquals(15, de.getAllSeries().size()); } @Test public void amountOfMatches02() { DoubleEliminationFormat de = new DoubleEliminationFormat(); de.start(TestUtilities.getTestTeams(30, 1), true); assertEquals(59, de.getAllSeries().size()); } @Test public void amountOfMatches03() { DoubleEliminationFormat de = new DoubleEliminationFormat(); de.start(TestUtilities.getTestTeams(12, 1), true); assertEquals(23, de.getAllSeries().size()); } @Test public void amountOfMatches04() { DoubleEliminationFormat de = new DoubleEliminationFormat(); de.start(TestUtilities.getTestTeams(19, 1), true); assertEquals(37, de.getAllSeries().size()); } @Test public void matchDependencies01() { DoubleEliminationFormat de = new DoubleEliminationFormat(); de.start(TestUtilities.getTestTeams(8, 1), true); Series extra = de.getExtraSeries(); List<Series> series = de.getAllSeries(); for (Series serie : series) { if (serie != extra) { assertTrue(extra.dependsOn(serie)); } } } @Test public void matchDependencies02() { DoubleEliminationFormat de = new DoubleEliminationFormat(); de.start(TestUtilities.getTestTeams(17, 1), true); Series extra = de.getExtraSeries(); List<Series> series = de.getAllSeries(); for (Series serie : series) { if (serie != extra) { assertTrue(extra.dependsOn(serie)); } } } @Test public void seedPlacingTest01() { List<Team> teams = TestUtilities.getTestTeams(8, 1); DoubleEliminationFormat de = new DoubleEliminationFormat(); de.start(teams, true); Series[] upperBracket = de.getUpperBracket(); int len = upperBracket.length; assertSame(1, upperBracket[len-1].getTeamOne().getInitialSeedValue()); assertSame(8, upperBracket[len-1].getTeamTwo().getInitialSeedValue()); assertSame(4, upperBracket[len-2].getTeamOne().getInitialSeedValue()); assertSame(5, upperBracket[len-2].getTeamTwo().getInitialSeedValue()); assertSame(2, upperBracket[len-3].getTeamOne().getInitialSeedValue()); assertSame(7, upperBracket[len-3].getTeamTwo().getInitialSeedValue()); assertSame(3, upperBracket[len-4].getTeamOne().getInitialSeedValue()); assertSame(6, upperBracket[len-4].getTeamTwo().getInitialSeedValue()); } @Test public void seedPlacingTest02() { List<Team> teams = TestUtilities.getTestTeams(5, 1); DoubleEliminationFormat de = new DoubleEliminationFormat(); de.start(teams, true); Series[] upperBracket = de.getUpperBracket(); int len = upperBracket.length; assertSame(1, upperBracket[len-5].getTeamOne().getInitialSeedValue()); assertSame(2, upperBracket[len-6].getTeamOne().getInitialSeedValue()); assertSame(3, upperBracket[len-6].getTeamTwo().getInitialSeedValue()); assertSame(4, upperBracket[len-2].getTeamOne().getInitialSeedValue()); assertSame(5, upperBracket[len-2].getTeamTwo().getInitialSeedValue()); } @Test public void onlyTwoTeams() { DoubleEliminationFormat de = new DoubleEliminationFormat(); de.start(TestUtilities.getTestTeams(2, 1), true); assertEquals(3, de.getAllSeries().size()); assertEquals(0, de.getLowerBracket().length); } @Test public void isExtraMatchNeeded01() { DoubleEliminationFormat de = new DoubleEliminationFormat(); de.start(TestUtilities.getTestTeams(4, 1), true); assertFalse(de.isExtraMatchNeeded()); // Play all matches except the last (the extra match) List<Series> series = de.getAllSeries(); for (int i = series.size() - 1; i > 0; i--) { series.get(i).setScores(1, 0, 0); series.get(i).setHasBeenPlayed(true); } assertFalse(de.isExtraMatchNeeded()); } @Test public void isExtraMatchNeeded02() { DoubleEliminationFormat de = new DoubleEliminationFormat(); de.start(TestUtilities.getTestTeams(4, 1), true); // Play all matches except the last (the extra match) List<Series> series = de.getAllSeries(); for (int i = series.size() - 1; i > 0; i--) { series.get(i).setScores(1, 0, 0); series.get(i).setHasBeenPlayed(true); } assertFalse(de.isExtraMatchNeeded()); // Change result of final match so lower bracket winner wins series.get(1).setScores(0, 1, 0); series.get(1).setHasBeenPlayed(true); assertTrue(de.isExtraMatchNeeded()); } @Test public void upcomingAndPendingMatches01() { DoubleEliminationFormat de = new DoubleEliminationFormat(); de.start(TestUtilities.getTestTeams(4, 1), true); assertEquals(2, de.getUpcomingMatches().size()); assertEquals(4, de.getPendingMatches().size()); } @Test public void upcomingAndPendingMatches02() { DoubleEliminationFormat de = new DoubleEliminationFormat(); de.start(TestUtilities.getTestTeams(7, 1), true); assertEquals(3, de.getUpcomingMatches().size()); assertEquals(9, de.getPendingMatches().size()); } @Test public void upcomingAndPendingMatches03() { DoubleEliminationFormat de = new DoubleEliminationFormat(); de.start(TestUtilities.getTestTeams(13, 1), true); assertEquals(5, de.getUpcomingMatches().size()); assertEquals(19, de.getPendingMatches().size()); } @Test public void losesMap01() { List<Team> teams = TestUtilities.getTestTeams(14, 1); DoubleEliminationFormat de = new DoubleEliminationFormat(); de.start(teams, true); // Play all matches except the last (the extra match) List<Series> series = de.getAllSeries(); for (int i = series.size() - 1; i > 0; i--) { series.get(i).setScores(1, 0, 0); series.get(i).setHasBeenPlayed(true); } // All matches have now been played, so all teams has 2 loses, except the winner HashMap<Team, Integer> losesMap = de.getLosesMap(); for (Team team : losesMap.keySet()) { if (team.getInitialSeedValue() == 1) { assertEquals(0, (int)losesMap.get(team)); } else { assertEquals(2, (int)losesMap.get(team)); } } } @Test public void topTeams01() { List<Team> teams = TestUtilities.getTestTeams(4, 1); DoubleEliminationFormat de = new DoubleEliminationFormat(); de.start(teams, true); // Play all matches except the last (the extra match) List<Series> series = de.getAllSeries(); for (int i = series.size() - 1; i > 0; i--) { Series serie = series.get(i); if (serie.getTeamOne().getInitialSeedValue() < serie.getTeamTwo().getInitialSeedValue()) { serie.setScores(1, 0, 0); } else { serie.setScores(0, 1, 0); } serie.setHasBeenPlayed(true); } List<Team> topTeams = de.getTopTeams(4, TieBreaker.GOALS_SCORED); for (int i = 0; i < topTeams.size(); i++) { assertSame(teams.get(i), topTeams.get(i)); } } @Test public void topTeams02() { List<Team> teams = TestUtilities.getTestTeams(32, 1); DoubleEliminationFormat de = new DoubleEliminationFormat(); de.start(teams, true); // Play all matches except the last (the extra match) List<Series> series = de.getAllSeries(); for (int i = series.size() - 1; i > 0; i--) { Series serie = series.get(i); if (serie.getTeamOne().getInitialSeedValue() < serie.getTeamTwo().getInitialSeedValue()) { serie.setScores(1, 0, 0); } else { serie.setScores(0, 1, 0); } serie.setHasBeenPlayed(true); } List<Team> topTeams = de.getTopTeams(8, TieBreaker.GOALS_SCORED); for (int i = 0; i < topTeams.size(); i++) { assertSame(teams.get(i), topTeams.get(i)); } } @Test public void stats01() { DoubleEliminationFormat de = new DoubleEliminationFormat(); List<Team> teams = TestUtilities.getTestTeams(4, 1); de.start(teams, true); // Play all matches. The highest seeded team wins 1-0 List<Series> allSeries = de.getAllSeries(); for (int matchIndex = allSeries.size() - 1; matchIndex > 0; matchIndex--) { Series series = allSeries.get(matchIndex); if (series.getTeamOne().getInitialSeedValue() < series.getTeamTwo().getInitialSeedValue()) { series.setScores(1, 0, 0); } else { series.setScores(0, 1, 0); } series.setHasBeenPlayed(true); } // Check if stats are as expected StatsTest.assertStats(teams.get(0), de, 3, 0, 3, 0); StatsTest.assertStats(teams.get(1), de, 2, 2, 2, 2); StatsTest.assertStats(teams.get(2), de, 1, 2, 1, 2); StatsTest.assertStats(teams.get(3), de, 0, 2, 0, 2); } }
10,037
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
SingleEliminationFormatTest.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/test/java/dk/aau/cs/ds306e18/tournament/model/format/SingleEliminationFormatTest.java
package dk.aau.cs.ds306e18.tournament.model.format; import dk.aau.cs.ds306e18.tournament.TestUtilities; import dk.aau.cs.ds306e18.tournament.model.Team; import dk.aau.cs.ds306e18.tournament.model.TieBreaker; import dk.aau.cs.ds306e18.tournament.model.match.Series; import dk.aau.cs.ds306e18.tournament.model.stats.StatsTest; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.*; public class SingleEliminationFormatTest { //there should be a correct amount of matches @Test public void amountOfMatchesTest01() { SingleEliminationFormat bracket = new SingleEliminationFormat(); bracket.start(TestUtilities.getTestTeams(8, 1), true); assertEquals(7, bracket.getAllSeries().size()); } //there should be a correct amount of matches @Test public void amountOfMatchesTest02() { SingleEliminationFormat bracket = new SingleEliminationFormat(); bracket.start(TestUtilities.getTestTeams(16, 1), true); assertEquals(15, bracket.getAllSeries().size()); } //final match should depend on all matches @Test public void dependsOnFinalMatch01() { SingleEliminationFormat bracket = new SingleEliminationFormat(); bracket.start(TestUtilities.getTestTeams(8, 1), true); List<Series> series = bracket.getAllSeries(); for (int n = 1; n < series.size(); n++) { assertTrue(series.get(0).dependsOn(series.get(n))); } } //final match should depend on all matches @Test public void dependsOnFinalMatch02() { SingleEliminationFormat bracket = new SingleEliminationFormat(); bracket.start(TestUtilities.getTestTeams(16, 1), true); List<Series> series = bracket.getAllSeries(); for (int n = 1; n < series.size(); n++) { assertTrue(series.get(0).dependsOn(series.get(n))); } } //final match should depend on all matches @Test public void dependsOnFinalMatch03() { SingleEliminationFormat bracket = new SingleEliminationFormat(); bracket.start(TestUtilities.getTestTeams(10, 1), true); List<Series> series = bracket.getAllSeries(); for (int n = 1; n < series.size(); n++) { assertTrue(series.get(0).dependsOn(series.get(n))); } } //The teams should be seeded correctly in first round @Test public void seedTest01() { List<Team> teamList = TestUtilities.getTestTeams(8, 1); SingleEliminationFormat bracket = new SingleEliminationFormat(); bracket.start(teamList, true); assertEquals(1, bracket.getAllSeries().get(bracket.getAllSeries().size() - 1).getTeamOne().getInitialSeedValue()); assertEquals(8, bracket.getAllSeries().get(bracket.getAllSeries().size() - 1).getTeamTwo().getInitialSeedValue()); assertEquals(4, bracket.getAllSeries().get(bracket.getAllSeries().size() - 2).getTeamOne().getInitialSeedValue()); assertEquals(5, bracket.getAllSeries().get(bracket.getAllSeries().size() - 2).getTeamTwo().getInitialSeedValue()); assertEquals(2, bracket.getAllSeries().get(bracket.getAllSeries().size() - 3).getTeamOne().getInitialSeedValue()); assertEquals(7, bracket.getAllSeries().get(bracket.getAllSeries().size() - 3).getTeamTwo().getInitialSeedValue()); assertEquals(3, bracket.getAllSeries().get(bracket.getAllSeries().size() - 4).getTeamOne().getInitialSeedValue()); assertEquals(6, bracket.getAllSeries().get(bracket.getAllSeries().size() - 4).getTeamTwo().getInitialSeedValue()); } //first match should be null, and best seeded team should be placed in next round @Test public void seedTest02() { SingleEliminationFormat bracket = new SingleEliminationFormat(); bracket.start(TestUtilities.getTestTeams(7, 1), true); assertNull(bracket.getMatchesAsArray()[6]); assertEquals(1, bracket.getMatchesAsArray()[2].getTeamOne().getInitialSeedValue()); } //match 3 should be null and snd seed should be placed in next round @Test public void seedTest03() { SingleEliminationFormat bracket = new SingleEliminationFormat(); bracket.start(TestUtilities.getTestTeams(6, 1), true); assertNull(bracket.getMatchesAsArray()[4]); assertEquals(2, bracket.getMatchesAsArray()[1].getTeamOne().getInitialSeedValue()); } //There should only be one match in first around, this should be the worst seeded teams. //The winner of this match should meet seed 1 @Test public void seedTest04() { SingleEliminationFormat bracket = new SingleEliminationFormat(); bracket.start(TestUtilities.getTestTeams(5, 1), true); assertNull(bracket.getMatchesAsArray()[6]); assertNull(bracket.getMatchesAsArray()[4]); assertNull(bracket.getMatchesAsArray()[3]); assertEquals(4, bracket.getMatchesAsArray()[5].getTeamOne().getInitialSeedValue()); assertEquals(5, bracket.getMatchesAsArray()[5].getTeamTwo().getInitialSeedValue()); } //Should return the correct amount of playable matches @Test public void upcomingMatchesTest01() { SingleEliminationFormat bracket = new SingleEliminationFormat(); bracket.start(TestUtilities.getTestTeams(8, 1), true); assertEquals(4, bracket.getUpcomingMatches().size()); Series series = bracket.getUpcomingMatches().get(0); series.setScores(1, 0, 0); series.setHasBeenPlayed(true); assertEquals(3, bracket.getUpcomingMatches().size()); } //Should return the correct amount of playable matches @Test public void upcomingMatchesTest02() { SingleEliminationFormat bracket = new SingleEliminationFormat(); bracket.start(TestUtilities.getTestTeams(6, 1), true); assertEquals(2, bracket.getUpcomingMatches().size()); } //Should return the correct amount of not-playable upcoming matches @Test public void pendingMatchesTest01() { SingleEliminationFormat bracket = new SingleEliminationFormat(); bracket.start(TestUtilities.getTestTeams(8, 1), true); assertEquals(3, bracket.getPendingMatches().size()); List<Series> allSeries = bracket.getAllSeries(); int seriesCount = allSeries.size(); allSeries.get(seriesCount - 1).setScores(1, 2, 0); allSeries.get(seriesCount - 1).setHasBeenPlayed(true); allSeries.get(seriesCount - 2).setScores(1, 2, 0); allSeries.get(seriesCount - 2).setHasBeenPlayed(true); assertEquals(2, bracket.getPendingMatches().size()); } //Should return the correct amount of played matches @Test public void completedMatchesTest01() { SingleEliminationFormat bracket = new SingleEliminationFormat(); bracket.start(TestUtilities.getTestTeams(8, 1), true); assertEquals(0, bracket.getCompletedMatches().size()); List<Series> allSeries = bracket.getAllSeries(); int seriesCount = allSeries.size(); allSeries.get(seriesCount - 1).setScores(1, 2, 0); allSeries.get(seriesCount - 1).setHasBeenPlayed(true); allSeries.get(seriesCount - 2).setScores(1, 2, 0); allSeries.get(seriesCount - 2).setHasBeenPlayed(true); assertEquals(2, bracket.getCompletedMatches().size()); } //Gets top 4 teams @Test public void getTopTeamsTest01() { SingleEliminationFormat bracket = generateBracketsAndWins(8); List<Team> teamList = new ArrayList<>(bracket.getTopTeams(4, TieBreaker.SEED)); int seedValue = 1; for (int i = 0; i < 4; i++) { assertEquals(seedValue, teamList.get(i).getInitialSeedValue()); seedValue++; } } //Gets top 6 teams @Test public void getTopTeamTest02() { SingleEliminationFormat bracket = generateBracketsAndWins(10); List<Team> teamList = new ArrayList<Team>(bracket.getTopTeams(6, TieBreaker.SEED)); int seedValue = 1; for (int i = 0; i < 6; i++) { assertEquals(seedValue, teamList.get(i).getInitialSeedValue()); seedValue++; } } //Tries to get top 10 teams in a 4 team stage, should only return 4 teams @Test public void getTopTeamTest03() { SingleEliminationFormat bracket = generateBracketsAndWins(5); List<Team> teamList = new ArrayList<Team>(bracket.getTopTeams(10, TieBreaker.SEED)); int seedValue = 1; for (int i = 0; i < 4; i++) { assertEquals(seedValue, teamList.get(i).getInitialSeedValue()); seedValue++; } } //StageStatus test pending-running-concluded @Test public void stageStatusTest01() { SingleEliminationFormat bracket = new SingleEliminationFormat(); assertEquals(StageStatus.PENDING, bracket.getStatus()); bracket.start(TestUtilities.getTestTeams(4, 1), true); assertEquals(StageStatus.RUNNING, bracket.getStatus()); bracket = generateBracketsAndWins(4); assertEquals(StageStatus.CONCLUDED, bracket.getStatus()); } //StageStatus should still be running if some matches has been played @Test public void stageStatusTest02() { SingleEliminationFormat bracket = new SingleEliminationFormat(); bracket.start(TestUtilities.getTestTeams(8, 1), true); List<Series> arrayList = bracket.getAllSeries(); arrayList.get(arrayList.size() - 1).setScores(1, 0, 0); arrayList.get(arrayList.size() - 1).setHasBeenPlayed(true); arrayList.get(arrayList.size() - 2).setScores(1, 0, 0); arrayList.get(arrayList.size() - 2).setHasBeenPlayed(true); assertEquals(StageStatus.RUNNING, bracket.getStatus()); } //Should throw exception if the match is not playable @Test(expected = IllegalStateException.class) public void unPlayableMatch() { SingleEliminationFormat bracket = new SingleEliminationFormat(); bracket.start(TestUtilities.getTestTeams(8, 1), true); bracket.getAllSeries().get(0).setScores(1, 0, 0); } //Should throw exception if the match is not playable @Test(expected = IllegalStateException.class) public void unPlayableMatch02() { SingleEliminationFormat bracket = new SingleEliminationFormat(); bracket.start(TestUtilities.getTestTeams(8, 1), true); bracket.getAllSeries().get(2).setHasBeenPlayed(true); } @Test public void withSeeding01() { int numberOfTeams = 4; List<Team> teams = TestUtilities.getTestTeams(numberOfTeams, 1); SingleEliminationFormat singleelimination = new SingleEliminationFormat(); singleelimination.start(teams, true); Series seriesOne = singleelimination.getAllSeries().get(2); assertSame(teams.get(0), seriesOne.getTeamOne()); assertSame(teams.get(3), seriesOne.getTeamTwo()); Series seriesTwo = singleelimination.getAllSeries().get(1); assertSame(teams.get(1), seriesTwo.getTeamOne()); assertSame(teams.get(2), seriesTwo.getTeamTwo()); } @Test public void withSeeding02() { int numberOfTeams = 8; List<Team> teams = TestUtilities.getTestTeams(numberOfTeams, 1); SingleEliminationFormat singleelimination = new SingleEliminationFormat(); singleelimination.start(teams, true); Series seriesOne = singleelimination.getAllSeries().get(6); assertSame(teams.get(0), seriesOne.getTeamOne()); assertSame(teams.get(7), seriesOne.getTeamTwo()); Series seriesTwo = singleelimination.getAllSeries().get(5); assertSame(teams.get(3), seriesTwo.getTeamOne()); assertSame(teams.get(4), seriesTwo.getTeamTwo()); Series seriesThree = singleelimination.getAllSeries().get(4); assertSame(teams.get(1), seriesThree.getTeamOne()); assertSame(teams.get(6), seriesThree.getTeamTwo()); Series seriesFour = singleelimination.getAllSeries().get(3); assertSame(teams.get(2), seriesFour.getTeamOne()); assertSame(teams.get(5), seriesFour.getTeamTwo()); } @Test public void withoutSeeding01() { int numberOfTeams = 4; List<Team> teams = TestUtilities.getTestTeams(numberOfTeams, 1); SingleEliminationFormat singleelimination = new SingleEliminationFormat(); singleelimination.start(teams, false); Series seriesOne = singleelimination.getAllSeries().get(2); assertSame(teams.get(0), seriesOne.getTeamOne()); assertSame(teams.get(1), seriesOne.getTeamTwo()); Series seriesTwo = singleelimination.getAllSeries().get(1); assertSame(teams.get(2), seriesTwo.getTeamOne()); assertSame(teams.get(3), seriesTwo.getTeamTwo()); } @Test public void withoutSeeding02() { int numberOfTeams = 8; List<Team> teams = TestUtilities.getTestTeams(numberOfTeams, 1); SingleEliminationFormat singleelimination = new SingleEliminationFormat(); singleelimination.start(teams, false); Series seriesOne = singleelimination.getAllSeries().get(6); assertSame(teams.get(0), seriesOne.getTeamOne()); assertSame(teams.get(1), seriesOne.getTeamTwo()); Series seriesTwo = singleelimination.getAllSeries().get(5); assertSame(teams.get(2), seriesTwo.getTeamOne()); assertSame(teams.get(3), seriesTwo.getTeamTwo()); Series seriesThree = singleelimination.getAllSeries().get(4); assertSame(teams.get(4), seriesThree.getTeamOne()); assertSame(teams.get(5), seriesThree.getTeamTwo()); Series seriesFour = singleelimination.getAllSeries().get(3); assertSame(teams.get(6), seriesFour.getTeamOne()); assertSame(teams.get(7), seriesFour.getTeamTwo()); } @Test public void matchIdentifiers01() { List<Team> teams = TestUtilities.getTestTeams(4, 1); SingleEliminationFormat singleElimination = new SingleEliminationFormat(); singleElimination.start(teams, true); List<Series> allSeries = singleElimination.getAllSeries(); assertEquals(3, allSeries.get(0).getIdentifier()); assertEquals(2, allSeries.get(1).getIdentifier()); assertEquals(1, allSeries.get(2).getIdentifier()); } @Test public void matchIdentifiers02() { List<Team> teams = TestUtilities.getTestTeams(6, 1); SingleEliminationFormat singleElimination = new SingleEliminationFormat(); singleElimination.start(teams, true); List<Series> allSeries = singleElimination.getAllSeries(); assertEquals(5, allSeries.get(0).getIdentifier()); assertEquals(4, allSeries.get(1).getIdentifier()); assertEquals(3, allSeries.get(2).getIdentifier()); assertEquals(2, allSeries.get(3).getIdentifier()); assertEquals(1, allSeries.get(4).getIdentifier()); } @Test public void stats01() { SingleEliminationFormat se = new SingleEliminationFormat(); List<Team> teams = TestUtilities.getTestTeams(4, 1); se.start(teams, true); // Play all matches. The highest seeded team wins 1-0 List<Series> allSeries = se.getAllSeries(); for (int matchIndex = allSeries.size() - 1; matchIndex >= 0; matchIndex--) { Series series = allSeries.get(matchIndex); if (series.getTeamOne().getInitialSeedValue() < series.getTeamTwo().getInitialSeedValue()) { series.setScores(1, 0, 0); } else { series.setScores(0, 1, 0); } series.setHasBeenPlayed(true); } // Check if stats are as expected StatsTest.assertStats(teams.get(0), se, 2, 0, 2, 0); StatsTest.assertStats(teams.get(1), se, 1, 1, 1, 1); StatsTest.assertStats(teams.get(2), se, 0, 1, 0, 1); StatsTest.assertStats(teams.get(3), se, 0, 1, 0, 1); } /** * Generates a bracket and sets wins according to the best seed * @param amountOfTeams the amount of teams */ public static SingleEliminationFormat generateBracketsAndWins(int amountOfTeams) { SingleEliminationFormat bracket = new SingleEliminationFormat(); bracket.start(TestUtilities.getTestTeams(amountOfTeams, 1), true); List<Series> allSeries = bracket.getAllSeries(); for (int matchIndex = allSeries.size() - 1; matchIndex >= 0; matchIndex--) { Series series = allSeries.get(matchIndex); if (series.getTeamOne().getInitialSeedValue() < series.getTeamTwo().getInitialSeedValue()) { series.setScores(1, 0, 0); } else { series.setScores(0, 1, 0); } series.setHasBeenPlayed(true); } return bracket; } }
16,900
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
RoundRobinFormatTest.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/test/java/dk/aau/cs/ds306e18/tournament/model/format/RoundRobinFormatTest.java
package dk.aau.cs.ds306e18.tournament.model.format; import dk.aau.cs.ds306e18.tournament.TestUtilities; import dk.aau.cs.ds306e18.tournament.model.Team; import dk.aau.cs.ds306e18.tournament.model.TieBreaker; import dk.aau.cs.ds306e18.tournament.model.match.Series; import dk.aau.cs.ds306e18.tournament.model.stats.StatsTest; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static dk.aau.cs.ds306e18.tournament.TestUtilities.*; import static org.junit.Assert.*; public class RoundRobinFormatTest { static int numberOfMatchesInRoundRobin(int x) { return x * (x - 1) / 2; } @Test public void start01() { int numberOfTeams = 4; int teamSize = 1; RoundRobinFormat rr = new RoundRobinFormat(); rr.start(getTestTeams(numberOfTeams, teamSize), true); assertEquals(rr.getStatus(), StageStatus.RUNNING); } @Test public void start02() { int numberOfTeams = 32; int teamSize = 1; RoundRobinFormat rr = new RoundRobinFormat(); rr.start(getTestTeams(numberOfTeams, teamSize), true); assertEquals(rr.getStatus(), StageStatus.RUNNING); } @Test public void findIdOfNextPlayer01() { int numberOfTeams = 20; int teamSize = 1; RoundRobinFormat rr = new RoundRobinFormat(); rr.start(getTestTeams(numberOfTeams, teamSize), true); assertEquals((rr.findIdOfNextTeam(3,numberOfTeams)), 13); assertEquals((rr.findIdOfNextTeam(1,numberOfTeams)), 11); for (int i = 1; i <= numberOfTeams; i++) { assertTrue(rr.findIdOfNextTeam(i,numberOfTeams) < numberOfTeams); assertTrue(rr.findIdOfNextTeam(i,numberOfTeams) > 0); if (i >= (numberOfTeams / 2)) { assertTrue(rr.findIdOfNextTeam(i, numberOfTeams) < i); } else assertTrue(rr.findIdOfNextTeam(i, numberOfTeams) > i); } } @Test public void getUpcomingMatches01() { //even 4 int numberOfTeams = 4; int teamSize = 1; RoundRobinFormat rr = new RoundRobinFormat(); rr.start(getTestTeams(numberOfTeams, teamSize), true); assertEquals(numberOfMatchesInRoundRobin(numberOfTeams), rr.getUpcomingMatches().size()); } @Test public void getUpcomingMatches02() { //even 6 int numberOfTeams = 6; int teamSize = 1; RoundRobinFormat rr = new RoundRobinFormat(); rr.start(getTestTeams(numberOfTeams, teamSize), true); assertEquals(numberOfMatchesInRoundRobin(numberOfTeams), rr.getUpcomingMatches().size()); } @Test public void getUpcomingMatches03() { //odd 5 int numberOfTeams = 5; int teamSize = 1; RoundRobinFormat rr = new RoundRobinFormat(); rr.start(getTestTeams(numberOfTeams, teamSize), true); assertEquals(numberOfMatchesInRoundRobin(numberOfTeams), rr.getUpcomingMatches().size()); } @Test public void getUpcomingMatches04() { // 0 teams int numberOfTeams = 0; int teamSize = 0; RoundRobinFormat rr = new RoundRobinFormat(); rr.start(getTestTeams(numberOfTeams, teamSize), true); assertEquals(0, rr.getUpcomingMatches().size()); } @Test public void getCompletedMatches01() { //non has been played int numberOfTeams = 4; int teamSize = 1; RoundRobinFormat rr = new RoundRobinFormat(); rr.start(getTestTeams(numberOfTeams, teamSize), true); assertEquals(0, rr.getCompletedMatches().size()); } @Test public void getCompletedMatches02() { //all has been played int numberOfTeams = 4; int teamSize = 1; RoundRobinFormat rr = new RoundRobinFormat(); rr.start(getTestTeams(numberOfTeams, teamSize), true); setAllMatchesToPlayed(rr.getUpcomingMatches()); assertEquals(numberOfMatchesInRoundRobin(numberOfTeams), rr.getCompletedMatches().size()); } @Test //more than 0 matches public void getAllMatches01() { int numberOfTeams = 4; int teamSize = 2; RoundRobinFormat rr = new RoundRobinFormat(); rr.start(getTestTeams(numberOfTeams, teamSize), true); assertEquals(numberOfMatchesInRoundRobin(numberOfTeams), rr.getAllSeries().size()); } @Test //0 matches public void getAllMatches02() { int numberOfTeams = 0; int teamSize = 2; RoundRobinFormat rr = new RoundRobinFormat(); rr.start(getTestTeams(numberOfTeams, teamSize), true); assertEquals(0, rr.getAllSeries().size()); } @Test public void getPendingMatches01() { int numberOfTeams = 4; int teamSize = 2; RoundRobinFormat rr = new RoundRobinFormat(); rr.start(getTestTeams(numberOfTeams, teamSize), true); assertEquals(0, rr.getPendingMatches().size()); } @Test public void getTopTeams01() { //No teams RoundRobinFormat rr = new RoundRobinFormat(); rr.start(new ArrayList<>(), true); assertEquals(0, rr.getTopTeams(0, TieBreaker.SEED).size()); } @Test public void getTopTeams02() { RoundRobinFormat rr = new RoundRobinFormat(); List<Team> teams = getTestTeams(7, 1); rr.start(teams, true); ArrayList<Team> top4Teams = new ArrayList<>(rr.getTopTeams(4, TieBreaker.SEED)); // Should match seeds when all have the same amount of points assertEquals(teams.get(0), top4Teams.get(0)); assertEquals(teams.get(1), top4Teams.get(1)); assertEquals(teams.get(2), top4Teams.get(2)); assertEquals(teams.get(3), top4Teams.get(3)); } @Test public void getTopTeams03() { RoundRobinFormat rr = new RoundRobinFormat(); List<Team> teams = getTestTeams(8, 1); rr.setNumberOfGroups(3); // group sizes: 2, 3, 3 rr.start(teams, true); // Assign goals equal to their seed, i.e. expected winner loses for (Series s : rr.getUpcomingMatches()) { int teamOneSeed = s.getTeamOne().getInitialSeedValue(); int teamTwoSeed = s.getTeamTwo().getInitialSeedValue(); s.setScores(teamOneSeed, teamTwoSeed, 0); s.setHasBeenPlayed(true); } ArrayList<Team> top7Teams = new ArrayList<>(rr.getTopTeams(7, TieBreaker.SEED)); // We expect: // 2 from group 0 // 3 from group 1 // 2 grom group 2 // And team 3 won't proceed as it is the loser of the last group assertEquals(teams.get(3), top7Teams.get(0)); assertEquals(teams.get(6), top7Teams.get(1)); assertEquals(teams.get(7), top7Teams.get(2)); assertEquals(teams.get(0), top7Teams.get(3)); assertEquals(teams.get(4), top7Teams.get(4)); assertEquals(teams.get(5), top7Teams.get(5)); assertEquals(teams.get(1), top7Teams.get(6)); } @Test public void getStatus01() { //Pending RoundRobinFormat rr = new RoundRobinFormat(); assertEquals(StageStatus.PENDING, rr.getStatus()); } @Test public void getStatus02() { //Running RoundRobinFormat rr = new RoundRobinFormat(); rr.start(getTestTeams(4, 2), true); assertEquals(StageStatus.RUNNING, rr.getStatus()); } @Test public void getStatus03() { //Concluded // max number of rounds and all played RoundRobinFormat rr = new RoundRobinFormat(); rr.start(getTestTeams(6, 2), true); setAllMatchesToPlayed(rr.getUpcomingMatches()); assertEquals(StageStatus.CONCLUDED, rr.getStatus()); } @Test public void groupSizes01() { //even group size, even number of teams in each group RoundRobinFormat rr = new RoundRobinFormat(); rr.setNumberOfGroups(2); rr.start(getTestTeams(12,2), true); assertEquals(2,rr.getGroups().size()); for (RoundRobinGroup group: rr.getGroups()) { assertEquals(6,group.getTeams().size()); assertEquals(15,group.getMatches().size()); } for (Series series : rr.getAllSeries()) { assertTrue(series.getTeamOne() != RoundRobinFormat.getDummyTeam() && series.getTeamTwo() != RoundRobinFormat.getDummyTeam()); } assertEquals(30,rr.getAllSeries().size()); assertNotSame(rr.getGroups().get(0), rr.getGroups().get(1)); } @Test public void groupSizes02() { //even group size, uneven number of teams in each group RoundRobinFormat rr = new RoundRobinFormat(); rr.setNumberOfGroups(2); rr.start(getTestTeams(10,2), true); assertEquals(2,rr.getGroups().size()); for (RoundRobinGroup group: rr.getGroups()) { assertEquals(5, group.getTeams().size()); assertEquals(10,group.getMatches().size()); } for (Series series : rr.getAllSeries()) { assertTrue(series.getTeamOne() != RoundRobinFormat.getDummyTeam() && series.getTeamTwo() != RoundRobinFormat.getDummyTeam()); } assertEquals(20,rr.getAllSeries().size()); assertNotSame(rr.getGroups().get(0), rr.getGroups().get(1)); } @Test public void groupSizes03() { //uneven group size, even number of teams in each group RoundRobinFormat rr = new RoundRobinFormat(); rr.setNumberOfGroups(3); rr.start(getTestTeams(18,2), true); assertEquals(3,rr.getGroups().size()); for (RoundRobinGroup group: rr.getGroups()) { assertEquals(6,group.getTeams().size()); assertEquals(15,group.getMatches().size()); } for (Series series : rr.getAllSeries()) { assertTrue(series.getTeamOne() != RoundRobinFormat.getDummyTeam() && series.getTeamTwo() != RoundRobinFormat.getDummyTeam()); } assertEquals(45,rr.getAllSeries().size()); assertNotSame(rr.getGroups().get(0), rr.getGroups().get(1)); assertNotSame(rr.getGroups().get(0), rr.getGroups().get(2)); } @Test public void groupSizes04() { //uneven group size, even number of teams in each group RoundRobinFormat rr = new RoundRobinFormat(); rr.setNumberOfGroups(3); rr.start(getTestTeams(10,2), true); assertEquals(3,rr.getGroups().size()); for (RoundRobinGroup group: rr.getGroups()) { if (group.getTeams().size() == 3) { assertEquals(3,group.getMatches().size()); } else if (group.getTeams().size() == 4) { assertEquals(6,group.getMatches().size()); } } for (Series series : rr.getAllSeries()) { assertTrue(series.getTeamOne() != RoundRobinFormat.getDummyTeam() && series.getTeamTwo() != RoundRobinFormat.getDummyTeam()); } assertEquals(12,rr.getAllSeries().size()); assertNotSame(rr.getGroups().get(0), rr.getGroups().get(1)); assertNotSame(rr.getGroups().get(0), rr.getGroups().get(2)); } @Test //more than 0 matches public void tooManyGroups() { int numberOfTeams = 10; int teamSize = 2; RoundRobinFormat rr = new RoundRobinFormat(); rr.setNumberOfGroups(20); rr.start(getTestTeams(numberOfTeams, teamSize), true); assertEquals(5, rr.getGroups().size()); } @Test //more than 0 matches public void tooFewGroups() { int numberOfTeams = 10; int teamSize = 2; RoundRobinFormat rr = new RoundRobinFormat(); rr.setNumberOfGroups(0); rr.start(getTestTeams(numberOfTeams, teamSize), true); assertEquals(1, rr.getGroups().size()); } @Test public void roundSizes01() { int numberOfTeams = 12; int numberOfGroups = 3; RoundRobinFormat rr = new RoundRobinFormat(); rr.setNumberOfGroups(numberOfGroups); rr.start(getTestTeams(numberOfTeams, 2), true); ArrayList<RoundRobinGroup> groups = rr.getGroups(); for (RoundRobinGroup group : groups) { assertEquals(3, group.getRounds().size()); for (ArrayList<Series> round : group.getRounds()) { assertEquals(2, round.size()); } } } @Test public void roundSizes02() { int numberOfTeams = 12; int numberOfGroups = 2; RoundRobinFormat rr = new RoundRobinFormat(); rr.setNumberOfGroups(numberOfGroups); rr.start(getTestTeams(numberOfTeams, 2), true); ArrayList<RoundRobinGroup> groups = rr.getGroups(); for (RoundRobinGroup group : groups) { assertEquals(5, group.getRounds().size()); for (ArrayList<Series> round : group.getRounds()) { assertEquals(3, round.size()); } } } @Test public void withSeeding01() { int numberOfTeams = 6; List<Team> teams = getTestTeams(numberOfTeams, 1); RoundRobinFormat roundrobin = new RoundRobinFormat(); roundrobin.setNumberOfGroups(2); roundrobin.start(teams, true); assertSame(teams.get(0), roundrobin.getGroups().get(0).getTeams().get(0)); assertSame(teams.get(2), roundrobin.getGroups().get(0).getTeams().get(1)); assertSame(teams.get(4), roundrobin.getGroups().get(0).getTeams().get(2)); assertSame(teams.get(1), roundrobin.getGroups().get(1).getTeams().get(0)); assertSame(teams.get(3), roundrobin.getGroups().get(1).getTeams().get(1)); assertSame(teams.get(5), roundrobin.getGroups().get(1).getTeams().get(2)); } @Test public void withSeeding02() { // with seeding and number of teams is not divisible by group count int numberOfTeams = 8; List<Team> teams = getTestTeams(numberOfTeams, 1); RoundRobinFormat roundrobin = new RoundRobinFormat(); roundrobin.setNumberOfGroups(3); roundrobin.start(teams, true); // Group 1 is seed 1 and 4 assertSame(teams.get(0), roundrobin.getGroups().get(0).getTeams().get(0)); assertSame(teams.get(3), roundrobin.getGroups().get(0).getTeams().get(1)); // Group 2 is seed 2, 5, and 7 assertSame(teams.get(1), roundrobin.getGroups().get(1).getTeams().get(0)); assertSame(teams.get(4), roundrobin.getGroups().get(1).getTeams().get(1)); assertSame(teams.get(6), roundrobin.getGroups().get(1).getTeams().get(2)); // Group 3 is seed 3, 6, and 8 assertSame(teams.get(2), roundrobin.getGroups().get(2).getTeams().get(0)); assertSame(teams.get(5), roundrobin.getGroups().get(2).getTeams().get(1)); assertSame(teams.get(7), roundrobin.getGroups().get(2).getTeams().get(2)); } @Test public void withoutSeeding01() { int numberOfTeams = 6; List<Team> teams = getTestTeams(numberOfTeams, 1); RoundRobinFormat roundrobin = new RoundRobinFormat(); roundrobin.setNumberOfGroups(2); roundrobin.start(teams, false); assertSame(teams.get(0), roundrobin.getGroups().get(0).getTeams().get(0)); assertSame(teams.get(1), roundrobin.getGroups().get(0).getTeams().get(1)); assertSame(teams.get(2), roundrobin.getGroups().get(0).getTeams().get(2)); assertSame(teams.get(3), roundrobin.getGroups().get(1).getTeams().get(0)); assertSame(teams.get(4), roundrobin.getGroups().get(1).getTeams().get(1)); assertSame(teams.get(5), roundrobin.getGroups().get(1).getTeams().get(2)); } @Test public void withoutSeeding02() { // without seeding and number of teams is not divisible by group count int numberOfTeams = 8; List<Team> teams = getTestTeams(numberOfTeams, 1); RoundRobinFormat roundrobin = new RoundRobinFormat(); roundrobin.setNumberOfGroups(3); roundrobin.start(teams, false); assertSame(teams.get(0), roundrobin.getGroups().get(0).getTeams().get(0)); assertSame(teams.get(1), roundrobin.getGroups().get(0).getTeams().get(1)); assertSame(teams.get(2), roundrobin.getGroups().get(1).getTeams().get(0)); assertSame(teams.get(3), roundrobin.getGroups().get(1).getTeams().get(1)); assertSame(teams.get(4), roundrobin.getGroups().get(1).getTeams().get(2)); assertSame(teams.get(5), roundrobin.getGroups().get(2).getTeams().get(0)); assertSame(teams.get(6), roundrobin.getGroups().get(2).getTeams().get(1)); assertSame(teams.get(7), roundrobin.getGroups().get(2).getTeams().get(2)); } @Test public void stats01() { RoundRobinFormat rr = new RoundRobinFormat(); List<Team> teams = TestUtilities.getTestTeams(4, 1); rr.start(teams, true); // Play all matches. The highest seeded team wins 1-0 for (Series series : rr.getAllSeries()) { if (series.getTeamOne().getInitialSeedValue() < series.getTeamTwo().getInitialSeedValue()) { series.setScores(1, 0, 0); } else { series.setScores(0, 1, 0); } series.setHasBeenPlayed(true); } // Check if stats are as expected StatsTest.assertStats(teams.get(0), rr, 3, 0, 3, 0); StatsTest.assertStats(teams.get(1), rr, 2, 1, 2, 1); StatsTest.assertStats(teams.get(2), rr, 1, 2, 1, 2); StatsTest.assertStats(teams.get(3), rr, 0, 3, 0, 3); } }
17,569
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
SeedingTest.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/test/java/dk/aau/cs/ds306e18/tournament/model/format/SeedingTest.java
package dk.aau.cs.ds306e18.tournament.model.format; import org.junit.Test; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; public class SeedingTest { @Test public void fairSeedList01() { List<Integer> list = Arrays.asList(1, 2, 3, 4); List<Integer> seededList = Seeding.fairSeedList(list); assertEquals(1, (int) seededList.get(0)); assertEquals(4, (int) seededList.get(1)); assertEquals(2, (int) seededList.get(2)); assertEquals(3, (int) seededList.get(3)); } @Test public void fairSeedList02() { List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8); List<Integer> seededList = Seeding.fairSeedList(list); assertEquals(1, (int) seededList.get(0)); assertEquals(8, (int) seededList.get(1)); assertEquals(4, (int) seededList.get(2)); assertEquals(5, (int) seededList.get(3)); assertEquals(2, (int) seededList.get(4)); assertEquals(7, (int) seededList.get(5)); assertEquals(3, (int) seededList.get(6)); assertEquals(6, (int) seededList.get(7)); } @Test public void simplePairwiseSeedList01() { List<Integer> list = Arrays.asList(1, 2, 3, 4); List<Integer> pairwiseList = Seeding.simplePairwiseSeedList(list); assertEquals(1, (int) pairwiseList.get(0)); assertEquals(4, (int) pairwiseList.get(1)); assertEquals(2, (int) pairwiseList.get(2)); assertEquals(3, (int) pairwiseList.get(3)); } @Test public void simplePairwiseSeedList02() { List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9); List<Integer> pairwiseList = Seeding.simplePairwiseSeedList(list); assertEquals(1, (int) pairwiseList.get(0)); assertEquals(9, (int) pairwiseList.get(1)); assertEquals(2, (int) pairwiseList.get(2)); assertEquals(8, (int) pairwiseList.get(3)); assertEquals(3, (int) pairwiseList.get(4)); assertEquals(7, (int) pairwiseList.get(5)); assertEquals(4, (int) pairwiseList.get(6)); assertEquals(6, (int) pairwiseList.get(7)); assertEquals(5, (int) pairwiseList.get(8)); } }
2,228
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
module-info.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/module-info.java
module cleopetra { requires javafx.controls; requires javafx.fxml; requires com.google.gson; requires org.controlsfx.controls; exports dk.aau.cs.ds306e18.tournament; opens dk.aau.cs.ds306e18.tournament.model; opens dk.aau.cs.ds306e18.tournament.model.format; opens dk.aau.cs.ds306e18.tournament.model.match; opens dk.aau.cs.ds306e18.tournament.model.stats; opens dk.aau.cs.ds306e18.tournament.rlbot; opens dk.aau.cs.ds306e18.tournament.rlbot.configuration; opens dk.aau.cs.ds306e18.tournament.serialization; opens dk.aau.cs.ds306e18.tournament.ui; opens dk.aau.cs.ds306e18.tournament.utility; }
653
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
Main.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/Main.java
package dk.aau.cs.ds306e18.tournament; import dk.aau.cs.ds306e18.tournament.settings.CleoPetraSettings; import dk.aau.cs.ds306e18.tournament.ui.LauncherController; import dk.aau.cs.ds306e18.tournament.utility.SaveLoad; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; public class Main extends Application { public static final System.Logger LOGGER = System.getLogger(Main.class.getName()); static { System.setProperty("java.util.logging.SimpleFormatter.format", "[%1$tT] %4$s: %5$s %n"); } @Override public void start(Stage primaryStage) throws Exception { List<String> args = getParameters().getRaw(); if (!args.isEmpty()) { final Path path = Paths.get(args.get(0)); if (path.toString().endsWith(".rlts") && Files.exists(path)) { SaveLoad.loadTournament(new File(path.toUri())); Stage systemStage = LauncherController.createSystemStage(); systemStage.show(); return; } } // Start program with the launcher AnchorPane launcherLoader = FXMLLoader.load(Main.class.getResource("ui/layout/Launcher.fxml")); primaryStage.setTitle("CleoPetra Launcher"); primaryStage.setScene(new Scene(launcherLoader)); primaryStage.setResizable(false); primaryStage.getIcons().add(new Image(Main.class.getResourceAsStream("ui/layout/images/logo.png"))); primaryStage.show(); } public static void main(String[] args) { CleoPetraSettings.setup(); launch(args); } }
1,863
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
TeamIdAdapter.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/serialization/TeamIdAdapter.java
package dk.aau.cs.ds306e18.tournament.serialization; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import dk.aau.cs.ds306e18.tournament.model.Team; import dk.aau.cs.ds306e18.tournament.model.Tournament; import java.io.IOException; /** * This adapter changes how teams are serialized. Instead of storing a copy of the team, this will instead store * the team's index based on the list of teams in the Tournament class. On deserialization the team in retrieved from * the same list. The list in the Tournament class overrides this behaviour with a TrueTeamListAdapter. */ public class TeamIdAdapter extends TypeAdapter<Team> { @Override public void write(JsonWriter out, Team team) throws IOException { // Determine the index of the team. Use -1 if team is null int id = -1; if (team != null) { id = Tournament.get().getTeams().indexOf(team); } // Store index out.value(id); } @Override public Team read(JsonReader in) throws IOException { // Read index int id = in.nextInt(); // Get the team from index if (id == -1) { return null; } else { return Tournament.get().getTeams().get(id); } } }
1,333
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
Serializer.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/serialization/Serializer.java
package dk.aau.cs.ds306e18.tournament.serialization; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import dk.aau.cs.ds306e18.tournament.model.Bot; import dk.aau.cs.ds306e18.tournament.model.Stage; import dk.aau.cs.ds306e18.tournament.model.Team; import dk.aau.cs.ds306e18.tournament.model.format.StageStatus; import dk.aau.cs.ds306e18.tournament.model.Tournament; import dk.aau.cs.ds306e18.tournament.model.format.Format; /** * SerializeManager handles all methods associated with serializing and deserializing a Tournament object */ public class Serializer { public static Gson gson = new GsonBuilder() //TODO; enable versioning .setVersion(int) .setPrettyPrinting() .enableComplexMapKeySerialization() // Enabling option to verbosely serialize round-map in SwissFormat .registerTypeAdapter(Format.class, new FormatAdapter()) // Handles Format inheritance .registerTypeAdapter(Team.class, new TeamIdAdapter()) // Stores teams by index based on list in Tournament class .registerTypeAdapter(Bot.class, new BotAdapter()) // Handles Bot inheritance and bot collection .create(); /** * Takes a tournament and returns the serialized object as a String * * @param tournament is the object to be serialized * @return JSON-string representation of given tournament parameter */ public static String serialize(Tournament tournament) { return gson.toJson(tournament); } /** * Takes a JSON-string representation of a Tournament object, deserializes it, repairs is, and returns it * * @param json the JSON-string representation * @return the reserialized Tournament object */ public static Tournament deserialize(String json) { Tournament tournament = gson.fromJson(json, Tournament.class); for (Stage stage : tournament.getStages()) { if (stage.getFormat().getStatus() != StageStatus.PENDING) { stage.getFormat().postDeserializationRepair(); } } return tournament; } }
2,127
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
FormatAdapter.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/serialization/FormatAdapter.java
package dk.aau.cs.ds306e18.tournament.serialization; import com.google.gson.*; import dk.aau.cs.ds306e18.tournament.Main; import dk.aau.cs.ds306e18.tournament.model.format.Format; import java.lang.reflect.Type; public class FormatAdapter implements JsonSerializer<Format>, JsonDeserializer<Format> { @Override public JsonElement serialize(Format src, Type typeOfSrc, JsonSerializationContext context) { JsonObject result = new JsonObject(); // denote type of class when serializing result.add("type", new JsonPrimitive(src.getClass().getSimpleName())); // append serialized context of class to json-object result.add("properties", context.serialize(src, src.getClass())); return result; } @Override public Format deserialize(JsonElement json, Type redundantType, JsonDeserializationContext context) { JsonObject jsonObject = json.getAsJsonObject(); // get SimpleName of class specified when serializing String type = jsonObject.get("type").getAsString(); // get all specified properties, that being fields withing specified class, JsonElement element = jsonObject.get("properties"); try { // specify location of classes, these are contained within root of the format package String thepackage = "dk.aau.cs.ds306e18.tournament.model.format."; // return the class found with given elements and class-type return context.deserialize(element, Class.forName(thepackage + type)); } catch (ClassNotFoundException e) { // if class has not been found, print error to user Main.LOGGER.log(System.Logger.Level.ERROR, "Error when deserializing stage format. Could not find package.", e); } return null; } }
1,816
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
BotAdapter.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/serialization/BotAdapter.java
package dk.aau.cs.ds306e18.tournament.serialization; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import dk.aau.cs.ds306e18.tournament.model.Bot; import dk.aau.cs.ds306e18.tournament.model.BotFromConfig; import dk.aau.cs.ds306e18.tournament.rlbot.configuration.BotSkill; import dk.aau.cs.ds306e18.tournament.model.PsyonixBotFromConfig; import dk.aau.cs.ds306e18.tournament.rlbot.BotCollection; import java.io.IOException; public class BotAdapter extends TypeAdapter<Bot> { @Override public void write(JsonWriter out, Bot value) throws IOException { out.beginObject(); // Bot is an interface, so we have to save the class in the json file out.name("class").value(value.getClass().getSimpleName()); // If the bot is based on a config file, just save the path to the config file if (value instanceof BotFromConfig) { BotFromConfig botFromConfig = (BotFromConfig) value; out.name("config").value(botFromConfig.getConfigPath()); if (value instanceof PsyonixBotFromConfig) { // For psyonix bots we also need to store the skill level PsyonixBotFromConfig psyonixBot = (PsyonixBotFromConfig) value; out.name("skill").value(psyonixBot.getBotSkill().getConfigValue()); } } out.endObject(); } @Override public Bot read(JsonReader in) throws IOException { in.beginObject(); in.nextName(); // This consumes the value's name, i.e. "class" in "class: BotFromConfig" String clazz = in.nextString(); if (PsyonixBotFromConfig.class.getSimpleName().equals(clazz)) { // Construct psyonix bot in.nextName(); String config = in.nextString(); in.nextName(); double skill = in.nextDouble(); in.endObject(); PsyonixBotFromConfig bot = new PsyonixBotFromConfig(config, BotSkill.getSkillFromNumber(skill)); // Add to BotCollection and return BotCollection.global.add(bot); return bot; } else if (BotFromConfig.class.getSimpleName().equals(clazz)) { // Construct bot from config in.nextName(); String config = in.nextString(); in.endObject(); BotFromConfig bot = new BotFromConfig(config); // Add to BotCollection and return BotCollection.global.add(bot); return bot; } in.endObject(); return null; // Unknown bot type } }
2,644
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
TrueTeamListAdapter.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/serialization/TrueTeamListAdapter.java
package dk.aau.cs.ds306e18.tournament.serialization; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import dk.aau.cs.ds306e18.tournament.model.Bot; import dk.aau.cs.ds306e18.tournament.model.Team; import java.io.IOException; import java.util.ArrayList; /** * This adapter is meant to override the behaviour of the TeamIdAdapter. The list of teams in the Tournament class * uses this adapter when serialized, which should be the only use of this. This adapter stores the actual teams in * a list, so the TeamIdAdapter can retrieve them again on deserialization. */ public class TrueTeamListAdapter extends TypeAdapter<ArrayList<Team>> { // Clean gson for teams (without turning them into id's) private final Gson teamSpecificGson = new GsonBuilder() .registerTypeAdapter(Bot.class, new BotAdapter()) .create(); @Override public void write(JsonWriter out, ArrayList<Team> value) throws IOException { // Construct array of actual teams out.beginArray(); for (Team team : value) { teamSpecificGson.toJson(team, Team.class, out); } out.endArray(); } @Override public ArrayList<Team> read(JsonReader in) throws IOException { ArrayList<Team> teams = new ArrayList<>(); // Re-construct ArrayList of teams in.beginArray(); while (!in.peek().equals(JsonToken.END_ARRAY)) { Team team = teamSpecificGson.fromJson(in, Team.class); team.postDeserializationRepair(); teams.add(team); } in.endArray(); return teams; } }
1,797
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
AutoNaming.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/utility/AutoNaming.java
package dk.aau.cs.ds306e18.tournament.utility; import dk.aau.cs.ds306e18.tournament.model.Bot; import dk.aau.cs.ds306e18.tournament.model.Team; import dk.aau.cs.ds306e18.tournament.model.Tournament; import java.util.*; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * Contains an algorithm for auto-naming teams using a piece of the team member's name. */ public class AutoNaming { private static final Set<String> IGNORED_PIECES = new HashSet<>(Arrays.asList( "bot", "psyonix", "a", "an", "the", "my", "that", "it", "of", "in", "as", "at", "on", "by", "for", "from", "to", "and", "or", "but" )); /** * Find a give a unique name of the given team. The name will consist of pieces from the * team members' name. */ public static void autoName(Team team, Collection<Team> otherTeams) { String teamName = getName(team); Set<String> otherTeamNames = otherTeams.stream() .filter(t -> t != team) .map(Team::getTeamName) .collect(Collectors.toSet()); teamName = uniquify(teamName, otherTeamNames); team.setTeamName(teamName); } /** * Checks if a team name is already present in a set of names, and if it is, a postfix "(i)" will * be added the end of the team name. E.g. "Team" already exist, then "Team" becomes "Team (1)". * The new unique name is returned. */ public static String uniquify(String teamName, Set<String> otherTeamsNames) { int i = 1; String candidateName = teamName; while (otherTeamsNames.contains(candidateName)) { i++; candidateName = teamName + " (" + i + ")"; } return candidateName; } /** * Finds a team name for the given team. The algorithm will try to find an * interesting piece from each bot's name and use it in the team name. * The algorithm isn't perfect, and characters other than letters and digits * can create weird names. * Example: ReliefBot + Beast from the East => Relief-Beast. */ public static String getName(Team team) { return getName(team.getBots().stream().map(Bot::getName).collect(Collectors.toList())); } /** * Finds a team name for the given list of bots. The algorithm will try to find an * interesting part from each bot's name and use it in the team name. * If there is only one unique name, that name will be used. * The algorithm isn't perfect, and characters other than letters and digits * can create weird names. * Example: ReliefBot + Beast from the East => Relief-Beast. */ public static String getName(List<String> botNames) { int botCount = botNames.size(); if (botCount == 0) return "Team"; if (botCount == 1) return botNames.get(0); // Check if there is only one unique name, in that case use that name long uniqueNames = botNames.stream().distinct().count(); if (uniqueNames == 1) return botNames.get(0); // Construct names from the short names of bots, separated by "-" // Example: ReliefBot + Beast from the East => Relief-Beast StringBuilder str = new StringBuilder(); for (int i = 0; i < botCount; i++) { String name = botNames.get(i); String shortName = getShortName(name); str.append(shortName); if (i != botCount - 1) { str.append("-"); } } return str.toString(); } /** * Finds a short name for the given bot name. The short name will be the first interesting "word" in * the bot's name. The function knows how to split logically ("ReliefBot" => "Relief" + "Bot") * and ignore common words ("of", "the", etc.). The algorithm isn't perfect, and characters * other than letters and digits can create weird names. */ public static String getShortName(String botName) { String[] pieces = getPieces(botName); Optional<String> shortName = Arrays.stream(pieces) // Remove pieces that are "Bot", "Psyonix", or common words like "of", "the", etc. .filter(s -> !IGNORED_PIECES.contains(s.toLowerCase())) // Remove substrings that are "bot", e.g. "Skybot" => "Sky" .map(s -> s.endsWith("bot") ? s.substring(0, s.length() - 3) : s) .findFirst(); return shortName.orElse(botName); } /** * Find all pieces of a name. */ private static String[] getPieces(String botName) { /* The following regex is used to split the bot name into pieces. The string is split the following places: - Between two letters or digits separated by spaces, regardless of casing (removing spaces) Examples: "A B" = ["A", "B"] "a b" = ["a", "b"] "2 a" = ["2", "a"] "A B" = ["A", "B"] "Air Bud" = ["Air", "Bud"] "Beast from the East" = ["Beast", "from", "the", "East"] - Between a letter (or digit) and an uppercase letter separated by -'s (removing the -'s) Examples: "A-B" = ["A", "B"] "A-b" = ["A-b"] "2-A" = ["2", "A"] "2-a" = ["2-a"] "2--A" = ["2", "A"] "2--a" = ["2--a"] "A-2" = ["A-2"] "Self-driving" = ["Self-driving"] - Between two chars where the first is lowercase or a digit and second is uppercase Examples: "AaB" = ["Aa", "B"] "2B" = ["2", "B"] "ReliefBot" = ["Relief", "Bot"] Since the split function removes what is matches, the regex uses positive lookbehind (?<=) and positive lookahead (?=) to check the characters around the split. Other characters than letters and digits will probably create errors, but they are rare in bot names, so it should be fine. Try it out on https://regex101.com */ return botName.split("(?<=[\\da-z])-*(?=[A-Z])|(?<=[\\da-zA-Z])\\ +(?=[\\da-zA-Z])"); } }
6,277
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
PowMath.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/utility/PowMath.java
package dk.aau.cs.ds306e18.tournament.utility; public class PowMath { /** Returns 2 to the power of n >= 0. */ public static int pow2(int n) { int res = 1; for (int i = 0; i < n; i++) { res *= 2; } return res; } /** Returns the 2-log of n ceiled to an integer. */ public static int log2(int n) { return (int) Math.ceil(Math.log(n) / Math.log(2)); } /** Returns true if the given number is a positive power of 2. */ public static boolean isPowOf2(int n) { // from https://codereview.stackexchange.com/a/172853 return n > 0 && ((n & (n - 1)) == 0); } }
659
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
OverlayData.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/utility/OverlayData.java
package dk.aau.cs.ds306e18.tournament.utility; import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; import dk.aau.cs.ds306e18.tournament.model.Bot; import dk.aau.cs.ds306e18.tournament.model.Tournament; import dk.aau.cs.ds306e18.tournament.model.match.Series; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * A data class to serialize data to overlay scripts. Contains data about team names and the bots on each team. */ public class OverlayData implements Serializable { public static final String CURRENT_MATCH_FILE_NAME = "current_match.json"; /** * Overlay data for an single bot */ static class OverlayBotData implements Serializable { @SerializedName("config_path") private final String configPath; @SerializedName("name") private final String name; @SerializedName("developer") private final String developer; @SerializedName("description") private final String description; @SerializedName("fun_fact") private final String funFact; @SerializedName("language") private final String language; @SerializedName("github") private final String github; public OverlayBotData(Bot bot) { this.configPath = bot.getConfigPath(); this.name = bot.getName(); this.developer = bot.getDeveloper(); this.description = bot.getDescription(); this.funFact = bot.getFunFact(); this.language = bot.getLanguage(); this.github = bot.getGitHub(); } } @SerializedName("blue_team_name") private final String blueTeamName; @SerializedName("orange_team_name") private final String orangeTeamName; @SerializedName("blue_bots") private final List<OverlayBotData> blueBots; @SerializedName("orange_bots") private final List<OverlayBotData> orangeBots; @SerializedName("series_length") private final int seriesLength; @SerializedName("blue_scores") private final List<Integer> blueScores; @SerializedName("orange_scores") private final List<Integer> orangeScores; @SerializedName("series_wins") private final List<Integer> seriesWins; // 0: blue won, 1: orange won, -1: unknown winner or draw public OverlayData(Series series) { blueTeamName = series.getBlueTeamAsString(); orangeTeamName = series.getOrangeTeamAsString(); blueBots = series.getBlueTeam().getBots().stream() .map(OverlayBotData::new) .collect(Collectors.toList()); orangeBots = series.getOrangeTeam().getBots().stream() .map(OverlayBotData::new) .collect(Collectors.toList()); seriesLength = series.getSeriesLength(); blueScores = series.getBlueScores().stream() .map(s -> s.orElse(-1)) .collect(Collectors.toList()); orangeScores = series.getOrangeScores().stream() .map(s -> s.orElse(-1)) .collect(Collectors.toList()); seriesWins = IntStream.range(0, seriesLength) .map(m -> { int blueScore = blueScores.get(m); int orangeScore = orangeScores.get(m); if (blueScore == -1 || orangeScore == -1 || blueScore == orangeScore) return -1; return blueScore > orangeScore ? 0 : 1; }) .boxed() .collect(Collectors.toList()); } /** * Write the overlay data to the location specified in RLBotSettings. */ public void write() throws IOException { String folderString = Tournament.get().getRlBotSettings().getOverlayPath(); if (folderString.isBlank()) throw new IOException("Overlay path is not set"); File folder = new File(folderString); if (!folder.exists()) throw new IOException("Overlay path does not exist"); if (!folder.isDirectory()) throw new IOException("Overlay path is not a directory"); Path path = new File(folder, CURRENT_MATCH_FILE_NAME).toPath(); Files.write(path, new Gson().toJson(this).getBytes()); } }
4,414
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
ListExt.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/utility/ListExt.java
package dk.aau.cs.ds306e18.tournament.utility; import java.util.List; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; public class ListExt { /** * Returns a list containing n elements of the supplied object. */ public static <T> List<T> nOf(int n, Supplier<T> generator) { return Stream.generate(generator).limit(n).collect(Collectors.toList()); } }
439
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
SaveLoad.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/utility/SaveLoad.java
package dk.aau.cs.ds306e18.tournament.utility; import dk.aau.cs.ds306e18.tournament.Main; import dk.aau.cs.ds306e18.tournament.model.Tournament; import dk.aau.cs.ds306e18.tournament.settings.CleoPetraSettings; import dk.aau.cs.ds306e18.tournament.settings.LatestPaths; import javafx.stage.FileChooser; import javafx.stage.Stage; import java.io.File; import java.io.IOException; import java.nio.file.Files; import static dk.aau.cs.ds306e18.tournament.serialization.Serializer.deserialize; import static dk.aau.cs.ds306e18.tournament.serialization.Serializer.serialize; public class SaveLoad { public static final String EXTENSION = "rlts"; /** * Opens a FileChooser and saves the Tournament singleton to the selected location, or does nothing if no * file is was selected. * @param fxstage the JavaFX Stage in control of the FileChooser. * @throws IOException thrown if something goes wrong during saving. */ public static void saveTournamentWithFileChooser(Stage fxstage) throws IOException { LatestPaths latestPaths = CleoPetraSettings.getLatestPaths(); FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Choose file name and save destination"); fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Tournament format (*." + EXTENSION + ")", "*." + EXTENSION)); fileChooser.setInitialFileName(Tournament.get().getName() + "." + EXTENSION); fileChooser.setInitialDirectory(latestPaths.getTournamentSaveDirectory()); File file = fileChooser.showSaveDialog(fxstage); if (file != null) { saveTournament(Tournament.get(), file); } } /** * Saves the given tournament to the given location. * @throws IOException thrown if something goes wrong during loading. */ public static void saveTournament(Tournament tournament, File file) throws IOException { CleoPetraSettings.getLatestPaths().setTournamentSaveDirectory(file.getParentFile()); Files.write(file.toPath(), serialize(tournament).getBytes()); Main.LOGGER.log(System.Logger.Level.INFO, "Tournament saved to " + file.getAbsolutePath()); } /** * Loads a tournament from a given file. * @return The loaded Tournament. * @throws IOException thrown if something goes wrong during loading. */ public static Tournament loadTournament(File file) throws IOException { CleoPetraSettings.getLatestPaths().setTournamentSaveDirectory(file.getParentFile()); Tournament tournament = deserialize(new String(Files.readAllBytes(file.toPath()))); if (tournament.getRlBotSettings().writeOverlayDataEnabled()) { CleoPetraSettings.getLatestPaths().setOverlayDirectory(new File(tournament.getRlBotSettings().getOverlayPath())); } Main.LOGGER.log(System.Logger.Level.INFO, "Tournament loaded from " + file.getAbsolutePath()); return tournament; } }
2,985
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
Alerts.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/utility/Alerts.java
package dk.aau.cs.ds306e18.tournament.utility; import javafx.geometry.Pos; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.scene.layout.AnchorPane; import javafx.util.Duration; import org.controlsfx.control.Notifications; public class Alerts { public static AnchorPane window = null; /** * Shows an information notification in the bottom right corner of the screen. Fades out after 3 seconds. * @param title The title of the notification. * @param text A short and precise explanation of the information wished to provide. */ public static void infoNotification (String title, String text){ Notifications.create() .title(title) .text(text) .graphic(null) .hideAfter(Duration.seconds(5)) .position(Pos.BOTTOM_RIGHT) .owner(window) .showInformation(); } /** * Shows an error notification in the bottom right corner of the screen. Fades out after 5 seconds. * @param title The title of the notification * @param text A short and precise explanation of the error. */ public static void errorNotification(String title, String text) { Notifications.create() .title(title) .text(text) .graphic(null) .hideAfter(Duration.seconds(8)) .position(Pos.BOTTOM_RIGHT) .owner(window) .showError(); } /** * Shows a confirmation box that requires the user to choose an option (OK or Cancel) * @param title The title of the alert. * @param text A short and precise explanation of the confirmation text. * @return Returns true if the user clicked OK, otherwise returns false. */ public static boolean confirmAlert(String title, String text){ Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle(title); alert.setHeaderText(null); alert.setContentText(text); alert.initOwner(window.getScene().getWindow()); return alert.showAndWait().get() == ButtonType.OK; } }
2,198
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
FileOperations.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/utility/FileOperations.java
package dk.aau.cs.ds306e18.tournament.utility; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; public class FileOperations { /** * Returns the file extension of a file. E.g. "folder/botname.cfg" returns "cfg". The method should also support * folders with dots in their name. */ public static String getFileExtension(File file) { String name = file.getName(); int i = name.lastIndexOf('.'); int p = Math.max(name.lastIndexOf('/'), name.lastIndexOf('\\')); if (i > p) { return name.substring(i + 1); } else { return ""; } } /** * Copies a file from source to destination, but only if the destination does not exist already. */ public static void copyIfMissing(Path source, Path destination) throws IOException { if (!Files.exists(destination)) { Files.copy(source, destination); } } /** * Copies a file from source to destination, but only if the destination does not exist already. */ public static void copyIfMissing(InputStream inputStream, Path destination) throws IOException { if (!Files.exists(destination)) { Files.copy(inputStream, destination); } } }
1,350
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
RLBotInstallation.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/rlbot/RLBotInstallation.java
package dk.aau.cs.ds306e18.tournament.rlbot; import java.nio.file.Path; import java.nio.file.Paths; public class RLBotInstallation { /** * @return The folder of bots called the RLBotPack. It is downloaded with the RLBotGUI. It is not guaranteed to * exist and can be null if APPDATA is not an environment variable. */ public static Path getPathToRLBotPack() { try { return Paths.get(System.getenv("APPDATA")).getParent().resolve("Local\\RLBotGUIX\\RLBotPackDeletable"); } catch (Exception e) { // Failed. Maybe we are on a Linux system return null; } } /** * @return The path to the Python installation that the RLBotGUI uses * (the new installation in %APPDATA%/Local/RLBotGUIX/...). It is not guaranteed to * exist and can be null if APPDATA is not an environment variable. */ public static Path getPathToPython() { try { return Paths.get(System.getenv("APPDATA")).getParent().resolve("Local\\RLBotGUIX\\Python311\\python.exe"); } catch (Exception e) { // Failed. Maybe we are on a Linux system return null; } } }
1,199
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
BotCollection.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/rlbot/BotCollection.java
package dk.aau.cs.ds306e18.tournament.rlbot; import dk.aau.cs.ds306e18.tournament.Main; import dk.aau.cs.ds306e18.tournament.model.Bot; import dk.aau.cs.ds306e18.tournament.model.BotFromConfig; import dk.aau.cs.ds306e18.tournament.model.PsyonixBotFromConfig; import dk.aau.cs.ds306e18.tournament.rlbot.configuration.BotSkill; import dk.aau.cs.ds306e18.tournament.settings.SettingsDirectory; import dk.aau.cs.ds306e18.tournament.utility.FileOperations; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.TreeSet; public class BotCollection extends TreeSet<Bot> { public static BotCollection global = new BotCollection(); public BotCollection() { super((a, b) -> { if (a == b) return 0; // Sort by bot type int diff = a.getBotType().ordinal() - b.getBotType().ordinal(); if (diff == 0) { // If type is the same, sort by bot name diff = a.getName().compareTo(b.getName()); if (diff == 0) { // If name is the same, sort by path diff = a.getConfigPath().compareTo(b.getConfigPath()); } } return diff; }); } /** * Add the default Psyonix bots to the bot collection. The bots will be loaded from the CleoPetra settings folder. * * @return returns true if succeeded. */ public boolean addPsyonixBots() { try { // Bots starting in the bot collection PsyonixBotFromConfig allstar = new PsyonixBotFromConfig(SettingsDirectory.PSYONIX_ALLSTAR.toString(), BotSkill.ALLSTAR); PsyonixBotFromConfig pro = new PsyonixBotFromConfig(SettingsDirectory.PSYONIX_PRO.toString(), BotSkill.PRO); PsyonixBotFromConfig rookie = new PsyonixBotFromConfig(SettingsDirectory.PSYONIX_ROOKIE.toString(), BotSkill.ROOKIE); addAll(Arrays.asList( allstar, pro, rookie )); return true; } catch (Exception e) { // Something went wrong. Report it, but continue Main.LOGGER.log(System.Logger.Level.ERROR, "Could not load default bots. Was SettingsDirectory::setup() called?", e); return false; } } /** * The RLBotGUI is able to download a pack filled with bots. If that pack is present, load it into the * bot collection. * * @return returns true if succeeded. */ public boolean addRLBotPackIfPresent() { try { // Get path to BotPack and try to load bots Path rlbotpackPath = RLBotInstallation.getPathToRLBotPack(); if (rlbotpackPath != null && Files.exists(rlbotpackPath)) { Main.LOGGER.log(System.Logger.Level.INFO, "Loading bots from RLBotGUI's BotPack."); return addAllBotsFromFolder(rlbotpackPath.toFile(), 10); } else { Main.LOGGER.log(System.Logger.Level.INFO, "RLBotGUI's BotPack does not exist."); } } catch (Exception e) { // Something went wrong. Report it, but continue Main.LOGGER.log(System.Logger.Level.ERROR, "Could not load bots for RLBotGUI's BotPack. Something went wrong.", e); } return false; } /** * Looks through a folder and all its sub-folders and adds all bots found to the bot collection. The bot must be a * bot config file that is a valid BotFromConfig bot. The method also provides a max depth that in can go in * sub-folders which ensures the search doesn't take too long. * @param folder The folder to be checked. * @param maxDepth the maximum depth that method can go in folders. * * @return returns true if a bot was found and added to the bot collection. */ public boolean addAllBotsFromFolder(File folder, int maxDepth) { boolean addedSomething = false; if (folder.isDirectory()) { File[] files = folder.listFiles(); if (files != null) { for (File file : files) { if (file.isDirectory() && maxDepth > 0) { // Check sub-folders using recursion addedSomething = addAllBotsFromFolder(file, maxDepth - 1) || addedSomething; } else if ("cfg".equals(FileOperations.getFileExtension(file)) && !"port.cfg".equals(file.getName()) && !"appearance.cfg".equals(file.getName())) { try { // Try to read bot BotFromConfig bot = new BotFromConfig(file.getAbsolutePath()); if (bot.loadedCorrectly()) { this.add(bot); addedSomething = true; } } catch (Exception e) { // Failed Main.LOGGER.log(System.Logger.Level.DEBUG, "Could not parse " + file.getName() + " as a bot.", e); } } } } } return addedSomething; } }
5,294
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
RLBotSettings.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/rlbot/RLBotSettings.java
package dk.aau.cs.ds306e18.tournament.rlbot; import dk.aau.cs.ds306e18.tournament.rlbot.configuration.MatchConfig; import java.util.Objects; /** * Settings related to the tournament or RLBot */ public class RLBotSettings { private MatchConfig matchConfig = new MatchConfig(); private boolean writeOverlayData = false; private String overlayPath = ""; private boolean useRLBotGUIPythonIfAvailable = true; public RLBotSettings() { } public RLBotSettings(MatchConfig matchConfig) { this.matchConfig = matchConfig; } public MatchConfig getMatchConfig() { return matchConfig; } public void setMatchConfig(MatchConfig matchConfig) { this.matchConfig = matchConfig; } public boolean writeOverlayDataEnabled() { return writeOverlayData; } public void setWriteOverlayData(boolean writeOverlayData) { this.writeOverlayData = writeOverlayData; } public String getOverlayPath() { return overlayPath; } public void setOverlayPath(String overlayPath) { this.overlayPath = overlayPath; } public boolean useRLBotGUIPythonIfAvailable() { return useRLBotGUIPythonIfAvailable; } public void setUseRLBotGUIPythonIfAvailable(boolean useRLBotGUIPythonIfAvailable) { this.useRLBotGUIPythonIfAvailable = useRLBotGUIPythonIfAvailable; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RLBotSettings that = (RLBotSettings) o; return writeOverlayData == that.writeOverlayData && Objects.equals(matchConfig, that.matchConfig); } @Override public int hashCode() { return Objects.hash(matchConfig, writeOverlayData); } }
1,841
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
MatchRunner.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/rlbot/MatchRunner.java
package dk.aau.cs.ds306e18.tournament.rlbot; import dk.aau.cs.ds306e18.tournament.Main; import dk.aau.cs.ds306e18.tournament.model.Bot; import dk.aau.cs.ds306e18.tournament.model.BotFromConfig; import dk.aau.cs.ds306e18.tournament.model.Tournament; import dk.aau.cs.ds306e18.tournament.model.match.Series; import dk.aau.cs.ds306e18.tournament.rlbot.configuration.MatchConfig; import dk.aau.cs.ds306e18.tournament.rlbot.configuration.ParticipantInfo; import dk.aau.cs.ds306e18.tournament.rlbot.configuration.TeamColor; import dk.aau.cs.ds306e18.tournament.settings.SettingsDirectory; import dk.aau.cs.ds306e18.tournament.utility.Alerts; import dk.aau.cs.ds306e18.tournament.utility.OverlayData; import java.io.*; import java.net.ConnectException; import java.net.Socket; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Optional; /** * This class maintains a RLBot runner process for starting matches. The runner process is the run.py running in * a separate command prompt. Communication between CleoPetra and the RLBot runner happens through a socket and * consists of simple commands like START, STOP, EXIT, which are defined in the subclass Command. If the RLBot runner * is not running when a command is issued, a new instance of the RLBot runner is started. */ public class MatchRunner { // The first %s will be replaced with the directory of the rlbot.cfg. // The second %s will be the drive 'C:' to change drive. // The third %s is the python installation path. private static final String COMMAND_FORMAT = "cmd.exe /c start cmd /c \"cd %s & %s & \"%s\" run.py\""; private static final String ADDR = "127.0.0.1"; private static final int PORT = 35353; // TODO Make user able to change the port in a settings file public static Optional<Integer> latestBlueScore = Optional.empty(); public static Optional<Integer> latestOrangeScore = Optional.empty(); private enum Command { START("START"), // Start the match described by the rlbot.cfg STOP("STOP"), // Stop the current match and all bot pids EXIT("EXIT"), // Close the run.py process FETCH("FETCH"); // Fetch the scores of the match private final String cmd; Command(String cmd) { this.cmd = cmd; } @Override public String toString() { return cmd; } } /** * Starts the given match in Rocket League. */ public static boolean startMatch(MatchConfig matchConfig, Series series) { // Checks settings and modifies rlbot.cfg file if everything is okay boolean ready = prepareMatch(matchConfig, series); if (!ready) { return false; } Main.LOGGER.log(System.Logger.Level.INFO, "Starting match in RLBot."); return sendCommandToRLBot(Command.START, true); } /** * Starts the RLBot runner, aka. the run.py, as a separate process in a separate cmd. * The runner might not be ready to accept commands immediately. This method returns true on success. */ public static boolean startRLBotRunner() { try { Alerts.infoNotification("Starting RLBot runner", "Attempting to start new instance of run.py for running matches."); Main.LOGGER.log(System.Logger.Level.INFO, "Starting RLBot runner. Attempting to start new instance of run.py for running matches."); String python = "python"; if (Tournament.get().getRlBotSettings().useRLBotGUIPythonIfAvailable()) { // Find python installation in RLBotGUI Path botPackPython = RLBotInstallation.getPathToPython(); if (botPackPython != null && Files.exists(botPackPython)) { python = botPackPython.toString(); Main.LOGGER.log(System.Logger.Level.INFO, "Found RLBotGUI python installation: " + python); } } Path pathToDirectory = SettingsDirectory.RUN_PY.getParent(); String cmd = String.format(COMMAND_FORMAT, pathToDirectory, pathToDirectory.toString().substring(0, 2), python); Main.LOGGER.log(System.Logger.Level.INFO, "Running command: " + cmd); Runtime.getRuntime().exec(cmd); return true; } catch (IOException e) { e.printStackTrace(); Alerts.errorNotification("Could not start RLBot runner", "Something went wrong starting the run.py."); Main.LOGGER.log(System.Logger.Level.ERROR, "Could not start RLBot runner. Something went wrong starting the run.py."); return false; } } public static boolean fetchScores() { return sendCommandToRLBot(Command.FETCH, false); } /** * Closes the RLBot runner. */ public static void closeRLBotRunner() { // If the command fails, the runner is probably not running anyway, so ignore any errors. sendCommandToRLBot(Command.EXIT, false); } /** * Stops the current match. */ public static void stopMatch() { sendCommandToRLBot(Command.STOP, false); } /** * Sends the given command to the RLBot runner. If the runner does not respond, this method will optionally * start a new RLBot runner instance and retry sending the command. If we believe the command was send * and received, this method returns true, otherwise false. */ private static boolean sendCommandToRLBot(Command cmd, boolean startRLBotIfMissingAndRetry) { Main.LOGGER.log(System.Logger.Level.INFO, "Sending command to RLBot runner: " + cmd.toString()); latestBlueScore = Optional.empty(); latestOrangeScore = Optional.empty(); try (Socket sock = new Socket(ADDR, PORT); PrintWriter writer = new PrintWriter(sock.getOutputStream(), true)) { writer.print(cmd.toString()); writer.flush(); Thread.sleep(80); // Fetching scores may take up to 60 ms // Parse answer BufferedReader reader = new BufferedReader(new InputStreamReader(sock.getInputStream())); String answer = reader.readLine(); if ("OK".equals(answer)) return true; else if ("ERR".equals(answer)) return false; else { // We fetched the scoreline then try { String[] split = answer.split(","); int blueScore = Integer.parseInt(split[0]); int orangeScore = Integer.parseInt(split[1]); latestBlueScore = Optional.of(blueScore); latestOrangeScore = Optional.of(orangeScore); return true; } catch (Exception ex) { throw new IllegalArgumentException("Unable to parse answer from run.py. \"" + answer + "\"", ex); } } } catch (ConnectException e) { // The run.py did not respond. Starting a new instance if allowed if (startRLBotIfMissingAndRetry) { try { startRLBotRunner(); Thread.sleep(200); // Retry return sendCommandToRLBot(cmd, false); } catch (InterruptedException ex) { ex.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); Alerts.errorNotification("IO Exception", "Failed to open socket and send message to run.py"); Main.LOGGER.log(System.Logger.Level.ERROR, "Failed to open socket and send message to run.py"); } catch (InterruptedException e) { e.printStackTrace(); } return false; } /** * Returns true if the given match can be started. */ public static boolean canStartMatch(Series series) { try { checkMatch(series); return true; } catch (IllegalStateException e) { return false; } } /** * Check the requirements for starting the match. Throws an IllegalStateException if anything is wrong. Does nothing * if everything is okay. */ private static void checkMatch(Series series) { // These methods throws IllegalStageException if anything is wrong checkBotConfigsInMatch(series); } /** * Throws an IllegalStateException if anything is wrong with the bots' config files for this match. Does nothing if * all the bots on both teams have a valid config file in a given match. */ private static void checkBotConfigsInMatch(Series series) { // Check if there are two teams if (series.getBlueTeam() == null) throw new IllegalStateException("There is no blue team for this match."); if (series.getOrangeTeam() == null) throw new IllegalStateException("There is no orange team for this match."); ArrayList<Bot> blueBots = series.getBlueTeam().getBots(); ArrayList<Bot> orangeBots = series.getOrangeTeam().getBots(); if (blueBots.size() == 0) throw new IllegalStateException("There are no bots on the blue team."); if (orangeBots.size() == 0) throw new IllegalStateException("There are no bots on the orange team."); ArrayList<Bot> bots = new ArrayList<>(); bots.addAll(blueBots); bots.addAll(orangeBots); for (Bot bot : bots) { String path = bot.getConfigPath(); // Check if BotFromConfig bots are loaded correctly if (bot instanceof BotFromConfig && !((BotFromConfig) bot).loadedCorrectly()) throw new IllegalStateException("The bot could not load from config: " + bot.getConfigPath()); // Check if bot cfg is set if (path == null || path.isEmpty()) throw new IllegalStateException("The bot '" + bot.getName() + "' has no config file."); // Check if bot cfg exists File file = new File(path); if (!file.exists() || !file.isFile() || file.isDirectory()) throw new IllegalStateException("The config file of the bot named '" + bot.getName() + "' is not found (path: '" + path + ")'"); } } /** * A pre-process for starting a match. This method will check if all config files are available and then modify the * rlbot.cfg to start the given match when rlbot is run. Returns false and shows an alert if something went wrong * during preparation. */ public static boolean prepareMatch(MatchConfig matchConfig, Series series) { try { // Check settings and config files checkMatch(series); insertParticipants(matchConfig, series); matchConfig.write(SettingsDirectory.MATCH_CONFIG.toFile()); // Write overlay data RLBotSettings settings = Tournament.get().getRlBotSettings(); if (settings.writeOverlayDataEnabled()) { try { OverlayData overlayData = new OverlayData(series); overlayData.write(); } catch (IOException e) { Path path = new File(settings.getOverlayPath(), OverlayData.CURRENT_MATCH_FILE_NAME).toPath(); Alerts.errorNotification("Could not write overlay data", "Failed to write overlay data to " + path); Main.LOGGER.log(System.Logger.Level.ERROR, "Could not write overlay data to " + path); e.printStackTrace(); } } Main.LOGGER.log(System.Logger.Level.INFO, "Updated match configuration (rlbot.cfg)."); return true; } catch (IllegalStateException e) { Alerts.errorNotification("Error occurred while configuring match", e.getMessage()); Main.LOGGER.log(System.Logger.Level.ERROR, "Error occurred while configuring match", e); } catch (IOException e) { Alerts.errorNotification("IO error occurred while configuring match", e.getMessage()); Main.LOGGER.log(System.Logger.Level.ERROR, "IO error occurred while configuring match", e); } return false; } /** * Inserts the participants in a match into the MatchConfig. Any existing participants in the MatchConfig will be * removed. */ private static void insertParticipants(MatchConfig config, Series series) { config.clearParticipants(); insertParticipantsFromTeam(config, series.getBlueTeam().getBots(), TeamColor.BLUE); insertParticipantsFromTeam(config, series.getOrangeTeam().getBots(), TeamColor.ORANGE); } /** * Inserts the participant info about each bot into the MatchConfig. The Bots in the array must be BotFromConfigs. */ private static void insertParticipantsFromTeam(MatchConfig config, ArrayList<Bot> bots, TeamColor color) { for (Bot bot : bots) { ParticipantInfo participant = new ParticipantInfo( bot.getBotSkill(), bot.getBotType(), color, ((BotFromConfig) bot).getConfig() ); config.addParticipant(participant); } } }
13,454
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
BotConfig.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/rlbot/configuration/BotConfig.java
package dk.aau.cs.ds306e18.tournament.rlbot.configuration; import java.io.File; import java.io.IOException; import java.util.Objects; /** * Class for reading from a bots config file. */ public class BotConfig { public final static String LOCATIONS_CONFIGURATION_HEADER = "Locations"; public final static String NAME = "name"; public final static String PYTHON_FILE = "python_file"; public final static String LOOKS_CONFIG = "looks_config"; public final static String DETAILS_CONFIGURATIONS_HEADER = "Details"; public final static String DEVELOPER = "developer"; public final static String DESCRIPTION = "description"; public final static String FUN_FACT = "fun_fact"; public final static String GITHUB = "github"; public final static String LANGUAGE = "language"; private File configFile; private String name; private File pythonFile; private File looksConfig; private String developer; private String description; private String funFact; private String github; private String language; public BotConfig(File configFile) throws IOException { this.configFile = configFile; ConfigFile config = new ConfigFile(configFile); // Ensuring BotConfig has required fields available if (!config.hasSection(LOCATIONS_CONFIGURATION_HEADER) || !config.hasValue(LOCATIONS_CONFIGURATION_HEADER, NAME) || !config.hasValue(LOCATIONS_CONFIGURATION_HEADER, PYTHON_FILE) || !config.hasValue(LOCATIONS_CONFIGURATION_HEADER, LOOKS_CONFIG)) { throw new IOException(configFile.toString() + " is missing fields in the " + LOCATIONS_CONFIGURATION_HEADER + " section and is probably not a bot."); } name = config.getString(LOCATIONS_CONFIGURATION_HEADER, NAME, ""); pythonFile = new File(config.getString(LOCATIONS_CONFIGURATION_HEADER, PYTHON_FILE, "")); looksConfig = new File(config.getString(LOCATIONS_CONFIGURATION_HEADER, LOOKS_CONFIG, "")); developer = config.getString(DETAILS_CONFIGURATIONS_HEADER, DEVELOPER, ""); description = config.getString(DETAILS_CONFIGURATIONS_HEADER, DESCRIPTION, ""); funFact = config.getString(DETAILS_CONFIGURATIONS_HEADER, FUN_FACT, ""); github = config.getString(DETAILS_CONFIGURATIONS_HEADER, GITHUB, ""); language = config.getString(DETAILS_CONFIGURATIONS_HEADER, LANGUAGE, ""); } public File getConfigFile() { return configFile; } public String getName() { return name; } public File getPythonFile() { return pythonFile; } public File getLooksConfig() { return looksConfig; } public String getDeveloper() { return developer; } public String getDescription() { return description; } public String getFunFact() { return funFact; } public String getGithub() { return github; } public String getLanguage() { return language; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; BotConfig botConfig = (BotConfig) o; return Objects.equals(configFile, botConfig.configFile) && Objects.equals(name, botConfig.name) && Objects.equals(pythonFile, botConfig.pythonFile) && Objects.equals(looksConfig, botConfig.looksConfig) && Objects.equals(developer, botConfig.developer) && Objects.equals(description, botConfig.description) && Objects.equals(funFact, botConfig.funFact) && Objects.equals(github, botConfig.github) && Objects.equals(language, botConfig.language); } @Override public int hashCode() { return Objects.hash(configFile, name, pythonFile, looksConfig, developer, description, funFact, github, language); } }
4,011
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
BotType.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/rlbot/configuration/BotType.java
package dk.aau.cs.ds306e18.tournament.rlbot.configuration; /** Enum over supported bot-types in the rlbot.cfg */ public enum BotType { HUMAN("human"), RLBOT("rlbot"), PSYONIX("psyonix"), PARTY_MEMBER_BOT("party_member_bot"); private String configValue; BotType(String configValue) { this.configValue = configValue; } public String getConfigValue() { return configValue; } public static BotType getTypeFromConfigValue(String typeValue) { for (BotType type : values()) { if (type.configValue.equals(typeValue)) { return type; } } return RLBOT; } @Override public String toString() { return this.configValue; } }
760
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
BotSkill.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/rlbot/configuration/BotSkill.java
package dk.aau.cs.ds306e18.tournament.rlbot.configuration; /** * Enum for bot skill values in the rlbot.cfg */ public enum BotSkill { ROOKIE("0.0"), PRO("0.5"), ALLSTAR("1.0"); private final String configValue; BotSkill(String configValue) { this.configValue = configValue; } public String getConfigValue() { return configValue; } /** * Turn a number into a valid skill type */ public static BotSkill getSkillFromNumber(double skill) { if (skill <= 0.0) return ROOKIE; if (skill <= 0.5) return PRO; return ALLSTAR; } }
620
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
MatchConfigOptions.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/rlbot/configuration/MatchConfigOptions.java
package dk.aau.cs.ds306e18.tournament.rlbot.configuration; import java.util.ArrayList; import java.util.Arrays; import java.util.Random; /** * Holds all the valid values for fields the MatchConfig file. Each one is represented by a enum consisting of two * strings: one to display in the UI, and one for it value in the config file. */ public class MatchConfigOptions { public enum GameMap { RANDOM_STANDARD("Random Standard Map", ""), DFH_STADIUM("DFH Stadium", "DFHStadium"), MANNFIELD("Mannfield", "Mannfield"), CHAMPIONS_FIELD("Champions Field", "ChampionsField"), URBAN_CENTRAL("Urban Central", "UrbanCentral"), BECKWITH_PARK("Beckwith Park", "BeckwithPark"), UTOPIA_COLISEUM("Utopia Coliseum", "UtopiaColiseum"), WASTELAND("Wasteland", "Wasteland"), NEO_TOKYO("Neo Tokyo", "NeoTokyo"), AQUADOME("Aquadome", "AquaDome"), STARBASE_ARC("Starbase Arc", "StarbaseArc"), FARMSTEAD("Farmstead", "Farmstead"), SALTY_SHORES("Salty Shores", "SaltyShores"), DFH_STADIUM_STORMY("DFH Stadium (stormy)", "DFHStadium_Stormy"), DFH_STADIUM_DAY("DFH Stadium (day)", "DFHStadium_Day"), MANNFIELD_STORMY("Mannfield (stormy)", "Mannfield_Stormy"), MANNFIELD_NIGHT("Mannfield (night)", "Mannfield_Night"), CHAMPIONS_FIELD_DAY("Champions Field (day)", "ChampionsField_Day"), BECKWITH_PARK_STORMY("Beckwith Park (stormy)", "BeckwithPark_Stormy"), BECKWITH_PARK_MIDNIGHT("Beckwith Park (midnight)", "BeckwithPark_Midnight"), URBAN_CENTRAL_NIGHT("Urban Central (night)", "UrbanCentral_Night"), URBAN_CENTRAL_DAWN("Urban Central (dawn)", "UrbanCentral_Dawn"), UTOPIA_COLISEUM_DUSK("Utopia Coliseum (dusk)", "UtopiaColiseum_Dusk"), DFH_STADIUM_SNOWY("DFH Stadium (snowy)", "DFHStadium_Snowy"), MANNFIELD_SNOWY("Mannfield (snowy)", "Mannfield_Snowy"), UTOPIA_COLISEUM_SNOWY("Utopia Coliseum (snowy)", "UtopiaColiseum_Snowy"), BADLANDS("Badlands", "Badlands"), BADLANDS_NIGHT("Badlands (night)", "Badlands_Night"), TOKYO_UNDERPASS("Tokyo Underpass", "TokyoUnderpass"), ARCTAGON("Arctagon", "Arctagon"), PILLARS("Pillars", "Pillars"), COSMIC("Cosmic", "Cosmic"), DOUBLE_GOAL("Double Goal", "DoubleGoal"), OCTAGON("Octagon", "Octagon"), UNDERPASS("Underpass", "Underpass"), UTOPIA_RETRO("Utopia Retro", "UtopiaRetro"), HOOPS_DUNK_HOUSE("Dunk House", "Hoops_DunkHouse"), DROPSHOT_CORE707("Core 707", "DropShot_Core707"), THROWBACK_STADIUM("Throwback Stadium", "ThrowbackStadium"), ; public final String guiName, configName; GameMap(String guiName, String configName) { this.guiName = guiName; this.configName = configName; } public static GameMap get(String value) { for (GameMap gm : values()) { if (gm.configName.equals(value)) return gm; } return CHAMPIONS_FIELD; } @Override public String toString() { return guiName; } public static final ArrayList<GameMap> standardMaps = new ArrayList<>(Arrays.asList( DFH_STADIUM, MANNFIELD, CHAMPIONS_FIELD, URBAN_CENTRAL, BECKWITH_PARK, UTOPIA_COLISEUM, WASTELAND, NEO_TOKYO, AQUADOME, STARBASE_ARC, FARMSTEAD, SALTY_SHORES, DFH_STADIUM_STORMY, DFH_STADIUM_DAY, MANNFIELD_STORMY, MANNFIELD_NIGHT, CHAMPIONS_FIELD_DAY, BECKWITH_PARK_STORMY, BECKWITH_PARK_MIDNIGHT, URBAN_CENTRAL_NIGHT, URBAN_CENTRAL_DAWN, UTOPIA_COLISEUM_DUSK, DFH_STADIUM_SNOWY, MANNFIELD_SNOWY, UTOPIA_COLISEUM_SNOWY )); public static GameMap getRandomStandardMap() { int index = new Random().nextInt(standardMaps.size()); return standardMaps.get(index); } } public enum GameMode { SOCCER("Soccer", "Soccer"), HOOPS("Hoops", "Hoops"), DROPSHOT("Dropshot", "Dropshot"), HOCKEY("Hockey", "Hockey"), RUMBLE("Rumble", "Rumble"), ; public final String guiName, configName; GameMode(String guiName, String configName) { this.guiName = guiName; this.configName = configName; } public static GameMode get(String value) { for (GameMode gm : values()) { if (gm.configName.equals(value)) return gm; } return SOCCER; } @Override public String toString() { return guiName; } } /* ------------------------- MUTATORS --------------------------- */ public enum MatchLength { FIVE_MINUTES("5 minutes", "5 Minutes"), TEN_MINUTES("10 minutes", "10 Minutes"), TWENTY_MINUTES("20 minutes", "20 Minutes"), UNLIMITED("Unlimited", "Unlimited"), ; public final String guiName, configName; MatchLength(String guiName, String configName) { this.guiName = guiName; this.configName = configName; } public static MatchLength get(String value) { for (MatchLength m : values()) { if (m.configName.equals(value)) return m; } return FIVE_MINUTES; } @Override public String toString() { return guiName; } } public enum MaxScore { UNLIMITED("Unlimited", "Unlimited"), ONE_GOAL("1 goal", "1 Goal"), THREE_GOALS("3 goals", "3 Goals"), FIVE_GOALS("5 goals", "5 Goals"), ; public final String guiName, configName; MaxScore(String guiName, String configName) { this.guiName = guiName; this.configName = configName; } public static MaxScore get(String value) { for (MaxScore m : values()) { if (m.configName.equals(value)) return m; } return UNLIMITED; } @Override public String toString() { return guiName; } } public enum Overtime { UNLIMITED("Unlimited", "Unlimited"), MAX_FIVE_MIN_FIRST_SCORE("Max 5 min, first Score", "+5 Max, First Score"), MAX_FIVE_MIN_RANDOM_TEAM("Max 5 min, random team", "+5 Max, Random Team"), ; public final String guiName, configName; Overtime(String guiName, String configName) { this.guiName = guiName; this.configName = configName; } public static Overtime get(String value) { for (Overtime m : values()) { if (m.configName.equals(value)) return m; } return UNLIMITED; } @Override public String toString() { return guiName; } } public enum GameSpeed { DEFAULT("Default", "Default"), SLOW_MO("Slo-mo", "Slo-mo"), TIME_WARP("Time warp", "Time warp"), ; public final String guiName, configName; GameSpeed(String guiName, String configName) { this.guiName = guiName; this.configName = configName; } public static GameSpeed get(String value) { for (GameSpeed m : values()) { if (m.configName.equals(value)) return m; } return DEFAULT; } @Override public String toString() { return guiName; } } public enum BallMaxSpeed { DEFAULT("Default", "Default"), SLOW("Slow", "Slow"), FAST("Fast", "Fast"), SUPER_FAST("Super fast", "Super Fast"), ; public final String guiName, configName; BallMaxSpeed(String guiName, String configName) { this.guiName = guiName; this.configName = configName; } public static BallMaxSpeed get(String value) { for (BallMaxSpeed m : values()) { if (m.configName.equals(value)) return m; } return DEFAULT; } @Override public String toString() { return guiName; } } public enum BallType { DEFAULT("Default", "Default"), CUBE("Cube", "Cube"), PUCK("Puck", "Puck"), BASKETBALL("Basketball", "Basketball"), ; public final String guiName, configName; BallType(String guiName, String configName) { this.guiName = guiName; this.configName = configName; } public static BallType get(String value) { for (BallType m : values()) { if (m.configName.equals(value)) return m; } return DEFAULT; } @Override public String toString() { return guiName; } } public enum BallWeight { DEFAULT("Default", "Default"), SUPER_LIGHT("Super light", "Super Light"), LIGHT("Light", "Light"), HEAVY("Heavy", "Heavy"), ; public final String guiName, configName; BallWeight(String guiName, String configName) { this.guiName = guiName; this.configName = configName; } public static BallWeight get(String value) { for (BallWeight m : values()) { if (m.configName.equals(value)) return m; } return DEFAULT; } @Override public String toString() { return guiName; } } public enum BallSize { DEFAULT("Default", "Default"), SMALL("Small", "Small"), LARGE("Large", "Large"), GIGANTIC("Gigantic", "Gigantic"), ; public final String guiName, configName; BallSize(String guiName, String configName) { this.guiName = guiName; this.configName = configName; } public static BallSize get(String value) { for (BallSize m : values()) { if (m.configName.equals(value)) return m; } return DEFAULT; } @Override public String toString() { return guiName; } } public enum BallBounciness { DEFAULT("Default", "Default"), LOW("Low", "Low"), HIGH("High", "High"), SUPER_HIGH("Super high", "Super High"), ; public final String guiName, configName; BallBounciness(String guiName, String configName) { this.guiName = guiName; this.configName = configName; } public static BallBounciness get(String value) { for (BallBounciness m : values()) { if (m.configName.equals(value)) return m; } return DEFAULT; } @Override public String toString() { return guiName; } } public enum BoostAmount { DEFAULT("Default", "Default"), UNLIMITED("Unlimited", "Unlimited"), RECHARGE_SLOW("Recharge (slow)", "Recharge (Slow)"), RECHARGE_FAST("Recharge (fast)", "Recharge (Fast)"), NO_BOOST("No boost", "No Boost"), ; public final String guiName, configName; BoostAmount(String guiName, String configName) { this.guiName = guiName; this.configName = configName; } public static BoostAmount get(String value) { for (BoostAmount m : values()) { if (m.configName.equals(value)) return m; } return DEFAULT; } @Override public String toString() { return guiName; } } public enum BoostStrength { TIMES_ONE("1x", "1x"), TIMES_ONE_AND_HALF("1.5x", "1.5x"), TIMES_TWO("2x", "2x"), TIMES_TEN("10x", "10x"), ; public final String guiName, configName; BoostStrength(String guiName, String configName) { this.guiName = guiName; this.configName = configName; } public static BoostStrength get(String value) { for (BoostStrength m : values()) { if (m.configName.equals(value)) return m; } return TIMES_ONE; } @Override public String toString() { return guiName; } } public enum RumblePowers { NONE("None", "None"), DEFAULT("Default", "Default"), SLOW("Slow", "Slow"), CIVILIZED("Civilized", "Civilized"), DESTRUCTION_DERBY("Destruction derby", "Destruction Derby"), SPRING_LOADED("Spring loaded", "Spring Loaded"), SPIKES_ONLY("Spikes only", "Spikes Only"), SPIKE_RUSH("Spike rush", "Spike Rush") ; public final String guiName, configName; RumblePowers(String guiName, String configName) { this.guiName = guiName; this.configName = configName; } public static RumblePowers get(String value) { for (RumblePowers m : values()) { if (m.configName.equals(value)) return m; } return NONE; } @Override public String toString() { return guiName; } } public enum Gravity { DEFAULT("Default", "Default"), LOW("Low", "Low"), HIGH("High", "High"), SUPER_HIGH("Super high", "Super High"), ; public final String guiName, configName; Gravity(String guiName, String configName) { this.guiName = guiName; this.configName = configName; } public static Gravity get(String value) { for (Gravity m : values()) { if (m.configName.equals(value)) return m; } return DEFAULT; } @Override public String toString() { return guiName; } } public enum Demolish { DEFAULT("Default", "Default"), DISABLED("Disabled", "Disabled"), FRIENDLY_FIRE("Friendly fire", "Friendly Fire"), ON_CONTACT("On contact", "On Contact"), ON_CONTACT_AND_FRIENDLY_FIRE("On contact (FF)", "On Contact (FF)"), ; public final String guiName, configName; Demolish(String guiName, String configName) { this.guiName = guiName; this.configName = configName; } public static Demolish get(String value) { for (Demolish m : values()) { if (m.configName.equals(value)) return m; } return DEFAULT; } @Override public String toString() { return guiName; } } public enum RespawnTime { THREE_SECONDS("3 seconds", "3 Seconds"), TWO_SECONDS("2 seconds", "2 Seconds"), ONE_SECOND("1 second", "1 Second"), DISABLE_GOAL_RESET("No goal reset", "Disable Goal Reset"), ; public final String guiName, configName; RespawnTime(String guiName, String configName) { this.guiName = guiName; this.configName = configName; } public static RespawnTime get(String value) { for (RespawnTime m : values()) { if (m.configName.equals(value)) return m; } return THREE_SECONDS; } @Override public String toString() { return guiName; } } }
16,018
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
ConfigFile.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/rlbot/configuration/ConfigFile.java
package dk.aau.cs.ds306e18.tournament.rlbot.configuration; import java.io.*; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Abstraction of a '.cfg'-file. * Can parse files like this: https://docs.python.org/3/library/configparser.html#supported-ini-file-structure * except indent sections and keys. * Inspired by: https://stackoverflow.com/a/15638381 */ public class ConfigFile { // Matches section headers like "[Details]" private final Pattern sectionPattern = Pattern.compile("\\[([^\\[\\]]*)\\]\\s*"); // Matches key-value pairs "key = value", the delimiter can be both '=' or ':' and the value can be omitted for null private final Pattern keyValuePattern = Pattern.compile("([^=:]*)(=|:)(.*)"); // Matches subsequent lines of multi-line values. These always start with indentation // It uses "[^\S\r\n]+" as indent pattern to not consume empty lines private final Pattern multiLineValuePattern = Pattern.compile("[^\\S\\r\\n]+(.*)"); // Matches empty lines and comments which start with '#' or ';' private final Pattern commentAndEmptyPattern = Pattern.compile("\\s*[#;].*|\\s*"); private Map<String, Map<String, String>> entries = new HashMap<>(); /** * Create empty ConfigFile. */ public ConfigFile() { } /** * Create ConfigFile based on a the entries of a config file. * @param file the file to parse. * @throws IOException */ public ConfigFile(File file) throws IOException { load(file); } /** * Fills this ConfigFile with the entries from the given config file. * @param file the config file to parse. * @throws IOException */ public void load(File file) throws IOException { try (BufferedReader br = new BufferedReader(new FileReader(file))) { int lineNumber = 0; String line; Map<String, String> currentSectionMap = null; String key = null; StringBuilder value = null; Matcher m; while ((line = br.readLine()) != null) { lineNumber++; // Parse potential multiline value (next line has indentation) if (key != null) { m = multiLineValuePattern.matcher(line); if (m.matches()) { value.append(" ").append(m.group(1).trim()); continue; } else { // No more lines of value. Store key value pair currentSectionMap.put(key, value.toString().trim()); key = null; value = null; } } // Ignore comments and empty lines m = commentAndEmptyPattern.matcher(line); if (m.matches()) { continue; } // Section m = sectionPattern.matcher(line); if (m.matches()) { String section = m.group(1).trim(); currentSectionMap = entries.computeIfAbsent(section, k -> new HashMap<>()); continue; } if (currentSectionMap != null) { // Key value pair m = keyValuePattern.matcher(line); if (m.matches()) { key = m.group(1).trim(); value = new StringBuilder(m.group(3).trim()); // key value pair is stored if next line shows that it is not a multiline value continue; } } throw new IOException("Incorrect format in config file (error at line " + lineNumber + ": " + file.toString() + ")."); } // Store last key value pair (happens when file does not end with a newline character) if (key != null) { currentSectionMap.put(key, value.toString().trim()); } } } /** * Write this config to the given file. * @param file */ public void write(File file) throws IOException { try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) { Set<String> sections = entries.keySet(); for (String section : sections) { // Section name bw.write("["); bw.write(section); bw.write("]"); bw.newLine(); Map<String, String> keyValuePairs = entries.get(section); Set<String> keys = keyValuePairs.keySet(); for (String key : keys) { // Key value pair bw.write(key); bw.write(" = "); bw.write(keyValuePairs.get(key)); bw.newLine(); } bw.newLine(); } } } /** * @return true if the given section exists. */ public boolean hasSection(String section) { Map<String, String> sectionMap = entries.get(section); return sectionMap != null; } /** * Creates a section if it does not exist. * @param section the name of the section */ public void createSection(String section) { entries.computeIfAbsent(section, k -> new HashMap<>()); } /** * @return true if the value exists. */ public boolean hasValue(String section, String key) { Map<String, String> sectionMap = entries.get(section); if (sectionMap == null) return false; return sectionMap.containsKey(key); } /** * Sets the given entry to the given value. * @param section the name of the section * @param key the name of the key * @param value the value */ public void set(String section, String key, String value) { Map<String, String> sectionMap = entries.computeIfAbsent(section, k -> new HashMap<>()); sectionMap.put(key, value); } /** * Sets the given entry to the given value. * @param section the name of the section * @param key the name of the key * @param value the value */ public void set(String section, String key, int value) { set(section, key, String.valueOf(value)); } /** * Sets the given entry to the given value. * @param section the name of the section * @param key the name of the key * @param value the value */ public void set(String section, String key, float value) { set(section, key, String.valueOf(value)); } /** * Sets the given entry to the given value. * @param section the name of the section * @param key the name of the key * @param value the value */ public void set(String section, String key, double value) { set(section, key, String.valueOf(value)); } /** * Sets the given entry to the given value. * @param section the name of the section * @param key the name of the key * @param value the value */ public void set(String section, String key, boolean value) { set(section, key, String.valueOf(value)); } /** * Returns the requested value as a string. If the entry does not exist, {@code defaultValue} is return instead. * @param section the name of the section * @param key the name of the key * @param defaultValue alternative return value * @return the requested value or {@code defaultValue} if the entry does not exist. */ public String getString(String section, String key, String defaultValue) { Map<String, String> sectionMap = entries.get(section); if (sectionMap == null) return defaultValue; String value = sectionMap.get(key); if (value == null) return defaultValue; return value; } /** * Returns the requested value as an integer. If the entry does not exist, {@code defaultValue} is return instead. * @param section the name of the section * @param key the name of the key * @param defaultValue alternative return value * @return the requested value or {@code defaultValue} if the entry does not exist. */ public int getInt(String section, String key, int defaultValue) { String value = getString(section, key, null); if (value == null) return defaultValue; return Integer.parseInt(value); } /** * Returns the requested value as a float. If the entry does not exist, {@code defaultValue} is return instead. * @param section the name of the section * @param key the name of the key * @param defaultValue alternative return value * @return the requested value or {@code defaultValue} if the entry does not exist. */ public float getFloat(String section, String key, float defaultValue) { String value = getString(section, key, null); if (value == null) return defaultValue; return Float.parseFloat(value); } /** * Returns the requested value as a double. If the entry does not exist, {@code defaultValue} is return instead. * @param section the name of the section * @param key the name of the key * @param defaultValue alternative return value * @return the requested value or {@code defaultValue} if the entry does not exist. */ public double getDouble(String section, String key, double defaultValue) { String value = getString(section, key, null); if (value == null) return defaultValue; return Double.parseDouble(value); } /** * Returns the requested value as a boolean. If the entry does not exist, {@code defaultValue} is return instead. * @param section the name of the section * @param key the name of the key * @param defaultValue alternative return value * @return the requested value or {@code defaultValue} if the entry does not exist. */ public boolean getBoolean(String section, String key, boolean defaultValue) { String value = getString(section, key, null); if (value == null) return defaultValue; return Boolean.parseBoolean(value); } }
10,402
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
ParticipantInfo.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/rlbot/configuration/ParticipantInfo.java
package dk.aau.cs.ds306e18.tournament.rlbot.configuration; import java.util.Objects; public class ParticipantInfo { private BotSkill skill; private BotType type; private TeamColor team; private BotConfig config; public ParticipantInfo(BotSkill skill, BotType type, TeamColor team, BotConfig config) { this.skill = skill; this.type = type; this.team = team; this.config = config; } public BotSkill getSkill() { return skill; } public void setSkill(BotSkill skill) { this.skill = skill; } public BotType getType() { return type; } public void setType(BotType type) { this.type = type; } public TeamColor getTeam() { return team; } public void setTeam(TeamColor team) { this.team = team; } public BotConfig getConfig() { return config; } public void setConfig(BotConfig config) { this.config = config; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ParticipantInfo that = (ParticipantInfo) o; return skill == that.skill && type == that.type && team == that.team && Objects.equals(config, that.config); } @Override public int hashCode() { return Objects.hash(skill, type, team, config); } }
1,483
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
TeamColor.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/rlbot/configuration/TeamColor.java
package dk.aau.cs.ds306e18.tournament.rlbot.configuration; /** * Enum for representation of teams in the rlbot.cfg */ public enum TeamColor { BLUE(0), ORANGE(1); private final int configValue; TeamColor(int configValue) { this.configValue = configValue; } public int getConfigValue() { return configValue; } public static TeamColor getFromInt(int index) { return index == 1 ? ORANGE : BLUE; } }
458
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
MatchConfig.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/rlbot/configuration/MatchConfig.java
package dk.aau.cs.ds306e18.tournament.rlbot.configuration; import dk.aau.cs.ds306e18.tournament.rlbot.configuration.MatchConfigOptions.*; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * Class for interfacing with a match config (usually called rlbot.cfg). */ public class MatchConfig { public final static String MATCH_CONFIGURATION_HEADER = "Match Configuration"; public final static String PARTICIPANT_COUNT_KEY = "num_participants"; public final static String GAME_MODE = "game_mode"; public final static String GAME_MAP = "game_map"; public final static String SKIP_REPLAYS = "skip_replays"; public final static String INSTANT_START = "start_without_countdown"; public final static String ENABLE_RENDERING = "enable_rendering"; public final static String ENABLE_STATE_SETTING = "enable_state_setting"; public final static String AUTO_SAVE_REPLAYS = "auto_save_replay"; public final static String PARTICIPANTS_CONFIGURATION_HEADER = "Participant Configuration"; public final static String PARTICIPANT_CONFIG_INDEXED = "participant_config_"; public final static String PARTICIPANT_TEAM_INDEXD = "participant_team_"; public final static String PARTICIPANT_TYPE_INDEXD = "participant_type_"; public final static String PARTICIPANT_SKILL_INDEXD = "participant_bot_skill_"; public final static String MUTATOR_CONFIGURATION_HEADER = "Mutator Configuration"; public final static String MUTATOR_MATCH_LENGTH = "Match Length"; public final static String MUTATOR_MAX_SCORE = "Max Score"; public final static String MUTATOR_OVERTIME = "Overtime"; public final static String MUTATOR_GAME_SPEED = "Game Speed"; public final static String MUTATOR_BALL_MAX_SPEED = "Ball Max Speed"; public final static String MUTATOR_BALL_TYPE = "Ball Type"; public final static String MUTATOR_BALL_WEIGHT = "Ball Weight"; public final static String MUTATOR_BALL_SIZE = "Ball Size"; public final static String MUTATOR_BALL_BOUNCINESS = "Ball Bounciness"; public final static String MUTATOR_BOOST_AMOUNT = "Boost Amount"; public final static String MUTATOR_RUMBLE = "Rumble"; public final static String MUTATOR_BOOST_STRENGTH = "Boost Strength"; public final static String MUTATOR_GRAVITY = "Gravity"; public final static String MUTATOR_DEMOLISH = "Demolish"; public final static String MUTATOR_RESPAWN_TIME = "Respawn Time"; private File configFile; private GameMap gameMap = GameMap.RANDOM_STANDARD; private GameMode gameMode = GameMode.SOCCER; private boolean skipReplays = false; private boolean instantStart = false; private boolean renderingEnabled = false; private boolean stateSettingEnabled = false; private boolean autoSaveReplays = false; private final List<ParticipantInfo> participants = new ArrayList<>(); private MatchLength matchLength = MatchLength.FIVE_MINUTES; private MaxScore maxScore = MaxScore.UNLIMITED; private Overtime overtime = Overtime.UNLIMITED; private GameSpeed gameSpeed = GameSpeed.DEFAULT; private BallMaxSpeed ballMaxSpeed = BallMaxSpeed.DEFAULT; private BallType ballType = BallType.DEFAULT; private BallWeight ballWeight = BallWeight.DEFAULT; private BallSize ballSize = BallSize.DEFAULT; private BallBounciness ballBounciness = BallBounciness.DEFAULT; private BoostAmount boostAmount = BoostAmount.DEFAULT; private BoostStrength boostStrength = BoostStrength.TIMES_ONE; private RumblePowers rumblePowers = RumblePowers.NONE; private Gravity gravity = Gravity.DEFAULT; private Demolish demolish = Demolish.DEFAULT; private RespawnTime respawnTime = RespawnTime.THREE_SECONDS; public MatchConfig() { } public MatchConfig(File configFile) throws IOException { this.configFile = configFile; ConfigFile config = new ConfigFile(configFile); // Load match settings gameMap = GameMap.get(config.getString(MATCH_CONFIGURATION_HEADER, GAME_MAP, gameMap.configName)); gameMode = GameMode.get(config.getString(MATCH_CONFIGURATION_HEADER, GAME_MODE, gameMode.configName)); skipReplays = config.getBoolean(MUTATOR_CONFIGURATION_HEADER, SKIP_REPLAYS, skipReplays); instantStart = config.getBoolean(MUTATOR_CONFIGURATION_HEADER, INSTANT_START, instantStart); // Load mutators matchLength = MatchLength.get(config.getString(MUTATOR_CONFIGURATION_HEADER, MUTATOR_MATCH_LENGTH, matchLength.configName)); maxScore = MaxScore.get(config.getString(MUTATOR_CONFIGURATION_HEADER, MUTATOR_MAX_SCORE, maxScore.configName)); overtime = Overtime.get(config.getString(MUTATOR_CONFIGURATION_HEADER, MUTATOR_OVERTIME, overtime.configName)); ballMaxSpeed = BallMaxSpeed.get(config.getString(MUTATOR_CONFIGURATION_HEADER, MUTATOR_BALL_MAX_SPEED, ballMaxSpeed.configName)); gameSpeed = GameSpeed.get(config.getString(MUTATOR_CONFIGURATION_HEADER, MUTATOR_GAME_SPEED, gameSpeed.configName)); ballType = BallType.get(config.getString(MUTATOR_CONFIGURATION_HEADER, MUTATOR_BALL_TYPE, ballType.configName)); ballWeight = BallWeight.get(config.getString(MUTATOR_CONFIGURATION_HEADER, MUTATOR_BALL_WEIGHT, ballWeight.configName)); ballSize = BallSize.get(config.getString(MUTATOR_CONFIGURATION_HEADER, MUTATOR_BALL_SIZE, ballSize.configName)); ballBounciness = BallBounciness.get(config.getString(MUTATOR_CONFIGURATION_HEADER, MUTATOR_BALL_BOUNCINESS, ballBounciness.configName)); boostAmount = BoostAmount.get(config.getString(MUTATOR_CONFIGURATION_HEADER, MUTATOR_BOOST_AMOUNT, boostAmount.configName)); boostStrength = BoostStrength.get(config.getString(MUTATOR_CONFIGURATION_HEADER, MUTATOR_BOOST_STRENGTH, boostStrength.configName)); rumblePowers = RumblePowers.get(config.getString(MUTATOR_CONFIGURATION_HEADER, MUTATOR_RUMBLE, rumblePowers.configName)); gravity = Gravity.get(config.getString(MUTATOR_CONFIGURATION_HEADER, MUTATOR_GRAVITY, gravity.configName)); demolish = Demolish.get(config.getString(MUTATOR_CONFIGURATION_HEADER, MUTATOR_DEMOLISH, demolish.configName)); respawnTime = RespawnTime.get(config.getString(MUTATOR_CONFIGURATION_HEADER, MUTATOR_RESPAWN_TIME, respawnTime.configName)); // Load participants int numParticipants = config.getInt(MATCH_CONFIGURATION_HEADER, PARTICIPANT_COUNT_KEY, 2); for (int i = 0; i < numParticipants; i++) { // Load the bot config file. It something fails, skip this bot. BotConfig botConfig; try { File botConfigFile = new File(config.getString(PARTICIPANTS_CONFIGURATION_HEADER, PARTICIPANT_CONFIG_INDEXED, "")); if (!botConfigFile.isAbsolute()) { botConfigFile = new File(configFile.getParentFile(), botConfigFile.toString()); } botConfig = new BotConfig(botConfigFile); } catch (Exception e) { botConfig = null; } // Load other participant info BotSkill skill = BotSkill.getSkillFromNumber(config.getDouble(PARTICIPANTS_CONFIGURATION_HEADER, PARTICIPANT_SKILL_INDEXD, 1.0)); BotType type = BotType.getTypeFromConfigValue(config.getString(PARTICIPANTS_CONFIGURATION_HEADER, PARTICIPANT_TYPE_INDEXD, "rlbot")); TeamColor color = TeamColor.getFromInt(config.getInt(PARTICIPANTS_CONFIGURATION_HEADER, PARTICIPANT_TEAM_INDEXD, 0)); ParticipantInfo participant = new ParticipantInfo(skill, type, color, botConfig); addParticipant(participant); } } /** * Write this MatchConfig to the given file. * @param file * @throws IOException */ public void write(File file) throws IOException { this.configFile = file; ConfigFile config = new ConfigFile(); // Select a random map if selected map is RANDOM_STANDARD String map = gameMap == GameMap.RANDOM_STANDARD ? GameMap.getRandomStandardMap().configName : gameMap.configName; // Match settings config.createSection(MATCH_CONFIGURATION_HEADER); config.set(MATCH_CONFIGURATION_HEADER, GAME_MAP, map); config.set(MATCH_CONFIGURATION_HEADER, GAME_MODE, gameMode.configName); config.set(MATCH_CONFIGURATION_HEADER, SKIP_REPLAYS, skipReplays); config.set(MATCH_CONFIGURATION_HEADER, INSTANT_START, instantStart); config.set(MATCH_CONFIGURATION_HEADER, ENABLE_RENDERING, renderingEnabled); config.set(MATCH_CONFIGURATION_HEADER, ENABLE_STATE_SETTING, stateSettingEnabled); config.set(MATCH_CONFIGURATION_HEADER, AUTO_SAVE_REPLAYS, autoSaveReplays); config.set(MATCH_CONFIGURATION_HEADER, PARTICIPANT_COUNT_KEY, participants.size()); // Mutators config.createSection(MUTATOR_CONFIGURATION_HEADER); config.set(MUTATOR_CONFIGURATION_HEADER, MUTATOR_MATCH_LENGTH, matchLength.configName); config.set(MUTATOR_CONFIGURATION_HEADER, MUTATOR_MAX_SCORE, maxScore.configName); config.set(MUTATOR_CONFIGURATION_HEADER, MUTATOR_OVERTIME, overtime.configName); config.set(MUTATOR_CONFIGURATION_HEADER, MUTATOR_GAME_SPEED, gameSpeed.configName); config.set(MUTATOR_CONFIGURATION_HEADER, MUTATOR_BALL_MAX_SPEED, ballMaxSpeed.configName); config.set(MUTATOR_CONFIGURATION_HEADER, MUTATOR_BALL_TYPE, ballType.configName); config.set(MUTATOR_CONFIGURATION_HEADER, MUTATOR_BALL_WEIGHT, ballWeight.configName); config.set(MUTATOR_CONFIGURATION_HEADER, MUTATOR_BALL_SIZE, ballSize.configName); config.set(MUTATOR_CONFIGURATION_HEADER, MUTATOR_BALL_BOUNCINESS, ballBounciness.configName); config.set(MUTATOR_CONFIGURATION_HEADER, MUTATOR_BOOST_AMOUNT, boostAmount.configName); config.set(MUTATOR_CONFIGURATION_HEADER, MUTATOR_BOOST_STRENGTH, boostStrength.configName); config.set(MUTATOR_CONFIGURATION_HEADER, MUTATOR_RUMBLE, rumblePowers.configName); config.set(MUTATOR_CONFIGURATION_HEADER, MUTATOR_GRAVITY, gravity.configName); config.set(MUTATOR_CONFIGURATION_HEADER, MUTATOR_DEMOLISH, demolish.configName); config.set(MUTATOR_CONFIGURATION_HEADER, MUTATOR_RESPAWN_TIME, respawnTime.configName); // Participants config.createSection(PARTICIPANTS_CONFIGURATION_HEADER); for (int i = 0; i < participants.size(); i++) { ParticipantInfo participant = participants.get(i); config.set(PARTICIPANTS_CONFIGURATION_HEADER, PARTICIPANT_CONFIG_INDEXED + i, participant.getConfig().getConfigFile().toString()); config.set(PARTICIPANTS_CONFIGURATION_HEADER, PARTICIPANT_TYPE_INDEXD + i, participant.getType().getConfigValue()); config.set(PARTICIPANTS_CONFIGURATION_HEADER, PARTICIPANT_SKILL_INDEXD + i, participant.getSkill().getConfigValue()); config.set(PARTICIPANTS_CONFIGURATION_HEADER, PARTICIPANT_TEAM_INDEXD + i, participant.getTeam().getConfigValue()); } config.write(file); } public GameMap getGameMap() { return gameMap; } public void setGameMap(GameMap gameMap) { this.gameMap = gameMap; } public GameMode getGameMode() { return gameMode; } public void setGameMode(GameMode gameMode) { this.gameMode = gameMode; } public boolean isSkipReplays() { return skipReplays; } public void setSkipReplays(boolean skipReplays) { this.skipReplays = skipReplays; } public boolean isInstantStart() { return instantStart; } public void setInstantStart(boolean instantStart) { this.instantStart = instantStart; } public boolean isRenderingEnabled() { return renderingEnabled; } public void setRenderingEnabled(boolean renderingEnabled) { this.renderingEnabled = renderingEnabled; } public boolean isStateSettingEnabled() { return stateSettingEnabled; } public void setStateSettingEnabled(boolean stateSettingEnabled) { this.stateSettingEnabled = stateSettingEnabled; } public boolean isAutoSaveReplays() { return autoSaveReplays; } public void setAutoSaveReplays(boolean autoSaveReplays) { this.autoSaveReplays = autoSaveReplays; } public List<ParticipantInfo> getParticipants() { return participants; } public void addParticipant(ParticipantInfo participant) { participants.add(participant); } public void clearParticipants() { participants.clear(); } public MatchLength getMatchLength() { return matchLength; } public void setMatchLength(MatchLength matchLength) { this.matchLength = matchLength; } public MaxScore getMaxScore() { return maxScore; } public void setMaxScore(MaxScore maxScore) { this.maxScore = maxScore; } public Overtime getOvertime() { return overtime; } public void setOvertime(Overtime overtime) { this.overtime = overtime; } public GameSpeed getGameSpeed() { return gameSpeed; } public void setGameSpeed(GameSpeed gameSpeed) { this.gameSpeed = gameSpeed; } public BallMaxSpeed getBallMaxSpeed() { return ballMaxSpeed; } public void setBallMaxSpeed(BallMaxSpeed ballMaxSpeed) { this.ballMaxSpeed = ballMaxSpeed; } public BallType getBallType() { return ballType; } public void setBallType(BallType ballType) { this.ballType = ballType; } public BallWeight getBallWeight() { return ballWeight; } public void setBallWeight(BallWeight ballWeight) { this.ballWeight = ballWeight; } public BallSize getBallSize() { return ballSize; } public void setBallSize(BallSize ballSize) { this.ballSize = ballSize; } public BallBounciness getBallBounciness() { return ballBounciness; } public void setBallBounciness(BallBounciness ballBounciness) { this.ballBounciness = ballBounciness; } public BoostAmount getBoostAmount() { return boostAmount; } public void setBoostAmount(BoostAmount boostAmount) { this.boostAmount = boostAmount; } public BoostStrength getBoostStrength() { return boostStrength; } public void setBoostStrength(BoostStrength boostStrength) { this.boostStrength = boostStrength; } public RumblePowers getRumblePowers() { return rumblePowers; } public void setRumblePowers(RumblePowers rumblePowers) { this.rumblePowers = rumblePowers; } public Gravity getGravity() { return gravity; } public void setGravity(Gravity gravity) { this.gravity = gravity; } public Demolish getDemolish() { return demolish; } public void setDemolish(Demolish demolish) { this.demolish = demolish; } public RespawnTime getRespawnTime() { return respawnTime; } public void setRespawnTime(RespawnTime respawnTime) { this.respawnTime = respawnTime; } public File getConfigFile() { return configFile; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MatchConfig that = (MatchConfig) o; return skipReplays == that.skipReplays && instantStart == that.instantStart && Objects.equals(configFile, that.configFile) && gameMap == that.gameMap && gameMode == that.gameMode && Objects.equals(participants, that.participants) && matchLength == that.matchLength && maxScore == that.maxScore && overtime == that.overtime && gameSpeed == that.gameSpeed && ballMaxSpeed == that.ballMaxSpeed && ballType == that.ballType && ballWeight == that.ballWeight && ballSize == that.ballSize && ballBounciness == that.ballBounciness && boostAmount == that.boostAmount && boostStrength == that.boostStrength && rumblePowers == that.rumblePowers && gravity == that.gravity && demolish == that.demolish && respawnTime == that.respawnTime; } @Override public int hashCode() { return Objects.hash(configFile, gameMap, gameMode, skipReplays, instantStart, participants, matchLength, maxScore, overtime, gameSpeed, ballMaxSpeed, ballType, ballWeight, ballSize, ballBounciness, boostAmount, boostStrength, rumblePowers, gravity, demolish, respawnTime); } }
17,044
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
ExitProgramController.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/ui/ExitProgramController.java
package dk.aau.cs.ds306e18.tournament.ui; import dk.aau.cs.ds306e18.tournament.Main; import dk.aau.cs.ds306e18.tournament.utility.Alerts; import dk.aau.cs.ds306e18.tournament.utility.SaveLoad; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.input.MouseEvent; import javafx.stage.Stage; import java.io.IOException; public class ExitProgramController extends DraggablePopupWindow { @FXML private Button cancelBtn; @FXML void cancelClose(ActionEvent event) { Stage exitStage = (Stage) cancelBtn.getScene().getWindow(); exitStage.close(); } @FXML void exitProgram(ActionEvent event) { System.exit(0); } @FXML public void saveTournament() { /* TODO: Handle if filechooser was closed during selection */ Stage stage = (Stage) cancelBtn.getScene().getWindow(); try { SaveLoad.saveTournamentWithFileChooser(stage); System.exit(0); } catch (IOException e) { e.printStackTrace(); Alerts.errorNotification("Error while saving", "Something went wrong while saving the tournament: " + e.getMessage()); Main.LOGGER.log(System.Logger.Level.ERROR, "Error while saving tournament", e); } } @FXML public void windowDragged(MouseEvent mouseEvent) { super.windowDragged(mouseEvent); } @FXML public void windowPressed(MouseEvent mouseEvent) { super.windowPressed(mouseEvent); } }
1,544
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
SeriesVisualController.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/ui/SeriesVisualController.java
package dk.aau.cs.ds306e18.tournament.ui; import dk.aau.cs.ds306e18.tournament.model.match.Series; import dk.aau.cs.ds306e18.tournament.model.Team; import dk.aau.cs.ds306e18.tournament.model.match.MatchChangeListener; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.HBox; import java.util.List; import java.util.Optional; public class SeriesVisualController implements MatchChangeListener { @FXML private HBox matchRoot; @FXML private Label identifierLabel; @FXML private AnchorPane identifierHolder; @FXML private Label textTeamTwoName; @FXML private HBox teamOneScoreContainer; @FXML private Label textTeamOneName; @FXML private HBox teamTwoScoreContainer; @FXML private HBox hboxTeamTwo; @FXML private HBox hboxTeamOne; private BracketOverviewTabController boc; private Series showedSeries; private boolean showIdentifier = false; private boolean disabled = false; @FXML private void initialize() { } /** Gets called when a match is clicked. */ @FXML void matchClicked(MouseEvent event) { if (!disabled) { matchRoot.getStyleClass().add("selectedMatch"); boc.setSelectedSeries(this); if (showedSeries.isReadyToPlay() && event.getButton().equals(MouseButton.PRIMARY) && event.getClickCount() == 2) { boc.openEditMatchPopup(); } } } /** Used to set the BracketOverviewController. Is used to ref that this is clicked/Selected. */ public void setBoc(BracketOverviewTabController boc){ this.boc = boc; } /** Clears the visuals match for both text and css. */ private void clearFields(){ matchRoot.setId(""); hboxTeamOne.getStyleClass().clear(); hboxTeamTwo.getStyleClass().clear(); textTeamOneName.setText(" "); textTeamTwoName.setText(" "); teamOneScoreContainer.getChildren().clear(); teamTwoScoreContainer.getChildren().clear(); } /** @return the match that this shows. */ public Series getShowedSeries() { return showedSeries; } /** Updates the state/ui of this match. */ public void setShowedSeries(Series series){ if (showedSeries != null) showedSeries.unregisterMatchChangeListener(this); showedSeries = series; showedSeries.registerMatchChangeListener(this); updateFields(); } @Override public void onMatchChanged(Series series) { updateFields(); } public void updateFields() { clearFields(); if (showedSeries == null) { return; } // Show identifier if (showIdentifier) { identifierHolder.setVisible(true); identifierHolder.setManaged(true); identifierLabel.setText("" + showedSeries.getIdentifier()); } else { identifierHolder.setVisible(false); identifierHolder.setManaged(false); } Series.Status status = showedSeries.getStatus(); Team teamOne = showedSeries.getTeamOne(); Team teamTwo = showedSeries.getTeamTwo(); // Set tags and id based on the given match and its status if (disabled) { // css id matchRoot.setId("disabled"); setupBlankScores(teamOneScoreContainer, showedSeries.getSeriesLength()); setupBlankScores(teamTwoScoreContainer, showedSeries.getSeriesLength()); } else if (status == Series.Status.NOT_PLAYABLE) { // css id matchRoot.setId("pending"); // Show known team or where they come from textTeamOneName.setText(showedSeries.getTeamOneAsString()); textTeamTwoName.setText(showedSeries.getTeamTwoAsString()); setupBlankScores(teamOneScoreContainer, showedSeries.getSeriesLength()); setupBlankScores(teamTwoScoreContainer, showedSeries.getSeriesLength()); if (teamOne == null) hboxTeamOne.getStyleClass().add("tbd"); if (teamTwo == null) hboxTeamTwo.getStyleClass().add("tbd"); } else { // Names and scores textTeamOneName.setText(teamOne.getTeamName()); textTeamTwoName.setText(teamTwo.getTeamName()); setupScores(teamOneScoreContainer, showedSeries.getTeamOneScores()); setupScores(teamTwoScoreContainer, showedSeries.getTeamTwoScores()); Series.Outcome outcome = showedSeries.getOutcome(); // css ids if (status == Series.Status.READY_TO_BE_PLAYED || outcome == Series.Outcome.DRAW) { matchRoot.setId("ready"); } else if (outcome == Series.Outcome.TEAM_ONE_WINS) { matchRoot.setId("played"); hboxTeamOne.getStyleClass().add("winner"); } else if (outcome == Series.Outcome.TEAM_TWO_WINS) { matchRoot.setId("played"); hboxTeamTwo.getStyleClass().add("winner"); } } // Set colors if (showedSeries.isTeamOneBlue()) { hboxTeamOne.getStyleClass().add("blue"); hboxTeamTwo.getStyleClass().add("orange"); } else { hboxTeamOne.getStyleClass().add("orange"); hboxTeamTwo.getStyleClass().add("blue"); } } /** * Populate a score container with blank scores. Used when the match is not playable yet. */ private void setupBlankScores(HBox container, int seriesLength) { for (int i = 0; i < seriesLength; i++) { MatchScoreController msc = MatchScoreController.loadNew(); if (msc != null) { msc.setScoreText("-"); container.getChildren().add(msc.getRoot()); } } } /** * Populate a score container with the given scores. */ private void setupScores(HBox container, List<Optional<Integer>> scores) { for (Optional<Integer> score : scores) { MatchScoreController msc = MatchScoreController.loadNew(); if (msc != null) { msc.setScoreText(score.map(Object::toString).orElse("-")); container.getChildren().add(msc.getRoot()); } } } public HBox getRoot() { return matchRoot; } public boolean isIdentifierShown() { return showIdentifier; } public void setShowIdentifier(boolean showIdentifier) { this.showIdentifier = showIdentifier; updateFields(); } public boolean isDisabled() { return disabled; } /** When disabled the match is visible but blank and cannot be interacted with. */ public void setDisabled(boolean disabled) { this.disabled = disabled; updateFields(); if (disabled) { matchRoot.getStyleClass().remove("selectable"); } else { matchRoot.getStyleClass().add("selectable"); } } /** Decouples the controller from the model, allowing the controller to be thrown to the garbage collector. */ public void decoupleFromModel() { showedSeries.unregisterMatchChangeListener(this); } }
7,381
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
RLBotSettingsTabController.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/ui/RLBotSettingsTabController.java
package dk.aau.cs.ds306e18.tournament.ui; import dk.aau.cs.ds306e18.tournament.model.Tournament; import dk.aau.cs.ds306e18.tournament.rlbot.MatchRunner; import dk.aau.cs.ds306e18.tournament.rlbot.RLBotSettings; import dk.aau.cs.ds306e18.tournament.rlbot.configuration.MatchConfig; import dk.aau.cs.ds306e18.tournament.rlbot.configuration.MatchConfigOptions.*; import dk.aau.cs.ds306e18.tournament.settings.CleoPetraSettings; import dk.aau.cs.ds306e18.tournament.settings.LatestPaths; import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.ChoiceBox; import javafx.scene.control.TextField; import javafx.scene.layout.HBox; import javafx.stage.DirectoryChooser; import javafx.stage.Window; import java.io.File; import java.util.function.BiConsumer; public class RLBotSettingsTabController { public static RLBotSettingsTabController instance; public Button resetAllButton; public ChoiceBox<GameMap> gameMapChoiceBox; public ChoiceBox<GameMode> gameModeChoiceBox; public CheckBox skipReplaysCheckbox; public CheckBox instantStartCheckbox; public CheckBox writeOverlayDataCheckbox; public TextField overlayPathTextField; public Button chooseOverlayPathButton; public CheckBox useRLBotGUIPythonCheckbox; public Button rlbotRunnerOpenButton; public Button rlbotRunnerCloseButton; public Button rlbotRunnerStopMatchButton; public ChoiceBox<MatchLength> matchLengthChoiceBox; public ChoiceBox<MaxScore> maxScoreChoiceBox; public ChoiceBox<Overtime> overtimeChoiceBox; public ChoiceBox<GameSpeed> gameSpeedChoiceBox; public ChoiceBox<BallMaxSpeed> ballMaxSpeedChoiceBox; public ChoiceBox<BallType> ballTypeChoiceBox; public ChoiceBox<BallWeight> ballWeightChoiceBox; public ChoiceBox<BallSize> ballSizeChoiceBox; public ChoiceBox<BallBounciness> ballBouncinessChoiceBox; public ChoiceBox<BoostAmount> boostAmountChoiceBox; public ChoiceBox<BoostStrength> boostStrengthChoiceBox; public ChoiceBox<RumblePowers> rumblePowersChoiceBox; public ChoiceBox<Gravity> gravityChoiceBox; public ChoiceBox<Demolish> demolishChoiceBox; public ChoiceBox<RespawnTime> respawnTimeChoiceBox; public CheckBox renderingCheckbox; public CheckBox stateSettingCheckbox; public CheckBox autoSaveReplaysCheckbox; @FXML private HBox tabRoot; @FXML private void initialize() { instance = this; RLBotSettings settings = Tournament.get().getRlBotSettings(); MatchConfig matchConfig = settings.getMatchConfig(); // General match settings setupChoiceBox(gameMapChoiceBox, GameMap.values(), matchConfig.getGameMap(), MatchConfig::setGameMap); setupChoiceBox(gameModeChoiceBox, GameMode.values(), matchConfig.getGameMode(), MatchConfig::setGameMode); skipReplaysCheckbox.setSelected(matchConfig.isSkipReplays()); skipReplaysCheckbox.selectedProperty().addListener((observable, oldValue, newValue) -> { Tournament.get().getRlBotSettings().getMatchConfig().setSkipReplays(newValue); }); instantStartCheckbox.setSelected(matchConfig.isInstantStart()); instantStartCheckbox.selectedProperty().addListener((observable, oldValue, newValue) -> { Tournament.get().getRlBotSettings().getMatchConfig().setInstantStart(newValue); }); renderingCheckbox.setSelected(matchConfig.isRenderingEnabled()); renderingCheckbox.selectedProperty().addListener((observable, oldValue, newValue) -> { Tournament.get().getRlBotSettings().getMatchConfig().setRenderingEnabled(newValue); }); stateSettingCheckbox.setSelected(matchConfig.isStateSettingEnabled()); stateSettingCheckbox.selectedProperty().addListener((observable, oldValue, newValue) -> { Tournament.get().getRlBotSettings().getMatchConfig().setStateSettingEnabled(newValue); }); autoSaveReplaysCheckbox.setSelected(matchConfig.isAutoSaveReplays()); autoSaveReplaysCheckbox.selectedProperty().addListener((observable, oldValue, newValue) -> { Tournament.get().getRlBotSettings().getMatchConfig().setAutoSaveReplays(newValue); }); // Mutators setupChoiceBox(matchLengthChoiceBox, MatchLength.values(), matchConfig.getMatchLength(), MatchConfig::setMatchLength); setupChoiceBox(maxScoreChoiceBox, MaxScore.values(), matchConfig.getMaxScore(), MatchConfig::setMaxScore); setupChoiceBox(overtimeChoiceBox, Overtime.values(), matchConfig.getOvertime(), MatchConfig::setOvertime); setupChoiceBox(gameSpeedChoiceBox, GameSpeed.values(), matchConfig.getGameSpeed(), MatchConfig::setGameSpeed); setupChoiceBox(ballMaxSpeedChoiceBox, BallMaxSpeed.values(), matchConfig.getBallMaxSpeed(), MatchConfig::setBallMaxSpeed); setupChoiceBox(ballTypeChoiceBox, BallType.values(), matchConfig.getBallType(), MatchConfig::setBallType); setupChoiceBox(ballWeightChoiceBox, BallWeight.values(), matchConfig.getBallWeight(), MatchConfig::setBallWeight); setupChoiceBox(ballSizeChoiceBox, BallSize.values(), matchConfig.getBallSize(), MatchConfig::setBallSize); setupChoiceBox(ballBouncinessChoiceBox, BallBounciness.values(), matchConfig.getBallBounciness(), MatchConfig::setBallBounciness); setupChoiceBox(boostAmountChoiceBox, BoostAmount.values(), matchConfig.getBoostAmount(), MatchConfig::setBoostAmount); setupChoiceBox(boostStrengthChoiceBox, BoostStrength.values(), matchConfig.getBoostStrength(), MatchConfig::setBoostStrength); setupChoiceBox(rumblePowersChoiceBox, RumblePowers.values(), matchConfig.getRumblePowers(), MatchConfig::setRumblePowers); setupChoiceBox(gravityChoiceBox, Gravity.values(), matchConfig.getGravity(), MatchConfig::setGravity); setupChoiceBox(demolishChoiceBox, Demolish.values(), matchConfig.getDemolish(), MatchConfig::setDemolish); setupChoiceBox(respawnTimeChoiceBox, RespawnTime.values(), matchConfig.getRespawnTime(), MatchConfig::setRespawnTime); // Other settings boolean writeOverlay = settings.writeOverlayDataEnabled(); writeOverlayDataCheckbox.setSelected(writeOverlay); writeOverlayDataCheckbox.selectedProperty().addListener((observable, oldValue, newValue) -> { Tournament.get().getRlBotSettings().setWriteOverlayData(newValue); overlayPathTextField.setDisable(!newValue); chooseOverlayPathButton.setDisable(!newValue); }); chooseOverlayPathButton.setDisable(!writeOverlay); overlayPathTextField.setDisable(!writeOverlay); overlayPathTextField.setText(settings.getOverlayPath()); overlayPathTextField.focusedProperty().addListener((observable, oldValue, newValue) -> { if (!newValue) { String path = overlayPathTextField.textProperty().get(); settings.setOverlayPath(path); } }); useRLBotGUIPythonCheckbox.setSelected(settings.useRLBotGUIPythonIfAvailable()); useRLBotGUIPythonCheckbox.selectedProperty().addListener((observable, oldValue, newValue) -> { Tournament.get().getRlBotSettings().setUseRLBotGUIPythonIfAvailable(newValue); }); update(); } /** * Setup a choice box for match config options. */ private <T> void setupChoiceBox(ChoiceBox<T> choiceBox, T[] values, T current, BiConsumer<MatchConfig, T> onSelect) { choiceBox.setItems(FXCollections.observableArrayList(values)); choiceBox.getSelectionModel().select(current); choiceBox.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { onSelect.accept(Tournament.get().getRlBotSettings().getMatchConfig(), newValue); }); } public void onActionResetAllButton(ActionEvent actionEvent) { Tournament.get().getRlBotSettings().setMatchConfig(new MatchConfig()); update(); } /** Updates all ui elements */ public void update() { RLBotSettings settings = Tournament.get().getRlBotSettings(); MatchConfig matchConfig = settings.getMatchConfig(); // General match settings gameMapChoiceBox.getSelectionModel().select(matchConfig.getGameMap()); gameModeChoiceBox.getSelectionModel().select(matchConfig.getGameMode()); skipReplaysCheckbox.setSelected(matchConfig.isSkipReplays()); instantStartCheckbox.setSelected(matchConfig.isInstantStart()); // Mutators matchLengthChoiceBox.getSelectionModel().select(matchConfig.getMatchLength()); maxScoreChoiceBox.getSelectionModel().select(matchConfig.getMaxScore()); overtimeChoiceBox.getSelectionModel().select(matchConfig.getOvertime()); gameSpeedChoiceBox.getSelectionModel().select(matchConfig.getGameSpeed()); ballMaxSpeedChoiceBox.getSelectionModel().select(matchConfig.getBallMaxSpeed()); ballTypeChoiceBox.getSelectionModel().select(matchConfig.getBallType()); ballWeightChoiceBox.getSelectionModel().select(matchConfig.getBallWeight()); ballSizeChoiceBox.getSelectionModel().select(matchConfig.getBallSize()); ballBouncinessChoiceBox.getSelectionModel().select(matchConfig.getBallBounciness()); boostAmountChoiceBox.getSelectionModel().select(matchConfig.getBoostAmount()); boostStrengthChoiceBox.getSelectionModel().select(matchConfig.getBoostStrength()); rumblePowersChoiceBox.getSelectionModel().select(matchConfig.getRumblePowers()); gravityChoiceBox.getSelectionModel().select(matchConfig.getGravity()); demolishChoiceBox.getSelectionModel().select(matchConfig.getDemolish()); respawnTimeChoiceBox.getSelectionModel().select(matchConfig.getRespawnTime()); // Other settings writeOverlayDataCheckbox.setSelected(settings.writeOverlayDataEnabled()); } public void onActionRLBotRunnerOpen(ActionEvent actionEvent) { MatchRunner.startRLBotRunner(); } public void onActionRLBotRunnerClose(ActionEvent actionEvent) { MatchRunner.closeRLBotRunner(); } public void onActionRLBotRunnerStopMatch(ActionEvent actionEvent) { MatchRunner.stopMatch(); } public void onActionChooseOverlayPath(ActionEvent actionEvent) { LatestPaths latestPaths = CleoPetraSettings.getLatestPaths(); DirectoryChooser dirChooser = new DirectoryChooser(); dirChooser.setTitle("Choose overlay folder"); dirChooser.setInitialDirectory(latestPaths.getOverlayDirectory()); Window window = chooseOverlayPathButton.getScene().getWindow(); File folder = dirChooser.showDialog(window); if (folder != null) { String path = folder.toString(); overlayPathTextField.setText(path); Tournament.get().getRlBotSettings().setOverlayPath(path); latestPaths.setOverlayDirectory(folder); } } }
11,155
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
BotInfoController.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/ui/BotInfoController.java
package dk.aau.cs.ds306e18.tournament.ui; import dk.aau.cs.ds306e18.tournament.Main; import dk.aau.cs.ds306e18.tournament.model.Bot; import dk.aau.cs.ds306e18.tournament.model.BotFromConfig; import dk.aau.cs.ds306e18.tournament.utility.Alerts; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.text.Text; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.stage.StageStyle; import javafx.stage.Window; import java.io.File; import java.io.IOException; public class BotInfoController extends DraggablePopupWindow { @FXML public Text botNameText; @FXML public Text botConfigPathText; @FXML public Text developersText; @FXML public Text descriptionText; @FXML public Text funFactText; @FXML public Text githubText; @FXML public Text languageText; @FXML public Text botTypeText; @FXML public Button showFilesButton; @FXML public Button closeButton; @FXML public Button reloadBot; private Bot bot; /** * Set which bot is shown. This is update all the information displayed. */ public void setBot(Bot bot) { this.bot = bot; botNameText.setText(bot.getName()); botConfigPathText.setText(bot.getConfigPath()); developersText.setText(bot.getDeveloper()); descriptionText.setText(bot.getDescription()); funFactText.setText(bot.getFunFact()); githubText.setText(bot.getGitHub()); languageText.setText(bot.getLanguage()); botTypeText.setText(bot.getBotType().toString()); } /** * Returns the displayed bot. */ public Bot getBot() { return bot; } @FXML public void onActionClose(ActionEvent actionEvent) { ((Stage) closeButton.getScene().getWindow()).close(); } @FXML public void onActionShowFiles(ActionEvent actionEvent) { // Check OS. We can only open File Explorer on Windows. if (System.getProperty("os.name").contains("Windows")) { // Try to show file explorer showing the bot's config file File file = new File(bot.getConfigPath()); boolean showFailed = true; if (file.exists()) { try { Runtime.getRuntime().exec("explorer.exe /select," + file.toString()); showFailed = false; } catch (IOException e) { e.printStackTrace(); } } // If something failed, let the user know if (showFailed) { Alerts.errorNotification("Could not show files.", "Could not open File Explorer showing the config file. Does the file exist?"); Main.LOGGER.log(System.Logger.Level.INFO, "Could not open File Explorer showing the config file."); } } else { Alerts.errorNotification("Could not show files.", "Could not open File Explorer since OS is not Windows."); Main.LOGGER.log(System.Logger.Level.ERROR, "Could not open File Explorer since OS is not Windows."); } } @FXML public void windowDragged(MouseEvent mouseEvent) { super.windowDragged(mouseEvent); } @FXML public void windowPressed(MouseEvent mouseEvent) { super.windowPressed(mouseEvent); } /** * Creates a popup window where information about a given bot is shown. * @param bot the bot * @param parent the parent window */ public static void showInfoForBot(Bot bot, Window parent) { try { Stage infoStage = new Stage(); infoStage.initStyle(StageStyle.TRANSPARENT); infoStage.initModality(Modality.APPLICATION_MODAL); FXMLLoader loader = new FXMLLoader(BotInfoController.class.getResource("layout/BotInfo.fxml")); AnchorPane infoPane = loader.load(); infoStage.setScene(new Scene(infoPane)); BotInfoController controller = loader.getController(); controller.setBot(bot); // Calculate the center position of the parent window. double centerXPosition = parent.getX() + parent.getWidth()/2d; double centerYPosition = parent.getY() + parent.getHeight()/2d; // Show info window at the center of the parent window. infoStage.setOnShown(ev -> { infoStage.setX(centerXPosition - infoStage.getWidth()/2d); infoStage.setY(centerYPosition - infoStage.getHeight()/2d); }); infoStage.show(); } catch (IOException e) { e.printStackTrace(); } } @FXML public void onActionReloadBot(ActionEvent actionEvent) { if (bot instanceof BotFromConfig) { ((BotFromConfig) bot).reload(); setBot(bot); // Updates all fields ParticipantSettingsTabController.instance.update(); } } }
5,102
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
LauncherController.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/ui/LauncherController.java
package dk.aau.cs.ds306e18.tournament.ui; import dk.aau.cs.ds306e18.tournament.Main; import dk.aau.cs.ds306e18.tournament.model.Tournament; import dk.aau.cs.ds306e18.tournament.settings.CleoPetraSettings; import dk.aau.cs.ds306e18.tournament.settings.LatestPaths; import dk.aau.cs.ds306e18.tournament.utility.Alerts; import dk.aau.cs.ds306e18.tournament.utility.FileOperations; import dk.aau.cs.ds306e18.tournament.utility.SaveLoad; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.image.Image; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.stage.FileChooser; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.stage.StageStyle; import java.io.File; import java.io.IOException; public class LauncherController { @FXML private AnchorPane baseAnchorpane; public static Stage createSystemStage (){ Stage systemStage = new Stage(); // Set min- width and height and title. systemStage.setMinWidth(800); systemStage.setMinHeight(650); systemStage.setMaximized(true); systemStage.setTitle("CleoPetra"); systemStage.getIcons().add(new Image(Main.class.getResourceAsStream("ui/layout/images/logo.png"))); // Set the correct scene for the system stage. try { AnchorPane systemRoot = FXMLLoader.load(LauncherController.class.getResource("layout/MainLayout.fxml")); Alerts.window = systemRoot; systemStage.setScene(new Scene(systemRoot)); } catch (IOException e) { Main.LOGGER.log(System.Logger.Level.ERROR, "Error while loading system stage", e); } // Create and load the exit popup when the user tries to close the system. Stage exitStage = new Stage(); exitStage.initStyle(StageStyle.TRANSPARENT); exitStage.initModality(Modality.APPLICATION_MODAL); systemStage.setOnCloseRequest(e -> { e.consume(); // Load exit program FXML file try { // Calculate the center position of the main window. double centerXPosition = systemStage.getX() + systemStage.getWidth()/2d; double centerYPosition = systemStage.getY() + systemStage.getHeight()/2d; AnchorPane exitRoot = FXMLLoader.load(LauncherController.class.getResource("layout/Exit.fxml")); exitStage.setScene(new Scene(exitRoot)); // Assign the position of the popup window whenever it is shown. exitStage.setOnShown(ev -> { exitStage.setX(centerXPosition - exitStage.getWidth()/2d); exitStage.setY(centerYPosition - exitStage.getHeight()/2d); exitStage.show(); }); exitStage.showAndWait(); } catch (IOException error) { error.printStackTrace(); } }); return systemStage; } private Stage getLauncherStage (){ return (Stage) baseAnchorpane.getScene().getWindow(); } @FXML void createNewTournament(ActionEvent event) { Stage systemStage = createSystemStage(); // Hide launcher stage and then show the system stage. getLauncherStage().hide(); systemStage.show(); } @FXML void openLocalTournament(ActionEvent event) { // Set file extension. String extension = "rlts"; // Create Filechooser and add extensionfilter and set initial directory to users documents folder. FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Open tournament file"); fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Tournament format (*." + extension + ")", "*." + extension)); fileChooser.setInitialDirectory(CleoPetraSettings.getLatestPaths().getTournamentSaveDirectory()); File file = fileChooser.showOpenDialog(getLauncherStage()); // Deserialize and set the loaded tournament. Then show the main stage. if (file != null){ try { SaveLoad.loadTournament(file); Stage systemStage = createSystemStage(); getLauncherStage().hide(); systemStage.show(); } catch (IOException e) { Alerts.errorNotification("Could not read selected file", "Something went wrong while loading tournament: " + e.getMessage()); Main.LOGGER.log(System.Logger.Level.ERROR, "Error while loading tournament", e); e.printStackTrace(); } } } }
4,759
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
StageFormatOption.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/ui/StageFormatOption.java
package dk.aau.cs.ds306e18.tournament.ui; import dk.aau.cs.ds306e18.tournament.model.format.*; public enum StageFormatOption { SINGLE_ELIMINATION("Single Elimination", SingleEliminationFormat.class), DOUBLE_ELIMINATION("Double Elimination", DoubleEliminationFormat.class), SWISS_SYSTEM("Swiss", SwissFormat.class), ROUND_ROBIN("Round Robin", RoundRobinFormat.class); private final String name; private final Class<?> clazz; StageFormatOption(String name, Class<?> clazz) { this.name = name; this.clazz = clazz; } @Override public String toString() { return name; } public Format getNewInstance() { try { return (Format) clazz.getDeclaredConstructor().newInstance(); } catch (Exception e) { e.printStackTrace(); } return null; } public static StageFormatOption getOption(Format format) { for (StageFormatOption option : values()) { if (option.clazz.isInstance(format)) { return option; } } return null; } }
1,117
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
ParticipantSettingsTabController.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/ui/ParticipantSettingsTabController.java
package dk.aau.cs.ds306e18.tournament.ui; import dk.aau.cs.ds306e18.tournament.Main; import dk.aau.cs.ds306e18.tournament.model.*; import dk.aau.cs.ds306e18.tournament.settings.CleoPetraSettings; import dk.aau.cs.ds306e18.tournament.settings.LatestPaths; import dk.aau.cs.ds306e18.tournament.utility.Alerts; import dk.aau.cs.ds306e18.tournament.rlbot.BotCollection; import dk.aau.cs.ds306e18.tournament.utility.AutoNaming; import javafx.application.Platform; import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.input.KeyEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.*; import javafx.stage.Stage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; public class ParticipantSettingsTabController { public static ParticipantSettingsTabController instance; @FXML private HBox participantSettingsTab; @FXML private ChoiceBox<SeedingOption> seedingChoicebox; @FXML private TextField teamNameTextField; @FXML private Button autoNameTeamButton; @FXML private Spinner<Integer> seedSpinner; @FXML private Button addTeamBtn; @FXML private Button removeTeamBtn; @FXML private ListView<Team> teamsListView; @FXML private VBox teamSettingsColumnVbox; @FXML private VBox botCollectionColumnVBox; @FXML private Button swapUpTeam; @FXML private Button swapDownTeam; @FXML private ListView<Bot> rosterListView; @FXML private Button loadConfigButton; @FXML private Button loadFolderButton; @FXML private Button loadBotPack; @FXML private ListView<Bot> botCollectionListView; @FXML private Button createTeamWithEachBotButton; private FileChooser botConfigFileChooser; private DirectoryChooser botFolderChooser; @FXML private void initialize() { instance = this; // Seeding Option seedingChoicebox.setItems(FXCollections.observableArrayList(SeedingOption.values())); seedingChoicebox.getSelectionModel().select(Tournament.get().getSeedingOption()); seedingChoicebox.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { Tournament.get().setSeedingOption(newValue); updateParticipantFields(); updateSeedSpinner(); teamsListView.refresh(); }); setUpTeamsListView(); // Seed spinner behaviour seedSpinner.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(1, Integer.MAX_VALUE)); seedSpinner.getValueFactory().valueProperty().addListener((observable, oldValue, newValue) -> { // Seed spinner should only be enabled when seeding option is manual. When the value change // we want to update the order in the team list view and the teams label in the list Team selectedTeam = getSelectedTeam(); if (selectedTeam != null && Tournament.get().getSeedingOption() == SeedingOption.MANUALLY) { selectedTeam.setInitialSeedValue(newValue); Tournament.get().sortTeamsBySeed(); teamsListView.setItems(FXCollections.observableArrayList(Tournament.get().getTeams())); teamsListView.refresh(); // Select text to make it easy to edit seedSpinner.getEditor().selectAll(); } }); seedSpinner.setEditable(true); seedSpinner.getEditor().textProperty().addListener((observable, oldText, newText) -> { // We allow empty strings and all positive numbers. If the string is empty, the text goes // back to saved seed value when focus is lost if (newText.equals("") || newText.matches("^([1-9][0-9]*)$")) { if (!newText.equals("")) { seedSpinner.getValueFactory().setValue(Integer.parseInt(newText)); } } else { seedSpinner.getEditor().setText(oldText); } }); seedSpinner.focusedProperty().addListener((observable, wasFocused, isNowFocused) -> { // Select all text, because that is user friendly for this case if (isNowFocused) { Platform.runLater(seedSpinner.getEditor()::selectAll); } // Focus lost and editor is currently empty, so set the text to the saved seed value if (wasFocused && seedSpinner.getEditor().getText().equals("")) { seedSpinner.getEditor().setText("" + getSelectedTeam().getInitialSeedValue()); } }); // Team roster list setup rosterListView.setCellFactory(listView -> new TeamRosterCell(this)); // Bot collection list setup BotCollection.global.addPsyonixBots(); botCollectionListView.setCellFactory(listView -> new BotCollectionCell(this)); botCollectionListView.setItems(FXCollections.observableArrayList(BotCollection.global)); // Setup file chooser botConfigFileChooser = new FileChooser(); botConfigFileChooser.setTitle("Choose a bot config file"); botConfigFileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Config (*.cfg)", "*.cfg")); botFolderChooser = new DirectoryChooser(); botFolderChooser.setTitle("Choose a folder with bots"); // Things are now setup // Update everything update(); } /** Updates all ui elements */ public void update() { teamsListView.setItems(FXCollections.observableArrayList(Tournament.get().getTeams())); teamsListView.refresh(); rosterListView.refresh(); botCollectionListView.refresh(); updateParticipantFields(); updateTeamFields(); } /** Sets up the listview for teams. Setting items, * adding listener and changing what is displayed. */ private void setUpTeamsListView(){ //Assign teams to the list in case of the tournament being loaded teamsListView.setItems(FXCollections.observableArrayList(Tournament.get().getTeams())); //Adds selectionsListener to team ListView teamsListView.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { updateParticipantFields(); updateTeamFields(); }); //Formatting what is displayed in the listView: id + name. teamsListView.setCellFactory(lv -> new ListCell<Team>() { public void updateItem(Team team, boolean empty) { super.updateItem(team, empty); if (empty) { setText(null); } else { SeedingOption seedingOption = Tournament.get().getSeedingOption(); switch (seedingOption) { case SEED_BY_ORDER: int index = teamsListView.getItems().indexOf(team) + 1; setText(index + ". " + team.getTeamName()); break; case MANUALLY: setText("Seed " + team.getInitialSeedValue() + ": " + team.getTeamName()); break; case NO_SEEDING: case RANDOM_SEEDING: setText(team.getTeamName()); break; } teamsListView.refresh(); } } }); } /** * Updates tournament values from fields when key released. */ @FXML void teamNameTextFieldOnKeyReleased(KeyEvent event) { Tournament.get().getTeams().get(getSelectedTeamIndex()).setTeamName(teamNameTextField.getText()); teamsListView.refresh(); } @FXML void onActionAddTeam(ActionEvent actionEvent) { //Create a team with a bot and add the team to the tournament Team team = new Team("Unnamed Team", new ArrayList<>(), teamsListView.getItems().size() + 1, ""); AutoNaming.autoName(team, Tournament.get().getTeams()); Tournament.get().addTeam(team); teamsListView.setItems(FXCollections.observableArrayList(Tournament.get().getTeams())); teamsListView.refresh(); teamsListView.getSelectionModel().selectLast(); rosterListView.setItems(FXCollections.observableArrayList(Tournament.get().getTeams().get(getSelectedTeamIndex()).getBots())); rosterListView.refresh(); } @FXML void onActionRemoveTeam(ActionEvent actionEvent) { rosterListView.getSelectionModel().clearSelection(); rosterListView.setItems(null); rosterListView.refresh(); if (getSelectedTeamIndex() != -1) { Tournament.get().removeTeam(getSelectedTeamIndex()); teamsListView.setItems(FXCollections.observableArrayList(Tournament.get().getTeams())); teamsListView.refresh(); teamsListView.getSelectionModel().selectLast(); } } /** * Update all fields in the first column. */ private void updateParticipantFields() { boolean started = Tournament.get().hasStarted(); SeedingOption seedingOption = Tournament.get().getSeedingOption(); seedingChoicebox.setDisable(started); teamsListView.refresh(); int selectedIndex = getSelectedTeamIndex(); // Handle team order button disabling / enabling swapUpTeam.setDisable(seedingOption != SeedingOption.SEED_BY_ORDER || selectedIndex <= 0 || started); swapDownTeam.setDisable(seedingOption != SeedingOption.SEED_BY_ORDER || selectedIndex == teamsListView.getItems().size() - 1 || started); removeTeamBtn.setDisable(selectedIndex == -1 || started); addTeamBtn.setDisable(started); } /** * Updates the textfields with the values from the selected team. */ private void updateTeamFields() { teamSettingsColumnVbox.setVisible(teamsListView.getItems().size() != 0); if (getSelectedTeamIndex() != -1) { Team selectedTeam = Tournament.get().getTeams().get(getSelectedTeamIndex()); teamNameTextField.setText(selectedTeam.getTeamName()); updateSeedSpinner(); rosterListView.getSelectionModel().clearSelection(); rosterListView.setItems(FXCollections.observableArrayList(selectedTeam.getBots())); rosterListView.refresh(); } //Check for empty names checkForEmptyTeamName(); } /** * Updates the value displayed in the seed spinner field for the team and also disables/enables it. */ private void updateSeedSpinner() { Team selectedTeam = getSelectedTeam(); if (selectedTeam != null) { int selectedTeamIndex = getSelectedTeamIndex(); SeedingOption seedingOption = Tournament.get().getSeedingOption(); seedSpinner.setDisable(seedingOption != SeedingOption.MANUALLY); int displayedValue = selectedTeam.getInitialSeedValue(); switch (seedingOption) { case SEED_BY_ORDER: displayedValue = selectedTeamIndex + 1; break; case MANUALLY: break; case NO_SEEDING: case RANDOM_SEEDING: displayedValue = 0; break; } seedSpinner.getValueFactory().valueProperty().setValue(displayedValue); } } /** * All teams with empty names with be renamed to "Team ?" */ private void checkForEmptyTeamName() { for (Team team : Tournament.get().getTeams()) { String nameCheck = team.getTeamName(); nameCheck = nameCheck.replaceAll("\\s+", ""); if (nameCheck.compareTo("") == 0) { team.setTeamName("Team ?"); } } } /** * Add a bot to the selected team roster and update the rosterListView */ public void addBotToSelectedTeamRoster(Bot bot) { Team selectedTeam = getSelectedTeam(); if (selectedTeam != null) { selectedTeam.addBot(bot); rosterListView.setItems(FXCollections.observableArrayList(selectedTeam.getBots())); rosterListView.refresh(); } } /** * Remove a bot to the selected team roster and update the rosterListView */ public void removeBotFromSelectedTeamRoster(int index) { Team selectedTeam = getSelectedTeam(); if (selectedTeam != null) { selectedTeam.removeBot(index); rosterListView.setItems(FXCollections.observableArrayList(selectedTeam.getBots())); rosterListView.refresh(); } } /** * Remove a bot from the bot collection and update the bot collection list view */ public void removeBotFromBotCollection(Bot bot) { BotCollection.global.remove(bot); botCollectionListView.setItems(FXCollections.observableArrayList(BotCollection.global)); botCollectionListView.refresh(); } /** * Swaps a team upwards in the list of teams. Used to allow ordering of Team and thereby their seed. */ @FXML private void swapTeamUpwards() { Tournament.get().swapTeams(getSelectedTeamIndex(), getSelectedTeamIndex() - 1); teamsListView.setItems(FXCollections.observableArrayList(Tournament.get().getTeams())); teamsListView.refresh(); } /** * Swaps a team downwards in the list of teams. Used to allow ordering of Team and thereby their seed. */ @FXML private void swapTeamDownwards() { Tournament.get().swapTeams(getSelectedTeamIndex(), getSelectedTeamIndex() + 1); teamsListView.setItems(FXCollections.observableArrayList(Tournament.get().getTeams())); teamsListView.refresh(); } public Team getSelectedTeam() { return teamsListView.getSelectionModel().getSelectedItem(); } public int getSelectedTeamIndex() { return teamsListView.getSelectionModel().getSelectedIndex(); } @FXML public void onActionLoadConfig(ActionEvent actionEvent) { // Open file chooser LatestPaths latestPaths = CleoPetraSettings.getLatestPaths(); botConfigFileChooser.setInitialDirectory(latestPaths.getBotConfigDirectory()); Window window = loadConfigButton.getScene().getWindow(); List<File> files = botConfigFileChooser.showOpenMultipleDialog(window); if (files != null) { // Add all selected bots to bot collection BotCollection.global.addAll(files.stream() .map(file -> { try { return new BotFromConfig(file.toString()); } catch (Exception e) { Alerts.errorNotification("Loading failed", "Could not load bot from: " + file); Main.LOGGER.log(System.Logger.Level.ERROR, "Could not load bot from: " + file, e); return null; } }) .filter(Objects::nonNull) .collect(Collectors.toList())); botCollectionListView.setItems(FXCollections.observableArrayList(BotCollection.global)); botCollectionListView.refresh(); latestPaths.setBotConfigDirectory(files.get(0).getParentFile()); } } @FXML public void onActionLoadFolder(ActionEvent actionEvent) { // Open directory chooser LatestPaths latestPaths = CleoPetraSettings.getLatestPaths(); botFolderChooser.setInitialDirectory(latestPaths.getBotConfigDirectory()); Window window = loadFolderButton.getScene().getWindow(); File folder = botFolderChooser.showDialog(window); if (folder != null) { // Find all bots in the folder and add them to bot collection BotCollection.global.addAllBotsFromFolder(folder, 10); botCollectionListView.setItems(FXCollections.observableArrayList(BotCollection.global)); botCollectionListView.refresh(); latestPaths.setBotConfigDirectory(folder); } } @FXML public void onActionLoadBotPack(ActionEvent actionEvent) { boolean success = BotCollection.global.addRLBotPackIfPresent(); botCollectionListView.setItems(FXCollections.observableArrayList(BotCollection.global)); botCollectionListView.refresh(); if (success) { Alerts.infoNotification("Bot pack loaded", "Found the RLBotGUI's bot pack and loaded the bots from it successfully."); } else { Alerts.errorNotification("Failed to load bot pack", "Unable to locate RLBotGUI's bot pack."); } } @FXML public void onActionAutoNameTeam(ActionEvent actionEvent) { Team team = getSelectedTeam(); AutoNaming.autoName(team, Tournament.get().getTeams()); updateTeamFields(); teamsListView.refresh(); } public void onActionCreateTeamWithEachBot(ActionEvent actionEvent) { try { javafx.stage.Stage createTeamsStage = new javafx.stage.Stage(); createTeamsStage.initStyle(StageStyle.TRANSPARENT); createTeamsStage.initModality(Modality.APPLICATION_MODAL); FXMLLoader loader = new FXMLLoader(ParticipantSettingsTabController.class.getResource("layout/CreateTeamsWithEachBot.fxml")); AnchorPane createTeamsStageRoot = loader.load(); createTeamsStage.setScene(new Scene(createTeamsStageRoot)); // Calculate the center position of the main window. javafx.stage.Stage mainWindow = (Stage) participantSettingsTab.getScene().getWindow(); double centerXPosition = mainWindow.getX() + mainWindow.getWidth()/2d; double centerYPosition = mainWindow.getY() + mainWindow.getHeight()/2d; // Assign popup window to the center of the main window. createTeamsStage.setOnShown(ev -> { createTeamsStage.setX(centerXPosition - createTeamsStage.getWidth()/2d); createTeamsStage.setY(centerYPosition - createTeamsStage.getHeight()/2d); createTeamsStage.show(); }); createTeamsStage.show(); } catch (IOException e) { e.printStackTrace(); } } }
18,828
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
ScoreSpinnerValueFactory.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/ui/ScoreSpinnerValueFactory.java
package dk.aau.cs.ds306e18.tournament.ui; import javafx.scene.control.SpinnerValueFactory; /** * A SpinnerValueFactory for scores. It accepts integers in a given range as well as empty strings and "-". */ public class ScoreSpinnerValueFactory extends SpinnerValueFactory<String> { private final int min; private final int max; public ScoreSpinnerValueFactory(int min, int max) { assert min <= max; this.min = min; this.max = max; } @Override public void decrement(int steps) { int value = getValueAsInt(); setValue(String.valueOf(Math.max(value - 1, min))); } @Override public void increment(int steps) { int value = getValueAsInt(); setValue(String.valueOf(Math.min(value + 1, max))); } private int getValueAsInt() { String s = getValue(); if (s == null || "".equals(s) || "-".equals(s)) return 0; else return Integer.parseInt(s); } }
973
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
DraggablePopupWindow.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/ui/DraggablePopupWindow.java
package dk.aau.cs.ds306e18.tournament.ui; import javafx.scene.Node; import javafx.scene.input.MouseEvent; import javafx.stage.Stage; /** * This abstract class is used to make pop-up windows draggable. */ public abstract class DraggablePopupWindow { private double x = 0; private double y = 0; protected void windowDragged(MouseEvent event) { Stage stage = (Stage) ((Node) event.getSource()).getScene().getWindow(); stage.setX(event.getScreenX() - x); stage.setY(event.getScreenY() - y); } protected void windowPressed(MouseEvent event) { x = event.getSceneX(); y = event.getSceneY(); } }
659
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
StatsTableWithPoints.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/ui/StatsTableWithPoints.java
package dk.aau.cs.ds306e18.tournament.ui; import dk.aau.cs.ds306e18.tournament.model.Team; import dk.aau.cs.ds306e18.tournament.model.format.Format; import dk.aau.cs.ds306e18.tournament.model.stats.Stats; import javafx.beans.property.SimpleIntegerProperty; import javafx.scene.control.TableColumn; import java.util.IdentityHashMap; import java.util.List; /** * StatsTableWithPoints differs from StatsTable in that it also has a column with points. These points can be awarded * due to the special rules in a particular format. The loses and goals column is not shown in the * StatsTableWithPoints as they are typically not important when points are used. */ public class StatsTableWithPoints extends StatsTable { private IdentityHashMap<Team, Integer> pointsMap; /** * Create a StatsTable to show points and stats for the given teams in the given stage/format. If format is null global stats * will be shown instead. */ public StatsTableWithPoints(List<Team> teams, Format format, IdentityHashMap<Team, Integer> pointsMap) { super(teams, format); this.pointsMap = pointsMap; } @Override protected void calculateSize() { super.calculateSize(); setPrefWidth(258); } @Override public void update() { clear(); prepareItems(); addTeamNameColumn(); addPointsColumn(); addWinsColumn(); addGoalDiffColumn(); } private void addPointsColumn() { TableColumn<Stats, Integer> pointsColumn = new TableColumn<>("Points"); pointsColumn.setCellValueFactory(cell -> new SimpleIntegerProperty(pointsMap == null ? 0 : pointsMap.get(cell.getValue().getTeam())).asObject()); pointsColumn.setSortType(TableColumn.SortType.DESCENDING); pointsColumn.setStyle("-fx-alignment: CENTER;"); getColumns().add(pointsColumn); getSortOrder().add(pointsColumn); } }
1,934
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
BotCollectionCell.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/ui/BotCollectionCell.java
package dk.aau.cs.ds306e18.tournament.ui; import dk.aau.cs.ds306e18.tournament.model.Bot; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ListCell; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import java.io.IOException; /** * This is a custom ListCell used to display bots in the bot collection panel in the participant settings tab. */ public class BotCollectionCell extends ListCell<Bot> { @FXML public HBox hbox; @FXML public Button addToTeamButton; @FXML public Label botNameLabel; @FXML public Button infoButton; @FXML public Button removeBotButton; @FXML public ImageView botTypeIcon; private ParticipantSettingsTabController participantSettingsTabController; public BotCollectionCell(ParticipantSettingsTabController participantSettingsTabController) { this.participantSettingsTabController = participantSettingsTabController; try { // Load the layout of the cell from the fxml file. The controller will be this class FXMLLoader fxmlLoader = new FXMLLoader(BotCollectionCell.class.getResource("layout/BotCollectionCell.fxml")); fxmlLoader.setController(this); fxmlLoader.load(); } catch (IOException e) { e.printStackTrace(); } } @Override protected void updateItem(Bot bot, boolean empty) { super.updateItem(bot, empty); // This text is not used by our custom cell setText(null); if (empty || bot == null) { // Nothing to display setGraphic(null); } else { // Display the bot name and a fitting icon botNameLabel.setText(bot.getName()); botTypeIcon.setImage(BotIcons.getIconForBot(bot)); setGraphic(hbox); } } @FXML public void onActionAddToTeam(ActionEvent actionEvent) { participantSettingsTabController.addBotToSelectedTeamRoster(getItem()); } @FXML public void onActionInfo(ActionEvent actionEvent) { BotInfoController.showInfoForBot(getItem(), getScene().getWindow()); } @FXML public void onActionRemove(ActionEvent actionEvent) { participantSettingsTabController.removeBotFromBotCollection(getItem()); } }
2,426
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
MatchScoreController.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/ui/MatchScoreController.java
package dk.aau.cs.ds306e18.tournament.ui; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Group; import javafx.scene.text.Text; import java.io.IOException; /** * A controller for the score text label on the MatchVisual, i.e. the part that can be repeated when the * series is longer. */ public class MatchScoreController { @FXML private Group root; @FXML private Text scoreText; public void setScoreText(String txt) { scoreText.setText(txt); } public Group getRoot() { return root; } public static MatchScoreController loadNew() { try { // Load the fxml document into the Controller and JavaFx node. FXMLLoader loader = new FXMLLoader(MatchScoreController.class.getResource("layout/MatchScore.fxml")); loader.load(); return loader.getController(); } catch (IOException e) { e.printStackTrace(); return null; } } }
996
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
CreateTeamsWithEachBotController.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/ui/CreateTeamsWithEachBotController.java
package dk.aau.cs.ds306e18.tournament.ui; import dk.aau.cs.ds306e18.tournament.model.Bot; import dk.aau.cs.ds306e18.tournament.model.Team; import dk.aau.cs.ds306e18.tournament.model.Tournament; import dk.aau.cs.ds306e18.tournament.rlbot.BotCollection; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.control.Button; import javafx.scene.control.Spinner; import javafx.scene.control.SpinnerValueFactory; import javafx.scene.input.MouseEvent; import javafx.stage.Stage; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; public class CreateTeamsWithEachBotController extends DraggablePopupWindow { @FXML private Button saveButton; @FXML private Spinner<Integer> teamSizeSpinner; @FXML private void initialize() { // Setup team size spinner teamSizeSpinner.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(1, 32, 1)); } public void closeWindow() { Stage window = (Stage) teamSizeSpinner.getScene().getWindow(); window.close(); } public void onCancelBtnPressed(ActionEvent actionEvent) { closeWindow(); } public void onSaveBtnPressed(ActionEvent actionEvent) { Tournament tournament = Tournament.get(); int seed = tournament.getTeams().size(); int teamSize = teamSizeSpinner.getValue(); for (Bot bot : BotCollection.global) { Team team = new Team(bot.getName(), Collections.nCopies(teamSize, bot), ++seed, ""); tournament.addTeam(team); } closeWindow(); Platform.runLater(ParticipantSettingsTabController.instance::update); } @FXML public void windowDragged(MouseEvent mouseEvent) { super.windowDragged(mouseEvent); } @FXML public void windowPressed(MouseEvent mouseEvent) { super.windowPressed(mouseEvent); } }
1,971
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
EditMatchScoreController.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/ui/EditMatchScoreController.java
package dk.aau.cs.ds306e18.tournament.ui; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.control.Spinner; import javafx.scene.layout.VBox; import java.io.IOException; import java.util.Optional; /** * A controller for the EditSeriesScore window part where you input the score for a single match, i.e the one * that is repeated when there series is longer. */ public class EditMatchScoreController { @FXML private VBox root; @FXML private Spinner<String> teamOneScoreSpinner; @FXML private Spinner<String> teamTwoScoreSpinner; public static EditMatchScoreController loadNew(Runnable onChange) { try { // Load the fxml document into the Controller and JavaFx node. FXMLLoader loader = new FXMLLoader(EditMatchScoreController.class.getResource("layout/EditMatchScore.fxml")); loader.load(); EditMatchScoreController controller = loader.getController(); controller.setupScoreSpinner(controller.teamOneScoreSpinner, onChange); controller.setupScoreSpinner(controller.teamTwoScoreSpinner, onChange); return controller; } catch (IOException e) { e.printStackTrace(); return null; } } /** * Adds behaviour to a score spinner. */ private void setupScoreSpinner(final Spinner<String> spinner, Runnable onChange) { // Values allowed in the spinner spinner.setValueFactory(new ScoreSpinnerValueFactory(0, 99)); spinner.setEditable(true); spinner.getEditor().textProperty().addListener((obs, oldText, newText) -> { // We allow empty strings, "-", and all positive numbers between 0 and 99 (inclusive) to be in the text field if (!(newText.equals("") || newText.matches("^(-|[0-9]|[1-9][0-9])$"))) { spinner.getEditor().setText(oldText); } else { onChange.run(); } }); // Select all text in text field when focused or edited spinner.getEditor().focusedProperty().addListener((obs, wasFocused, isNowFocused) -> { if (isNowFocused){ // Have to call using Platform::runLater because the spinner does something when it gains focus that interrupts. Platform.runLater(spinner.getEditor()::selectAll); } }); spinner.valueProperty().addListener(((observable, oldValue, newValue) -> { spinner.getEditor().selectAll(); })); } public VBox getRoot() { return root; } /** * Interpret and return the currently written score as an integer. If the written score is "" or "-" an empty * value is returned. */ public Optional<Integer> getTeamOneScore() { String scoreText = teamOneScoreSpinner.getEditor().getText(); return "".equals(scoreText) || "-".equals(scoreText) ? Optional.empty() : Optional.of(Integer.parseInt(scoreText)); } /** * Interpret and return the currently written score as an integer. If the written score is "" or "-" an empty * value is returned. */ public Optional<Integer> getTeamTwoScore() { String scoreText = teamTwoScoreSpinner.getEditor().getText(); return "".equals(scoreText) || "-".equals(scoreText) ? Optional.empty() : Optional.of(Integer.parseInt(scoreText)); } /** * Set the displayed scores. */ public void setScores(Optional<Integer> teamOneScore, Optional<Integer> teamTwoScore) { teamOneScoreSpinner.getEditor().setText(teamOneScore.map(Object::toString).orElse("-")); teamTwoScoreSpinner.getEditor().setText(teamTwoScore.map(Object::toString).orElse("-")); } }
3,791
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
BotIcons.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/ui/BotIcons.java
package dk.aau.cs.ds306e18.tournament.ui; import dk.aau.cs.ds306e18.tournament.model.Bot; import dk.aau.cs.ds306e18.tournament.rlbot.configuration.BotType; import javafx.scene.image.Image; public class BotIcons { private static Image rlbotIcon = new Image(BotCollectionCell.class.getResourceAsStream("layout/images/rlbot small square logo.png")); private static Image psyonixIcon = new Image(BotCollectionCell.class.getResourceAsStream("layout/images/psyonix small square logo.png")); /** * Returns an Image representing the bot. */ public static Image getIconForBot(Bot bot) { if (bot.getBotType() == BotType.PSYONIX) return psyonixIcon; return rlbotIcon; } }
711
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
MainController.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/ui/MainController.java
package dk.aau.cs.ds306e18.tournament.ui; import dk.aau.cs.ds306e18.tournament.Main; import dk.aau.cs.ds306e18.tournament.utility.Alerts; import dk.aau.cs.ds306e18.tournament.utility.SaveLoad; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.control.Tab; import javafx.scene.image.ImageView; import javafx.scene.input.MouseEvent; import javafx.stage.Stage; import java.io.IOException; public class MainController { @FXML public TournamentSettingsTabController tournamentSettingsTabController; @FXML public ParticipantSettingsTabController participantSettingsTabController; @FXML public RLBotSettingsTabController rlBotSettingsTabController; @FXML public BracketOverviewTabController bracketOverviewTabController; @FXML public ImageView saveTournamentBtn; @FXML public Tab tournamentSettingsTab; @FXML public Tab participantSettingsTab; @FXML public Tab rlbotSettingsTab; @FXML public Tab bracketOverviewTab; @FXML private void initialize() { Main.LOGGER.log(System.Logger.Level.INFO, "Initializing UI"); } public void onTabSelectionChanged(Event event) { // TODO Make references to other controllers work so we can avoid using singleton instances. Might require newer version of java if (tournamentSettingsTab.isSelected()) { TournamentSettingsTabController.instance.update(); } else if (participantSettingsTab.isSelected()) { ParticipantSettingsTabController.instance.update(); } else if (rlbotSettingsTab.isSelected()) { RLBotSettingsTabController.instance.update(); } else if (bracketOverviewTab.isSelected()) { BracketOverviewTabController.instance.update(); } } @FXML void onSaveIconClicked(MouseEvent event) { Stage fxstage = (Stage) saveTournamentBtn.getScene().getWindow(); try { SaveLoad.saveTournamentWithFileChooser(fxstage); Alerts.infoNotification("Saved", "Tournament was successfully saved."); } catch (IOException e) { Alerts.errorNotification("Error while saving", "Something went wrong while saving the tournament: " + e.getMessage()); Main.LOGGER.log(System.Logger.Level.ERROR, "Error while saving tournament", e); e.printStackTrace(); } } }
2,355
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
BracketOverviewTabController.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/ui/BracketOverviewTabController.java
package dk.aau.cs.ds306e18.tournament.ui; import dk.aau.cs.ds306e18.tournament.Main; import dk.aau.cs.ds306e18.tournament.model.format.StageStatusChangeListener; import dk.aau.cs.ds306e18.tournament.model.match.MatchResultDependencyException; import dk.aau.cs.ds306e18.tournament.model.match.Series; import dk.aau.cs.ds306e18.tournament.rlbot.MatchRunner; import dk.aau.cs.ds306e18.tournament.model.Bot; import dk.aau.cs.ds306e18.tournament.model.format.StageStatus; import dk.aau.cs.ds306e18.tournament.model.Tournament; import dk.aau.cs.ds306e18.tournament.model.format.Format; import dk.aau.cs.ds306e18.tournament.model.match.MatchChangeListener; import dk.aau.cs.ds306e18.tournament.utility.Alerts; import dk.aau.cs.ds306e18.tournament.ui.bracketObjects.ModelCoupledUI; import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.stage.StageStyle; import java.io.IOException; public class BracketOverviewTabController implements StageStatusChangeListener, MatchChangeListener { public static BracketOverviewTabController instance; @FXML private VBox startTournamentInstructionsHolder; @FXML private GridPane bracketOverviewTab; @FXML private VBox selectedMatchVBox; @FXML private VBox overviewVBox; @FXML private Button playMatchBtn; //@FXML private Button modifyConfigBtn; @FXML private Button fetchScoresBtn; @FXML private Button editMatchBtn; @FXML private Button switchColorsBtn; @FXML private Button extendSeriesBtn; @FXML private Button shortenSeriesBtn; @FXML private Label blueTeamNameLabel; @FXML private ListView<Bot> blueTeamListView; @FXML private Label orangeTeamNameLabel; @FXML private ListView<Bot> orangeTeamListView; @FXML private ScrollPane overviewScrollPane; @FXML private GridPane selectedMatchInfo; @FXML private HBox stageNavigationButtonsHolder; @FXML private Button nextStageBtn; @FXML private Button prevStageBtn; @FXML private Label startRequirementsLabel; @FXML private Button startTournamentBtn; @FXML private Label stageNameLabel; @FXML private Label botNameLabel; @FXML private Label botDeveloperLabel; @FXML private Label botDescriptionLabel; @FXML private VBox botInfoBox; private int showedStageIndex = -1; private ModelCoupledUI coupledBracket; private Format showedFormat; private SeriesVisualController selectedSeries; @FXML private void initialize() { instance = this; // Listeners for the listviews. Handles the clear of selection of the other listview and updates the // bot info box according to the selection. blueTeamListView.getSelectionModel().selectedItemProperty().addListener(observable -> { if (blueTeamListView.getItems() != null){ if (!(blueTeamListView.getItems().isEmpty())){ if (getSelectedBot(blueTeamListView) != null){ botInfoBox.setVisible(true); updateBotInfo(getSelectedBot(blueTeamListView)); clearSelectionOfTableview(orangeTeamListView); } } } }); orangeTeamListView.getSelectionModel().selectedItemProperty().addListener(observable -> { if (orangeTeamListView.getItems() != null){ if (!(orangeTeamListView.getItems().isEmpty())){ if (getSelectedBot(orangeTeamListView) != null){ botInfoBox.setVisible(true); updateBotInfo(getSelectedBot(orangeTeamListView)); clearSelectionOfTableview(blueTeamListView); } } } }); } /** * Clears the selection of a given ListView. */ private void clearSelectionOfTableview(ListView<Bot> listView){ if (getSelectedBot(listView) != null) { listView.getSelectionModel().clearSelection(); } } /** * Updates the labels on boxInfo according to a given bot. * @param selectedBot The given bot wished to receive details from. */ private void updateBotInfo(Bot selectedBot){ botNameLabel.setText(selectedBot.getName()); botDeveloperLabel.setText(selectedBot.getDeveloper()); botDescriptionLabel.setText(selectedBot.getDescription()); } /** * Updates all elements depending on the state of the tournament and the shown stage. */ public void update() { Tournament tournament = Tournament.get(); if (!tournament.hasStarted()) { showedStageIndex = -1; showedFormat = null; showStartTournamentInstructions(true); setSelectedSeries(null); updateStageNavigationButtons(); } else { if (showedStageIndex == -1) showedStageIndex = 0; showStartTournamentInstructions(false); showStage(tournament.getStages().get(showedStageIndex)); updateStageNavigationButtons(); } updateTeamViewer(selectedSeries == null ? null : selectedSeries.getShowedSeries()); } /** @return a string that contains text describing the requirements for starting the tournament. */ private String getRequirementsText(){ //Are requirements met if(Tournament.get().canStart()) return "You have met the requirements for starting a tournament."; int numberOfStages = Tournament.get().getStages().size(); int numberOfTeams = Tournament.get().getTeams().size(); StringBuilder sb = new StringBuilder(); sb.append("Before you start, you need to have "); if (numberOfStages < Tournament.START_REQUIREMENT_STAGES) { sb.append("at least ").append(Tournament.START_REQUIREMENT_STAGES).append(Tournament.START_REQUIREMENT_STAGES > 1 ? " stages" : " stage"); if(numberOfTeams < Tournament.START_REQUIREMENT_TEAMS) sb.append(" and "); } if (numberOfTeams < Tournament.START_REQUIREMENT_TEAMS) sb.append(Tournament.START_REQUIREMENT_TEAMS - numberOfTeams).append((numberOfTeams == 1) ? " more team" : " more teams"); return sb.append(".").toString(); } private void showStartTournamentInstructions(boolean show) { startTournamentBtn.setDisable(!Tournament.get().canStart()); startRequirementsLabel.setText(getRequirementsText()); startTournamentInstructionsHolder.setManaged(show); startTournamentInstructionsHolder.setVisible(show); overviewScrollPane.setManaged(!show); overviewScrollPane.setVisible(!show); stageNameLabel.setManaged(!show); stageNameLabel.setVisible(!show); } public void showStage(dk.aau.cs.ds306e18.tournament.model.Stage stage) { if (coupledBracket != null) { coupledBracket.decoupleFromModel(); showedFormat.unregisterStatusChangedListener(this); } showedFormat = stage.getFormat(); showedFormat.registerStatusChangedListener(this); stageNameLabel.setText(stage.getName()); Node bracket = showedFormat.getBracketFXNode(this); overviewScrollPane.setContent(bracket); if (bracket instanceof ModelCoupledUI) { coupledBracket = (ModelCoupledUI) bracket; } else { coupledBracket = null; Main.LOGGER.log(System.Logger.Level.ERROR, "PANIC! " + bracket.getClass() + " does not implement ModelCoupledUI."); } } /** * @param series the match to be visualised * @return a gridPane containing the visualisation of the given match. */ public SeriesVisualController loadSeriesVisual(Series series) { //Load the fxml document into the Controller and JavaFx node. FXMLLoader loader = new FXMLLoader(BracketOverviewTabController.class.getResource("layout/SeriesVisual.fxml")); HBox root = null; SeriesVisualController mvc = null; try { root = loader.load(); mvc = loader.getController(); } catch (IOException e) { e.printStackTrace(); } mvc.setBoc(this); mvc.setShowedSeries(series); return mvc; } /** * Sets the selected match. */ public void setSelectedSeries(SeriesVisualController match) { if (selectedSeries != null){ selectedSeries.getShowedSeries().unregisterMatchChangeListener(this); selectedSeries.getRoot().getStyleClass().remove("selectedMatch"); } this.selectedSeries = match; updateTeamViewer(match == null ? null : match.getShowedSeries()); if(selectedSeries != null) { selectedSeries.getShowedSeries().registerMatchChangeListener(this); } } /** * Deselects the match when a right click is registered within the scrollpane. */ @FXML void deselectOnRightClick(MouseEvent event) { if (event.getButton().equals(MouseButton.SECONDARY)){ setSelectedSeries(null); } } /** * Updates the team viewer on match clicked in overviewTab */ private void updateTeamViewer(Series series) { boolean disable = (series == null); botInfoBox.setVisible(false); selectedMatchInfo.setDisable(disable); if (series != null && series.getBlueTeam() != null) { // Blue team blueTeamNameLabel.setText(series.getBlueTeam().getTeamName()); blueTeamListView.setItems(FXCollections.observableArrayList(series.getBlueTeam().getBots())); blueTeamListView.refresh(); } else { // Orange team is unknown blueTeamNameLabel.setText("Blue team"); blueTeamListView.setItems(null); blueTeamListView.refresh(); } if (series != null && series.getOrangeTeam() != null) { // Orange team orangeTeamNameLabel.setText(series.getOrangeTeam().getTeamName()); orangeTeamListView.setItems(FXCollections.observableArrayList(series.getOrangeTeam().getBots())); orangeTeamListView.refresh(); } else { // Orange team is unknown orangeTeamNameLabel.setText("Orange team"); orangeTeamListView.setItems(null); orangeTeamListView.refresh(); } updateMatchPlayAndEditButtons(); } /** Disables/Enables the play and edit match buttons */ public void updateMatchPlayAndEditButtons() { if (selectedSeries == null || selectedSeries.getShowedSeries().getStatus() == Series.Status.NOT_PLAYABLE) { editMatchBtn.setDisable(true); playMatchBtn.setDisable(true); //modifyConfigBtn.setDisable(true); fetchScoresBtn.setDisable(true); switchColorsBtn.setDisable(true); } else { editMatchBtn.setDisable(false); // If match can't be played an error popup is displayed explaining why playMatchBtn.setDisable(false); //modifyConfigBtn.setDisable(false); // Only allow fetching of scores if the series is not over fetchScoresBtn.setDisable(selectedSeries.getShowedSeries().hasBeenPlayed()); // color switching is disabled when match has been played to avoid confusion when comparing replays and bracket switchColorsBtn.setDisable(selectedSeries.getShowedSeries().hasBeenPlayed()); } if (selectedSeries == null) { extendSeriesBtn.setDisable(true); shortenSeriesBtn.setDisable(true); } else { extendSeriesBtn.setDisable(false); shortenSeriesBtn.setDisable(selectedSeries.getShowedSeries().getSeriesLength() == 1); } } /** * Toggles edit for match scores */ @FXML void editMatchBtnOnAction() { openEditMatchPopup(); } /** * Creates a popup window allowing to change match score and state. */ public void openEditMatchPopup(){ try { Stage editMatchScoreStage = new Stage(); editMatchScoreStage.initStyle(StageStyle.TRANSPARENT); editMatchScoreStage.initModality(Modality.APPLICATION_MODAL); FXMLLoader loader = new FXMLLoader(BracketOverviewTabController.class.getResource("layout/EditSeriesScore.fxml")); AnchorPane editMatchStageRoot = loader.load(); EditSeriesScoreController emsc = loader.getController(); emsc.setSeries(selectedSeries.getShowedSeries()); editMatchScoreStage.setScene(new Scene(editMatchStageRoot)); // Calculate the center position of the main window. Stage mainWindow = (Stage) bracketOverviewTab.getScene().getWindow(); double centerXPosition = mainWindow.getX() + mainWindow.getWidth()/2d; double centerYPosition = mainWindow.getY() + mainWindow.getHeight()/2d; // Assign popup window to the center of the main window. editMatchScoreStage.setOnShown(ev -> { editMatchScoreStage.setX(centerXPosition - editMatchScoreStage.getWidth()/2d); editMatchScoreStage.setY(centerYPosition - editMatchScoreStage.getHeight()/2d); editMatchScoreStage.show(); }); editMatchScoreStage.show(); } catch (IOException e) { e.printStackTrace(); } } public void onStartTournamentButtonPressed(ActionEvent actionEvent) { if (Tournament.get().canStart()) { Tournament.get().start(); Main.LOGGER.log(System.Logger.Level.INFO, "Tournament started."); update(); } else { Alerts.errorNotification("Failed to start tournament", "You must have at least two teams and one stage to start a tournament."); Main.LOGGER.log(System.Logger.Level.ERROR, "Failed to start tournament due to requirements not being met."); } } private void updateStageNavigationButtons() { if (showedStageIndex == -1 || showedFormat == null) { nextStageBtn.setDisable(true); prevStageBtn.setDisable(true); } else { prevStageBtn.setDisable(showedStageIndex == 0); boolean concluded = Tournament.get().getStages().get(showedStageIndex).getFormat().getStatus() == StageStatus.CONCLUDED; boolean isLastStage = Tournament.get().getStages().size() - 1 == showedStageIndex; nextStageBtn.setDisable(!concluded || isLastStage); } } @Override public void onStageStatusChanged(Format format, StageStatus oldStatus, StageStatus newStatus) { updateStageNavigationButtons(); } @Override public void onMatchChanged(Series series) { updateTeamViewer(selectedSeries.getShowedSeries()); } public void prevStageBtnOnAction(ActionEvent actionEvent) { showedStageIndex--; showStage(Tournament.get().getStages().get(showedStageIndex)); setSelectedSeries(null); updateStageNavigationButtons(); } public void nextStageBtnOnAction(ActionEvent actionEvent) { int latestStageIndex = Tournament.get().getCurrentStageIndex(); if (showedStageIndex == latestStageIndex) { Tournament.get().startNextStage(); } showedStageIndex++; showStage(Tournament.get().getStages().get(showedStageIndex)); setSelectedSeries(null); updateStageNavigationButtons(); } public void onPlayMatchBtnAction(ActionEvent actionEvent) { MatchRunner.startMatch(Tournament.get().getRlBotSettings().getMatchConfig(), selectedSeries.getShowedSeries()); } public void fetchScoresButtonOnAction(ActionEvent actionEvent) { if (selectedSeries != null && MatchRunner.fetchScores()) { Series series = selectedSeries.getShowedSeries(); int blueScore = MatchRunner.latestBlueScore.get(); int orangeScore = MatchRunner.latestOrangeScore.get(); Main.LOGGER.log(System.Logger.Level.INFO, "Fetched scores: " + blueScore + "-" + orangeScore); try { // Insert scores if possible if (series.isTeamOneBlue()) { series.setScoresOfUnplayedMatch(blueScore, orangeScore); } else { series.setScoresOfUnplayedMatch(orangeScore, blueScore); } Alerts.infoNotification( "Fetched " + blueScore + "-" + orangeScore, "Successfully fetched the scoreline " + blueScore + "-" + orangeScore + "."); // Is series over now? Series.Outcome outcome = Series.winnerIfScores(series.getTeamOneScores(), series.getTeamTwoScores()); if (outcome != Series.Outcome.DRAW && outcome != Series.Outcome.UNKNOWN) { series.setScores(series.getTeamOneScores(), series.getTeamTwoScores(), true); } } catch (IllegalStateException ex) { Alerts.errorNotification("No missing results", "The selected series does not contain any matches without scores."); Main.LOGGER.log(System.Logger.Level.INFO, "The selected series does not contain any matches without scores."); } } else { Alerts.errorNotification("Fetching failed", "Failed to fetch scores. Is the CleoPetra's command prompt running?"); Main.LOGGER.log(System.Logger.Level.ERROR, "Failed to fetch scores."); } } public void modifyConfigButtonOnAction(ActionEvent actionEvent) { boolean ready = MatchRunner.prepareMatch(Tournament.get().getRlBotSettings().getMatchConfig(), selectedSeries.getShowedSeries()); if (ready) { Alerts.infoNotification("Modified config file", "The rlbot.cfg was successfully modified to the selected match."); } } /** * Method to return the selected bot in a given Listview * @param listView the listview to be checked for selection * @return the bot that is selected. */ private Bot getSelectedBot(ListView<Bot> listView) { return listView.getSelectionModel().getSelectedItem(); } public void onSwitchColorsBtnAction(ActionEvent actionEvent) { selectedSeries.getShowedSeries().setTeamOneToBlue(!selectedSeries.getShowedSeries().isTeamOneBlue()); } public void extendSeriesBtnOnAction(ActionEvent actionEvent) { carefullyChangeSeriesLength(selectedSeries.getShowedSeries().getSeriesLength() + 2); } public void shortenSeriesBtnOnAction(ActionEvent actionEvent) { // We assume the button is only clickable if the match length is greater than 1 carefullyChangeSeriesLength(selectedSeries.getShowedSeries().getSeriesLength() - 2); } /** * Changes the selected series length. In case this change the outcome of the series (and other series * depends on this outcome) an alert prompt is shown, and the user must confirm if they want to proceed. */ public void carefullyChangeSeriesLength(int length) { Series series = selectedSeries.getShowedSeries(); boolean force = false; boolean cancelled = false; while (!cancelled) { try { series.setSeriesLength(length, force); break; } catch (MatchResultDependencyException e) { // An MatchResultDependencyException is thrown if the outcome has changed and subsequent matches depends on this outcome // Ask if the user wants to proceed force = Alerts.confirmAlert("The outcome of this match has changed", "This change will reset the subsequent matches. Do you want to proceed?"); cancelled = !force; } } } }
20,408
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
TeamRosterCell.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/ui/TeamRosterCell.java
package dk.aau.cs.ds306e18.tournament.ui; import dk.aau.cs.ds306e18.tournament.model.Bot; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ListCell; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import java.io.IOException; /** * This is a custom ListCell used to display bots in a team's list of bots in the participant settings tab. */ public class TeamRosterCell extends ListCell<Bot> { @FXML public HBox hbox; @FXML public Label botNameLabel; @FXML public Button infoButton; @FXML public Button removeBotButton; @FXML public ImageView botTypeIcon; private Image rlbotIcon = new Image(TeamRosterCell.class.getResourceAsStream("layout/images/rlbot small square logo.png")); private Image psyonixIcon = new Image(TeamRosterCell.class.getResourceAsStream("layout/images/psyonix small square logo.png")); private ParticipantSettingsTabController participantSettingsTabController; public TeamRosterCell(ParticipantSettingsTabController participantSettingsTabController) { this.participantSettingsTabController = participantSettingsTabController; try { // Load the layout of the cell from the fxml file. The controller will be this class FXMLLoader fxmlLoader = new FXMLLoader(BotCollectionCell.class.getResource("layout/TeamRosterCell.fxml")); fxmlLoader.setController(this); fxmlLoader.load(); } catch (IOException e) { e.printStackTrace(); } } @Override protected void updateItem(Bot bot, boolean empty) { super.updateItem(bot, empty); // This text is not used by our custom cell setText(null); if (empty || bot == null) { // Nothing to display setGraphic(null); } else { // Display the bot name and a fitting icon botNameLabel.setText(bot.getName()); botTypeIcon.setImage(BotIcons.getIconForBot(bot)); setGraphic(hbox); } } @FXML public void onActionInfo(ActionEvent actionEvent) { BotInfoController.showInfoForBot(getItem(), getScene().getWindow()); } @FXML public void onActionRemove(ActionEvent actionEvent) { participantSettingsTabController.removeBotFromSelectedTeamRoster(getIndex()); } }
2,515
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
TournamentSettingsTabController.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/ui/TournamentSettingsTabController.java
package dk.aau.cs.ds306e18.tournament.ui; import dk.aau.cs.ds306e18.tournament.model.Stage; import dk.aau.cs.ds306e18.tournament.model.Tournament; import dk.aau.cs.ds306e18.tournament.model.format.SingleEliminationFormat; import dk.aau.cs.ds306e18.tournament.model.TieBreaker; import javafx.beans.InvalidationListener; import javafx.beans.Observable; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.*; import javafx.scene.input.KeyEvent; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import java.util.Collections; public class TournamentSettingsTabController { public static TournamentSettingsTabController instance; @FXML private GridPane tournamentSettingsTab; @FXML private TextField nameTextField; @FXML private ListView<Stage> stagesListView; @FXML private Button addStageBtn; @FXML private Button removeStageBtn; @FXML private VBox stageSettingsVBox; @FXML private Text selectStageText; @FXML private Text stageSettingsHeadLabel; @FXML private HBox stageSettingsContent; @FXML private TextField stageNameTextfield; @FXML private Spinner<Integer> defaultSeriesLengthSpinner; @FXML private ChoiceBox<StageFormatOption> formatChoicebox; @FXML private Button swapUp; @FXML private Button swapDown; @FXML private VBox formatUniqueSettingsHolder; @FXML private Spinner<Integer> teamsInStageSpinner; @FXML private Label teamsInStageAll; @FXML private void initialize() { instance = this; setUpStageListView(); updateGeneralTournamentSettings(); // Setup teams wanted in stage spinner teamsInStageSpinner.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(2, Integer.MAX_VALUE)); teamsInStageSpinner.getEditor().textProperty().addListener((obs, oldValue, newValue) -> { try { int value = Integer.parseInt(newValue); // This will throw the exception if the text is not a number getSelectedStage().setNumberOfTeamsWanted(value); } catch (NumberFormatException e) { teamsInStageSpinner.getEditor().setText(oldValue); } }); // Setup default series length spinner defaultSeriesLengthSpinner.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(1, 21, 1, 2)); defaultSeriesLengthSpinner.getEditor().textProperty().addListener((obs, oldValue, newValue) -> { try { Integer.parseInt(newValue); // This will throw the exception if the text is not a number } catch (NumberFormatException e) { defaultSeriesLengthSpinner.getEditor().setText(oldValue); } }); defaultSeriesLengthSpinner.getEditor().focusedProperty().addListener((observable, oldValue, newValue) -> { int length = Integer.parseInt(defaultSeriesLengthSpinner.getEditor().getText()); if (length % 2 == 0) length++; int safeLength = Math.max(length, 1); defaultSeriesLengthSpinner.getEditor().setText("" + safeLength); getSelectedStage().getFormat().setDefaultSeriesLength(safeLength); }); // Retrieve possible formats and add to a choicebox formatChoicebox.setItems(FXCollections.observableArrayList(StageFormatOption.values())); // Listener for the format choicebox. Used to change a Stage format when a different format is chosen formatChoicebox.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { Stage selectedStage = getSelectedStage(); if (selectedStage != null && StageFormatOption.getOption(selectedStage.getFormat()) != newValue) { selectedStage.setFormat(newValue.getNewInstance()); selectedStage.getFormat().setDefaultSeriesLength(defaultSeriesLengthSpinner.getValue()); } updateFormatUniqueSettings(); }); } /** Sets up the listview for stages. Setting items * and adding listener. */ private void setUpStageListView(){ /* Assign items to the list in case of a tournament being loaded */ stagesListView.setItems(FXCollections.observableArrayList(Tournament.get().getStages())); /* By default the stage settings are hidden. * This listener is used to show the stage settings when there is at least one Stage added. * Also handles disabling and enabling of buttons for stages. */ stagesListView.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { stageSettingsVBox.setVisible(stagesListView.getItems().size() != 0); /* Set content inside stage settings to show chosen stage */ updateStageSettings(); updateStageListButtons(); }); } /** Updates the settings unique to the selected stage's format */ public void updateFormatUniqueSettings() { Stage selectedStage = getSelectedStage(); formatUniqueSettingsHolder.getChildren().clear(); if (selectedStage != null) { Node formatSettings = selectedStage.getFormat().getSettingsFXNode(); if (formatSettings != null) { formatUniqueSettingsHolder.getChildren().add(selectedStage.getFormat().getSettingsFXNode()); } } } /** Updates all ui elements */ public void update() { updateGeneralTournamentSettings(); updateStageSettings(); } /** Updates all general tournament settings like tournament name, tiebreaker rule, and stage list*/ public void updateGeneralTournamentSettings() { Tournament tournament = Tournament.get(); nameTextField.setText(tournament.getName()); stagesListView.refresh(); updateStageListButtons(); } /** Updates the buttons under the stage list */ public void updateStageListButtons() { boolean started = Tournament.get().hasStarted(); if (stagesListView.getItems().size() == 0) { // If the stageListView has no items. Then the remove, up and down buttons is disabled. swapUp.setDisable(true); swapDown.setDisable(true); removeStageBtn.setDisable(true); } else { // Swap up and down depends on selected index. Remove is always enabled unless tournament has started int selectedIndex = getSelectedIndex(); swapUp.setDisable(selectedIndex == 0 || started); swapDown.setDisable(selectedIndex == stagesListView.getItems().size() - 1 && selectedIndex != -1 || started); removeStageBtn.setDisable(started); } addStageBtn.setDisable(started); } /** Updates all general stage settings like name and teams in stage. */ public void updateStageSettings() { boolean started = Tournament.get().hasStarted(); Stage selectedStage = getSelectedStage(); if (selectedStage != null) { stageNameTextfield.setText(selectedStage.getName()); formatChoicebox.getSelectionModel().select(StageFormatOption.getOption(selectedStage.getFormat())); formatChoicebox.setDisable(started); if (selectedStage.getStageNumber() != 1) { teamsInStageAll.setVisible(false); teamsInStageSpinner.setVisible(true); teamsInStageSpinner.getValueFactory().setValue(selectedStage.getNumberOfTeamsWanted()); } else { teamsInStageAll.setVisible(true); teamsInStageSpinner.setVisible(false); } teamsInStageSpinner.setDisable(started); defaultSeriesLengthSpinner.getValueFactory().setValue(selectedStage.getFormat().getDefaultSeriesLength()); defaultSeriesLengthSpinner.setDisable(started); } updateFormatUniqueSettings(); formatUniqueSettingsHolder.setDisable(started); } @FXML void nameTextFieldOnKeyReleased(KeyEvent event) { Tournament.get().setName(nameTextField.getText()); } @FXML void stageNameTextFieldOnKeyReleased(KeyEvent event) { getSelectedStage().setName(stageNameTextfield.getText()); stagesListView.refresh(); } /** * Adds a stage to the stages list and also to the tournament model. */ @FXML void addStageBtnOnAction(ActionEvent actionEvent) { // increments unique id Tournament.get().addStage(new Stage("New Stage", new SingleEliminationFormat())); stagesListView.setItems(FXCollections.observableArrayList(Tournament.get().getStages())); stagesListView.refresh(); stagesListView.getSelectionModel().selectLast(); } /** * Removes a stage from the Stages list and also from the tournament model. */ @FXML void removeStageBtnOnAction() { if (getSelectedIndex() != -1) { Tournament.get().removeStage(getSelectedIndex()); stagesListView.getItems().remove(getSelectedIndex()); } } /** * Swaps a stage upwards in the list of stages. Used to allow ordering of stages. * This also swaps the stages in the tournament model. */ @FXML private void swapStageUpwards() { if (getSelectedIndex() != 0 && getSelectedIndex() != -1) { Collections.swap(stagesListView.getItems(), getSelectedIndex(), getSelectedIndex() - 1); Tournament.get().swapStages(stagesListView.getItems().get(getSelectedIndex()), stagesListView.getItems().get(getSelectedIndex() - 1)); stagesListView.getSelectionModel().select(getSelectedIndex() - 1); } } /** * Swaps a stage downwards in the list of stages. Used to allow ordering of stages. * This also swaps the stages in the tournament model. */ @FXML private void swapStageDownwards() { int listSize = stagesListView.getItems().size(); if (getSelectedIndex() != listSize - 1 && getSelectedIndex() != -1) { Collections.swap(stagesListView.getItems(), getSelectedIndex(), getSelectedIndex() + 1); Tournament.get().swapStages(stagesListView.getItems().get(getSelectedIndex()), stagesListView.getItems().get(getSelectedIndex() + 1)); stagesListView.getSelectionModel().select(getSelectedIndex() + 1); } } private Stage getSelectedStage() { return stagesListView.getSelectionModel().getSelectedItem(); } private int getSelectedIndex() { return stagesListView.getSelectionModel().getSelectedIndex(); } }
10,973
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
EditSeriesScoreController.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/ui/EditSeriesScoreController.java
package dk.aau.cs.ds306e18.tournament.ui; import dk.aau.cs.ds306e18.tournament.model.match.MatchResultDependencyException; import dk.aau.cs.ds306e18.tournament.model.match.Series; import dk.aau.cs.ds306e18.tournament.utility.Alerts; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.Label; import javafx.scene.input.MouseEvent; import javafx.scene.layout.HBox; import javafx.scene.paint.Paint; import javafx.stage.Stage; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; /** * Controller for the pop-up window where scores are edited. */ public class EditSeriesScoreController extends DraggablePopupWindow { private static final Paint BLUE_FILL = Paint.valueOf("#6a82fc"); private static final Paint ORANGE_FILL = Paint.valueOf("#f5af18"); @FXML private CheckBox seriesFinishedCheckBox; @FXML private Label teamOneNameLabel; @FXML private Label teamTwoNameLabel; @FXML private HBox scoresContainer; @FXML private Button extendSeriesButton; @FXML private Button shortenSeriesButton; @FXML private Button saveButton; private Series series; private List<EditMatchScoreController> scoreControllers = new ArrayList<>(); /** * Checks the scores in the spinners. If they are okay, save button is enabled, other match-is-over checkbox * and save button is disabled accordingly. */ private void checkScoresAndUpdateUI() { List<Optional<Integer>> teamOneScores = scoreControllers.stream().map(EditMatchScoreController::getTeamOneScore).collect(Collectors.toList()); List<Optional<Integer>> teamTwoScores = scoreControllers.stream().map(EditMatchScoreController::getTeamTwoScore).collect(Collectors.toList()); Series.Outcome outcome = Series.winnerIfScores(teamOneScores, teamTwoScores); boolean seriesCanBeOver = outcome != Series.Outcome.UNKNOWN && outcome != Series.Outcome.DRAW; seriesFinishedCheckBox.setDisable(!seriesCanBeOver); seriesFinishedCheckBox.setSelected(seriesCanBeOver); } public void setSeries(Series series) { if (series == null) { closeWindow(); } this.series = series; teamOneNameLabel.setText(series.getTeamOne().getTeamName()); teamTwoNameLabel.setText(series.getTeamTwo().getTeamName()); if (series.isTeamOneBlue()) { teamOneNameLabel.setTextFill(BLUE_FILL); teamTwoNameLabel.setTextFill(ORANGE_FILL); } else { teamOneNameLabel.setTextFill(ORANGE_FILL); teamTwoNameLabel.setTextFill(BLUE_FILL); } setupScores(); checkScoresAndUpdateUI(); } /** * Setup score editors for each match in the series based on the model's current state. */ private void setupScores() { scoresContainer.getChildren().clear(); scoreControllers.clear(); for (int i = 0; i < series.getSeriesLength(); i++) { EditMatchScoreController scoreController = EditMatchScoreController.loadNew(this::checkScoresAndUpdateUI); scoresContainer.getChildren().add(scoreController.getRoot()); scoreControllers.add(scoreController); scoreController.setScores( series.getTeamOneScore(i), series.getTeamTwoScore(i) ); } } @FXML public void windowDragged(MouseEvent mouseEvent) { super.windowDragged(mouseEvent); } @FXML public void windowPressed(MouseEvent mouseEvent) { super.windowPressed(mouseEvent); } @FXML private void onCancelBtnPressed(ActionEvent actionEvent) { closeWindow(); } private void closeWindow() { Stage window = (Stage) teamOneNameLabel.getScene().getWindow(); window.close(); } @FXML private void onSaveBtnPressed(ActionEvent actionEvent) { List<Optional<Integer>> teamOneScores = new ArrayList<>(); List<Optional<Integer>> teamTwoScores = new ArrayList<>(); for (EditMatchScoreController scoreController : scoreControllers) { teamOneScores.add(scoreController.getTeamOneScore()); teamTwoScores.add(scoreController.getTeamTwoScore()); } boolean played = seriesFinishedCheckBox.isSelected(); boolean force = false; boolean cancelled = false; while (!cancelled) { try { series.setScores( scoreControllers.size(), teamOneScores, teamTwoScores, played, force); closeWindow(); break; } catch (MatchResultDependencyException e) { // An MatchResultDependencyException is thrown if the outcome has changed and subsequent matches depends on this outcome // Ask if the user wants to proceed force = Alerts.confirmAlert("The outcome of this match has changed", "This change will reset the subsequent matches. Do you want to proceed?"); cancelled = !force; } } } public void onActionExtendSeriesButton(ActionEvent actionEvent) { for (int i = 0; i < 2; i++) { EditMatchScoreController scoreController = EditMatchScoreController.loadNew(this::checkScoresAndUpdateUI); scoresContainer.getChildren().add(scoreController.getRoot()); scoreControllers.add(scoreController); scoreController.setScores(Optional.empty(), Optional.empty()); } saveButton.getScene().getWindow().sizeToScene(); checkScoresAndUpdateUI(); } public void onActionShortenSeriesButton(ActionEvent actionEvent) { int oldLength = scoreControllers.size(); if (oldLength > 1) { scoresContainer.getChildren().remove(oldLength - 2, oldLength); scoreControllers.remove(oldLength - 1); scoreControllers.remove(oldLength - 2); } saveButton.getScene().getWindow().sizeToScene(); checkScoresAndUpdateUI(); } }
6,299
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
StatsTable.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/ui/StatsTable.java
package dk.aau.cs.ds306e18.tournament.ui; import dk.aau.cs.ds306e18.tournament.model.Team; import dk.aau.cs.ds306e18.tournament.model.format.Format; import dk.aau.cs.ds306e18.tournament.model.stats.Stats; import dk.aau.cs.ds306e18.tournament.model.stats.StatsChangeListener; import dk.aau.cs.ds306e18.tournament.ui.bracketObjects.ModelCoupledUI; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleStringProperty; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class StatsTable extends TableView<Stats> implements StatsChangeListener, ModelCoupledUI { private List<Team> teams; private Format format; /** * Create a StatsTable to show stats for the given teams in the given stage/format. If format is null global stats * will be shown instead. */ public StatsTable(List<Team> teams, Format format) { super(); this.teams = new ArrayList<>(teams); this.format = format; setFocusTraversable(false); setMouseTransparent(true); calculateSize(); update(); registerAsListener(); } protected void calculateSize() { int items = teams.size(); setPrefHeight(23.5 + 24.5 * items); // Table heights are a nightmare. This creates an okay result. setPrefWidth(306); setMinHeight(USE_PREF_SIZE); setMaxHeight(USE_PREF_SIZE); } /** * Clears the table for columns and cells. */ public void clear() { getItems().clear(); getColumns().clear(); getSortOrder().clear(); } /** * Adds the relevant Stats items to the table. If format is null global stats will be used. */ protected void prepareItems() { List<Stats> stats = teams.stream() .map(t -> format == null ? t.getStatsManager().getGlobalStats() : t.getStatsManager().getStats(format)) .collect(Collectors.toList()); getItems().addAll(stats); } protected void addTeamNameColumn() { TableColumn<Stats, String> nameColumn = new TableColumn<>("Name"); nameColumn.setCellValueFactory(cell -> new SimpleStringProperty(cell.getValue().getTeam().getTeamName())); nameColumn.setMinWidth(110); nameColumn.setMaxWidth(110); getColumns().add(nameColumn); } protected void addWinsColumn() { TableColumn<Stats, Integer> winsColumn = new TableColumn<>("Wins"); winsColumn.setCellValueFactory(cell -> new SimpleIntegerProperty(cell.getValue().getWins()).asObject()); winsColumn.setSortType(TableColumn.SortType.DESCENDING); winsColumn.setStyle("-fx-alignment: CENTER;"); getColumns().add(winsColumn); getSortOrder().add(winsColumn); } protected void addLosesColumn() { TableColumn<Stats, Integer> losesColumn = new TableColumn<>("Loses"); losesColumn.setCellValueFactory(cell -> new SimpleIntegerProperty(cell.getValue().getLoses()).asObject()); losesColumn.setSortType(TableColumn.SortType.ASCENDING); losesColumn.setStyle("-fx-alignment: CENTER;"); getColumns().add(losesColumn); getSortOrder().add(losesColumn); } protected void addGoalDiffColumn() { TableColumn<Stats, Integer> goalDifferenceColumn = new TableColumn<>("GDiff"); goalDifferenceColumn.setCellValueFactory(cell -> new SimpleIntegerProperty(cell.getValue().getGoalDifference()).asObject()); goalDifferenceColumn.setSortType(TableColumn.SortType.DESCENDING); goalDifferenceColumn.setStyle("-fx-alignment: CENTER;"); getColumns().add(goalDifferenceColumn); getSortOrder().add(goalDifferenceColumn); } protected void addGoalsColumn() { TableColumn<Stats, Integer> goalsColumn = new TableColumn<>("Goals"); goalsColumn.setCellValueFactory(cell -> new SimpleIntegerProperty(cell.getValue().getGoals()).asObject()); goalsColumn.setSortType(TableColumn.SortType.DESCENDING); goalsColumn.setStyle("-fx-alignment: CENTER;"); getColumns().add(goalsColumn); getSortOrder().add(goalsColumn); } /** * Updates all values in the table. */ public void update() { clear(); prepareItems(); addTeamNameColumn(); addWinsColumn(); addLosesColumn(); addGoalDiffColumn(); addGoalsColumn(); } private void registerAsListener() { for (Team team : teams) { Stats stats = format == null ? team.getStatsManager().getGlobalStats() : team.getStatsManager().getStats(format); stats.registerStatsChangeListener(this); } } private void unregisterAsListener() { for (Team team : teams) { Stats stats = format == null ? team.getStatsManager().getGlobalStats() : team.getStatsManager().getStats(format); stats.unregisterStatsChangeListener(this); } } @Override public void statsChanged(Stats stats) { update(); } @Override public void decoupleFromModel() { unregisterAsListener(); teams = null; format = null; } }
5,388
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
RoundRobinNode.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/ui/bracketObjects/RoundRobinNode.java
package dk.aau.cs.ds306e18.tournament.ui.bracketObjects; import dk.aau.cs.ds306e18.tournament.model.format.RoundRobinFormat; import dk.aau.cs.ds306e18.tournament.model.format.RoundRobinGroup; import dk.aau.cs.ds306e18.tournament.model.match.Series; import dk.aau.cs.ds306e18.tournament.ui.BracketOverviewTabController; import dk.aau.cs.ds306e18.tournament.ui.SeriesVisualController; import dk.aau.cs.ds306e18.tournament.ui.StatsTable; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Label; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.text.Font; import java.util.ArrayList; public class RoundRobinNode extends VBox implements ModelCoupledUI { private final Insets MARGINS = new Insets(0, 8, 8, 0); private final Insets ROUND_PADDING = new Insets(0,5,28,0); private final Insets LABEL_PADDING = new Insets(0,16,0,0); private final Insets TABLE_MARGIN = new Insets(0,0,0,64); private final RoundRobinFormat roundRobin; private final BracketOverviewTabController boc; private ArrayList<SeriesVisualController> mvcs = new ArrayList<>(); private ArrayList<StatsTable> statsTables = new ArrayList<>(); public RoundRobinNode(RoundRobinFormat roundRobin, BracketOverviewTabController boc) { this.roundRobin = roundRobin; this.boc = boc; update(); } /** Updates all UI elements for the round robin stage. */ private void update() { removeElements(); ArrayList<RoundRobinGroup> groups = roundRobin.getGroups(); for(int i = 0; i < groups.size(); i++) getChildren().add(getGroupBox(groups.get(i), i)); } /** Creates a hbox containing a group with rounds of matches. * @param rrgroup the RoundRobinGroup that the box should contain. * @param groupNumber the number of the group. * @return a hbox containing a group with rounds of matches. */ private HBox getGroupBox(RoundRobinGroup rrgroup, int groupNumber){ HBox box = new HBox(); box.setPadding(ROUND_PADDING); //Set up label and its box Label groupLabel = new Label("G" + (groupNumber + 1)); groupLabel.setFont(new Font("Calibri", 28)); groupLabel.setTextFill(Color.valueOf("#C1C1C1")); HBox labelBox = new HBox(); labelBox.setAlignment(Pos.CENTER); labelBox.setPadding(LABEL_PADDING); labelBox.getChildren().add(groupLabel); box.getChildren().add(labelBox); // Add rounds to this group. Each round is a contained in a VBox for(int i = 0; i < rrgroup.getRounds().size(); i++) box.getChildren().add(getRoundBox(rrgroup.getRounds().get(i), i)); // Leaderboard for the group StatsTable table = new StatsTable(rrgroup.getTeams(), roundRobin); box.getChildren().add(table); HBox.setMargin(table, TABLE_MARGIN); statsTables.add(table); return box; } /** Returns a vbox that contains a round of matches. * @param series the matches in the round. * @param roundNumber the number of the round. * @return a vbox that contains a round of matches. */ private VBox getRoundBox(ArrayList<Series> series, int roundNumber){ VBox box = new VBox(); box.getChildren().add(new Label("Round " + (roundNumber + 1))); //Add matches for (Series serie : series) { SeriesVisualController vmatch = boc.loadSeriesVisual(serie); VBox.setMargin(vmatch.getRoot(), MARGINS); box.getChildren().add(vmatch.getRoot()); mvcs.add(vmatch); } return box; } @Override public void decoupleFromModel() { removeElements(); } /** Completely remove all UI elements. */ public void removeElements() { for (SeriesVisualController mvc : mvcs) { mvc.decoupleFromModel(); } for (StatsTable table : statsTables) { table.decoupleFromModel(); } getChildren().clear(); mvcs.clear(); statsTables.clear(); } }
4,168
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
SingleEliminationNode.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/ui/bracketObjects/SingleEliminationNode.java
package dk.aau.cs.ds306e18.tournament.ui.bracketObjects; import dk.aau.cs.ds306e18.tournament.model.format.SingleEliminationFormat; import dk.aau.cs.ds306e18.tournament.model.match.Series; import dk.aau.cs.ds306e18.tournament.ui.BracketOverviewTabController; import dk.aau.cs.ds306e18.tournament.ui.SeriesVisualController; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.geometry.VPos; import javafx.scene.layout.GridPane; import javafx.scene.layout.VBox; import java.util.ArrayList; import static dk.aau.cs.ds306e18.tournament.utility.PowMath.pow2; /** Used to display the a single elimination stage. */ public class SingleEliminationNode extends GridPane implements ModelCoupledUI { private final Insets MARGINS = new Insets(0, 0, 16, 0); private final int CELL_HEIGHT = 48; private final SingleEliminationFormat singleElimination; private final BracketOverviewTabController boc; private ArrayList<SeriesVisualController> mvcs = new ArrayList<>(); /** Used to display the a single elimination stage. */ public SingleEliminationNode(SingleEliminationFormat singleElimination, BracketOverviewTabController boc){ this.singleElimination = singleElimination; this.boc = boc; update(); } /** Updates all ui elements for the single elimination stage. */ private void update() { removeElements(); Series[] seriesArray = singleElimination.getMatchesAsArray(); int rounds = singleElimination.getRounds(); int m = 0; // match index for (int r = 0; r < rounds; r++) { int matchesInRound = pow2(r); int column = rounds - 1 - r; int cellSpan = pow2(column); // Add matches for round r for (int i = 0; i < matchesInRound; i++) { Series series = seriesArray[m]; m++; VBox box = new VBox(); // Some matches can be null if (series != null) { SeriesVisualController mvc = boc.loadSeriesVisual(series); mvcs.add(mvc); box.getChildren().add(mvc.getRoot()); mvc.setShowIdentifier(true); } box.setAlignment(Pos.CENTER); box.setMinHeight(CELL_HEIGHT * cellSpan); add(box, column, (matchesInRound - 1 - i) * cellSpan); setRowSpan(box, cellSpan); setMargin(box, MARGINS); setValignment(box, VPos.CENTER); } } } @Override public void decoupleFromModel() { removeElements(); } /** Completely remove all ui elements. */ public void removeElements() { getChildren().clear(); for (SeriesVisualController mvc : mvcs) { mvc.decoupleFromModel(); } mvcs.clear(); } }
2,912
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
SwissSettingsNode.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/ui/bracketObjects/SwissSettingsNode.java
package dk.aau.cs.ds306e18.tournament.ui.bracketObjects; import dk.aau.cs.ds306e18.tournament.model.format.SwissFormat; import javafx.scene.control.Label; import javafx.scene.control.Spinner; import javafx.scene.control.SpinnerValueFactory; import javafx.scene.layout.BorderPane; import javafx.scene.text.Font; public class SwissSettingsNode extends BorderPane { private final SwissFormat swiss; public SwissSettingsNode(SwissFormat swiss) { this.swiss = swiss; // Rounds label Label roundsLabel = new Label("Rounds:"); roundsLabel.setFont(new Font("System", 16)); setLeft(roundsLabel); // Rounds spinner Spinner<Integer> roundsSpinner = new Spinner<>(new SpinnerValueFactory.IntegerSpinnerValueFactory(1, Integer.MAX_VALUE)); roundsSpinner.setEditable(true); roundsSpinner.getValueFactory().setValue(swiss.getRoundCount()); roundsSpinner.getEditor().textProperty().addListener((obs, oldValue, newValue) -> { try { int value = Integer.valueOf(newValue); //This will throw the exception if the value not only contains numbers swiss.setRoundCount(value); } catch (NumberFormatException e) { roundsSpinner.getEditor().setText("1"); //Setting default value } }); setRight(roundsSpinner); } }
1,388
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
SwissNode.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/ui/bracketObjects/SwissNode.java
package dk.aau.cs.ds306e18.tournament.ui.bracketObjects; import dk.aau.cs.ds306e18.tournament.model.match.Series; import dk.aau.cs.ds306e18.tournament.model.format.SwissFormat; import dk.aau.cs.ds306e18.tournament.model.match.MatchChangeListener; import dk.aau.cs.ds306e18.tournament.model.match.MatchPlayedListener; import dk.aau.cs.ds306e18.tournament.ui.BracketOverviewTabController; import dk.aau.cs.ds306e18.tournament.ui.SeriesVisualController; import dk.aau.cs.ds306e18.tournament.ui.StatsTableWithPoints; import javafx.geometry.Insets; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import java.util.ArrayList; /** Used to display the a swiss stage. */ public class SwissNode extends HBox implements MatchPlayedListener, MatchChangeListener, ModelCoupledUI { private final Insets MARGINS = new Insets(0, 8, 8, 0); private final Insets COLUMN_MARGINS = new Insets(0, 32, 8, 0); private final Insets TABLE_MARGINS = new Insets(0, 64, 0, 0); private final SwissFormat swiss; private final BracketOverviewTabController boc; private Button generateRoundButton; private ArrayList<SeriesVisualController> mvcs = new ArrayList<>(); private StatsTableWithPoints table; public SwissNode(SwissFormat swiss, BracketOverviewTabController boc) { this.boc = boc; this.swiss = swiss; // Register to events from all matches for (Series series : swiss.getAllSeries()) { series.registerMatchChangeListener(this); series.registerMatchPlayedListener(this); } update(); } /** Updates all ui elements for the swiss stage. */ private void update() { removeElements(); table = new StatsTableWithPoints(swiss.getTeams(), swiss, swiss.getTeamPointsMap()); HBox.setMargin(table, TABLE_MARGINS); getChildren().add(table); ArrayList<ArrayList<Series>> rounds = swiss.getRounds(); int numberOfRounds = rounds.size(); // Create that amount of columns matching the number of generated rounds. for (int i = 0; i < numberOfRounds; i++) { VBox column = new VBox(); // Round Label Label roundLabel = new Label("Round " + (i + 1)); VBox.setMargin(roundLabel, MARGINS); column.getChildren().add(roundLabel); // Get all matches from round and add them to the column ArrayList<Series> round = rounds.get(i); for (Series series : round) { SeriesVisualController vmatch = boc.loadSeriesVisual(series); VBox.setMargin(vmatch.getRoot(), MARGINS); column.getChildren().add(vmatch.getRoot()); mvcs.add(vmatch); } getChildren().add(column); HBox.setMargin(column, COLUMN_MARGINS); } // If there can be generated another round, then add a column more that contains a button for generating. if (swiss.hasUnstartedRounds()) { getChildren().add(getNextRoundVBox(numberOfRounds + 1)); } } @Override public void decoupleFromModel() { removeElements(); // Unregister from events from all matches for (Series m : swiss.getAllSeries()) { m.unregisterMatchChangeListener(this); m.unregisterMatchPlayedListener(this); } } /** Completely remove all ui elements. */ public void removeElements() { for (SeriesVisualController mvc : mvcs) { mvc.decoupleFromModel(); } getChildren().clear(); mvcs.clear(); generateRoundButton = null; if (table != null) { table.decoupleFromModel(); table = null; } } /** @return the vbox that has the "generate next round" button. */ private VBox getNextRoundVBox(int roundNumber) { // Column vbox VBox column = new VBox(); // Round Label Label roundLabel = new Label("Round " + roundNumber); VBox.setMargin(roundLabel, MARGINS); column.getChildren().add(roundLabel); // Generate next round button generateRoundButton = new Button(); generateRoundButton.setText("Generate Round"); generateRoundButton.setOnMouseClicked(e -> { swiss.startNextRound(); // Register to events from newest round for (Series m : swiss.getRounds().get(swiss.getRounds().size() - 1)) { m.registerMatchPlayedListener(this); m.registerMatchChangeListener(this); } update(); }); column.getChildren().add(generateRoundButton); updateGenerateRoundButton(); return column; } /** Enables or disables generate round button depending on the state. */ private void updateGenerateRoundButton() { if (generateRoundButton != null) generateRoundButton.setDisable(!swiss.canStartNextRound()); } @Override public void onMatchPlayed(Series series) { updateGenerateRoundButton(); } @Override public void onMatchChanged(Series series) { } }
5,270
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
RoundRobinSettingsNode.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/ui/bracketObjects/RoundRobinSettingsNode.java
package dk.aau.cs.ds306e18.tournament.ui.bracketObjects; import dk.aau.cs.ds306e18.tournament.model.format.RoundRobinFormat; import javafx.scene.control.Label; import javafx.scene.control.Spinner; import javafx.scene.control.SpinnerValueFactory; import javafx.scene.layout.BorderPane; import javafx.scene.text.Font; public class RoundRobinSettingsNode extends BorderPane { private final RoundRobinFormat roundRobin; public RoundRobinSettingsNode(RoundRobinFormat roundRobin) { this.roundRobin = roundRobin; // Groups label Label groupsLabel = new Label("Groups:"); groupsLabel.setFont(new Font("System", 16)); setLeft(groupsLabel); // Groups spinner Spinner<Integer> groupsSpinner = new Spinner<>(new SpinnerValueFactory.IntegerSpinnerValueFactory(1, Integer.MAX_VALUE)); groupsSpinner.setEditable(true); groupsSpinner.getValueFactory().setValue(roundRobin.getNumberOfGroups()); groupsSpinner.getEditor().textProperty().addListener((obs, oldValue, newValue) -> { try { int value = Integer.valueOf(newValue); //This will throw the exception if the value not only contains numbers roundRobin.setNumberOfGroups(value); } catch (NumberFormatException e) { groupsSpinner.getEditor().setText("1"); //Setting default value } }); setRight(groupsSpinner); } }
1,451
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
DoubleEliminationNode.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/ui/bracketObjects/DoubleEliminationNode.java
package dk.aau.cs.ds306e18.tournament.ui.bracketObjects; import dk.aau.cs.ds306e18.tournament.model.format.*; import dk.aau.cs.ds306e18.tournament.model.match.Series; import dk.aau.cs.ds306e18.tournament.ui.BracketOverviewTabController; import dk.aau.cs.ds306e18.tournament.ui.SeriesVisualController; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.geometry.VPos; import javafx.scene.Node; import javafx.scene.layout.GridPane; import javafx.scene.layout.VBox; import javafx.scene.paint.Paint; import javafx.scene.shape.Line; import java.util.ArrayList; import static dk.aau.cs.ds306e18.tournament.utility.PowMath.pow2; public class DoubleEliminationNode extends VBox implements ModelCoupledUI, StageStatusChangeListener { private final Insets MARGINS = new Insets(0, 0, 16, 0); private final int SPACE_BETWEEN_BRACKETS_AND_LINE = 32; private final int CELL_HEIGHT = 48; private final DoubleEliminationFormat doubleElimination; private final BracketOverviewTabController boc; private final GridPane upperGrid = new GridPane(); private final GridPane lowerGrid = new GridPane(); private SeriesVisualController extraMatchMVC; private ArrayList<SeriesVisualController> mvcs = new ArrayList<>(); /** Used to display the a double elimination stage. */ public DoubleEliminationNode(DoubleEliminationFormat doubleElimination, BracketOverviewTabController boc){ this.doubleElimination = doubleElimination; this.boc = boc; doubleElimination.registerStatusChangedListener(this); getChildren().add(upperGrid); getChildren().add(getLine()); getChildren().add(lowerGrid); setSpacing(SPACE_BETWEEN_BRACKETS_AND_LINE); update(); } /** Updates all ui elements for the double elimination stage. */ private void update() { removeElements(); // Upper bracket Series[] upperBracket = doubleElimination.getUpperBracket(); int rounds = doubleElimination.getUpperBracketRounds(); int m = 0; // match index for (int r = 0; r < rounds; r++) { int matchesInRound = pow2(r); int column = rounds - 1 - r; int rowSpan = pow2(column); // Add matches for round r for (int i = 0; i < matchesInRound; i++) { Series series = upperBracket[m++]; VBox box = createMatchBox(series, rowSpan, false); upperGrid.add(box, column, (matchesInRound - 1 - i) * rowSpan); } } // Final match is added to upper bracket VBox finalsBox = createMatchBox(doubleElimination.getFinalSeries(), pow2(rounds - 1), false); upperGrid.add(finalsBox, rounds, 0); // Extra match is only shown when needed VBox extraBox = createMatchBox(doubleElimination.getExtraSeries(), pow2(rounds - 1), true); upperGrid.add(extraBox, rounds + 1, 0); updateDisplayOfExtraMatch(); // Lower bracket Series[] lowerBracket = doubleElimination.getLowerBracket(); if (lowerBracket.length > 0) { int matchesInCurrentRound = pow2(rounds - 2); int column = 0; int rowSpan = 1; m = 0; // match index while (true) { for (int i = 0; i < matchesInCurrentRound; i++) { Series series = lowerBracket[m++]; VBox box = createMatchBox(series, rowSpan, false); lowerGrid.add(box, column, i * rowSpan); } // Half the number of matches in a round every other round if (column % 2 == 1) { if (matchesInCurrentRound == 1) { break; // We can't do more halving } matchesInCurrentRound /= 2; rowSpan *= 2; } column++; } } } private VBox createMatchBox(Series series, int rowSpan, boolean isExtra) { VBox box = new VBox(); // Some matches are null because of byes. In those cases the VBox will just be empty if (series != null) { SeriesVisualController mvc = boc.loadSeriesVisual(series); mvcs.add(mvc); box.getChildren().add(mvc.getRoot()); mvc.setShowIdentifier(true); if (isExtra) { extraMatchMVC = mvc; } } box.setAlignment(Pos.CENTER); box.setMinHeight(CELL_HEIGHT * rowSpan); GridPane.setRowSpan(box, rowSpan); GridPane.setMargin(box, MARGINS); GridPane.setValignment(box, VPos.CENTER); return box; } /** Creates the line between upper and lower bracket */ private Node getLine() { int width = 180 * (doubleElimination.getUpperBracketRounds() + 2); Line line = new Line(0, 0, width, 0); line.setStroke(Paint.valueOf("#c1c1c1")); VBox box = new VBox(); box.getChildren().add(line); VBox.setMargin(line, MARGINS); return box; } @Override public void decoupleFromModel() { removeElements(); doubleElimination.unregisterStatusChangedListener(this); } /** Completely remove all ui elements. */ public void removeElements() { upperGrid.getChildren().clear(); lowerGrid.getChildren().clear(); for (SeriesVisualController mvc : mvcs) { mvc.decoupleFromModel(); } mvcs.clear(); } private void updateDisplayOfExtraMatch() { extraMatchMVC.setDisabled(!doubleElimination.isExtraMatchNeeded()); } @Override public void onStageStatusChanged(Format format, StageStatus oldStatus, StageStatus newStatus) { updateDisplayOfExtraMatch(); } }
5,874
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
LatestPaths.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/settings/LatestPaths.java
package dk.aau.cs.ds306e18.tournament.settings; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.nio.file.Files; import java.util.Properties; /** * A helper class to handle paths to where tournament files, bots, and overlays are stored. Main usage is * making file chooser start from a reasonable directory. */ public class LatestPaths { // If we have no info about where things are stored we will use the current working directory private static final File FALLBACK_DIR = new File("").getAbsoluteFile(); private static final String KEY_TOURNAMENT_SAVE_DIR = "lastTournamentSaveDir"; private static final String KEY_BOT_CONFIG_DIR = "lastBotConfigDir"; private static final String KEY_OVERLAY_DIR = "lastOverlayDir"; private final Properties properties; /** * Create a new LatestPaths based on the given properties file. */ public LatestPaths(Properties properties) { this.properties = properties; } /** * Returns the directory where the latest tournament file was saved or a reasonable fallback directory. */ public File getTournamentSaveDirectory() { String tournamentSaveDirectory = properties.getProperty(KEY_TOURNAMENT_SAVE_DIR); if (tournamentSaveDirectory != null) { File dir = new File(tournamentSaveDirectory); // Dir might not exist anymore. In that case we will forget about it if (dir.exists()) return dir; else properties.remove(KEY_TOURNAMENT_SAVE_DIR); } return FALLBACK_DIR; } /** * Update latest tournament save directory. */ public void setTournamentSaveDirectory(File dir) { if (dir.exists()) { properties.setProperty(KEY_TOURNAMENT_SAVE_DIR, dir.getAbsolutePath()); saveProperties(); } } /** * Returns the directory where the latest bot(s) was loaded from or a reasonable fallback directory. */ public File getBotConfigDirectory() { String botConfigDirectory = properties.getProperty(KEY_BOT_CONFIG_DIR); if (botConfigDirectory != null) { File dir = new File(botConfigDirectory); // Dir might not exist anymore. In that case we will forget about it if (dir.exists()) return dir; else properties.remove(KEY_BOT_CONFIG_DIR); } // Fallback to tournament save dir return getTournamentSaveDirectory(); } /** * Update latest bot config directory. */ public void setBotConfigDirectory(File dir) { if (dir.exists()) { properties.setProperty(KEY_BOT_CONFIG_DIR, dir.getAbsolutePath()); saveProperties(); } } /** * Returns the directory where the latest overlay was stored or a reasonable fallback directory. */ public File getOverlayDirectory() { String overlayDirectory = properties.getProperty(KEY_OVERLAY_DIR); if (overlayDirectory != null) { File dir = new File(overlayDirectory); // Dir might not exist anymore. In that case we will forget about it if (dir.exists()) return dir; else properties.remove(KEY_TOURNAMENT_SAVE_DIR); } // Fallback to tournament save dir return getTournamentSaveDirectory(); } /** * Update latest overlay directory. */ public void setOverlayDirectory(File dir) { if (dir.exists()) { properties.setProperty(KEY_OVERLAY_DIR, dir.getAbsolutePath()); saveProperties(); } } private void saveProperties() { try (OutputStream fs = Files.newOutputStream(SettingsDirectory.PROPERTIES)) { properties.store(fs, null); } catch (IOException e) { e.printStackTrace(); } } }
3,878
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
SettingsDirectory.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/settings/SettingsDirectory.java
package dk.aau.cs.ds306e18.tournament.settings; import dk.aau.cs.ds306e18.tournament.Main; import dk.aau.cs.ds306e18.tournament.utility.FileOperations; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; /** * This class contains paths to all the files in the settings directory, which makes it easy to refer to the any given * file. The setup method should be called on start up to ensure that the require directories and files exists. */ public class SettingsDirectory { public static final Path BASE = Paths.get(System.getProperty("user.home")).resolve(".cleopetra/"); public static final Path PROPERTIES = BASE.resolve("cleopetra.properties"); public static final Path PSYONIX_BOTS = BASE.resolve("psyonix_bots"); public static final Path PSYONIX_APPEARANCE = PSYONIX_BOTS.resolve("psyonix_appearance.cfg"); public static final Path PSYONIX_ALLSTAR = PSYONIX_BOTS.resolve("psyonix_allstar.cfg"); public static final Path PSYONIX_PRO = PSYONIX_BOTS.resolve("psyonix_pro.cfg"); public static final Path PSYONIX_ROOKIE = PSYONIX_BOTS.resolve("psyonix_rookie.cfg"); public static final Path MATCH_FILES = BASE.resolve("rlbot"); public static final Path MATCH_CONFIG = MATCH_FILES.resolve("rlbot.cfg"); public static final Path RUN_PY = MATCH_FILES.resolve("run.py"); }
1,417
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
CleoPetraSettings.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/settings/CleoPetraSettings.java
package dk.aau.cs.ds306e18.tournament.settings; import dk.aau.cs.ds306e18.tournament.Main; import dk.aau.cs.ds306e18.tournament.utility.FileOperations; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.Properties; public class CleoPetraSettings { private static Properties properties; private static LatestPaths latestPaths; /** * Setup/load the settings for CleoPetra, located in 'user.home/.cleopetra/', and makes sure the required * files are present. Should always be called on start up. */ public static void setup() { try { Files.createDirectories(SettingsDirectory.BASE); // CleoPetra properties if (Files.notExists(SettingsDirectory.PROPERTIES)) { Files.createFile(SettingsDirectory.PROPERTIES); } try (InputStream fs = Files.newInputStream(SettingsDirectory.PROPERTIES)) { properties = new Properties(); properties.load(fs); } latestPaths = new LatestPaths(properties); // Files for starting matches. 'rlbot.cfg' is created right before match start. Files.createDirectories(SettingsDirectory.MATCH_FILES); Files.copy(Main.class.getResourceAsStream("settings/files/run.py"), SettingsDirectory.RUN_PY, StandardCopyOption.REPLACE_EXISTING); setupPsyonixBots(); } catch (IOException e) { e.printStackTrace(); } } /** * Copies the Psyonix bot config files to the CleoPetra settings folder so they can be read by the RLBot framework. * If the files already exists, they won't be replaced. This allows the user to change the config files * (e.g. change the appearance) and customize their Psyonix bots. * * @throws IOException thrown if something goes wrong during copying the files or if URI path is wrong. */ private static void setupPsyonixBots() throws IOException { Files.createDirectories(SettingsDirectory.PSYONIX_BOTS); FileOperations.copyIfMissing(Main.class.getResourceAsStream("settings/files/psyonix_appearance.cfg"), SettingsDirectory.PSYONIX_APPEARANCE); FileOperations.copyIfMissing(Main.class.getResourceAsStream("settings/files/psyonix_allstar.cfg"), SettingsDirectory.PSYONIX_ALLSTAR); FileOperations.copyIfMissing(Main.class.getResourceAsStream("settings/files/psyonix_pro.cfg"), SettingsDirectory.PSYONIX_PRO); FileOperations.copyIfMissing(Main.class.getResourceAsStream("settings/files/psyonix_rookie.cfg"), SettingsDirectory.PSYONIX_ROOKIE); } public static LatestPaths getLatestPaths() { return latestPaths; } }
2,823
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
SeedingOption.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/model/SeedingOption.java
package dk.aau.cs.ds306e18.tournament.model; public enum SeedingOption { SEED_BY_ORDER("By order in list"), MANUALLY("Manually"), NO_SEEDING("No seeding"), RANDOM_SEEDING("Random seeding"); private String optionText; SeedingOption(String optionText) { this.optionText = optionText; } @Override public String toString() { return optionText; } }
404
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
BotFromConfig.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/model/BotFromConfig.java
package dk.aau.cs.ds306e18.tournament.model; import dk.aau.cs.ds306e18.tournament.rlbot.configuration.BotSkill; import dk.aau.cs.ds306e18.tournament.rlbot.configuration.BotType; import dk.aau.cs.ds306e18.tournament.rlbot.configuration.BotConfig; import java.io.File; import java.util.Objects; public class BotFromConfig implements Bot { private String pathToConfig; private BotConfig config; private boolean configLoadedCorrectly = false; public BotFromConfig(String pathToConfig) { this.pathToConfig = pathToConfig; reload(); } /** * Returns true if the config file that this bot is based on was loaded correctly and is valid. False otherwise. */ public boolean loadedCorrectly() { return configLoadedCorrectly && config != null; } /** * Reload the config file that this was bot was based on. * @return true if the config file that this bot is based on was loaded correctly and is valid. False otherwise. */ public boolean reload() { try { config = new BotConfig(new File(pathToConfig)); configLoadedCorrectly = true; } catch (Exception e) { configLoadedCorrectly = false; throw new RuntimeException("Could not load bot from config " + pathToConfig + ", reason: " + e.getMessage()); } return loadedCorrectly(); } @Override public String getDescription() { if (configLoadedCorrectly) return config.getDescription(); else return "Could not load bot from config"; } @Override public String getName() { if (configLoadedCorrectly) return config.getName(); else return "Could not load bot from config"; } @Override public String getDeveloper() { if (configLoadedCorrectly) return config.getDeveloper(); else return "Could not load bot from config"; } @Override public String getConfigPath() { return pathToConfig; } public BotConfig getConfig() { return config; } @Override public String getFunFact() { if (configLoadedCorrectly) return config.getFunFact(); else return "Could not load bot from config"; } @Override public String getGitHub() { if (configLoadedCorrectly) return config.getGithub(); else return "Could not load bot from config"; } @Override public String getLanguage() { if (configLoadedCorrectly) return config.getLanguage(); else return "Could not load bot from config"; } @Override public BotType getBotType() { return BotType.RLBOT; } @Override public BotSkill getBotSkill() { return BotSkill.ALLSTAR; } @Override public String toString() { return getName(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; BotFromConfig that = (BotFromConfig) o; return Objects.equals(pathToConfig, that.pathToConfig); } @Override public int hashCode() { return Objects.hash(pathToConfig); } }
3,198
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
Bot.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/model/Bot.java
package dk.aau.cs.ds306e18.tournament.model; import dk.aau.cs.ds306e18.tournament.rlbot.configuration.BotSkill; import dk.aau.cs.ds306e18.tournament.rlbot.configuration.BotType; public interface Bot { String getDescription(); String getName(); String getDeveloper(); String getConfigPath(); String getFunFact(); String getGitHub(); String getLanguage(); BotType getBotType(); BotSkill getBotSkill(); }
440
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
Team.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/model/Team.java
package dk.aau.cs.ds306e18.tournament.model; import dk.aau.cs.ds306e18.tournament.model.stats.StatsManager; import java.util.ArrayList; import java.util.List; import java.util.Objects; public class Team { public static final int MAX_SIZE = 32; private String teamName; private ArrayList<Bot> bots; private int initialSeedValue; private String description; transient private StatsManager statsManager; public Team(String teamName, List<Bot> bots, int initialSeedValue, String description) { this.teamName = teamName; this.bots = bots == null ? new ArrayList<>() : new ArrayList<>(bots); // List can't be null to avoid NullPointerExceptions this.initialSeedValue = initialSeedValue; this.description = description; statsManager = new StatsManager(this); } public String getTeamName() { return teamName; } public void setTeamName(String teamName) { this.teamName = teamName; } public int getInitialSeedValue() { return initialSeedValue; } public void setInitialSeedValue(int initialSeedValue) { this.initialSeedValue = initialSeedValue; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int size() { return bots.size(); } public boolean addBot(Bot bot) { if (bots.size() < MAX_SIZE) { return bots.add(bot); } return false; } public boolean removeBot(Bot bot) { return bots.remove(bot); } public Bot removeBot(int index) { if (0 <= index && index < bots.size()) { return bots.remove(index); } return null; } public ArrayList<Bot> getBots() { return new ArrayList<>(bots); } public ArrayList<String> getConfigPaths() { ArrayList<String> paths = new ArrayList<>(); for (Bot bot : bots) { paths.add(bot.getConfigPath()); } return paths; } public StatsManager getStatsManager() { return statsManager; } /** * Repairs properties that cannot be deserialized. */ public void postDeserializationRepair() { statsManager = new StatsManager(this); } @Override public String toString() { return teamName; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Team team = (Team) o; return getInitialSeedValue() == team.getInitialSeedValue() && Objects.equals(getTeamName(), team.getTeamName()) && Objects.equals(getBots(), team.getBots()) && Objects.equals(getDescription(), team.getDescription()); } @Override public int hashCode() { return Objects.hash(getTeamName(), getBots(), getInitialSeedValue(), getDescription()); } }
3,043
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
Stage.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/model/Stage.java
package dk.aau.cs.ds306e18.tournament.model; import dk.aau.cs.ds306e18.tournament.model.format.Format; import dk.aau.cs.ds306e18.tournament.model.format.StageStatus; import java.util.Objects; public class Stage { private String name; private Format format; private int numberOfTeamsWanted = 8; private int stageNumber; public Stage(String name, Format format) { this.name = name; this.format = format; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Format getFormat() { return format; } public int getStageNumber() { return stageNumber; } void setStageNumber(int stageNumber) { if (this.format.getStatus() != StageStatus.PENDING) throw new IllegalStateException("Stage has already started."); this.stageNumber = stageNumber; } public void setFormat(Format format) { if (this.format.getStatus() != StageStatus.PENDING) throw new IllegalStateException("Stage has already started."); this.format = format; } public int getNumberOfTeamsWanted() { return numberOfTeamsWanted; } public void setNumberOfTeamsWanted(int numberOfTeamsWanted) { if (this.format.getStatus() != StageStatus.PENDING) throw new IllegalStateException("Stage has already started."); this.numberOfTeamsWanted = numberOfTeamsWanted; } @Override public String toString() { return name; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Stage stage = (Stage) o; return getStageNumber() == stage.getStageNumber() && getNumberOfTeamsWanted() == stage.getNumberOfTeamsWanted() && Objects.equals(getName(), stage.getName()) && Objects.equals(getFormat(), stage.getFormat()); } @Override public int hashCode() { return Objects.hash(getName(), getFormat(), getNumberOfTeamsWanted(), getStageNumber()); } }
2,180
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
Tournament.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/model/Tournament.java
package dk.aau.cs.ds306e18.tournament.model; import com.google.gson.annotations.JsonAdapter; import dk.aau.cs.ds306e18.tournament.model.format.StageStatus; import dk.aau.cs.ds306e18.tournament.rlbot.RLBotSettings; import dk.aau.cs.ds306e18.tournament.serialization.TrueTeamListAdapter; import java.util.*; public class Tournament { private static Tournament instance; public static Tournament get() { if (instance == null) instance = new Tournament(); return instance; } public static final int START_REQUIREMENT_TEAMS = 2; public static final int START_REQUIREMENT_STAGES = 1; private RLBotSettings rlBotSettings = new RLBotSettings(); private String name = "Unnamed Tournament"; @JsonAdapter(TrueTeamListAdapter.class) // Teams in this list are serialized as actual teams, other instances of teams will be their index in this list private ArrayList<Team> teams = new ArrayList<>(); private ArrayList<Stage> stages = new ArrayList<>(); private TieBreaker tieBreaker = TieBreaker.GOAL_DIFF; private SeedingOption seedingOption = SeedingOption.SEED_BY_ORDER; private boolean started = false; private int currentStageIndex = -1; public Tournament() { instance = this; } public RLBotSettings getRlBotSettings() { return rlBotSettings; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void addTeam(Team team) { if (started) throw new IllegalStateException("Tournament has already started."); teams.add(team); } public void addTeams(Collection<? extends Team> teams) { if (started) throw new IllegalStateException("Tournament has already started."); this.teams.addAll(teams); } public void removeTeam(Team team) { if (started) throw new IllegalStateException("Tournament has already started."); teams.remove(team); } public void removeTeam(int index) { if (started) throw new IllegalStateException("Tournament has already started."); teams.remove(index); } public void swapTeams(Team a, Team b) { swapTeams(teams.indexOf(a), teams.indexOf(b)); } public void swapTeams(int a, int b) { Collections.swap(teams, a, b); } public void sortTeamsBySeed() { teams.sort(Comparator.comparingInt(Team::getInitialSeedValue)); } public List<Team> getTeams() { return new ArrayList<>(teams); } public void addStage(Stage stage) { if (started) throw new IllegalStateException("Tournament has already started."); stages.add(stage); stage.setStageNumber(stages.size()); } public void removeStage(Stage stage) { if (started) throw new IllegalStateException("Tournament has already started."); stages.remove(stage); recalculateStageNumbers(); } public void removeStage(int index) { if (started) throw new IllegalStateException("Tournament has already started."); stages.remove(index); recalculateStageNumbers(); } private void recalculateStageNumbers() { for (int i = 0; i < stages.size(); i++) { stages.get(i).setStageNumber(i + 1); } } public List<Stage> getStages() { return new ArrayList<>(stages); } public void swapStages(Stage primaryStage, Stage secondaryStage) { Collections.swap(stages, stages.indexOf(primaryStage), stages.indexOf(secondaryStage)); recalculateStageNumbers(); } /** Returns the number of stages that has not started yet. */ public int getUpcomingStagesCount() { return stages.size() - currentStageIndex - 1; } /** Returns true there stages that has not started yet. */ public boolean hasUpcomingStages() { return getUpcomingStagesCount() > 0; } public Stage getCurrentStage() { if (stages.isEmpty() || currentStageIndex == -1) return null; return stages.get(currentStageIndex); } public int getCurrentStageIndex() { return currentStageIndex; } public void startNextStage() { if (!started) throw new IllegalStateException("The first stage should be started through the start() method."); if (!hasUpcomingStages()) throw new IllegalStateException("There are no more pending stages."); if (currentStageIndex != -1 && getCurrentStage().getFormat().getStatus() != StageStatus.CONCLUDED) throw new IllegalStateException("Previous stage has not been concluded."); // State is ok // Find teams to transfer List<Team> transferedTeams; boolean seeding = seedingOption != SeedingOption.NO_SEEDING; if (currentStageIndex == -1) { // This is the first stage, so all teams are transferred transferedTeams = new ArrayList<>(teams); if (seedingOption == SeedingOption.SEED_BY_ORDER) { // Assign seeds based on order for (int i = 0; i < teams.size(); i++) { teams.get(i).setInitialSeedValue(i + 1); } transferedTeams.sort(Comparator.comparingInt(Team::getInitialSeedValue)); } else if (seedingOption == SeedingOption.MANUALLY) { // Seeds was assigned ny user. If some teams have the same seed value, shuffle those final Random random = new Random(); transferedTeams.sort((a, b) -> { if (a == b) return 0; int comparison = Integer.compare(a.getInitialSeedValue(), b.getInitialSeedValue()); if (comparison == 0) { return random.nextBoolean() ? 1 : -1; } return comparison; }); } else if (seedingOption == SeedingOption.RANDOM_SEEDING) { // Random seeding. We give everyone a seed value of 0 and shuffle the order for (Team team : teams) { team.setInitialSeedValue(0); } Collections.shuffle(transferedTeams); } else if (seedingOption == SeedingOption.NO_SEEDING) { // Give everyone a seed value of zero, but no change to the order for (Team team : teams) { team.setInitialSeedValue(0); } } } else { // Not the first stage, so we find the best teams of previous stage and use their order as seeding regardless of seeding option int wantedTeamCount = stages.get(currentStageIndex + 1).getNumberOfTeamsWanted(); transferedTeams = getCurrentStage().getFormat().getTopTeams(wantedTeamCount, tieBreaker); seeding = true; } // Proceed to next stage currentStageIndex++; getCurrentStage().getFormat().start(transferedTeams, seeding); } public boolean hasStarted() { return started; } public boolean canStart() { return teams.size() >= START_REQUIREMENT_TEAMS && stages.size() >= START_REQUIREMENT_STAGES; } public void start() { if (started) throw new IllegalStateException("Tournament has already started."); if (teams.size() < START_REQUIREMENT_TEAMS) throw new IllegalStateException("There must be at least two teams in the tournament."); if (stages.size() < START_REQUIREMENT_STAGES) throw new IllegalStateException("There must be at least one stage in the tournament."); started = true; startNextStage(); } public SeedingOption getSeedingOption() { return seedingOption; } public void setSeedingOption(SeedingOption seedingOption) { this.seedingOption = seedingOption; } public TieBreaker getTieBreaker() { return tieBreaker; } public void setTieBreaker(TieBreaker tieBreaker) { if (started) throw new IllegalStateException("Tournament has already started."); this.tieBreaker = tieBreaker; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Tournament that = (Tournament) o; return started == that.started && currentStageIndex == that.currentStageIndex && Objects.equals(getRlBotSettings(), that.getRlBotSettings()) && Objects.equals(getName(), that.getName()) && Objects.equals(getTeams(), that.getTeams()) && Objects.equals(getStages(), that.getStages()) && Objects.equals(getTieBreaker(), that.getTieBreaker()); } @Override public int hashCode() { return Objects.hash(getRlBotSettings(), getName(), getTeams(), getStages(), getTieBreaker(), started, currentStageIndex); } public void setTournament (Tournament newTournament) { instance = newTournament; } }
9,120
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z