Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*************************************************************************
- * Einföld beinagrind fyrir tölvuleiknum Pong.
- *
- *************************************************************************/
- import java.awt.event.KeyEvent;
- public class Pong {
- public static void main(String[] args) {
- int stig = 0; //stig
- // set the scale of the coordinate system
- StdDraw.setXscale(-1.0, 1.0);
- StdDraw.setYscale(-1.0, 1.0);
- // initial values of ball
- double rx = 0.480, ry = 0.860; // position
- double vx = 0.015, vy = 0.023; // velocity
- double radius = 0.05; // radius
- // initial values of paddle
- double[] px = { -0.2, 0.2, 0.2, -0.2 };
- double[] py = { -0.85, -0.85, -.90, -0.90 };
- double dpx = 0.018; // inc. paddle movement
- //initial value of box
- double bx = Math.random(), by = 0.51;
- for (int i = 0; i < 1; i--) {
- by = Math.random();
- if (by > 0.5) {
- break;
- }
- }
- // main animation loop
- while (true) {
- // bounce ball off wall according to law of elastic collision
- if (Math.abs(rx + vx) > 1.0 - radius) vx = -vx;
- if (ry + vy > 1.0 - radius) vy = -vy;
- if (py[0] > ry + vy) { //Athuga bolta á spaða
- if (px[0] < rx + vx && px[1] > rx + vx) {
- vy = -vy;
- stig++;
- }
- }
- if (by + radius > ry + vy && by - radius < ry + vy) { //Athuga bolta á kassa
- if (bx + radius > rx + vx && bx - radius < rx + vx) {
- bx = Math.random();
- for (int i = 0; i < 1; i--) {
- by = Math.random();
- if (by > 0.5) {
- break;
- }
- }
- stig += 2;
- }
- }
- StdDraw.text(0.7, 0.9, "Stig: " + stig); //Skrifa stig
- if (ry + vy < -0.9) { //Athuga bolta á botn gluggans
- break;
- }
- // update ball position
- rx = rx + vx;
- ry = ry + vy;
- // check if paddle moved
- if (StdDraw.isKeyPressed(KeyEvent.VK_LEFT) && px[0] - dpx >= -1.0)
- for (int i = 0; i < 4; i++) px[i] -= dpx;
- if (StdDraw.isKeyPressed(KeyEvent.VK_RIGHT) && px[1] + dpx <= 1.0)
- for (int i = 0; i < 4; i++) px[i] += dpx;
- StdDraw.clear();
- // draw ball on the screen
- StdDraw.setPenColor(StdDraw.RED);
- StdDraw.filledCircle(rx, ry, radius);
- // Teikna kassa
- StdDraw.setPenColor(StdDraw.BOOK_BLUE);
- StdDraw.filledSquare(bx, by, 0.05);
- // draw paddle on the screen
- StdDraw.setPenColor(StdDraw.BLUE);
- StdDraw.filledPolygon(px, py);
- // display and pause for 20 ms
- StdDraw.show();
- StdDraw.pause(20);
- }
- StdDraw.clear();
- StdDraw.text(0.1, 0.1, "Þú tapaðir með " + stig + " stig");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement