User Tools

Site Tools


resources_for_tetris

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revisionBoth sides next revision
resources_for_tetris [2022/05/09 11:17] – created frchrisresources_for_tetris [2022/05/09 11:49] frchris
Line 2: Line 2:
  
 The basic falling item, with a Key Listener: The basic falling item, with a Key Listener:
 +<code>
 +import java.awt.Color;
 +import java.awt.Font;
 +import java.awt.Graphics;
 +import java.awt.event.ActionEvent;
 +import java.awt.event.ActionListener;
 +import java.awt.event.KeyEvent;
 +import java.awt.event.KeyListener;
 +import javax.swing.JFrame;
 +import javax.swing.JPanel;
 +import javax.swing.Timer;
 +
 +public class Tetris extends JPanel implements KeyListener, ActionListener
 +{
 + public static int WIDTH=800;
 + public static int HEIGHT=600;
 + private Font titleFont, regularFont;
 + private int x,y;
 + private Timer timer1, timer2;
 +
 +
 + public Tetris() 
 + {
 +
 + //initialize variables here...
 + titleFont = new Font("Roman", Font.BOLD, 18);
 + regularFont = new Font("Helvetica", Font.PLAIN, 12);
 + y=0;
 + x=200;
 + timer1 = new Timer(50, this); //1000=1 seconds
 + timer2 = new Timer(2000, this); //1000=1 seconds
 + timer1.start();
 +
 + }
 + public static void main(String[] args) {
 + Tetris app= new Tetris();
 + JFrame window = new JFrame("Timer Example");
 + window.setSize(WIDTH, HEIGHT);
 + window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 + window.getContentPane().add(app);
 + window.addKeyListener(app);
 + //window.pack();
 + window.setVisible(true);
 +
 + }
 + public void paintComponent(Graphics g){
 + super.paintComponent(g);
 + g.setColor(Color.WHITE);
 + g.fillRect(0, 0, getWidth(),getHeight());
 + g.setColor(Color.BLUE);
 + g.setFont(titleFont);
 + g.drawString("Tetris Example", 20, 20);
 + g.setColor(Color.BLACK);
 + g.setFont(regularFont);
 + g.drawString("y = "+y, 20, 40);
 + g.fillRect(x, y, 10, 10);
 +
 + }
 +
 +
 + // These 3 methods need to be declares to implement the KeyListener Interface
 + @Override
 + public void keyTyped(KeyEvent e) {}
 +
 + @Override
 + public void keyPressed(KeyEvent e) {
 + int code=e.getKeyCode();
 +       
 +       if (code ==39) // right
 +       x=(x+1)%HEIGHT;
 +       else if (code == 37 && x>0) //left
 +       x--;
 +       repaint();
 + }
 +
 + @Override
 + public void keyReleased(KeyEvent e) {}
 + @Override
 + public void actionPerformed(ActionEvent e) {
 +
 +      if (e.getSource()==timer1){
 +     y=(y+1)%WIDTH;
 +      }
 +      repaint();
 + }
 +
 +}
 +</code>
  
resources_for_tetris.txt · Last modified: 2022/05/23 16:43 by frchris

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki