Advertisement
Guest User

Untitled

a guest
Mar 8th, 2023
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.28 KB | None | 0 0
  1. package Package;
  2. import javax.swing.*;
  3. import java.awt.*;
  4.  
  5. public class Main {
  6. public static void main(String[] args) {
  7. /*
  8. JFrame myFrame = new JFrame("Snake Game");
  9. myFrame.setTitle("Snake By Seba");
  10. ImageIcon image = new ImageIcon("Snake_logo.png");
  11. myFrame.setIconImage(image.getImage());
  12. myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  13. JButton button = new JButton();
  14. button.setBounds(150, 350, 200, 50);
  15. button.addActionListener(e -> {
  16. start_function(); // avvia la funzione initBoard()
  17. });
  18. myFrame.add(button);
  19. Font buttonFont = new Font("Arial", Font.BOLD, 20);
  20.  
  21. button.setForeground(Color.GREEN);
  22. button.setFont(buttonFont);
  23. button.setBackground(Color.BLUE);
  24. button.revalidate();
  25. button.repaint();
  26.  
  27. */
  28. JFrame myFrame = new JFrame("Snake Game");
  29. myFrame.setTitle("Snake By Seba");
  30. ImageIcon image = new ImageIcon("Snake_logo.png");
  31. myFrame.setIconImage(image.getImage());
  32. myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  33. myFrame.add(new SnakeGame());
  34. myFrame.pack();
  35. myFrame.setLocationRelativeTo(null);
  36. myFrame.setVisible(true);
  37. }
  38. }
  39.  
  40.  
  41.  
  42. package Package;
  43.  
  44. import java.awt.*;
  45. import java.awt.event.ActionEvent;
  46. import java.awt.event.ActionListener;
  47. import java.awt.event.KeyEvent;
  48. import java.awt.event.KeyListener;
  49. import java.util.LinkedList;
  50. import java.util.Random;
  51. import javax.swing.*;
  52. import javax.swing.border.Border;
  53. import java.awt.Graphics2D;
  54. public class SnakeGame extends JPanel implements ActionListener, KeyListener {
  55.  
  56. //Costanti
  57. private static final int WIDTH = 500;
  58. private static final int HEIGHT = 600;
  59. private static final int DOT_SIZE = 10;
  60. private static final int RAND_POS = 50;
  61. private static final int DELAY = 140;
  62.  
  63. //Variabili di gioco
  64. private boolean inGame = true;
  65. JButton button = new JButton("Restart");
  66. ImageIcon muretto = new ImageIcon("muretto.png");
  67. ImageIcon melaR = new ImageIcon("melaR.png");
  68. ImageIcon melaG = new ImageIcon("melaG.png");
  69. ImageIcon melaB = new ImageIcon("melaB.png");
  70. private int snakeL;
  71. private int appleX;
  72. private int appleY;
  73. private int appleG_X;
  74. private int appleG_Y;
  75. private int appleB_X;
  76. private int appleB_Y;
  77. private final int[] wallX = new int[20];
  78. private final int[] wallY = new int[20];
  79. private final Random r = new Random();
  80. private int chooseA;
  81. private LinkedList<Point> snake;
  82. private int direction = KeyEvent.VK_RIGHT;
  83.  
  84. public SnakeGame() {
  85. initBoard();
  86. }
  87. //TODO: sezione initBoard/Game
  88. public void initBoard() {
  89. // inizializza il gioco
  90. setBackground(new Color(128, 208, 63));
  91. setFocusable(true);
  92. //Border blackBorder = BorderFactory.createLineBorder(Color.BLACK, 10);
  93. //setBorder(blackBorder);
  94. addKeyListener(this);
  95. setPreferredSize(new Dimension(WIDTH, HEIGHT));
  96. revalidate();
  97. repaint();
  98. initGame();
  99. }
  100. private void initGame() {
  101. //Inizializza una nuova partita
  102. snakeL = 2;//Lunghezza iniziale snake
  103. snake = new LinkedList<>();
  104. for (int i = 0; i < snakeL; i++) {
  105. snake.add(new Point(50, 50));
  106. }
  107. newApple();
  108. createWall();
  109. Timer timer = new Timer(DELAY, this);
  110. timer.start();
  111. }
  112.  
  113. //TODO: sezione movimenti
  114. private void move() {
  115. // muove il serpente
  116. Point head = snake.getFirst();
  117. switch(direction) {
  118. case KeyEvent.VK_LEFT:
  119. head = new Point(head.x - DOT_SIZE, head.y);
  120. break;
  121. case KeyEvent.VK_RIGHT:
  122. head = new Point(head.x + DOT_SIZE, head.y);
  123. break;
  124. case KeyEvent.VK_UP:
  125. head = new Point(head.x, head.y - DOT_SIZE);
  126. break;
  127. case KeyEvent.VK_DOWN:
  128. head = new Point(head.x, head.y + DOT_SIZE);
  129. break;
  130. }
  131. if (head.x >= WIDTH) {
  132. head.x = 0;
  133. } else if (head.x < 0) {
  134. head.x = WIDTH - DOT_SIZE;
  135. }
  136. if (head.y >= HEIGHT) {
  137. head.y = 0;
  138. } else if (head.y < 0) {
  139. head.y = HEIGHT - DOT_SIZE;
  140. }
  141. if (snake.contains(head)) {
  142. //Il serpente ha colpito se stesso
  143. inGame = false;
  144. } else {
  145. //Il serpente si è mosso sulla casella vuota
  146. snake.addFirst(head);
  147. if (snake.size() > snakeL) {
  148. //Rimuove la coda del serpente se si è allungato per permettere lo spostamento
  149. snake.removeLast();
  150. }
  151. }
  152. }
  153.  
  154. //TODO: sezione drawSnake
  155. private void drawSnake(Graphics s) {
  156. //Disegna il serpente
  157. s.setColor(new Color(19, 80, 42));
  158. for (Point p : snake) {
  159. s.fillRect(p.x, p.y, DOT_SIZE, DOT_SIZE);
  160. }
  161. s.setColor(Color.BLUE);
  162. Font f1 = new Font(Font.SANS_SERIF, Font.BOLD, 40);
  163. s.setFont(f1);
  164. s.setColor(Color.BLUE);
  165. s.drawString("Score: " + (snakeL - 2), 175, 560);
  166. s.setColor(Color.BLACK);
  167. Graphics2D g2 = (Graphics2D) s;
  168. g2.setStroke(new BasicStroke(20));
  169. g2.drawLine(0, 500, 500, 500);
  170. }
  171. //TODO: sezione drawApple
  172. private void drawApple(Graphics g) {
  173. //Mela importata via immagine
  174. g.drawImage(melaR.getImage(), appleX, appleY, null);
  175. //--------------------------------------------------------------
  176. //disegna la mela
  177. /*
  178. g.setColor(Color.RED);
  179. g.fillOval(appleX, appleY, DOT_SIZE, DOT_SIZE);
  180. wallMovement();
  181. */
  182. }
  183.  
  184. private void drawGoldApple(Graphics g) {
  185. g.drawImage(melaG.getImage(), appleG_X, appleG_Y, null);
  186. }
  187.  
  188. private void drawBlueApple(Graphics g) {
  189. g.drawImage(melaB.getImage(), appleB_X, appleB_Y, null);
  190. }
  191.  
  192. //TODO: sezione newApple
  193. private void newApple() {
  194. //Genera una nuova mela in posizione casuale
  195. do {
  196. chooseA = r.nextInt() % 40;
  197. } while (chooseA < 0);
  198.  
  199. if (chooseA != 0 && chooseA > 15) {
  200. for (int i = 0; i < 20; i++) {
  201. do {
  202. appleX = r.nextInt(RAND_POS) * DOT_SIZE;
  203. appleY = r.nextInt(RAND_POS) * DOT_SIZE;
  204. } while (appleX == wallX[i] && appleY == wallY[i] || appleX >= 490 || appleX <= 10 || appleY >= 490 || appleY <= 10);
  205. }
  206. } else if (chooseA == 0) {
  207. for (int i = 0; i < 20; i++) {
  208. do {
  209. appleG_X = r.nextInt(RAND_POS) * DOT_SIZE;
  210. appleG_Y = r.nextInt(RAND_POS) * DOT_SIZE;
  211. } while (appleG_X == wallX[i] && appleG_Y == wallY[i] || appleG_X >= 490 || appleG_X <= 10 || appleG_Y >= 490 || appleG_Y <= 10);
  212. }
  213. } else {
  214. for (int i = 0; i < 20; i++) {
  215. do {
  216. appleB_X = r.nextInt(RAND_POS) * DOT_SIZE;
  217. appleB_Y = r.nextInt(RAND_POS) * DOT_SIZE;
  218. } while (appleB_X == wallX[i] && appleB_Y == wallY[i] || appleB_X >= 490 || appleB_X <= 10 || appleB_Y >= 490 || appleB_Y <= 10);
  219. }
  220. }
  221. }
  222.  
  223. //TODO: sezione checkApple
  224. private void checkApple() {
  225. // controlla se il serpente ha mangiato la mela rossa
  226. if (snake.getFirst().x == appleX && snake.getFirst().y == appleY) {
  227. snakeL++;
  228. newApple();
  229. wallMovement();
  230. }
  231. }
  232.  
  233. private void checkBlueApple(){
  234. //Controlla se il serpente ha mangiato la mela blu
  235. if(snake.getFirst().x == appleB_X && snake.getFirst().y == appleB_Y){
  236. snakeL++;
  237. snakeL++;
  238. newApple();
  239. wallMovement();
  240. }
  241. }
  242.  
  243. private void checkGoldApple(){
  244. //Controlla se il serpente ha mangiato la mela d'oro
  245. if(snake.getFirst().x == appleG_X && snake.getFirst().y == appleG_Y){
  246. snakeL++;
  247. snakeL++;
  248. snakeL++;
  249. snakeL++;
  250. snakeL++;
  251. newApple();
  252. wallMovement();
  253. }
  254. }
  255.  
  256. //TODO: sezione checkCollisions
  257. private boolean checkCollisions() {
  258. //Controllo per la collisione del serpente con qualche muro
  259. Point head = snake.getFirst();
  260. for(int i = 0; i < 20; i++){
  261. if ((head.x >= wallX[i] && head.x < wallX[i] + DOT_SIZE) && (head.y >= wallY[i] && head.y < wallY[i] + DOT_SIZE)) {
  262. inGame = false;
  263. break;
  264. }
  265. }
  266. return inGame;
  267. }
  268. private void checkBoard(){
  269. //Controllo per la collisione del serpente con i bordi
  270. Point head = snake.getFirst();
  271. if (head.x == 0 || head.x == 490 || head.y == 0 || head.y == 490) {
  272. inGame = false;
  273. }
  274. }
  275.  
  276. //TODO: sezione wall
  277. private void createWall() {
  278. int wallWidth = 2 * DOT_SIZE;
  279. int wallHeight = 2 * DOT_SIZE;
  280. int wallBuffer = 2 * DOT_SIZE;
  281. int boardWidth = WIDTH - 2 * wallBuffer;
  282. int boardHeight = HEIGHT - 2 * wallBuffer;
  283. boardHeight -= 100;
  284.  
  285. //Genera i muri con coordinate random
  286. for(int i = 0; i < 20; i++){
  287. do {
  288. wallX[i] = r.nextInt(boardWidth / wallWidth) * wallWidth + wallBuffer;
  289. wallY[i] = r.nextInt(boardHeight / wallHeight) * wallHeight + wallBuffer;
  290. }while(wallX[i] <= 10 && wallX[i] >=490 && wallY[i] <= 10 && wallY[i] >= 490);
  291. }
  292. }
  293.  
  294. private void drawWall(Graphics g){
  295. g.setColor(Color.BLACK);
  296. for(int i = 0; i < 20; i++){
  297. //Muretti importati via immagine
  298. g.drawImage(muretto.getImage(), wallX[i], wallY[i], null);
  299. //------------------------
  300.  
  301. //Muretti disegnati
  302. //g.fillRect(wallX[i], wallY[i], DOT_SIZE, DOT_SIZE);
  303. }
  304. }
  305.  
  306. private void wallMovement(){
  307. if (snakeL % 2 == 0) {
  308. for(int i = 0; i < 20; i++){
  309. if(i%2 == 0){
  310. wallX[i] += 10;
  311. wallY[i] -= 10;
  312. } else{
  313. wallX[i] -= 10;
  314. wallY[i] += 10;
  315. }
  316. }
  317. } else{
  318. for(int i = 0; i < 20; i++){
  319. if(i%2 == 0){
  320. wallX[i] -= 10;
  321. wallY[i] += 10;
  322. } else{
  323. wallX[i] += 10;
  324. wallY[i] -= 10;
  325. }
  326. }
  327. }
  328. }
  329.  
  330. //TODO: sezione azioni
  331.  
  332. @Override public void paintComponent(Graphics g) {
  333. super.paintComponent(g);
  334. inGame = checkCollisions();
  335. checkBoard();
  336. if (inGame) {
  337. drawSnake(g);
  338. if(chooseA > 15){
  339. drawApple(g);
  340. } else if(chooseA == 0){
  341. drawGoldApple(g);
  342. } else if(chooseA >= 1){
  343. drawBlueApple(g);
  344. }
  345. drawWall(g);
  346. } else {
  347. gameOver(g);
  348. }
  349. }
  350.  
  351. @Override public void actionPerformed(ActionEvent e) {
  352. if (inGame) {
  353. move();
  354. if(chooseA > 15) {
  355. checkApple();
  356. }else if(chooseA == 0){
  357. checkGoldApple();
  358. } else if(chooseA >= 1){
  359. checkBlueApple();
  360. }
  361. }
  362. repaint();
  363. }
  364.  
  365. @Override public void keyPressed(KeyEvent e) {
  366. int key = e.getKeyCode();
  367. if (key == KeyEvent.VK_LEFT && direction != KeyEvent.VK_RIGHT) {
  368. direction = KeyEvent.VK_LEFT;
  369. } else if (key == KeyEvent.VK_RIGHT && direction != KeyEvent.VK_LEFT) {
  370. direction = KeyEvent.VK_RIGHT;
  371. } else if (key == KeyEvent.VK_UP && direction != KeyEvent.VK_DOWN) {
  372. direction = KeyEvent.VK_UP;
  373. } else if (key == KeyEvent.VK_DOWN && direction != KeyEvent.VK_UP) {
  374. direction = KeyEvent.VK_DOWN;
  375. }
  376. }
  377. @Override public void keyReleased(KeyEvent e) {
  378. }
  379.  
  380. @Override public void keyTyped (KeyEvent e){
  381. }
  382.  
  383. //TODO: sezione gameOver
  384. private void gameOver(Graphics g) {
  385. //Visualizza il messaggio di gameOver
  386. String msg = "Game Over";
  387. Font f1 = new Font(Font.SANS_SERIF, Font.BOLD, 25);
  388. g.setFont(f1);
  389. g.setColor(Color.BLUE);
  390. g.drawString(msg, (WIDTH - g.getFontMetrics().stringWidth(msg)) / 2, HEIGHT / 2);
  391. g.drawString("Final score: " + (snakeL - 2), (WIDTH - g.getFontMetrics().stringWidth("Final score: " + (snakeL - 2))) / 2, (HEIGHT / 2) + 20);
  392. button.setBounds(150, 350, 200, 50);
  393. button.addActionListener(e -> initGame());
  394. add(button);
  395. Font buttonFont = new Font("Arial", Font.BOLD, 20);
  396.  
  397. button.setForeground(Color.GREEN);
  398. button.setFont(buttonFont);
  399. button.setBackground(Color.BLUE);
  400. revalidate();
  401. repaint();
  402. }
  403. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement