这是每 5 秒生成和绘制一个四氨基图形的代码。然而,这个数字被淹没了两次,因此扭曲了原始画面。
这里 tetramino 图形由 10x10 像素块组成。构造函数图形告诉块的位置和颜色。方法paint(Graphics g) 逐块绘制图f。
import java.applet.*;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;
import javax.swing.Timer;
public class Tetris extends Applet {
Dimension size;
int x1,y1;
private int xs=0,ys=0;
public int getXs() {
return xs;
}
public void setXs(int xs) {
this.xs = xs;
}
public int getYs() {
return ys;
}
public void setYs(int ys) {
this.ys = ys;
}
public void rotate(){
}
public Figure generate(){
Figure i = new Figure(new int[][]{new int[]{1},new int[]{1},new int[]{1},new int[]{1}},Color.CYAN);
Figure j = new Figure(new int[][]{new int[]{1,0,0}, new int[]{1,1,1}},Color.BLUE);
Figure l = new Figure(new int[][]{new int[]{0,0,1}, new int[]{1,1,1}},Color.ORANGE);
Figure o = new Figure(new int[][]{new int[]{1,1}, new int[]{1,1}},Color.YELLOW);
Figure s = new Figure(new int[][]{new int[]{0,1,1}, new int[]{1,1,0}},Color.GREEN);
Figure t = new Figure(new int[][]{new int[]{1,1,1}, new int[]{0,1,0}},Color.PINK);
Figure z = new Figure(new int[][]{new int[]{1,1,0}, new int[]{0,1,1}},Color.RED);
Figure[] genSet = {i,j,l,o,s,t,z};
int index =((int) (Math.random() * 7)) ;
//System.out.println(index);
return genSet[index];
}
public void drop(){
}
public void shift(){
}
public void movecheck(){
}
public void actiondelay(){
ActionListener actionlistener = new ActionListener() {
public void actionPerformed(ActionEvent actionevent){
repaint();
}
};
Timer timer = new Timer(5000,actionlistener);
timer.start();
}
public void init(){
setSize(200,400);
setBackground(Color.black);
size = getSize();
}
public void paint(Graphics g){
super.paint(g);
System.out.println("________________");
Graphics2D g2d = (Graphics2D) g.create();
Figure f = generate();
int length = f.getX()[0].length;
for(int j =0; j<f.getX().length;j++){
System.out.println();
ys = 0;
for(int i=0;i<length;i++){
if (f.getX()[j][i] == 1){
Rectangle2D p = new Rectangle2D.Double(xs,xs,xs+10,ys+10);
g2d.setColor(f.getY());
g2d.draw(p);
//g2d.drawRect(p.x, p.y, p.width, p.height);
//g2d.fillRect(p.x, p.y, p.width, p.height);
//System.out.println("widnth: " +p.width + " | height: " + p.height + " end ");
System.out.print("*");
}
else System.out.print(" ");
ys+=10;
}
xs+=10;
}
xs=0;
ys=0;
actiondelay();
//g.setColor(Color.white);
//g.drawRect(45, 95, 55, 105);
}
}
import java.awt.Color;
public class Figure{
int[][] x;
Color y;
public Figure(int[][] x , Color y){
this.x=x;
this.y=y;
}
public int[][] getX() {
return x;
}
public void setX(int[][] x) {
this.x = x;
}
public Color getY() {
return y;
}
public void setY(Color y) {
this.y = y;
}
}