Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import javax.swing.*;
- import java.awt.*;
- import java.awt.event.*;
- public class Game extends JFrame{
- Rectangle hero = new Rectangle(0, 0, 50, 50);
- int score = 0;
- int gX, gY;
- long startTime, endTime;
- int seconds;
- public static void main(String[] args){
- new Game();
- }
- public Game(){
- setSize(400,400); //Size
- setTitle("Pick'n Stick"); //Name of the game
- setDefaultCloseOperation(3);
- setVisible(true);
- setResizable(false);
- addKeyListener(new Input());
- moveGobbler();
- hero.x = 50;
- hero.y = 50;
- startTime = System.currentTimeMillis();
- }
- public void paint(Graphics g){
- if(hero.intersects(gX,gY,20,20)){
- endTime = System.currentTimeMillis();
- seconds = (int) (endTime - startTime) / 1000;
- moveGobbler();
- score += 100 - seconds;
- startTime = endTime;
- }
- Image offScreen = createImage(getWidth(), getHeight());
- draw(offScreen.getGraphics());
- g.drawImage(offScreen, 0, 0, null);
- }
- public void draw(Graphics g) //COLLOR AND FORMS
- {
- g.setColor(Color.GREEN); //Color of the Background
- g.fillRect(0, 0, 400, 400);
- g.setColor(Color.YELLOW);
- g.fillOval(gX,gY,20,20);
- g.setColor(Color.BLUE); //Color of the "hero
- g.fillRect(hero.x, hero.y, 50, 50);
- g.setColor(Color.BLACK); //Score
- g.drawString("Score; " + score, 25, 55);
- repaint();
- }
- private void moveGobbler()
- {
- gX = (int) (Math.random() * 400);
- gY = (int) (Math.random() * 400);
- if(gY < 30)
- gY = 30;
- else if(gY > 380)
- gY = 380;
- if (gX > 380)
- gX = 380;
- }
- private class Input implements KeyListener
- {
- @Override
- public void keyPressed(KeyEvent e) {
- int keyCode = e.getKeyCode();
- if(keyCode == e.VK_UP){
- if(hero.y > 25)
- hero.y -= 7;
- else
- hero.y = 25;
- }
- if(keyCode == e.VK_DOWN){
- if(hero.y < 350)
- hero.y += 7;
- else
- hero.y = 350;
- }
- if(keyCode == e.VK_LEFT){
- if(hero.x > 0)
- hero.x -= 7;
- else
- hero.x = 0;
- }
- if(keyCode == e.VK_RIGHT){
- if(hero.x < 350)
- hero.x += 7;
- else
- hero.x = 350;
- }
- }
- @Override
- public void keyReleased(KeyEvent arg0) {
- }
- @Override
- public void keyTyped(KeyEvent arg0) {
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment