Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.Color;
- import java.awt.Graphics;
- import java.awt.Graphics2D;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.awt.event.KeyEvent;
- import java.awt.event.KeyListener;
- import java.awt.geom.Rectangle2D;
- import javax.swing.JFrame;
- import javax.swing.Timer;
- public class Main extends JFrame implements ActionListener , KeyListener{
- private static final long serialVersionUID = 3206847208968227199L;
- public static int Score = 0;
- public static boolean run = true;
- Timer tm = new Timer(5 , this);
- double velx = 0, vely = 0 ;
- int x = 0, y = 0;
- public static void setScore(){
- do{
- Score = Score + 1 ;
- }while(run);
- }
- public void up(){
- vely = -1.5;
- velx = 0;
- }
- public void down(){
- vely = 1.5;
- velx = 0;
- }
- public void left(){
- velx = -1.5;
- vely = 0;
- }
- public void right(){
- velx = 1.5;
- vely = 0;
- }
- @Override
- public void keyTyped(KeyEvent e) {
- }
- @Override
- public void keyPressed(KeyEvent e) {
- int code = e.getKeyCode();
- if(code == KeyEvent.VK_UP){
- if(y <= 20){
- y = 20;
- }else{
- up();
- }
- }
- if(code == KeyEvent.VK_DOWN){
- if(y >= 400){
- y = 460;
- }else{
- down();
- }
- }
- if(code == KeyEvent.VK_LEFT){
- if(x <= 0){
- x = 0;
- }else{
- left();
- }
- }
- if(code == KeyEvent.VK_RIGHT){
- if(x >= 400){
- x = 460;
- }else{
- right();
- }
- }
- }
- @Override
- public void keyReleased(KeyEvent e) {
- int code = e.getKeyCode();
- if(code == KeyEvent.VK_UP){
- velx = 0;
- vely = -0.1;
- }
- if(code == KeyEvent.VK_DOWN){
- velx = 0;
- vely = 0.1;
- }
- if(code == KeyEvent.VK_LEFT){
- velx = -0.1;
- vely = 0;
- }
- if(code == KeyEvent.VK_RIGHT){
- velx = 0.1;
- vely = 0;
- }
- }
- public void paint(Graphics g){
- super.paintComponents(g);
- Graphics2D g2 = (Graphics2D) g;
- g2.setColor(Color.BLACK);
- g2.fill(new Rectangle2D.Double(x , y , 40 , 40));
- g2.drawString("Score : " + Score, 5 , 10 );
- tm.start();
- }
- public Main(){
- addKeyListener(this);
- pack();
- setTitle("Game");
- setSize(500, 500);
- setResizable(false);
- setVisible(true);
- setLocationRelativeTo(null);
- setDefaultCloseOperation(EXIT_ON_CLOSE);
- }
- public static void main(String [] args) {
- new Main();
- }
- @Override
- public void actionPerformed(ActionEvent arg0) {
- repaint();
- x += velx;
- y += vely;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement