⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 game.java

📁 俄罗斯方块-JAVA源代码 的逐步实现
💻 JAVA
字号:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import javax.swing.*;

import java.io.*;

public class Game extends Applet implements Runnable{

	private int xpos=100,ypos=0;
	private SquareShape currShape;
	private Image buffer;//画布对象
    private Graphics bg;
    private Thread th;
    private JButton btnStart=new JButton("开始");
    
    public Game()
    {
    	th=new Thread(this);
    }
	public void init() {
		
		this.setLayout(null);
		
		buffer=this.createImage(200,400);//创建画布大小	
		bg=buffer.getGraphics();
		bg.fillRect(0,0,200,400);
		
		currShape=new Ding();
		currShape.setPlace(xpos,ypos);

		btnStart.setBounds(220,20,60,20);
		btnStart.addMouseListener(new MouseAdapter()
		{
			public void mouseClicked(MouseEvent e)
			{
				th.start();
				
				requestFocus(true);//让applet得到焦点
		    }
		}
		);
		this.add(btnStart);
		
		this.addKeyListener(new GameKeyLister());
	}

	public void update(Graphics g)//实现不闪烁
	{
		g.clipRect(0,0,200,400);
		paint(g);
	}
	
	public void paint(Graphics g) {//图画由两部分组成,一部分为背景,另一部分为图形
	   
	   btnStart.repaint();

	   g.drawImage(buffer,0,0,null);//背景
	   currShape.drawShape(g);//图形
	}
	public void run()
	{
		while(true)
		{
			ypos+=20;
			currShape.setPlace(xpos,ypos);
			if(currShape.getBottom()>400)
			{
				ypos-=20;
				currShape.setPlace(xpos,ypos);										
			}
		
			repaint();
			try{
				
				Thread.sleep(500);				
			}
			catch(InterruptedException e)
			{	}
		}
		
	}
	class GameKeyLister extends KeyAdapter
	{
		public void keyReleased(KeyEvent e)
		{
			int keyCode=e.getKeyCode();
			if(keyCode==KeyEvent.VK_UP)
			{
				currShape.rotate();
				currShape.setPlace(xpos,ypos);
				
				while(currShape.getLeft()<0)
				{
					xpos+=20;
					currShape.setPlace(xpos,ypos);
				}
				while(currShape.getRight()>200)
				{
					xpos-=20;
					currShape.setPlace(xpos,ypos);					
				}
				while(currShape.getBottom()>400)
				{
					ypos-=20;
					currShape.setPlace(xpos,ypos);										
				}
				repaint();
			}
			else if(keyCode==KeyEvent.VK_RIGHT)
			{
				xpos+=20;
				currShape.setPlace(xpos,ypos);
				
				if(currShape.getRight()>200)
				{
					xpos-=20;
					currShape.setPlace(xpos,ypos);
				}
				
				repaint();
			}
			else if(keyCode==KeyEvent.VK_LEFT)
			{
				xpos-=20;
				currShape.setPlace(xpos,ypos);
				
				if(currShape.getLeft()<0)
				{
					xpos+=20;
					currShape.setPlace(xpos,ypos);
				}
				
				repaint();
				
			}
			else if(keyCode==KeyEvent.VK_DOWN)
			{
				ypos+=20;
				currShape.setPlace(xpos,ypos);
				
				if(currShape.getBottom()>400)
				{
					ypos-=20;
					currShape.setPlace(xpos,ypos);										
				}
				
				repaint();
				
			}
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -