Advertisement
ignacy123

FlappyBird - Player

May 13th, 2024 (edited)
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. import javax.imageio.ImageIO;
  2. import java.awt.*;
  3. import java.awt.event.KeyEvent;
  4. import java.awt.event.KeyListener;
  5. import java.awt.image.BufferedImage;
  6. import java.io.File;
  7. import java.io.IOException;
  8. import java.util.ArrayList;
  9. import java.util.List;
  10.  
  11. public class Player implements KeyListener {
  12.  
  13. public int x = 0;
  14. public int y = 0;
  15. private int speed = 5;
  16. private String direction = "down";
  17. private List<BufferedImage> animations;
  18.  
  19. public Player() {
  20. try {
  21. animations = List.of(
  22. ImageIO.read(new File("src/files/flappy_bird_1.png"))
  23. );
  24.  
  25. } catch (IOException e) {
  26. throw new RuntimeException(e);
  27. }
  28. }
  29.  
  30. public void drawPlayer(Graphics2D g2) {
  31. BufferedImage bufferedImage = animations.get(0);
  32. g2.drawImage(bufferedImage, x, y, 80, 80, null);
  33. }
  34.  
  35. @Override
  36. public void keyTyped(KeyEvent e) {
  37.  
  38. }
  39.  
  40. @Override
  41. public void keyPressed(KeyEvent e) {
  42. int keyCode = e.getKeyCode();
  43.  
  44. if (keyCode == KeyEvent.VK_UP) {
  45. direction = "up";
  46. System.out.println("up");
  47. }
  48. if (keyCode == KeyEvent.VK_DOWN) {
  49. System.out.println("down");
  50. direction = "down";
  51. }
  52. if (keyCode == KeyEvent.VK_LEFT) {
  53. System.out.println("left");
  54. direction = "left";
  55. }
  56. if (keyCode == KeyEvent.VK_RIGHT) {
  57. System.out.println("right");
  58. direction = "right";
  59. }
  60. }
  61.  
  62. public void update() {
  63. switch (direction) {
  64. case "up" -> y -= speed;
  65. case "down" -> y += speed;
  66. case "left" -> x -= speed;
  67. case "right" -> x += speed;
  68. }
  69. }
  70.  
  71. @Override
  72. public void keyReleased(KeyEvent e) {
  73.  
  74. }
  75.  
  76. }
  77.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement