-
Notifications
You must be signed in to change notification settings - Fork 0
/
Window.java
1930 lines (1721 loc) · 59 KB
/
Window.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package apcs;
import java.awt.Color;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseMotionListener;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.imageio.ImageIO;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.JApplet;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
/**
* Window is a lightweight graphics library that makes it much easier to
* build interactive games and simulations with Java.
*/
public class Window extends JApplet {
// Serial version UID
private static final long serialVersionUID = 1L;
// Information about the currently active WindowInstance.
private static boolean initialized = false;
private static int width, height;
private static final int defaultWidth = 500, defaultHeight = 500;
// Mapping between String names and underlying integer values for color codes
// and mappings from human-readable keys to virtual keys.
private static Map <String, Integer> keyMap;
private static Map <String, Integer> colorMap;
private static ArrayList <String> imagePath;
/**
* Creates a Window with the given width and height.
* @param width - the width of the window
* @param height - the height of the window
* @return an object to represent this window instance
*/
public static WindowInstance size(int width, int height) {
// Run the initialization routine the first time a window is created.
if (! initialized) {
initialize();
Window.width = width;
Window.height = height;
initialized = true;
}
if (! isApplet) {
isApplication = true;
}
// Thread safety locks on the Window class.
synchronized (Window.class) {
// Get the currently running instance, if there is one.
WindowInstance instance = instanceMap.get();
// If there is no instance already running, create one and set it as the current instance.
if (instance == null) {
// Create a JFrame for the window.
JFrame frame = new JFrame("");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Window window = new Window();
window.bufferSize = new Dimension(width, height);
instanceMap.set(window.master);
// Create a container for the frame's content.
Container pane = frame.getContentPane();
pane.add(window);
pane.setSize(window.getSize());
pane.setMinimumSize(window.getSize());
// frame.getContentPane().setIgnoreRepaint(true);
// Initialize and start the window.
window.init();
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
window.start();
return window.master;
}
return instance;
}
}
/**
* Returns the width of the window.
* @return width of the window, in pixels.
*/
public static int width() {
return getInstanceFromThread().getWidth();
}
/**
* Returns the height of the window.
* @return height of the window, in pixels.
*/
public static int height() {
return getInstanceFromThread().getHeight();
}
/**
* Wait for the given number of seconds.
*/
public static void wait(double seconds) {
sleep((int) (seconds * 1000));
}
/**
* Wait for the given number of seconds.
*/
public static void wait(int seconds) {
sleep(seconds * 1000);
}
/**
* Wait for the given number of milliseconds.
*/
public static void sleep(int milliseconds) {
try {
Thread.sleep(milliseconds);
} catch (Exception ignored) {}
}
/**
* Rolls a dice of the given number of sides, and returns the
* value that was randomly rolled (between 1 and sides inclusive)
* @param sides - number of sides on the dice
* @return the value that was rolled, in the inclusive range [1, sides]
*/
public static int rollDice(int sides) {
if (sides < 1) sides = 1;
return (int) (Math.random() * sides + 1);
}
/**
* Returns a random number between min and max inclusive.
* @param min - minimum random number
* @param max - maximum random number
* @return
*/
public static int random(int min, int max) {
if (min > max)
return (int) (max + Math.random() * (min - max + 1));
else
return (int) (min + Math.random() * (max - min + 1));
}
public static boolean flipCoin() {
return Math.random() < 0.5;
}
/**
* Key-related methods.
*/
public static class key {
/**
* Returns true if the given key is pressed.
*/
public static boolean pressed(String key) {
if (key == null || keyMap == null) return false;
else if (keyMap.containsKey(key))
return Window.getInstanceFromThread().isVirtualKeyPressed(keyMap.get(key));
else if (key.length() > 0)
return Window.key.pressed(key.charAt(0));
return false;
}
/**
* Returns true if the given key is not pressed.
*/
public static boolean released(String key) {
return ! pressed(key);
}
/**
* Returns true if the key for the given character is pressed.
* @param key - the key to check for presses
* @return - true if the key is pressed, false otherwise
*/
public static boolean pressed(char key) {
return getInstanceFromThread().isKeyPressed(key);
}
/**
* Returns true if the given key is not pressed.
*/
public static boolean released(char key) {
return ! pressed(key);
}
}
/**
* Mouse-related methods.
*/
public static class mouse {
/**
* Returns true if the mouse is clicked.
* @return whether or not the mouse is clicked.
*/
public static boolean clicked() {
return getInstanceFromThread().isMouseClicked();
}
/**
* Returns true if the mouse is not clicked.
* @return whether or not the mouse is released.
*/
public static boolean released() {
return ! clicked();
}
/**
* Returns the x coordinate of the mouse.
*/
public static int getX() {
return Window.getInstanceFromThread().getMouseX();
}
/**
* Returns the y coordinate of the mouse.
*/
public static int getY() {
return Window.getInstanceFromThread().getMouseY();
}
/**
* Waits for a click to be registered.
*/
public static void waitForClick() {
while (! getInstanceFromThread().isMouseClicked()) {
Window.sleep(10);
}
}
/**
* Waits for any ongoing click to be released.
*/
public static void waitForRelease() {
while (getInstanceFromThread().isMouseClicked()) {
Window.sleep(10);
}
}
}
/**
* For playing sounds.
*/
public static class sound {
public static void play(final String file) {
new Thread() {
public void run() {
// Open an audio input stream.
try {
AudioInputStream audioIn = AudioSystem.getAudioInputStream(new File(file));
// Get a sound clip resource.
Clip clip = AudioSystem.getClip();
// Open audio clip and load samples from the audio input stream.
clip.open(audioIn);
clip.start();
} catch (UnsupportedAudioFileException e) {
System.err.println(file + " is not a supported audio file type.");
e.printStackTrace();
} catch (IOException e) {
System.err.println("Could not play the sound.");
} catch (LineUnavailableException e) {
System.err.println("Line is not available to play sounds.");
}
}
}.start();
}
}
/**
* Creates a simple client-server mesh for distributing key-value pairs.
* The mesh can also be deployed as a stand-alone program via the Mesh class,
* which implements the same basic methods. For the sake of simplicity,
* keys are strings, and values are either integers, doubles, or strings.
*
* @see Mesh
*/
public static class mesh {
// The default port that the Window library should use.
private static final int DEFAULT_PORT = 4965;
// References to threads for master-slave network.
private static Server server;
private static Client client;
private static ConcurrentHashMap <String, String> stringCache;
private static ConcurrentHashMap <String, Double> doubleCache;
private static ConcurrentHashMap <String, Integer> intCache;
private static boolean running = false;
/**
* Initializes the data structures of the mesh.
*/
private static void initialize() {
stringCache = new ConcurrentHashMap <String, String> ();
doubleCache = new ConcurrentHashMap <String, Double> ();
intCache = new ConcurrentHashMap <String, Integer> ();
running = true;
}
/**
* Starts a mesh at the default port.
*/
public static void start() {
start(DEFAULT_PORT);
}
/**
* Starts a mesh at the given port.
* @param port - the port number to listen on
*/
public static void start(int port) {
if (! running) {
initialize();
server = new Server(port);
server.start();
}
}
/**
* Joins the mesh at the given IP address, with the default port.
* @param ip - the IP address of the server hosting the mesh
*/
public static void join(String ip) {
join(ip, DEFAULT_PORT);
}
/**
* Joins the mesh at the given IP address and port.
* @param ip - the IP address of the server hosting the mesh
* @param port - the port the server is listening on
*/
public static void join(String ip, int port) {
if (! running) {
initialize();
client = new Client(ip, port);
client.start();
}
}
/**
* Writes a key-value pair to the mesh, so all clients can read them.
*
* @param key - a unique identifier for this value
* @param value - an integer value
*/
public static void write(String key, int value) {
if (running) {
// If this value has not changed from its locally cached value.
if (intCache.containsKey(key) &&
intCache.get(key) == value) return;
// Send a new value through this instance's respective thread.
if (server != null)
server.put(null, key, value);
else if (client != null)
client.put(key, value);
}
}
/**
* Writes a key-value pair to the mesh, so all clients can read them.
*
* @param key - a unique identifier for this value
* @param value - a double value
*/
public static void write(String key, double value) {
if (running) {
// If this value has not changed from its locally cached value.
if (doubleCache.containsKey(key) &&
doubleCache.get(key) == value) return;
// Send a new value through this instance's respective thread.
if (server != null)
server.put(null, key, value);
else if (client != null)
client.put(key, value);
}
}
/**
* Writes a key-value pair to the mesh, so all clients can read them.
*
* @param key - a unique identifier for this value
* @param value - a double value
*/
public static void write(String key, String value) {
if (running) {
// If this value has not changed from its locally cached value.
if (stringCache.containsKey(key) &&
stringCache.get(key).equals(value)) return;
// Send a new value through this instance's respective thread.
if (server != null)
server.put(null, key, value);
else if (client != null)
client.put(key, value);
}
}
/**
* Reads an integer value from the distributed key-value store.
* @param key - the unique identifier for the requested value
*/
public static int read(String key) {
if (intCache.containsKey(key))
return intCache.get(key);
else return 0;
}
/**
* Reads a precise value from the distributed key-value store.
* @param key - the unique identifier for the requested value
*/
public static double readDouble(String key) {
if (doubleCache.containsKey(key))
return doubleCache.get(key);
else return 0;
}
/**
* Reads a string value from the distributed key-value store.
* @param key - the unique identifier for the requested value
*/
public static String readString(String key) {
if (stringCache.containsKey(key))
return stringCache.get(key);
else return null;
}
/**
* Thread for a server listening on the given port.
*/
private static class Server extends Thread {
private int port;
private ServerSocket master;
private ArrayList <ServerClient> clients;
/**
* Initialize this thread to listen on the given port.
* @param port
*/
public Server(int port) {
this.port = port;
}
/**
* Starts listening on the given port.
*/
public void run() {
try {
master = new ServerSocket(port);
clients = new ArrayList <ServerClient> ();
System.out.println("Starting mesh at " + InetAddress.getLocalHost().getHostAddress() + ", port " + port);
// Keep listening for new clients
while (true) {
Socket newClient = master.accept();
Window.mesh.message("connection from " + newClient.getInetAddress().getHostAddress());
ServerClient client = new ServerClient(newClient, this);
synchronized(clients) {
clients.add(client);
client.start();
}
}
}
catch (IOException e) {
error("Could not create server at port " + port);
}
}
/**
*
* @param client - the client that is sending the new value, or null if it is originating from the server.
* @param key - unique ID of the data
* @param value - the integer value
*/
public void put(ServerClient client, String key, int value) {
intCache.put(key, value);
synchronized(clients) {
for (ServerClient c : clients) {
if (c != client) {
c.put(key, value);
}
}
}
}
/**
*
* @param client - the client that is sending the new value, or null if it is originating from the server.
* @param key - unique ID of the data
* @param value - the integer value
*/
public void put(ServerClient client, String key, double value) {
doubleCache.put(key, value);
synchronized(clients) {
for (ServerClient c : clients) {
if (c != client) {
c.put(key, value);
}
}
}
}
/**
*
* @param client - the client that is sending the new value, or null if it is originating from the server.
* @param key - unique ID of the data
* @param value - the integer value
*/
public void put(ServerClient client, String key, String value) {
stringCache.put(key, value);
synchronized(clients) {
for (ServerClient c : clients) {
if (c != client) {
c.put(key, value);
}
}
}
}
}
private static class ServerClient extends Thread {
private Server master;
private BufferedReader input;
private PrintWriter output;
private String ip;
private boolean connected = false;
private long bandwidth = 0;
public ServerClient(Socket socket, Server master) {
try {
this.master = master;
ip = socket.getInetAddress().getHostAddress();
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
output = new PrintWriter(socket.getOutputStream(), true);
connected = true;
}
catch (IOException e) {}
}
public void run() {
if (! connected) return;
// Copy all current data to client
StringBuilder initialUpdate = new StringBuilder();
for (String key : intCache.keySet())
initialUpdate.append('#').append(key).append('=').append(intCache.get(key)).append('\n');
for (String key : doubleCache.keySet())
initialUpdate.append('%').append(key).append('=').append(doubleCache.get(key)).append('\n');
for (String key : stringCache.keySet())
initialUpdate.append('$').append(key).append('=').append(stringCache.get(key)).append('\n');
output.println(initialUpdate);
bandwidth += initialUpdate.length();
Window.mesh.message("updated " + ip);
// Keep reading updates from the client until disconnect, and update all other clients with updates
try {
while (true) {
String line = input.readLine();
if (line == null)
break;
bandwidth += line.length();
char type = line.charAt(0);
int equals = line.indexOf('=');
String key = line.substring(1, equals);
if (type == '#')
master.put(this, key, Integer.parseInt(line.substring(equals + 1)));
else if (type == '%')
master.put(this, key, Double.parseDouble(line.substring(equals + 1)));
else if (type == '$')
master.put(this, key, line.substring(equals + 1));
}
input.close();
output.close();
} catch (IOException e) {
}
}
public void put(String key, int value) {
if (connected) {
output.println('#' + key + '=' + value);
}
}
public void put(String key, double value) {
if (connected) {
output.println('%' + key + '=' + value);
}
}
public void put(String key, String value) {
if (connected) {
output.println('$' + key + '=' + value);
}
}
}
private static class Client extends Thread {
Socket socket;
BufferedReader input;
PrintWriter output;
String ip;
boolean connected = false;
public Client(String ip, int port) {
try {
this.socket = new Socket(ip, port);
this.ip = ip;
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
output = new PrintWriter(socket.getOutputStream(), true);
connected = true;
} catch (IOException e) {}
}
public void run() {
if (! connected) {
error("Could not connect to " + ip + ".");
return;
}
try {
while (true) {
String line = input.readLine();
if (line == null) {
error("Connection to " + ip + " closed.");
break;
}
if (line.length() > 0) {
char type = line.charAt(0);
int equals = line.indexOf('=');
String key = line.substring(1, equals);
if (type == '#')
intCache.put(key, Integer.parseInt(line.substring(equals + 1)));
else if (type == '%')
doubleCache.put(key, Double.parseDouble(line.substring(equals + 1)));
else if (type == '$')
stringCache.put(key, line.substring(equals + 1));
}
}
connected = false;
input.close();
output.close();
socket.close();
} catch (IOException e) {}
}
public void put(String key, int value) {
if (connected && key != null) {
intCache.put(key, value);
output.println('#' + key + '=' + value);
}
}
public void put(String key, double value) {
if (connected && key != null) {
doubleCache.put(key, value);
output.println('%' + key + '=' + value);
}
}
public void put(String key, String value) {
if (connected && key != null) {
stringCache.put(key, value);
output.println('$' + key + '=' + value);
}
}
}
/**
* Prints a mesh message.
*/
private static DateFormat messageDateFormat = new SimpleDateFormat("HH:mm:ss");
public static void message(String m) {
System.out.println("[ " + messageDateFormat.format(new Date()) + " ] " + m);
}
public static void error(String e) {
System.err.println("[ " + messageDateFormat.format(new Date()) + " ] " + e);
}
}
public static class out {
/**
* Fills the circle at the given (x, y) coordinate with the given radius.
* @param x - the x coordinate of the circle
* @param y - the y coordinate of the circle
* @param radius - the radius of the circle
*/
public static void circle(int x, int y, int radius) {
if (! initialized) Window.size(defaultWidth, defaultHeight);
Window.getInstanceFromThread().fillOval(x - radius, y - radius, radius * 2, radius * 2);
}
/**
* Fills the circle at the given (x, y) coordinate with the given radius.
* @param x - the x coordinate of the circle
* @param y - the y coordinate of the circle
* @param radius - the radius of the circle
*/
public static void circle(double x, double y, double radius) {
if (! initialized) Window.size(defaultWidth, defaultHeight);
Window.getInstanceFromThread().fillOval((int) (x - radius), (int) (y - radius), (int) (radius * 2), (int) (radius * 2));
}
/**
* Fills the circle at the given (x, y) coordinate with the given radius.
* @param x - the x coordinate of the circle
* @param y - the y coordinate of the circle
* @param radius - the radius of the circle
*/
public static void circle(int x, int y, double radius) {
if (! initialized) Window.size(defaultWidth, defaultHeight);
Window.getInstanceFromThread().fillOval((int) (x - radius), (int) (y - radius), (int) (radius * 2), (int) (radius * 2));
}
/**
* Creates a line from the (x, y) coordinate to the (endx, endy) coordinate.
* @param x - starting x coordinate
* @param y - starting y coordinate
* @param endx - ending x coordinate
* @param endy - ending y coordinate
*/
public static void line(int x, int y, int endx, int endy) {
if (! initialized) Window.size(defaultWidth, defaultHeight);
Window.getInstanceFromThread().drawLine(x, y, endx, endy);
}
/**
* Creates a line from the (x, y) coordinate to the (endx, endy) coordinate.
* @param x - starting x coordinate
* @param y - starting y coordinate
* @param endx - ending x coordinate
* @param endy - ending y coordinate
*/
public static void line(double x, double y, double endx, double endy) {
if (! initialized) Window.size(defaultWidth, defaultHeight);
Window.getInstanceFromThread().drawLine((int) x, (int) y, (int) endx, (int) endy);
}
/**
* Fills a rectangle centered at the given x, y coordinate with the given width and height.
* @param x - x coordinate of the rectangle
* @param y - y coordinate of the rectangle
* @param width - width of the rectangle
* @param height - height of the rectangle
*/
public static void rectangle(int x, int y, int width, int height) {
if (! initialized) Window.size(defaultWidth, defaultHeight);
Window.getInstanceFromThread().fillRect(x - width / 2, y - height / 2, width, height);
}
/**
* Fills a rectangle centered at the given x, y coordinate, rotated around its center by the given angle.
* @param x - x coordinate of the rectangle
* @param y - y coordinate of the rectangle
* @param width - width of the rectangle
* @param height - height of the rectangle
* @param angle - an angle in degrees
*/
public static void rectangle(int x, int y, int width, int height, double angle) {
if (! initialized) Window.size(defaultWidth, defaultHeight);
angle = Math.toRadians(angle);
Window.out.polygon(x + rotatedX(- width / 2, - height / 2, angle), y + rotatedY(-width / 2, -height / 2, angle),
x + rotatedX(-width / 2, height / 2, angle), y + rotatedY(-width / 2, height / 2, angle),
x + rotatedX(width / 2, height / 2, angle), y + rotatedY(width / 2, height / 2, angle),
x + rotatedX(width / 2, -height / 2, angle), y + rotatedY(width / 2, -height / 2, angle));
}
// Used in rotation calculations.
private static int rotatedX(int x, int y, double angle) {
return (int) (x * Math.cos(angle) - y * Math.sin(angle));
}
// Used in rotation calculations.
private static int rotatedY(int x, int y, double angle) {
return (int) (x * Math.sin(angle) + y * Math.cos(angle));
}
/**
* Fills a square centered at the given x, y coordinate with the given side length.
* @param x - the x coordinate of the square
* @param y - the y coordinate of the square
* @param side - side length of the square
*/
public static void square(int x, int y, int side) {
if (! initialized) Window.size(defaultWidth, defaultHeight);
Window.getInstanceFromThread().fillRect(x - side / 2, y - side / 2, side, side);
}
/**
* Fills a square centered at the given x, y coordinate with the given side length, rotated by the given angle.
* @param x - the x coordinate of the square
* @param y - the y coordinate of the square
* @param side - side length of the square
* @param angle - the angle to rotate the square by
*/
public static void square(int x, int y, int side, double angle) {
rectangle(x, y, side, side, angle);
}
/**
* Fills the oval centered at the given (x, y) coordinate with the given width and height.
* @param x - x coordinate of the oval's center
* @param y - y coordinate of the oval's center
* @param width - width of the oval
* @param height - height of the oval
*/
public static void oval(int x, int y, int width, int height) {
if (! initialized) Window.size(defaultWidth, defaultHeight);
Window.getInstanceFromThread().fillOval(x - width / 2, y - height / 2, width, height);
}
/**
* Draws an arc at the given x and y coordinate with the given width, height, start angle, and arc angle.
* @param x - starting x coordinate
* @param y - starting y coordinate
* @param width - width of the arc
* @param height - height of the arc
* @param startAngle - starting angle
* @param arcAngle - angle that the arc curves by
*/
public static void arc(int x, int y, int width, int height, int startAngle, int arcAngle) {
if (! initialized) Window.size(defaultWidth, defaultHeight);
Window.getInstanceFromThread().drawArc(x - width / 2, y - height / 2, width, height, startAngle, arcAngle);
}
/**
* Fills a polygon with the given list of x, y coordinates as vertices.
* @param x - list of x coordinates
* @param y - list of y coordinates
*/
public static void polygon(int[] x, int[] y) {
if (! initialized) Window.size(defaultWidth, defaultHeight);
Window.getInstanceFromThread().fillPolygon(x, y);
}
/**
* Fills a polygon with the given list of x, y coordinates.
*/
public static void polygon(int ... coordinates) {
if (! initialized) Window.size(defaultWidth, defaultHeight);
if (coordinates != null && coordinates.length > 0) {
int[] x = new int[coordinates.length / 2];
int[] y = new int[coordinates.length / 2];
for (int i = 0 ; i < coordinates.length / 2 ; i++) {
x[i] = coordinates[i * 2];
if (i * 2 + 1 < coordinates.length) {
y[i] = coordinates[i * 2 + 1];
}
}
Window.getInstanceFromThread().fillPolygon(x, y);
}
}
/**
* Draws the given text at the given (x, y) coordinate.
* @param text - the text to draw
* @param x - the x coordinate of the text's bottom left corner.
* @param y - the y coordinate of the text's bottom right corner.
*/
public static void print(String text, int x, int y) {
if (! initialized) Window.size(defaultWidth, defaultHeight);
Window.getInstanceFromThread().drawText(text, x, y);
}
/**
* Draws the given number at the (x, y) coordinate.
* @param value - the number to draw
* @param x - the x coordinate of the text's bottom left corner.
* @param y - the y coordinate of the text's bottom right corner.
*/
public static void print(int value, int x, int y) {
if (! initialized) Window.size(defaultWidth, defaultHeight);
Window.getInstanceFromThread().drawText(Integer.toString(value), x, y);
}
/**
* Draws the given number at the (x, y) coordinate.
* @param value - the number to draw
* @param x - the x coordinate of the text's bottom left corner.
* @param y - the y coordinate of the text's bottom right corner.
*/
public static void print(double value, int x, int y) {
if (! initialized) Window.size(defaultWidth, defaultHeight);
Window.getInstanceFromThread().drawText(Double.toString(value), x, y);
}
/**
* Sets the background to the given RGB value.
* @param red - red component
* @param green - green component
* @param blue - blue component
*/
public static void background(int red, int green, int blue) {
if (! initialized) Window.size(defaultWidth, defaultHeight);
Window.getInstanceFromThread().setColor(red, green, blue);
Window.getInstanceFromThread().fillRect(0, 0, Window.width, Window.height);
}
/**
* Sets the background to the given color name.
* @param color - name of the background color.
*/
public static void background(String color) {
if (! initialized) Window.size(defaultWidth, defaultHeight);
if (color != null) {
Window.out.color(color);
Window.getInstanceFromThread().fillRect(0, 0, Window.width, Window.height);
}
}
/**
* Sets the background to the current color.
*/
public static void background() {
if (! initialized) Window.size(defaultWidth, defaultHeight);
Window.getInstanceFromThread().fillRect(0, 0, Window.width, Window.height);
}
/**
* Clears the background to the initial black color.
*/
public static void clear() {
if (! initialized) Window.size(defaultWidth, defaultHeight);
Window.getInstanceFromThread().setColor(0, 0, 0);
Window.getInstanceFromThread().fillRect(0, 0, Window.width, Window.height);
}
/**
* Sets the color to the given HSB value (hue, saturation, and brightness)
* @param hue - hue component
* @param saturation - saturation component
* @param brightness - brightness component
*/
public static void color(float hue, float saturation, float brightness) {
if (! initialized) Window.size(defaultWidth, defaultHeight);
Window.getInstanceFromThread().setHSB(hue, saturation, brightness);
}
/**
* Sets the color to the given String color - if the color isn't built in, this will choose black.