├── .gitignore ├── JavaSnakey.jar ├── src ├── SnakeGame.java ├── SnakeFrame.java ├── LeaderboardPanel.java ├── LobbyPanel.java └── GamePanel.java ├── Spanish version └── src │ ├── SnakeGame.java │ ├── SnakeFrame.java │ ├── LeaderboardPanel.java │ ├── LobbyPanel.java │ └── GamePanel.java └── readme.txt /.gitignore: -------------------------------------------------------------------------------- 1 | code from youtube.java 2 | classes 3 | snake.ico 4 | -------------------------------------------------------------------------------- /JavaSnakey.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/choidavid4/JavaSnakey/HEAD/JavaSnakey.jar -------------------------------------------------------------------------------- /src/SnakeGame.java: -------------------------------------------------------------------------------- 1 | public class SnakeGame{ 2 | public static void main(String[] args){ 3 | new SnakeFrame(); 4 | } 5 | } 6 | 7 | -------------------------------------------------------------------------------- /Spanish version/src/SnakeGame.java: -------------------------------------------------------------------------------- 1 | public class SnakeGame{ 2 | public static void main(String[] args){ 3 | new SnakeFrame(); 4 | } 5 | } 6 | 7 | -------------------------------------------------------------------------------- /readme.txt: -------------------------------------------------------------------------------- 1 | Hi! I am choidavid4 and this is my first "real" game in Java! Hope you enjoy it! 2 | 3 | You should compile every file in src using javac and run the class 'SnakeGame' to play. 4 | 5 | I am gonna leave a .jar compiled in java 11 in case you don't want to compile it yourself. Just double click it and it should work. 6 | 7 | The game has a lot of stuff that is kinda annoying like the font or the fact that the window is small and unrezisable but as my first game I am pretty proud of it. 8 | 9 | Happy crawling! -------------------------------------------------------------------------------- /src/SnakeFrame.java: -------------------------------------------------------------------------------- 1 | import javax.swing.*; 2 | import java.awt.event.*; 3 | 4 | class SnakeFrame extends JFrame{ 5 | LobbyPanel lobbyPanel = new LobbyPanel(this); 6 | GamePanel gamePanel = new GamePanel(this); 7 | LeaderboardPanel leaderboardPanel = new LeaderboardPanel(this); 8 | private boolean addedLeaderboard = false; 9 | 10 | public SnakeFrame(){ 11 | 12 | this.add(lobbyPanel); 13 | 14 | this.setTitle("Java Snakey"); 15 | this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 16 | this.pack(); 17 | this.setResizable(false); 18 | this.setLocationRelativeTo(null); 19 | this.setVisible(true); 20 | 21 | this.add(gamePanel); 22 | 23 | } 24 | 25 | public void switchToGamePanel(){ 26 | lobbyPanel.setVisible(false); 27 | gamePanel.setVisible(true); 28 | gamePanel.requestFocus(); 29 | gamePanel.startGame(); 30 | } 31 | 32 | public void switchToLobbyPanel(){ 33 | //Goes back from gamePanel to LobbyPanel 34 | gamePanel.gameOver(); 35 | gamePanel.setVisible(false); 36 | lobbyPanel.setVisible(true); 37 | lobbyPanel.requestFocus(); 38 | } 39 | 40 | public void gameToLeaderboard(){ 41 | gamePanel.setVisible(false); 42 | leaderboardPanel.loadScoreList(); 43 | leaderboardPanel.setVisible(true); 44 | leaderboardPanel.requestFocus(); 45 | } 46 | 47 | public void leaderboardToGame(){ 48 | leaderboardPanel.setVisible(false); 49 | gamePanel.setVisible(true); 50 | gamePanel.requestFocus(); 51 | gamePanel.startGame(); 52 | } 53 | 54 | public void leaderboardToLobby(){ 55 | leaderboardPanel.setVisible(false); 56 | lobbyPanel.setVisible(true); 57 | lobbyPanel.requestFocus(); 58 | } 59 | 60 | public void switchToLeaderboardPanel(){ 61 | if(addedLeaderboard){ 62 | lobbyPanel.setVisible(false); 63 | leaderboardPanel.loadScoreList(); 64 | leaderboardPanel.setVisible(true); 65 | leaderboardPanel.requestFocus(); 66 | }else{ 67 | lobbyPanel.setVisible(false); 68 | gamePanel.setVisible(false); 69 | this.add(leaderboardPanel); 70 | leaderboardPanel.loadScoreList(); 71 | leaderboardPanel.requestFocus(); 72 | addedLeaderboard = true; 73 | } 74 | 75 | 76 | } 77 | } -------------------------------------------------------------------------------- /Spanish version/src/SnakeFrame.java: -------------------------------------------------------------------------------- 1 | import javax.swing.*; 2 | import java.awt.event.*; 3 | 4 | class SnakeFrame extends JFrame{ 5 | LobbyPanel lobbyPanel = new LobbyPanel(this); 6 | GamePanel gamePanel = new GamePanel(this); 7 | LeaderboardPanel leaderboardPanel = new LeaderboardPanel(this); 8 | private boolean addedLeaderboard = false; 9 | 10 | public SnakeFrame(){ 11 | 12 | this.add(lobbyPanel); 13 | 14 | this.setTitle("Java Snakey"); 15 | this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 16 | this.pack(); 17 | this.setResizable(false); 18 | this.setLocationRelativeTo(null); 19 | this.setVisible(true); 20 | 21 | this.add(gamePanel); 22 | 23 | } 24 | 25 | public void switchToGamePanel(){ 26 | lobbyPanel.setVisible(false); 27 | gamePanel.setVisible(true); 28 | gamePanel.requestFocus(); 29 | gamePanel.startGame(); 30 | } 31 | 32 | public void switchToLobbyPanel(){ 33 | //Goes back from gamePanel to LobbyPanel 34 | gamePanel.gameOver(); 35 | gamePanel.setVisible(false); 36 | lobbyPanel.setVisible(true); 37 | lobbyPanel.requestFocus(); 38 | } 39 | 40 | public void gameToLeaderboard(){ 41 | gamePanel.setVisible(false); 42 | leaderboardPanel.loadScoreList(); 43 | leaderboardPanel.setVisible(true); 44 | leaderboardPanel.requestFocus(); 45 | } 46 | 47 | public void leaderboardToGame(){ 48 | leaderboardPanel.setVisible(false); 49 | gamePanel.setVisible(true); 50 | gamePanel.requestFocus(); 51 | gamePanel.startGame(); 52 | } 53 | 54 | public void leaderboardToLobby(){ 55 | leaderboardPanel.setVisible(false); 56 | lobbyPanel.setVisible(true); 57 | lobbyPanel.requestFocus(); 58 | } 59 | 60 | public void switchToLeaderboardPanel(){ 61 | if(addedLeaderboard){ 62 | lobbyPanel.setVisible(false); 63 | leaderboardPanel.loadScoreList(); 64 | leaderboardPanel.setVisible(true); 65 | leaderboardPanel.requestFocus(); 66 | }else{ 67 | lobbyPanel.setVisible(false); 68 | gamePanel.setVisible(false); 69 | this.add(leaderboardPanel); 70 | leaderboardPanel.loadScoreList(); 71 | leaderboardPanel.requestFocus(); 72 | addedLeaderboard = true; 73 | } 74 | 75 | 76 | } 77 | } -------------------------------------------------------------------------------- /src/LeaderboardPanel.java: -------------------------------------------------------------------------------- 1 | import javax.swing.*; 2 | import java.awt.*; 3 | import java.io.*; 4 | import java.util.*; 5 | import java.awt.event.*; 6 | 7 | public class LeaderboardPanel extends JPanel{ 8 | public static final int SCREEN_WIDTH = 600; 9 | public static final int SCREEN_HEIGHT = 600; 10 | public static final Font TITLE_FONT = new Font("Arial", 0, 42); 11 | public static final Font LINE_FONT = new Font("Arial", 0 , 32); 12 | public static final Font HEADER_FONT = new Font("Arial", Font.BOLD , 32); 13 | ArrayList scoreList = new ArrayList(); 14 | SnakeFrame parentFrame; 15 | JPanel scores; 16 | 17 | 18 | 19 | public LeaderboardPanel(JFrame frame){ 20 | parentFrame = (SnakeFrame) frame; 21 | 22 | this.setPreferredSize(new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT)); 23 | this.setFocusable(true); 24 | this.setBackground(Color.black); 25 | this.setLayout(new BorderLayout()); 26 | this.addKeyListener(new MyKeyAdapter()); 27 | 28 | JLabel title = new JLabel("Top 10 Snakeys"); 29 | title.setForeground(Color.white); 30 | title.setFont(TITLE_FONT); 31 | title.setHorizontalAlignment(SwingConstants.CENTER); 32 | title.setPreferredSize(new Dimension(SCREEN_WIDTH, 100)); 33 | 34 | this.add(title, BorderLayout.NORTH); 35 | 36 | GridLayout grid = new GridLayout(11, 2); 37 | scores = new JPanel(grid); 38 | scores.setBackground(new Color(0,0,0,0)); 39 | scores.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); 40 | 41 | 42 | 43 | 44 | 45 | } 46 | 47 | private JLabel getLabelItem(String text){ 48 | JLabel aux = new JLabel(text, SwingConstants.CENTER); 49 | 50 | aux.setForeground(Color.white); 51 | aux.setFont(LINE_FONT); 52 | 53 | return aux; 54 | } 55 | 56 | public void loadScoreList(){ 57 | try{ 58 | scoreList.clear(); 59 | BufferedReader buffer = new BufferedReader(new FileReader(new File("scores.data"))); 60 | String line; 61 | String[] nameScore; 62 | Score aux; 63 | while((line = buffer.readLine()) != null){ 64 | nameScore = line.split(","); 65 | aux = new Score(nameScore[0], Integer.parseInt(nameScore[1])); 66 | scoreList.add(aux); 67 | } 68 | System.out.println("ArrayList loaded successfully"); 69 | }catch(Exception ex){ 70 | System.out.println("Error trying to read Leaderboard File"); 71 | }finally{ 72 | scores.removeAll(); 73 | scores.repaint(); 74 | JLabel nameLabel = getLabelItem("Name"); 75 | JLabel scoreLabel = getLabelItem("Score"); 76 | nameLabel.setFont(HEADER_FONT); 77 | scoreLabel.setFont(HEADER_FONT); 78 | 79 | scores.add(nameLabel); 80 | scores.add(scoreLabel); 81 | 82 | for(int i = 0; i < 10; i++){ 83 | Score score1 = scoreList.get(i); 84 | JLabel nameLabel1 = getLabelItem(score1.name); 85 | JLabel scoreLabel1 = getLabelItem(String.valueOf(score1.score)); 86 | 87 | scores.add(nameLabel1); 88 | scores.add(scoreLabel1); 89 | } 90 | this.add(scores, BorderLayout.CENTER); 91 | } 92 | } 93 | 94 | public void reloadScoreList(){ 95 | 96 | } 97 | 98 | class MyKeyAdapter extends KeyAdapter{ 99 | public void keyPressed(KeyEvent ev){ 100 | int keyCode = ev.getKeyCode(); 101 | if (keyCode == KeyEvent.VK_ESCAPE){ 102 | parentFrame.leaderboardToLobby(); 103 | } 104 | } 105 | } 106 | } 107 | 108 | class Score implements Comparable{ 109 | String name; 110 | int score; 111 | 112 | public Score(String name, int score){ 113 | this.name = name; 114 | this.score = score; 115 | } 116 | 117 | public String toString(){ 118 | return "name: " + this.name + " score: " + this.score; 119 | } 120 | 121 | public int getScore(){ 122 | return score; 123 | } 124 | 125 | public String getName(){ 126 | return name; 127 | } 128 | 129 | public int compareTo(Object o){ 130 | Score b = (Score) o; 131 | return this.score - b.score; 132 | } 133 | } 134 | 135 | /* 136 | class LeaderboardPanelTestDrive{ 137 | public static void main(String[] args){ 138 | JFrame frame = new JFrame("LeaderboardPanelTestDrive"); 139 | 140 | frame.add(new LeaderboardPanel()); 141 | 142 | frame.pack(); 143 | frame.setLocationRelativeTo(null); 144 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 145 | frame.setVisible(true); 146 | } 147 | }*/ -------------------------------------------------------------------------------- /Spanish version/src/LeaderboardPanel.java: -------------------------------------------------------------------------------- 1 | import javax.swing.*; 2 | import java.awt.*; 3 | import java.io.*; 4 | import java.util.*; 5 | import java.awt.event.*; 6 | 7 | public class LeaderboardPanel extends JPanel{ 8 | public static final int SCREEN_WIDTH = 600; 9 | public static final int SCREEN_HEIGHT = 600; 10 | public static final Font TITLE_FONT = new Font("Arial", 0, 42); 11 | public static final Font LINE_FONT = new Font("Arial", 0 , 32); 12 | public static final Font HEADER_FONT = new Font("Arial", Font.BOLD , 32); 13 | ArrayList scoreList = new ArrayList(); 14 | SnakeFrame parentFrame; 15 | JPanel scores; 16 | 17 | 18 | 19 | public LeaderboardPanel(JFrame frame){ 20 | parentFrame = (SnakeFrame) frame; 21 | 22 | this.setPreferredSize(new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT)); 23 | this.setFocusable(true); 24 | this.setBackground(Color.black); 25 | this.setLayout(new BorderLayout()); 26 | this.addKeyListener(new MyKeyAdapter()); 27 | 28 | JLabel title = new JLabel("Top 10 Snakeys"); 29 | title.setForeground(Color.white); 30 | title.setFont(TITLE_FONT); 31 | title.setHorizontalAlignment(SwingConstants.CENTER); 32 | title.setPreferredSize(new Dimension(SCREEN_WIDTH, 100)); 33 | 34 | this.add(title, BorderLayout.NORTH); 35 | 36 | GridLayout grid = new GridLayout(11, 2); 37 | scores = new JPanel(grid); 38 | scores.setBackground(new Color(0,0,0,0)); 39 | scores.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); 40 | 41 | 42 | 43 | 44 | 45 | } 46 | 47 | private JLabel getLabelItem(String text){ 48 | JLabel aux = new JLabel(text, SwingConstants.CENTER); 49 | 50 | aux.setForeground(Color.white); 51 | aux.setFont(LINE_FONT); 52 | 53 | return aux; 54 | } 55 | 56 | public void loadScoreList(){ 57 | try{ 58 | scoreList.clear(); 59 | BufferedReader buffer = new BufferedReader(new FileReader(new File("scores.data"))); 60 | String line; 61 | String[] nameScore; 62 | Score aux; 63 | while((line = buffer.readLine()) != null){ 64 | nameScore = line.split(","); 65 | aux = new Score(nameScore[0], Integer.parseInt(nameScore[1])); 66 | scoreList.add(aux); 67 | } 68 | System.out.println("ArrayList loaded successfully"); 69 | }catch(Exception ex){ 70 | System.out.println("Error trying to read Leaderboard File"); 71 | }finally{ 72 | scores.removeAll(); 73 | scores.repaint(); 74 | JLabel nameLabel = getLabelItem("Nombre"); 75 | JLabel scoreLabel = getLabelItem("Puntaje"); 76 | nameLabel.setFont(HEADER_FONT); 77 | scoreLabel.setFont(HEADER_FONT); 78 | 79 | scores.add(nameLabel); 80 | scores.add(scoreLabel); 81 | 82 | for(int i = 0; i < 10; i++){ 83 | Score score1 = scoreList.get(i); 84 | JLabel nameLabel1 = getLabelItem(score1.name); 85 | JLabel scoreLabel1 = getLabelItem(String.valueOf(score1.score)); 86 | 87 | scores.add(nameLabel1); 88 | scores.add(scoreLabel1); 89 | } 90 | this.add(scores, BorderLayout.CENTER); 91 | } 92 | } 93 | 94 | public void reloadScoreList(){ 95 | 96 | } 97 | 98 | class MyKeyAdapter extends KeyAdapter{ 99 | public void keyPressed(KeyEvent ev){ 100 | int keyCode = ev.getKeyCode(); 101 | if (keyCode == KeyEvent.VK_ESCAPE){ 102 | parentFrame.leaderboardToLobby(); 103 | } 104 | } 105 | } 106 | } 107 | 108 | class Score implements Comparable{ 109 | String name; 110 | int score; 111 | 112 | public Score(String name, int score){ 113 | this.name = name; 114 | this.score = score; 115 | } 116 | 117 | public String toString(){ 118 | return "name: " + this.name + " score: " + this.score; 119 | } 120 | 121 | public int getScore(){ 122 | return score; 123 | } 124 | 125 | public String getName(){ 126 | return name; 127 | } 128 | 129 | public int compareTo(Object o){ 130 | Score b = (Score) o; 131 | return this.score - b.score; 132 | } 133 | } 134 | 135 | /* 136 | class LeaderboardPanelTestDrive{ 137 | public static void main(String[] args){ 138 | JFrame frame = new JFrame("LeaderboardPanelTestDrive"); 139 | 140 | frame.add(new LeaderboardPanel()); 141 | 142 | frame.pack(); 143 | frame.setLocationRelativeTo(null); 144 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 145 | frame.setVisible(true); 146 | } 147 | }*/ -------------------------------------------------------------------------------- /Spanish version/src/LobbyPanel.java: -------------------------------------------------------------------------------- 1 | import java.awt.*; 2 | import javax.swing.*; 3 | import java.awt.event.*; 4 | 5 | class LobbyPanel extends JPanel{ 6 | public static final String TITLE_MESSAGE = "Java Snakey"; 7 | public static final String CREATOR_MESSAGE = "Creado por @deivchoi en 2021"; 8 | public static final Font TITLE_FONT = new Font("Playball", 0 , 62); 9 | public static final Font MENU_FONT = new Font("Arial", 0 , 28); 10 | public static final Font CREATOR_FONT = new Font("Arial", 0 , 14); 11 | public static final int SCREEN_WIDTH = GamePanel.SCREEN_WIDTH; 12 | public static final int SCREEN_HEIGHT = GamePanel.SCREEN_HEIGHT; 13 | public static final String[] MENU_ITEMS = {"Jugar", "Mejores Snakeys", "Salir"}; 14 | private int selectedMenuItem = 0; 15 | SnakeFrame parentFrame; 16 | 17 | public LobbyPanel(JFrame frame){ 18 | parentFrame = (SnakeFrame) frame; 19 | this.addKeyListener(new MyKeyAdapter()); 20 | this.setBackground(Color.black); 21 | this.setPreferredSize(new Dimension(SCREEN_WIDTH,SCREEN_HEIGHT)); 22 | //Lo hacemos focusable para que tome teclas 23 | this.setFocusable(true); 24 | this.requestFocus(); 25 | } 26 | 27 | public void paintComponent(Graphics g){ 28 | //Tenemos que llamar al paintComponent() de super para no perder el background color seteado en JPanel. 29 | super.paintComponent(g); 30 | drawTitle(g); 31 | drawMenu(g); 32 | drawCreator(g); 33 | } 34 | 35 | private void drawTitle(Graphics g){ 36 | g.setColor(Color.white); 37 | g.setFont(TITLE_FONT); 38 | 39 | FontMetrics metrics = g.getFontMetrics(); 40 | int x = (SCREEN_WIDTH - metrics.stringWidth(TITLE_MESSAGE)) / 2; 41 | int y = metrics.getHeight() + 100; 42 | 43 | g.drawString(TITLE_MESSAGE, x, y); 44 | } 45 | 46 | private void drawMenu(Graphics g){ 47 | g.setColor(Color.white); 48 | g.setFont(MENU_FONT); 49 | 50 | FontMetrics metrics = g.getFontMetrics(); 51 | for(int i = 0; i < MENU_ITEMS.length; i++){ 52 | int x = (SCREEN_WIDTH - metrics.stringWidth(MENU_ITEMS[i])) / 2; //Horizontal center 53 | int y = metrics.getHeight() + 300 + (i * (metrics.getHeight() + 20)); 54 | g.drawString(MENU_ITEMS[i], x, y); 55 | if (selectedMenuItem == i){ 56 | drawTriangle(x - 30, y - 20, g); 57 | } 58 | } 59 | } 60 | 61 | private void drawTriangle(int x, int y, Graphics g){ 62 | g.setColor(Color.white); 63 | int[] xPoints = {x, x + 20, x}; 64 | int[] yPoints = {y, y+10, y+20}; 65 | g.fillPolygon(xPoints, yPoints, 3); 66 | } 67 | 68 | private void drawCreator(Graphics g){ 69 | g.setColor(Color.white); 70 | g.setFont(CREATOR_FONT); 71 | 72 | FontMetrics metrics = g.getFontMetrics(); 73 | int x = SCREEN_WIDTH - metrics.stringWidth(CREATOR_MESSAGE) - 10; 74 | int y = SCREEN_WIDTH - metrics.getHeight(); 75 | 76 | g.drawString(CREATOR_MESSAGE, x, y); 77 | } 78 | 79 | private class MyKeyAdapter extends KeyAdapter{ 80 | public void keyPressed(KeyEvent e){ 81 | switch(e.getKeyCode()){ 82 | case KeyEvent.VK_UP: 83 | decrementMenu(); 84 | repaint(); 85 | break; 86 | case KeyEvent.VK_DOWN: 87 | incrementMenu(); 88 | //System.out.println(selectedMenuItem); 89 | repaint(); 90 | break; 91 | case KeyEvent.VK_ENTER: 92 | switchPanels(); 93 | break; 94 | case KeyEvent.VK_ESCAPE: 95 | System.exit(0); 96 | break; 97 | 98 | } 99 | 100 | } 101 | } 102 | 103 | private void switchPanels(){ 104 | switch(selectedMenuItem){ 105 | case 0: 106 | parentFrame.switchToGamePanel(); 107 | break; 108 | case 1: 109 | parentFrame.switchToLeaderboardPanel(); 110 | break; 111 | case 2: 112 | System.exit(0); 113 | break; 114 | } 115 | } 116 | 117 | private void print(String m){ 118 | System.out.println(m); 119 | } 120 | 121 | private void incrementMenu(){ 122 | //Siempre escribir las clases y los metodos pensando en expansion. Mientras menos toquemos el source code mejor 123 | int lastItemIndex = MENU_ITEMS.length - 1; 124 | if(selectedMenuItem < lastItemIndex){ //3 125 | selectedMenuItem++; 126 | }else{ 127 | selectedMenuItem = 0; 128 | } 129 | } 130 | 131 | private void decrementMenu(){ 132 | int lastItemIndex = MENU_ITEMS.length - 1; 133 | if(selectedMenuItem > 0){ 134 | selectedMenuItem--; 135 | }else{ 136 | selectedMenuItem = lastItemIndex; 137 | } 138 | } 139 | 140 | public int getSelectedMenuItem(){ 141 | return selectedMenuItem; 142 | } 143 | 144 | } -------------------------------------------------------------------------------- /src/LobbyPanel.java: -------------------------------------------------------------------------------- 1 | import java.awt.*; 2 | import javax.swing.*; 3 | import java.awt.event.*; 4 | 5 | class LobbyPanel extends JPanel{ 6 | public static final String TITLE_MESSAGE = "Java Snakey"; 7 | public static final String CREATOR_MESSAGE = "Created by @deivchoi in 2021"; 8 | public static final Font TITLE_FONT = new Font("Playball", 0 , 62); 9 | public static final Font MENU_FONT = new Font("Arial", 0 , 28); 10 | public static final Font CREATOR_FONT = new Font("Arial", 0 , 14); 11 | public static final int SCREEN_WIDTH = GamePanel.SCREEN_WIDTH; 12 | public static final int SCREEN_HEIGHT = GamePanel.SCREEN_HEIGHT; 13 | public static final String[] MENU_ITEMS = {"Play", "Leaderboards", "Exit"}; 14 | private int selectedMenuItem = 0; 15 | SnakeFrame parentFrame; 16 | 17 | 18 | 19 | public LobbyPanel(JFrame frame){ 20 | parentFrame = (SnakeFrame) frame; 21 | 22 | 23 | this.addKeyListener(new MyKeyAdapter()); 24 | 25 | this.setBackground(Color.black); 26 | this.setPreferredSize(new Dimension(SCREEN_WIDTH,SCREEN_HEIGHT)); 27 | //Lo hacemos focusable para que tome teclas 28 | this.setFocusable(true); 29 | this.requestFocus(); 30 | } 31 | 32 | public void paintComponent(Graphics g){ 33 | //Tenemos que llamar al paintComponent() de super para no perder el background color seteado en JPanel. 34 | super.paintComponent(g); 35 | drawTitle(g); 36 | drawMenu(g); 37 | drawCreator(g); 38 | } 39 | 40 | private void drawTitle(Graphics g){ 41 | g.setColor(Color.white); 42 | g.setFont(TITLE_FONT); 43 | 44 | FontMetrics metrics = g.getFontMetrics(); 45 | int x = (SCREEN_WIDTH - metrics.stringWidth(TITLE_MESSAGE)) / 2; 46 | int y = metrics.getHeight() + 100; 47 | 48 | g.drawString(TITLE_MESSAGE, x, y); 49 | } 50 | 51 | private void drawMenu(Graphics g){ 52 | g.setColor(Color.white); 53 | g.setFont(MENU_FONT); 54 | 55 | FontMetrics metrics = g.getFontMetrics(); 56 | for(int i = 0; i < MENU_ITEMS.length; i++){ 57 | int x = (SCREEN_WIDTH - metrics.stringWidth(MENU_ITEMS[i])) / 2; //Horizontal center 58 | int y = metrics.getHeight() + 300 + (i * (metrics.getHeight() + 20)); 59 | g.drawString(MENU_ITEMS[i], x, y); 60 | if (selectedMenuItem == i){ 61 | drawTriangle(x - 30, y - 20, g); 62 | } 63 | } 64 | } 65 | 66 | private void drawTriangle(int x, int y, Graphics g){ 67 | g.setColor(Color.white); 68 | int[] xPoints = {x, x + 20, x}; 69 | int[] yPoints = {y, y+10, y+20}; 70 | g.fillPolygon(xPoints, yPoints, 3); 71 | } 72 | 73 | private void drawCreator(Graphics g){ 74 | g.setColor(Color.white); 75 | g.setFont(CREATOR_FONT); 76 | 77 | FontMetrics metrics = g.getFontMetrics(); 78 | int x = SCREEN_WIDTH - metrics.stringWidth(CREATOR_MESSAGE) - 10; 79 | int y = SCREEN_WIDTH - metrics.getHeight(); 80 | 81 | g.drawString(CREATOR_MESSAGE, x, y); 82 | } 83 | 84 | private class MyKeyAdapter extends KeyAdapter{ 85 | public void keyPressed(KeyEvent e){ 86 | switch(e.getKeyCode()){ 87 | case KeyEvent.VK_UP: 88 | decrementMenu(); 89 | repaint(); 90 | break; 91 | case KeyEvent.VK_DOWN: 92 | incrementMenu(); 93 | //System.out.println(selectedMenuItem); 94 | repaint(); 95 | break; 96 | case KeyEvent.VK_ENTER: 97 | switchPanels(); 98 | break; 99 | case KeyEvent.VK_ESCAPE: 100 | System.exit(0); 101 | break; 102 | 103 | } 104 | 105 | } 106 | } 107 | 108 | private void switchPanels(){ 109 | switch(selectedMenuItem){ 110 | case 0: 111 | parentFrame.switchToGamePanel(); 112 | break; 113 | case 1: 114 | parentFrame.switchToLeaderboardPanel(); 115 | break; 116 | case 2: 117 | System.exit(0); 118 | break; 119 | } 120 | } 121 | 122 | private void print(String m){ 123 | System.out.println(m); 124 | } 125 | 126 | private void incrementMenu(){ 127 | //Siempre escribir las clases y los metodos pensando en expansion. Mientras menos toquemos el source code mejor 128 | int lastItemIndex = MENU_ITEMS.length - 1; 129 | if(selectedMenuItem < lastItemIndex){ //3 130 | selectedMenuItem++; 131 | }else{ 132 | selectedMenuItem = 0; 133 | } 134 | } 135 | 136 | private void decrementMenu(){ 137 | int lastItemIndex = MENU_ITEMS.length - 1; 138 | if(selectedMenuItem > 0){ 139 | selectedMenuItem--; 140 | }else{ 141 | selectedMenuItem = lastItemIndex; 142 | } 143 | } 144 | 145 | public int getSelectedMenuItem(){ 146 | return selectedMenuItem; 147 | } 148 | 149 | } -------------------------------------------------------------------------------- /src/GamePanel.java: -------------------------------------------------------------------------------- 1 | import javax.swing.*; 2 | import javax.swing.Timer; 3 | import java.awt.*; 4 | import java.awt.event.*; 5 | import java.util.*; 6 | import java.io.*; 7 | 8 | class GamePanel extends JPanel implements ActionListener{ 9 | public static final int SCREEN_WIDTH = 600; 10 | public static final int SCREEN_HEIGHT = 600; 11 | public static final int UNIT_SIZE = 25; 12 | //Must be a square window. 13 | public static final int GAME_UNITS = (int) (SCREEN_WIDTH/UNIT_SIZE) * (SCREEN_HEIGHT/UNIT_SIZE); 14 | public static final int HORIZONTAL_UNITS = SCREEN_WIDTH/UNIT_SIZE; 15 | public static final int VERTICAL_UNITS = SCREEN_HEIGHT/UNIT_SIZE; 16 | public static final int DELAY = 100; 17 | public static final int INITIAL_SNAKE_SIZE = 6; 18 | private boolean running = false; 19 | private int appleX; 20 | private int appleY; 21 | private Timer timer = new Timer(DELAY, this); 22 | private char direction; 23 | private int[] snakeX = new int[GAME_UNITS]; 24 | private int[] snakeY = new int[GAME_UNITS]; 25 | private int snakeSize; 26 | private int applesEaten; 27 | SnakeFrame parentFrame; 28 | boolean keyInput = false; 29 | private int lowestScore; 30 | private ArrayList scoreList = new ArrayList(); 31 | private boolean showJTextField = false; 32 | private String playerName = ""; 33 | String[] gameOverMessages = {"Maybe next time!", "Sorry Snakey!", "Don't lose hope yet!", "GG WP", "Time for shedding", "Nice Keyboard", "Ow :(", "Ooh That hurts!"}; 34 | String randomGameOverMessage = ""; 35 | private Score actualScore; 36 | 37 | 38 | GamePanel(JFrame frame){ 39 | parentFrame = (SnakeFrame) frame; 40 | 41 | //Si el panel no es focuseable, no va a escuchar las teclas 42 | this.setFocusable(true); 43 | this.requestFocus(); 44 | this.addKeyListener(new MyKeyAdapter()); 45 | this.setPreferredSize(new Dimension(SCREEN_WIDTH,SCREEN_HEIGHT)); 46 | this.setBackground(Color.black); 47 | //Timer is a class from Swing that fires up an ActionEvent every given interval of miliseconds. In this case, timer activates this class every quarter of a second. 48 | } 49 | 50 | public void startGame(){ 51 | snakeSize = INITIAL_SNAKE_SIZE; 52 | applesEaten = 0; 53 | for(int i = 0; i < snakeSize; i++){ 54 | snakeX[i] = 0; 55 | snakeY[i] = 0; 56 | } 57 | direction = 'R'; 58 | timer.start(); 59 | newApple(); 60 | System.out.println("Initialized game panel startGame()"); 61 | loadScoreList(); 62 | loadLowestScore(); 63 | randomGameOverMessage = gameOverMessages[random(gameOverMessages.length)]; 64 | } 65 | 66 | //same method as the one in leaderboardPanel 67 | public void loadScoreList(){ 68 | try{ 69 | scoreList.clear(); 70 | BufferedReader buffer = new BufferedReader(new FileReader(new File("scores.data"))); 71 | String line; 72 | String[] nameScore; 73 | Score aux; 74 | while((line = buffer.readLine()) != null){ 75 | nameScore = line.split(","); 76 | aux = new Score(nameScore[0], Integer.parseInt(nameScore[1])); 77 | scoreList.add(aux); 78 | } 79 | System.out.println("ArrayList loaded successfully"); 80 | System.out.println(scoreList); 81 | }catch(Exception ex){ 82 | System.out.println("Error trying to read file"); 83 | } 84 | } 85 | 86 | public void loadLowestScore(){ 87 | //vamos a sortear una vez por las dudas. sort() SORTEA DE MENOR A MAYOR 88 | scoreList.sort(Comparator.reverseOrder()); 89 | lowestScore = scoreList.get(9).getScore(); 90 | System.out.println("lowestScore: " + lowestScore); 91 | } 92 | 93 | 94 | 95 | public void actionPerformed(ActionEvent ev){ 96 | move(); 97 | checkCollision(); 98 | eatApple(); 99 | repaint(); 100 | } 101 | 102 | 103 | 104 | public void paintComponent(Graphics g){ 105 | super.paintComponent(g); 106 | /* 107 | //Drawing a grid 108 | for(int i = 0; i < HORIZONTAL_UNITS; i++){ 109 | //vertical line 110 | g.drawLine(i * (UNIT_SIZE), 0, i * (UNIT_SIZE), SCREEN_HEIGHT); 111 | g.drawLine(0, i * (UNIT_SIZE), SCREEN_WIDTH, i * (UNIT_SIZE)); 112 | } 113 | */ 114 | 115 | //Drawing apple with appleX and appleY 116 | g.setColor(Color.red); 117 | g.fillOval(appleX , appleY, UNIT_SIZE, UNIT_SIZE); 118 | //Drawing snake head 119 | g.setColor(Color.green); 120 | g.fillRect(snakeX[0], snakeY[0], UNIT_SIZE, UNIT_SIZE); 121 | //snake Body 122 | for(int i = 1; i < snakeSize; i++){ 123 | g.fillRect(snakeX[i], snakeY[i], UNIT_SIZE, UNIT_SIZE); 124 | } 125 | 126 | //Draw score String 127 | g.setColor(Color.white); 128 | g.setFont(new Font("MS Gothic", Font.PLAIN, 25)); 129 | FontMetrics fontSize = g.getFontMetrics(); 130 | int fontX = SCREEN_WIDTH - fontSize.stringWidth("Score: " + applesEaten) - 10; 131 | int fontY = fontSize.getHeight(); 132 | g.drawString("Score: " + applesEaten, fontX, fontY); 133 | 134 | if(!timer.isRunning()){ 135 | //print game over screen 136 | g.setColor(Color.white); 137 | g.setFont(new Font("MS Gothic", Font.PLAIN, 58)); 138 | 139 | String message = randomGameOverMessage; 140 | fontSize = g.getFontMetrics(); 141 | fontX = (SCREEN_WIDTH - fontSize.stringWidth(message)) / 2 ; 142 | fontY = (SCREEN_HEIGHT - fontSize.getHeight()) /2; 143 | g.drawString(message, fontX, fontY); 144 | 145 | g.setFont(new Font("MS Gothic", Font.PLAIN, 24)); 146 | message = "Press F2 to restart"; 147 | fontSize = g.getFontMetrics(); 148 | fontX = (SCREEN_WIDTH - fontSize.stringWidth(message)) / 2 ; 149 | fontY = fontY + fontSize.getHeight() + 20; 150 | g.drawString(message, fontX, fontY); 151 | 152 | if(showJTextField){ 153 | drawJTextField(g); 154 | drawPlayerName(g); 155 | 156 | } 157 | 158 | } 159 | } 160 | 161 | public void drawJTextField(Graphics g){ 162 | g.setFont(new Font("MS Gothic", Font.PLAIN, 24)); 163 | String message = "Insert your name"; 164 | FontMetrics fontSize = g.getFontMetrics(); 165 | //Horizontal center 166 | int fontX = (SCREEN_WIDTH - fontSize.stringWidth(message)) / 2 ; 167 | g.drawString(message, fontX, 350); 168 | } 169 | 170 | public void drawPlayerName(Graphics g){ 171 | g.setFont(new Font("MS Gothic", Font.PLAIN, 24)); 172 | FontMetrics fontSize = g.getFontMetrics(); 173 | //Horizontal center 174 | int fontX = (SCREEN_WIDTH - fontSize.stringWidth(playerName)) / 2 ; 175 | g.drawString(playerName, fontX, 400); 176 | } 177 | 178 | 179 | 180 | public void newApple(){ 181 | //numero random entre 0 y 23 * unit size 182 | int x = random(HORIZONTAL_UNITS) * UNIT_SIZE; 183 | int y = random(VERTICAL_UNITS) * UNIT_SIZE; 184 | Point provisional = new Point(x,y); 185 | Point snakePos = new Point(); 186 | boolean newApplePermission = true; 187 | for(int i = 0; i < snakeSize; i++){ 188 | snakePos.setLocation(snakeX[i], snakeY[i]); 189 | if(provisional.equals(snakePos)){ 190 | newApplePermission = false; 191 | } 192 | } 193 | //System.out.println(provisional); 194 | //System.out.println(newApplePermission); 195 | if(newApplePermission){ 196 | appleX = x; 197 | appleY = y; 198 | }else{ 199 | newApple(); 200 | } 201 | } 202 | 203 | public void checkCollision(){ 204 | if(snakeX[0] >= (SCREEN_WIDTH) || snakeX[0] < 0 || snakeY[0] >= (SCREEN_HEIGHT) || snakeY[0] < 0){ 205 | gameOver(); 206 | } 207 | for(int i = 1; i < snakeSize; i++){ 208 | if((snakeX[0] == snakeX[i]) && (snakeY[0] == snakeY[i])){ 209 | gameOver(); 210 | } 211 | } 212 | } 213 | 214 | public void eatApple(){ 215 | if(snakeX[0] == appleX && snakeY[0] == appleY){ 216 | snakeSize++; 217 | applesEaten++; 218 | newApple(); 219 | } 220 | } 221 | 222 | public void move(){ 223 | //Este metodo se ejecuta cada vez que timer nos lo permite 224 | //Hay que recorrer la serpiente de atras para adelante 225 | for(int i = snakeSize; i > 0; i--){ 226 | snakeX[i] = snakeX[i-1]; 227 | snakeY[i] = snakeY[i-1]; 228 | } 229 | //System.out.println("snakeX[0] = " + snakeX[0]); 230 | switch(direction){ 231 | case 'R': 232 | snakeX[0] += UNIT_SIZE; 233 | break; 234 | case 'L': 235 | snakeX[0] -= UNIT_SIZE; 236 | break; 237 | case 'U': 238 | snakeY[0] -= UNIT_SIZE; 239 | break; 240 | case 'D': 241 | snakeY[0] += UNIT_SIZE; 242 | break; 243 | } 244 | 245 | keyInput = false; 246 | } 247 | 248 | public void gameOver(){ 249 | timer.stop(); 250 | if(applesEaten > lowestScore){ 251 | showJTextField = true; 252 | } 253 | 254 | } 255 | 256 | 257 | public int random(int range){ 258 | //returns an int from 0 to range 259 | return (int)(Math.random() * range); 260 | } 261 | 262 | class MyKeyAdapter extends KeyAdapter{ 263 | public void keyPressed(KeyEvent k){ 264 | 265 | switch(k.getKeyCode()){ 266 | case (KeyEvent.VK_DOWN): 267 | if(direction != 'U' && keyInput == false){ 268 | direction = 'D'; 269 | keyInput = true; 270 | } 271 | break; 272 | case (KeyEvent.VK_UP): 273 | if(direction != 'D' && !keyInput){ 274 | direction = 'U'; 275 | keyInput = true; 276 | } 277 | break; 278 | case (KeyEvent.VK_LEFT): 279 | if(direction != 'R' && keyInput == false){ 280 | direction = 'L'; 281 | keyInput = true; 282 | } 283 | break; 284 | case (KeyEvent.VK_RIGHT): 285 | if(direction != 'L' && keyInput == false){ 286 | direction = 'R'; 287 | keyInput = true; 288 | } 289 | break; 290 | case (KeyEvent.VK_F2): 291 | if(!timer.isRunning()){ 292 | startGame(); 293 | } 294 | break; 295 | case KeyEvent.VK_ESCAPE: 296 | parentFrame.switchToLobbyPanel(); 297 | break; 298 | } 299 | 300 | if(showJTextField){ 301 | if(k.getKeyCode() == KeyEvent.VK_ENTER){ 302 | actualScore = new Score(playerName, applesEaten); 303 | scoreList.add(actualScore); 304 | playerName = ""; 305 | sortAndSave(); 306 | showJTextField = false; 307 | parentFrame.switchToLobbyPanel(); 308 | }else if(k.getKeyCode() == KeyEvent.VK_BACK_SPACE && playerName.length() > 0){ 309 | StringBuilder sb = new StringBuilder(playerName); 310 | sb.deleteCharAt(sb.length() - 1); 311 | playerName = sb.toString(); 312 | } 313 | else{ 314 | if(!k.isActionKey() && k.getKeyCode() != KeyEvent.VK_SHIFT && k.getKeyCode() != KeyEvent.VK_BACK_SPACE){ 315 | playerName = playerName + k.getKeyChar(); 316 | } 317 | } 318 | 319 | repaint(); 320 | } 321 | //System.out.println(direction); 322 | } 323 | } 324 | 325 | public void sortAndSave(){ 326 | try{ 327 | BufferedWriter bw = new BufferedWriter(new FileWriter(new File("scores.data"))); 328 | scoreList.sort(Comparator.reverseOrder()); 329 | for(int i = 0; i < 10; i++){ 330 | Score element = scoreList.get(i); 331 | bw.write(element.name + "," + String.valueOf(element.score) + "\n"); 332 | 333 | } 334 | bw.flush(); 335 | }catch(IOException ex){ 336 | System.out.println("Error writing file"); 337 | } 338 | 339 | } 340 | 341 | public void sleep(int millis){ 342 | try{ 343 | Thread.sleep(millis); 344 | System.out.println("Slept"); 345 | }catch(Exception ex){ 346 | System.out.println("Fatal Error in sleep() method"); 347 | } 348 | } 349 | 350 | } -------------------------------------------------------------------------------- /Spanish version/src/GamePanel.java: -------------------------------------------------------------------------------- 1 | import javax.swing.*; 2 | import javax.swing.Timer; 3 | import java.awt.*; 4 | import java.awt.event.*; 5 | import java.util.*; 6 | import java.io.*; 7 | 8 | class GamePanel extends JPanel implements ActionListener{ 9 | public static final int SCREEN_WIDTH = 600; 10 | public static final int SCREEN_HEIGHT = 600; 11 | public static final int UNIT_SIZE = 25; 12 | //Must be a square window. 13 | public static final int GAME_UNITS = (int) (SCREEN_WIDTH/UNIT_SIZE) * (SCREEN_HEIGHT/UNIT_SIZE); 14 | public static final int HORIZONTAL_UNITS = SCREEN_WIDTH/UNIT_SIZE; 15 | public static final int VERTICAL_UNITS = SCREEN_HEIGHT/UNIT_SIZE; 16 | public static final int DELAY = 100; 17 | public static final int INITIAL_SNAKE_SIZE = 6; 18 | private boolean running = false; 19 | private int appleX; 20 | private int appleY; 21 | private Timer timer = new Timer(DELAY, this); 22 | private char direction; 23 | private int[] snakeX = new int[GAME_UNITS]; 24 | private int[] snakeY = new int[GAME_UNITS]; 25 | private int snakeSize; 26 | private int applesEaten; 27 | SnakeFrame parentFrame; 28 | boolean keyInput = false; 29 | private int lowestScore; 30 | private ArrayList scoreList = new ArrayList(); 31 | private boolean showJTextField = false; 32 | private String playerName = ""; 33 | String[] gameOverMessages = {"suerte la proxima!", "Lo sentimos Snakey!", "Dale que se puede!", "GG WP", "Hora de mudar", "Buen teclado", "Ow :(", "Uhh eso dolio!", "Que tristeza"}; 34 | String randomGameOverMessage = ""; 35 | private Score actualScore; 36 | 37 | 38 | GamePanel(JFrame frame){ 39 | parentFrame = (SnakeFrame) frame; 40 | 41 | //Si el panel no es focuseable, no va a escuchar las teclas 42 | this.setFocusable(true); 43 | this.requestFocus(); 44 | this.addKeyListener(new MyKeyAdapter()); 45 | this.setPreferredSize(new Dimension(SCREEN_WIDTH,SCREEN_HEIGHT)); 46 | this.setBackground(Color.black); 47 | //Timer is a class from Swing that fires up an ActionEvent every given interval of miliseconds. In this case, timer activates this class every quarter of a second. 48 | } 49 | 50 | public void startGame(){ 51 | snakeSize = INITIAL_SNAKE_SIZE; 52 | applesEaten = 0; 53 | for(int i = 0; i < snakeSize; i++){ 54 | snakeX[i] = 0; 55 | snakeY[i] = 0; 56 | } 57 | direction = 'R'; 58 | timer.start(); 59 | newApple(); 60 | System.out.println("Initialized game panel startGame()"); 61 | loadScoreList(); 62 | loadLowestScore(); 63 | randomGameOverMessage = gameOverMessages[random(gameOverMessages.length)]; 64 | } 65 | 66 | //same method as the one in leaderboardPanel 67 | public void loadScoreList(){ 68 | try{ 69 | scoreList.clear(); 70 | BufferedReader buffer = new BufferedReader(new FileReader(new File("scores.data"))); 71 | String line; 72 | String[] nameScore; 73 | Score aux; 74 | while((line = buffer.readLine()) != null){ 75 | nameScore = line.split(","); 76 | aux = new Score(nameScore[0], Integer.parseInt(nameScore[1])); 77 | scoreList.add(aux); 78 | } 79 | System.out.println("ArrayList loaded successfully"); 80 | System.out.println(scoreList); 81 | }catch(Exception ex){ 82 | System.out.println("Error trying to read file"); 83 | } 84 | } 85 | 86 | public void loadLowestScore(){ 87 | //vamos a sortear una vez por las dudas. sort() SORTEA DE MENOR A MAYOR 88 | scoreList.sort(Comparator.reverseOrder()); 89 | lowestScore = scoreList.get(9).getScore(); 90 | System.out.println("lowestScore: " + lowestScore); 91 | } 92 | 93 | 94 | 95 | public void actionPerformed(ActionEvent ev){ 96 | move(); 97 | checkCollision(); 98 | eatApple(); 99 | repaint(); 100 | } 101 | 102 | 103 | 104 | public void paintComponent(Graphics g){ 105 | super.paintComponent(g); 106 | /* 107 | //Drawing a grid 108 | for(int i = 0; i < HORIZONTAL_UNITS; i++){ 109 | //vertical line 110 | g.drawLine(i * (UNIT_SIZE), 0, i * (UNIT_SIZE), SCREEN_HEIGHT); 111 | g.drawLine(0, i * (UNIT_SIZE), SCREEN_WIDTH, i * (UNIT_SIZE)); 112 | } 113 | */ 114 | 115 | //Drawing apple with appleX and appleY 116 | g.setColor(Color.red); 117 | g.fillOval(appleX , appleY, UNIT_SIZE, UNIT_SIZE); 118 | //Drawing snake head 119 | g.setColor(Color.green); 120 | g.fillRect(snakeX[0], snakeY[0], UNIT_SIZE, UNIT_SIZE); 121 | //snake Body 122 | for(int i = 1; i < snakeSize; i++){ 123 | g.fillRect(snakeX[i], snakeY[i], UNIT_SIZE, UNIT_SIZE); 124 | } 125 | 126 | //Draw score String 127 | g.setColor(Color.white); 128 | g.setFont(new Font("MS Gothic", Font.PLAIN, 25)); 129 | FontMetrics fontSize = g.getFontMetrics(); 130 | int fontX = SCREEN_WIDTH - fontSize.stringWidth("Puntaje: " + applesEaten) - 10; 131 | int fontY = fontSize.getHeight(); 132 | g.drawString("Puntaje: " + applesEaten, fontX, fontY); 133 | 134 | if(!timer.isRunning()){ 135 | //print game over screen 136 | g.setColor(Color.white); 137 | g.setFont(new Font("MS Gothic", Font.PLAIN, 58)); 138 | 139 | String message = randomGameOverMessage; 140 | fontSize = g.getFontMetrics(); 141 | fontX = (SCREEN_WIDTH - fontSize.stringWidth(message)) / 2 ; 142 | fontY = (SCREEN_HEIGHT - fontSize.getHeight()) /2; 143 | g.drawString(message, fontX, fontY); 144 | 145 | g.setFont(new Font("MS Gothic", Font.PLAIN, 24)); 146 | message = "Presiona F2 para reiniciar"; 147 | fontSize = g.getFontMetrics(); 148 | fontX = (SCREEN_WIDTH - fontSize.stringWidth(message)) / 2 ; 149 | fontY = fontY + fontSize.getHeight() + 20; 150 | g.drawString(message, fontX, fontY); 151 | 152 | if(showJTextField){ 153 | drawJTextField(g); 154 | drawPlayerName(g); 155 | 156 | } 157 | 158 | } 159 | } 160 | 161 | public void drawJTextField(Graphics g){ 162 | g.setFont(new Font("MS Gothic", Font.PLAIN, 24)); 163 | String message = "Ingresa tu nombre:"; 164 | FontMetrics fontSize = g.getFontMetrics(); 165 | //Horizontal center 166 | int fontX = (SCREEN_WIDTH - fontSize.stringWidth(message)) / 2 ; 167 | g.drawString(message, fontX, 350); 168 | } 169 | 170 | public void drawPlayerName(Graphics g){ 171 | g.setFont(new Font("MS Gothic", Font.PLAIN, 24)); 172 | FontMetrics fontSize = g.getFontMetrics(); 173 | //Horizontal center 174 | int fontX = (SCREEN_WIDTH - fontSize.stringWidth(playerName)) / 2 ; 175 | g.drawString(playerName, fontX, 400); 176 | } 177 | 178 | 179 | 180 | public void newApple(){ 181 | //numero random entre 0 y 23 * unit size 182 | int x = random(HORIZONTAL_UNITS) * UNIT_SIZE; 183 | int y = random(VERTICAL_UNITS) * UNIT_SIZE; 184 | Point provisional = new Point(x,y); 185 | Point snakePos = new Point(); 186 | boolean newApplePermission = true; 187 | for(int i = 0; i < snakeSize; i++){ 188 | snakePos.setLocation(snakeX[i], snakeY[i]); 189 | if(provisional.equals(snakePos)){ 190 | newApplePermission = false; 191 | } 192 | } 193 | //System.out.println(provisional); 194 | //System.out.println(newApplePermission); 195 | if(newApplePermission){ 196 | appleX = x; 197 | appleY = y; 198 | }else{ 199 | newApple(); 200 | } 201 | } 202 | 203 | public void checkCollision(){ 204 | if(snakeX[0] >= (SCREEN_WIDTH) || snakeX[0] < 0 || snakeY[0] >= (SCREEN_HEIGHT) || snakeY[0] < 0){ 205 | gameOver(); 206 | } 207 | for(int i = 1; i < snakeSize; i++){ 208 | if((snakeX[0] == snakeX[i]) && (snakeY[0] == snakeY[i])){ 209 | gameOver(); 210 | } 211 | } 212 | } 213 | 214 | public void eatApple(){ 215 | if(snakeX[0] == appleX && snakeY[0] == appleY){ 216 | snakeSize++; 217 | applesEaten++; 218 | newApple(); 219 | } 220 | } 221 | 222 | public void move(){ 223 | //Este metodo se ejecuta cada vez que timer nos lo permite 224 | //Hay que recorrer la serpiente de atras para adelante 225 | for(int i = snakeSize; i > 0; i--){ 226 | snakeX[i] = snakeX[i-1]; 227 | snakeY[i] = snakeY[i-1]; 228 | } 229 | //System.out.println("snakeX[0] = " + snakeX[0]); 230 | switch(direction){ 231 | case 'R': 232 | snakeX[0] += UNIT_SIZE; 233 | break; 234 | case 'L': 235 | snakeX[0] -= UNIT_SIZE; 236 | break; 237 | case 'U': 238 | snakeY[0] -= UNIT_SIZE; 239 | break; 240 | case 'D': 241 | snakeY[0] += UNIT_SIZE; 242 | break; 243 | } 244 | 245 | keyInput = false; 246 | } 247 | 248 | public void gameOver(){ 249 | timer.stop(); 250 | if(applesEaten > lowestScore){ 251 | showJTextField = true; 252 | } 253 | 254 | } 255 | 256 | 257 | public int random(int range){ 258 | //returns an int from 0 to range 259 | return (int)(Math.random() * range); 260 | } 261 | 262 | class MyKeyAdapter extends KeyAdapter{ 263 | public void keyPressed(KeyEvent k){ 264 | 265 | switch(k.getKeyCode()){ 266 | case (KeyEvent.VK_DOWN): 267 | if(direction != 'U' && keyInput == false){ 268 | direction = 'D'; 269 | keyInput = true; 270 | } 271 | break; 272 | case (KeyEvent.VK_UP): 273 | if(direction != 'D' && !keyInput){ 274 | direction = 'U'; 275 | keyInput = true; 276 | } 277 | break; 278 | case (KeyEvent.VK_LEFT): 279 | if(direction != 'R' && keyInput == false){ 280 | direction = 'L'; 281 | keyInput = true; 282 | } 283 | break; 284 | case (KeyEvent.VK_RIGHT): 285 | if(direction != 'L' && keyInput == false){ 286 | direction = 'R'; 287 | keyInput = true; 288 | } 289 | break; 290 | case (KeyEvent.VK_F2): 291 | if(!timer.isRunning()){ 292 | startGame(); 293 | } 294 | break; 295 | case KeyEvent.VK_ESCAPE: 296 | parentFrame.switchToLobbyPanel(); 297 | break; 298 | } 299 | 300 | if(showJTextField){ 301 | if(k.getKeyCode() == KeyEvent.VK_ENTER){ 302 | actualScore = new Score(playerName, applesEaten); 303 | scoreList.add(actualScore); 304 | playerName = ""; 305 | sortAndSave(); 306 | showJTextField = false; 307 | parentFrame.switchToLobbyPanel(); 308 | }else if(k.getKeyCode() == KeyEvent.VK_BACK_SPACE && playerName.length() > 0){ 309 | StringBuilder sb = new StringBuilder(playerName); 310 | sb.deleteCharAt(sb.length() - 1); 311 | playerName = sb.toString(); 312 | } 313 | else{ 314 | if(!k.isActionKey() && k.getKeyCode() != KeyEvent.VK_SHIFT && k.getKeyCode() != KeyEvent.VK_BACK_SPACE){ 315 | playerName = playerName + k.getKeyChar(); 316 | } 317 | } 318 | 319 | repaint(); 320 | } 321 | //System.out.println(direction); 322 | } 323 | } 324 | 325 | public void sortAndSave(){ 326 | try{ 327 | BufferedWriter bw = new BufferedWriter(new FileWriter(new File("scores.data"))); 328 | scoreList.sort(Comparator.reverseOrder()); 329 | for(int i = 0; i < 10; i++){ 330 | Score element = scoreList.get(i); 331 | bw.write(element.name + "," + String.valueOf(element.score) + "\n"); 332 | 333 | } 334 | bw.flush(); 335 | }catch(IOException ex){ 336 | System.out.println("Error writing file"); 337 | } 338 | 339 | } 340 | 341 | public void sleep(int millis){ 342 | try{ 343 | Thread.sleep(millis); 344 | System.out.println("Slept"); 345 | }catch(Exception ex){ 346 | System.out.println("Fatal Error in sleep() method"); 347 | } 348 | } 349 | 350 | } --------------------------------------------------------------------------------