![](https://www.04ip.com/zb_users/upload/2023/09/20230925110604169561116449641.jpg)
正文
投篮小游戏的java代码 投篮小游戏链接
![](/static/style/weixin/images/xcx_logo.png)
【扫一扫了解最新限行尾号】
复制小程序
求一个简单的Java小游戏的代码
连连看的小源码
package Lianliankan;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class lianliankan implements ActionListener
{
JFrame mainFrame; //主面板
Container thisContainer;
JPanel centerPanel,southPanel,northPanel; //子面板
JButton diamondsButton[][] = new JButton[6][5];//游戏按钮数组
JButton exitButton,resetButton,newlyButton; //退出,重列,重新开始按钮
JLabel fractionLable=new JLabel("0"); //分数标签
JButton firstButton,secondButton; //分别记录两次被选中的按钮
int grid[][] = new int[8][7];//储存游戏按钮位置
static boolean pressInformation=false; //判断是否有按钮被选中
int x0=0,y0=0,x=0,y=0,fristMsg=0,secondMsg=0,validateLV; //游戏按钮的位置坐标
int i,j,k,n;//消除方法控制
public void init(){
mainFrame=new JFrame("JKJ连连看");
thisContainer = mainFrame.getContentPane();
thisContainer.setLayout(new BorderLayout());
centerPanel=new JPanel();
southPanel=new JPanel();
northPanel=new JPanel();
thisContainer.add(centerPanel,"Center");
thisContainer.add(southPanel,"South");
thisContainer.add(northPanel,"North");
centerPanel.setLayout(new GridLayout(6,5));
for(int cols = 0;cols 6;cols++){
for(int rows = 0;rows 5;rows++ ){
diamondsButton[cols][rows]=new JButton(String.valueOf(grid[cols+1][rows+1]));
diamondsButton[cols][rows].addActionListener(this);
centerPanel.add(diamondsButton[cols][rows]);
}
}
exitButton=new JButton("退出");
exitButton.addActionListener(this);
resetButton=new JButton("重列");
resetButton.addActionListener(this);
newlyButton=new JButton("再来一局");
newlyButton.addActionListener(this);
southPanel.add(exitButton);
southPanel.add(resetButton);
southPanel.add(newlyButton);
fractionLable.setText(String.valueOf(Integer.parseInt(fractionLable.getText())));
northPanel.add(fractionLable);
mainFrame.setBounds(280,100,500,450);
mainFrame.setVisible(true);
}
public void randomBuild() {
int randoms,cols,rows;
for(int twins=1;twins=15;twins++) {
randoms=(int)(Math.random()*25+1);
for(int alike=1;alike=2;alike++) {
cols=(int)(Math.random()*6+1);
rows=(int)(Math.random()*5+1);
while(grid[cols][rows]!=0) {
cols=(int)(Math.random()*6+1);
rows=(int)(Math.random()*5+1);
}
this.grid[cols][rows]=randoms;
}
}
}
public void fraction(){
fractionLable.setText(String.valueOf(Integer.parseInt(fractionLable.getText())+100));
}
public void reload() {
int save[] = new int[30];
int n=0,cols,rows;
int grid[][]= new int[8][7];
for(int i=0;i=6;i++) {
for(int j=0;j=5;j++) {
if(this.grid[i][j]!=0) {
save[n]=this.grid[i][j];
n++;
}
}
}
n=n-1;
this.grid=grid;
while(n=0) {
cols=(int)(Math.random()*6+1);
rows=(int)(Math.random()*5+1);
while(grid[cols][rows]!=0) {
cols=(int)(Math.random()*6+1);
rows=(int)(Math.random()*5+1);
}
this.grid[cols][rows]=save[n];
n--;
}
mainFrame.setVisible(false);
pressInformation=false; //这里一定要将按钮点击信息归为初始
init();
for(int i = 0;i 6;i++){
for(int j = 0;j 5;j++ ){
if(grid[i+1][j+1]==0)
diamondsButton[i][j].setVisible(false);
}
}
}
public void estimateEven(int placeX,int placeY,JButton bz) {
if(pressInformation==false) {
x=placeX;
y=placeY;
secondMsg=grid[x][y];
secondButton=bz;
pressInformation=true;
}
else {
x0=x;
y0=y;
fristMsg=secondMsg;
firstButton=secondButton;
x=placeX;
y=placeY;
secondMsg=grid[x][y];
secondButton=bz;
if(fristMsg==secondMsg secondButton!=firstButton){
xiao();
}
}
}
public void xiao() { //相同的情况下能不能消去。仔细分析,不一条条注释
if((x0==x (y0==y+1||y0==y-1)) || ((x0==x+1||x0==x-1)(y0==y))){ //判断是否相邻
remove();
}
else{
for (j=0;j7;j++ ) {
if (grid[x0][j]==0){ //判断第一个按钮同行哪个按钮为空
if (yj) { //如果第二个按钮的Y坐标大于空按钮的Y坐标说明第一按钮在第二按钮左边
for (i=y-1;i=j;i-- ){ //判断第二按钮左侧直到第一按钮中间有没有按钮
if (grid[x][i]!=0) {
k=0;
break;
}
else{ k=1; } //K=1说明通过了第一次验证
}
if (k==1) {
linePassOne();
}
}
if (yj){ //如果第二个按钮的Y坐标小于空按钮的Y坐标说明第一按钮在第二按钮右边
for (i=y+1;i=j ;i++ ){ //判断第二按钮左侧直到第一按钮中间有没有按钮
if (grid[x][i]!=0){
k=0;
break;
}
else { k=1; }
}
if (k==1){
linePassOne();
}
}
if (y==j ) {
linePassOne();
}
}
if (k==2) {
if (x0==x) {
remove();
}
if (x0x) {
for (n=x0;n=x-1;n++ ) {
if (grid[n][j]!=0) {
k=0;
break;
}
if(grid[n][j]==0 n==x-1) {
remove();
}
}
}
if (x0x) {
for (n=x0;n=x+1 ;n-- ) {
if (grid[n][j]!=0) {
k=0;
break;
}
if(grid[n][j]==0 n==x+1) {
remove();
}
}
}
}
}
for (i=0;i8;i++ ) { //列
if (grid[i][y0]==0) {
if (xi) {
for (j=x-1;j=i ;j-- ) {
if (grid[j][y]!=0) {
k=0;
break;
}
else { k=1; }
}
if (k==1) {
rowPassOne();
}
}
if (xi) {
for (j=x+1;j=i;j++ ) {
if (grid[j][y]!=0) {
k=0;
break;
}
else { k=1; }
}
if (k==1) {
rowPassOne();
}
}
if (x==i) {
rowPassOne();
}
}
if (k==2){
if (y0==y) {
remove();
}
if (y0y) {
for (n=y0;n=y-1 ;n++ ) {
if (grid[i][n]!=0) {
k=0;
break;
}
if(grid[i][n]==0 n==y-1) {
remove();
}
}
}
if (y0y) {
for (n=y0;n=y+1 ;n--) {
if (grid[i][n]!=0) {
k=0;
break;
}
if(grid[i][n]==0 n==y+1) {
remove();
}
}
}
}
}
}
}
public void linePassOne(){
if (y0j){ //第一按钮同行空按钮在左边
for (i=y0-1;i=j ;i-- ){ //判断第一按钮同左侧空按钮之间有没按钮
if (grid[x0][i]!=0) {
k=0;
break;
}
else { k=2; } //K=2说明通过了第二次验证
}
}
if (y0j){ //第一按钮同行空按钮在与第二按钮之间
for (i=y0+1;i=j ;i++){
if (grid[x0][i]!=0) {
k=0;
break;
}
else{ k=2; }
}
}
}
public void rowPassOne(){
if (x0i) {
for (j=x0-1;j=i ;j-- ) {
if (grid[j][y0]!=0) {
k=0;
break;
}
else { k=2; }
}
}
if (x0i) {
for (j=x0+1;j=i ;j++ ) {
if (grid[j][y0]!=0) {
k=0;
break;
}
else { k=2; }
}
}
}
public void remove(){
firstButton.setVisible(false);
secondButton.setVisible(false);
fraction();
pressInformation=false;
k=0;
grid[x0][y0]=0;
grid[x][y]=0;
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==newlyButton){
int grid[][] = new int[8][7];
this.grid = grid;
randomBuild();
mainFrame.setVisible(false);
pressInformation=false;
init();
}
if(e.getSource()==exitButton)
System.exit(0);
if(e.getSource()==resetButton)
reload();
for(int cols = 0;cols 6;cols++){
for(int rows = 0;rows 5;rows++ ){
if(e.getSource()==diamondsButton[cols][rows])
estimateEven(cols+1,rows+1,diamondsButton[cols][rows]);
}
}
}
public static void main(String[] args) {
lianliankan llk = new lianliankan();
llk.randomBuild();
llk.init();
}
}
//old 998 lines
//new 318 lines
急求一个java的躲避弹球小游戏的代码
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.Timer;
public class PinBall
{
private final int TABLE_WIDTH = 300;//桌面宽度
private final int TABLE_HEIGHT = 400;//桌面高度
private final int RACKET_Y = 340;//球拍的垂直位置
private final int RACKET_HEIGHT = 20;//球拍高度
private final int RACKET_WIDTH = 60;//球拍宽度
private final int BALL_SIZE = 16;//球的大小
private Frame f = new Frame("弹球游戏");//实例化一个窗口
Random rand = new Random();//实例化一个随机数生成器
private int ySpeed = 10;//小球的纵向运动数度、
private double xyRate = rand.nextDouble() - 0.5;//返回一个-0.5到0.5之间的比率用控制小球运动方向
private int xSpeed = (int)(ySpeed*xyRate*2);//这个横向速度在-10到10之间,产生左右摆动运动效果
private int ballX = rand.nextInt(200)+20;//小球开始的横坐标位置,200表示产生0到100之间的随机数
private int ballY = rand.nextInt(10)+20;//小球开始的纵坐标位置
private int racketX = rand.nextInt(200);//球拍开始时的横坐标位置
private MyCanvas tableArea = new MyCanvas();//实力化一个画布工具,集成Canvas类
private String shape = "";//保存需要绘制图形的字符串属性
Timer timer;//声明一个时间变量
private boolean isLose = false;//表示游戏是否结束
public void init()
{
tableArea.setPreferredSize(new Dimension(TABLE_WIDTH,TABLE_HEIGHT));//定义画布大小
f.add(tableArea);//添加画布到窗口
KeyAdapter keyProcessor = new KeyAdapter()//实例化一个键盘监听事件适配器
{
public void keyPressed(KeyEvent ke)//重写适配器里面的按下某键盘方法
{
if(ke.getKeyCode()==KeyEvent.VK_LEFT)//按下键盘左键时
{
if(racketX 0)//球拍左边框不能出画布的左边框
racketX -=10;//按一左键次向左移动10个像素
}
if(ke.getKeyCode()==KeyEvent.VK_RIGHT)//按下键盘右键时
{
if(racketX TABLE_WIDTH - RACKET_WIDTH)//球拍右边框不能出画布的右边框
racketX +=10;//按一次右键移动向右移动10个像素
}
}
};
f.addKeyListener(keyProcessor);//给窗口添加键盘监听器
tableArea.addKeyListener(keyProcessor);//给画布添加键盘监听器
ActionListener taskPerformer = new ActionListener()//这里是实例化了一个监听接口,这个接口里面只有一个方法
{
public void actionPerformed(ActionEvent evt)//重写这个接口里面的方法,判断小球的位置
{
if(ballX=0 || ballX=TABLE_WIDTH-BALL_SIZE)//保证小球横向上在画布之内运动
{
xSpeed = -xSpeed;//触发反方向运动
}
if(ballY=RACKET_Y-BALL_SIZE(ballXracketX||ballXracketX+RACKET_WIDTH))//出了球拍的可击打范围
{
timer.stop();//停止对监听器的触发
isLose=true;//将标志isLose变量置为true
tableArea.repaint();//调用画布的重绘方法
}
else if(ballY=0||(ballY=RACKET_Y-BALL_SIZEballYracketXballX=racketX+RACKET_WIDTH))//小球在球拍之内,而其到达球拍的高度
{
ySpeed=-ySpeed;//上下方向改变,小球反弹
}
ballY+=ySpeed;//小球的坐标在纵向上增加
ballX+=xSpeed;//小球的坐标在横向上的增加
tableArea.repaint();//调用画布的重绘方法3
}
};
timer = new Timer(100,taskPerformer);//每隔0.1秒运行一次监听器
timer.start();//计时器开始运行
f.addWindowListener(new MyListener());//关闭窗口事件
f.pack();//设置窗口最佳大小
f.setVisible(true);//显示窗口
}
class MyListener extends WindowAdapter//关闭窗口的类
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
public static void main(String[] args)//程序入口
{
new PinBall().init();//调用PinBall类里面的init()方法
}
class MyCanvas extends Canvas//建一个集成Canvas类的类
{
public void paint(Graphics g)//重写父类的绘图方法
{
if(isLose)//如果isLose为真,则在画布里打印“游戏已结束”
{
g.setColor(new Color(255,0,0));//当前颜色
g.setFont(new Font("黑体",Font.BOLD,30));//字体名称,样式,大小
g.drawString("游戏已结束!",50,200);//按坐标绘制文字图形
}
else//负责
{
g.setColor(new Color(240,240,80));//当前颜色
g.fillOval(ballX,ballY,BALL_SIZE,BALL_SIZE);//填充颜色,根据坐标和长宽填充圆形
g.setColor(new Color(80,80,200));//当前颜色
g.fillRect(racketX,RACKET_Y,RACKET_WIDTH,RACKET_HEIGHT);//填充颜色,根据坐标和长宽填充矩形
}
}
}
}
高分求高手补全一个java小游戏,内详
最不会加注释投篮小游戏的java代码了投篮小游戏的java代码,不知道行不行,一共149行,要求全部完成。
import java.awt.BorderLayout;
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 java.util.Random;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Racer extends JFrame {
private MyPanel drawPanel;
public static final int LINE_LEN = 20; // 方格投篮小游戏的java代码的边长
public static final int NUM = 20; // 方格投篮小游戏的java代码的个数为NUM*NUM
private static final int EDGE_WIDTH = 25; // 边距
public static final int OBSTACLE_NUM = 10; //屏幕上同时出现投篮小游戏的java代码的障碍物数量
Racer() {
getContentPane().setLayout(new BorderLayout());
drawPanel = new MyPanel(this);
getContentPane().add(drawPanel, "Center"); //把游戏面板放到屏幕中央
setSize((LINE_LEN + 1) * NUM + EDGE_WIDTH, (LINE_LEN + 1) * NUM
+ EDGE_WIDTH); //设置窗口大小
setVisible(true); //显示窗口
drawPanel.requestFocusInWindow(); //在窗口显示后要求接受键盘输入
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口时结束程序
}
public static void main(String[] args) {
Racer r = new Racer();
}
}
class MyPanel extends JPanel implements ActionListener, KeyListener {
private Racer owner;
private static boolean flag = false; // 画路时,交替地画出黑白方块
private int num = Racer.NUM;
private int len = Racer.LINE_LEN;
private int x = 0; //汽车的位置,一开始为0
private int[] obstacleX = new int[Racer.OBSTACLE_NUM]; //所有障碍物的X坐标
private int[] obstacleY = new int[Racer.OBSTACLE_NUM]; //所有障碍物的Y坐标
private int[] carX = {8, 7, 8, 9, 8, 7, 8, 9}; //汽车方格的X坐标
private int[] carY = {16, 17, 17, 17, 18, 19, 19, 19}; //汽车方格的Y坐标
Random rand = new Random(); //随机数生成器
Timer timer; //动画计时更新,用javax.swing.Timer和键盘的输入较为匹配,可以避免直接用线程出现的一些问题
int LEFT_KEY = KeyEvent.VK_W; //按w键为往左,如果要按左键往左的话LEFT_KEY = KeyEvent.VK_LEFT
int RIGHT_KEY = KeyEvent.VK_D; //按w键为往左,如果要按右键往右的话LEFT_KEY = KeyEvent.VK_RIGHT
MyPanel(Racer r) {
owner = r;
timer = new Timer(200, this); //时间间隔为200毫秒
timer.start(); //开始游戏更新
addKeyListener(this); //注册键盘输入
for(int i=0;iobstacleX.length;i++) { //给与每个障碍物随机的坐标
obstacleX[i] = rand.nextInt(Racer.NUM-2)+1; //X在路面的左面1和右面NUM-1之间
obstacleY[i] = rand.nextInt(Racer.NUM) - num; //y在路面上方-1到-1-NUM之间,游戏开始时看不到
}
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==LEFT_KEY) x--; //按往左的键时减小x变量
else if(e.getKeyCode()==RIGHT_KEY) x++; //按往右的键时增加x变量
if(x-6) x=-6; //如果出了左边界的话把车放回边界内
if(x9) x=9; //如果出了右边界的话把车放回边界内
repaint(); //重新画一编移动后的车
}
public void paint(Graphics g) {
g.clearRect(0, 0, getSize().width, getSize().height);
drawBkgnd(g); // 画背景
drawRoad(g); // 画路
drawCar(g); // 画车
drawObstacles(g); //画障碍物
}
private void drawBkgnd(Graphics g) {
for (int i = 0; i = num; i++) {
g.drawLine(0, i * len, len * num, i * len); //画横线
g.drawLine(i * len, 0, i * len, len * num); //画竖线
}
}
private void drawRoad(Graphics g) {
if (flag) {
for (int i = 0; i num; i += 2) { //交替涂路边的格子
g.fillRect(0, i * len, len, len);
g.fillRect((num - 1) * len, i * len, len, len);
}
} else {
for (int i = 1; i num; i += 2) {
g.fillRect(0, i * len, len, len);
g.fillRect((num - 1) * len, i * len, len, len);
}
}
}
private void drawCar(Graphics g) {
for(int i=0;icarX.length;i++) {
g.fillRect((carX[i] + x)*len, carY[i]*len, len, len); //把汽车所占有的格子涂黑
}
}
private void drawObstacles(Graphics g) {
for(int i=0;iobstacleX.length;i++) {
g.fillRect(obstacleX[i]*len, obstacleY[i]*len, len, len); //把障碍物占有的格子涂黑
}
}
private boolean collision() {
for(int i=0;iobstacleX.length;i++) { //对于每个障碍物的格子
for(int j=0;jcarX.length;j++) { //对于每个汽车的格子
if(obstacleX[i] == carX[j]+x obstacleY[i] == carY[j]) //如果障碍物的坐标和汽车的坐标一样的话
return true; //相撞发生了
}
}
return false;
}
public void actionPerformed(ActionEvent e) {
if(collision()) { //检测有没有撞到障碍物
timer.stop(); //暂停游戏
JOptionPane.showMessageDialog(this, "你输了,按OK重新开始。"); //显示结束信息
//这里用户按下了ok
for(int i=0;iobstacleX.length;i++) { //重新设置障碍物的位置
obstacleX[i] = rand.nextInt(Racer.NUM-2)+1;
obstacleY[i] = rand.nextInt(Racer.NUM) - num;
}
x=0; //重置汽车的位置
timer.start(); //恢复游戏
}
for(int i=0;iobstacleY.length;i++) { //对于每个障碍物
obstacleY[i]++; //让障碍物往下移动一格
if(obstacleY[i]=num) { //如果障碍物移动到网格的下面去了
obstacleX[i]=rand.nextInt(num-2)+1; //随机给一个新的X坐标
obstacleY[i]=0; //恢复到屏幕上放
}
}
flag=!flag; //更新路边的斑马格
repaint(); //重画屏幕
}
public void keyReleased(KeyEvent e) {} //没有用到的方法,继承KeyListener必须声明
public void keyTyped(KeyEvent e) {} //同上
}
Java 求一段射击小游戏的代码(让一个小图片随机出现)
1、在JFrame上用网格布局批量实例化一些JLabel 2、建立一个线程获得一个随机数,根据随机数给某个JLabel设置icon 3、线程sleep(1000); 4、移除这个JLabel的icon 5、线程循环
跪求JAVA编写的小游戏源代码
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.awt.image.*;
import java.awt.geom.*;
import java.util.*;
class Car{
Image img;
int x, y;
Dimension dim;
Car(Image img){
this.img=img;
}
Car(Image img, int x, int y){
this.img=img; this.x=x; this.y=y;
}
Car(Image img, int x, int y, Dimension dim){
this(img, x, y);
this.dim=dim;
}
void draw(Graphics g, ImageObserver observer){
g.drawImage(img, x, y, observer);
}
int getX(){ return x;}
int getY(){ return y;}
void setX(int x){this.x=x;}
void setY(int y){this.y=y;}
void setLocation(int x, int y){
this.x=x; this.y=y;
}
int getWidth(){ return img.getWidth(null);}
int getHeight(){ return img.getHeight(null);}
Rectangle2D getRectangle(){
return new Rectangle2D.Float(x, y, getWidth(), getHeight());
}
void move(int dx, int dy){
x+=dx;
y+=dy;
if(dim!=null){
if(x0)x=0;
if(x+getWidth()dim.getWidth())
x=(int)dim.getWidth()-getWidth();
}
}
boolean intersects(Car car){
return getRectangle().intersects(car.getRectangle());
}
boolean intersects(int x, int y){
return getRectangle().intersects(x, y, getWidth(), getHeight());
}
}
public class CarRace extends Applet implements KeyListener, Runnable{
Image buff;
Canvas screen;
Graphics2D gs, gb;
Car redCar;
Car[] enemy=new Car[20];
Button bStart;
Thread game;
boolean loop=true;
Dimension dim=new Dimension(200, 300);
int road;
Random rnd=new Random();
public void init(){
prepareResource();
setBackground(Color.blue);
initScreen();
add(screen);
bStart=new Button("霸烙 矫累");
add(bStart);
bStart.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
screen.requestFocus();
if(!game.isAlive())
game.start();
}
});
}
void prepareResource(){
Image imgRed=getImage(getCodeBase(),"images/red_car.gif");
Image imgBlue=getImage(getCodeBase(),"images/blue_car.gif");
Image imgGreen=getImage(getCodeBase(),"images/green_car.gif");
MediaTracker mt=new MediaTracker(this);
try{
mt.addImage(imgRed, 0);
mt.addImage(imgBlue, 1);
mt.addImage(imgGreen, 2);
mt.waitForAll();
}catch(Exception e){}
buff=createImage((int)dim.getWidth(), (int)dim.getHeight());
gb=(Graphics2D)buff.getGraphics();
redCar=new Car(imgRed, 80,250, dim);
for(int i=0;i10;i++){
enemy[i]=new Car(imgBlue, 0, 0);
}
for(int i=10;ienemy.length;i++){
enemy[i]=new Car(imgGreen, 0, 0);
}
for(int i=0;ienemy.length;i++){
setEnemy(i);
}
game=new Thread(this);
}
public void stop(){
loop=false;
}
public void run(){
while(loop){
drawScreen();
try{ Thread.sleep(50);}catch(Exception e){}
}
}
void initScreen(){
screen=new Canvas(){
public void paint(Graphics g){
if(gs==null){
gs=(Graphics2D)screen.getGraphics();
}
drawScreen();
}
};
screen.setSize(dim);
screen.addKeyListener(this);
}
void setEnemy(int en){
int x, y;
next:while(true){
x=rnd.nextInt((int)dim.getWidth()-enemy[en].getWidth());
y=-rnd.nextInt(5000)-200;
for(int j=0;jenemy.length;j++){
if(j!=en enemy[j].intersects(x, y))continue next;
}
enemy[en].setLocation(x, y);
break;
}
}
void check(Car en){
if(redCar.intersects(en)){
if(redCar.getX()en.getX()){
en.move(-20, 0);
redCar.move(20, 0);
}
else{
en.move(20,0);
redCar.move(-20, 0);
}
}
}
synchronized void drawScreen(){
gb.clearRect(0, 0, (int)dim.getWidth(), (int)dim.getHeight());
gb.setPaint(new Color(100, 100, 100));
gb.fillRect(0, 0, (int)dim.getWidth(), (int)dim.getHeight());
drawRoad();
for(int i=0;ienemy.length;i++){
enemy[i].move(0, 15);
enemy[i].draw(gb, screen);
if(enemy[i].getY()dim.getHeight())
setEnemy(i);
check(enemy[i]);
}
redCar.draw(gb, screen);
gs.drawImage(buff, 0,0, screen);
}
void drawRoad(){
road+=80;
gb.setPaint(Color.yellow);
gb.fillRect((int)dim.getWidth()/2, road,10,150);
if(road=dim.getHeight())road=-150;
}
public void keyPressed(KeyEvent ke){
if(ke.getKeyCode()==KeyEvent.VK_LEFT){
redCar.move(-10,0);
}
else if(ke.getKeyCode()==KeyEvent.VK_RIGHT){
redCar.move(10,0);
}
}
public void keyReleased(KeyEvent ke){}
public void keyTyped(KeyEvent ke){}
}
这个是一个典型的Applet,文件名应该是CarRace.java,需要图片作为车子等等,本人也是别人给的,但是还要个.html文件来运行它,代码为:
Applet code="CarRace.class" width=250 height=350
/Applet
请楼主采纳
求java小游戏源代码
表1. CheckerDrag.java
// CheckerDrag.javaimport java.awt.*;import java.awt.event.*;public class CheckerDrag extends java.applet.Applet{ // Dimension of checkerboard square. // 棋盘上每个小方格的尺寸 final static int SQUAREDIM = 40; // Dimension of checkerboard -- includes black outline. // 棋盘的尺寸 – 包括黑色的轮廓线 final static int BOARDDIM = 8 * SQUAREDIM + 2; // Dimension of checker -- 3/4 the dimension of a square. // 棋子的尺寸 – 方格尺寸的3/4 final static int CHECKERDIM = 3 * SQUAREDIM / 4; // Square colors are dark green or white. // 方格的颜色为深绿色或者白色 final static Color darkGreen = new Color (0, 128, 0); // Dragging flag -- set to true when user presses mouse button over checker // and cleared to false when user releases mouse button. // 拖动标记 --当用户在棋子上按下鼠标按键时设为true, // 释放鼠标按键时设为false boolean inDrag = false; // Left coordinate of checkerboard's upper-left corner. // 棋盘左上角的左方向坐标 int boardx; // Top coordinate of checkerboard's upper-left corner. //棋盘左上角的上方向坐标 int boardy; // Left coordinate of checker rectangle origin (upper-left corner). // 棋子矩形原点(左上角)的左方向坐标 int ox; // Top coordinate of checker rectangle origin (upper-left corner). // 棋子矩形原点(左上角)的上方向坐标 int oy; // Left displacement between mouse coordinates at time of press and checker // rectangle origin. // 在按键时的鼠标坐标与棋子矩形原点之间的左方向位移 int relx; // Top displacement between mouse coordinates at time of press and checker // rectangle origin. // 在按键时的鼠标坐标与棋子矩形原点之间的上方向位移 int rely; // Width of applet drawing area. // applet绘图区域的宽度 int width; // Height of applet drawing area. // applet绘图区域的高度 int height; // Image buffer. // 图像缓冲 Image imBuffer; // Graphics context associated with image buffer. // 图像缓冲相关联的图形背景 Graphics imG; public void init () { // Obtain the size of the applet's drawing area. // 获取applet绘图区域的尺寸 width = getSize ().width; height = getSize ().height; // Create image buffer. // 创建图像缓冲 imBuffer = createImage (width, height); // Retrieve graphics context associated with image buffer. // 取出图像缓冲相关联的图形背景 imG = imBuffer.getGraphics (); // Initialize checkerboard's origin, so that board is centered. // 初始化棋盘的原点,使棋盘在屏幕上居中 boardx = (width - BOARDDIM) / 2 + 1; boardy = (height - BOARDDIM) / 2 + 1; // Initialize checker's rectangle's starting origin so that checker is // centered in the square located in the top row and second column from // the left. // 初始化棋子矩形的起始原点,使得棋子在第一行左数第二列的方格里居中 ox = boardx + SQUAREDIM + (SQUAREDIM - CHECKERDIM) / 2 + 1; oy = boardy + (SQUAREDIM - CHECKERDIM) / 2 + 1; // Attach a mouse listener to the applet. That listener listens for // mouse-button press and mouse-button release events. // 向applet添加一个用来监听鼠标按键的按下和释放事件的鼠标监听器 addMouseListener (new MouseAdapter () { public void mousePressed (MouseEvent e) { // Obtain mouse coordinates at time of press. // 获取按键时的鼠标坐标 int x = e.getX (); int y = e.getY (); // If mouse is over draggable checker at time // of press (i.e., contains (x, y) returns // true), save distance between current mouse // coordinates and draggable checker origin // (which will always be positive) and set drag // flag to true (to indicate drag in progress). // 在按键时如果鼠标位于可拖动的棋子上方 // (也就是contains (x, y)返回true),则保存当前 // 鼠标坐标与棋子的原点之间的距离(始终为正值)并且 // 将拖动标志设为true(用来表明正处在拖动过程中) if (contains (x, y)) { relx = x - ox; rely = y - oy; inDrag = true; } } boolean contains (int x, int y) { // Calculate center of draggable checker. // 计算棋子的中心位置 int cox = ox + CHECKERDIM / 2; int coy = oy + CHECKERDIM / 2; // Return true if (x, y) locates with bounds // of draggable checker. CHECKERDIM / 2 is the // radius. // 如果(x, y)仍处于棋子范围内则返回true // CHECKERDIM / 2为半径 return (cox - x) * (cox - x) + (coy - y) * (coy - y) CHECKERDIM / 2 * CHECKERDIM / 2; } public void mouseReleased (MouseEvent e) { // When mouse is released, clear inDrag (to // indicate no drag in progress) if inDrag is // already set. // 当鼠标按键被释放时,如果inDrag已经为true, // 则将其置为false(用来表明不在拖动过程中) if (inDrag) inDrag = false; } }); // Attach a mouse motion listener to the applet. That listener listens // for mouse drag events. //向applet添加一个用来监听鼠标拖动事件的鼠标运动监听器 addMouseMotionListener (new MouseMotionAdapter () { public void mouseDragged (MouseEvent e) { if (inDrag) { // Calculate draggable checker's new // origin (the upper-left corner of // the checker rectangle). // 计算棋子新的原点(棋子矩形的左上角) int tmpox = e.getX () - relx; int tmpoy = e.getY () - rely; // If the checker is not being moved // (at least partly) off board, // assign the previously calculated // origin (tmpox, tmpoy) as the // permanent origin (ox, oy), and // redraw the display area (with the // draggable checker at the new // coordinates). // 如果棋子(至少是棋子的一部分)没有被 // 移出棋盘,则将之前计算的原点 // (tmpox, tmpoy)赋值给永久性的原点(ox, oy), // 并且刷新显示区域(此时的棋子已经位于新坐标上) if (tmpox boardx tmpoy boardy tmpox + CHECKERDIM boardx + BOARDDIM tmpoy + CHECKERDIM boardy + BOARDDIM) { ox = tmpox; oy = tmpoy; repaint (); } } } }); } public void paint (Graphics g) { // Paint the checkerboard over which the checker will be dragged. // 在棋子将要被拖动的位置上绘制棋盘 paintCheckerBoard (imG, boardx, boardy); // Paint the checker that will be dragged. // 绘制即将被拖动的棋子 paintChecker (imG, ox, oy); // Draw contents of image buffer. // 绘制图像缓冲的内容 g.drawImage (imBuffer, 0, 0, this); } void paintChecker (Graphics g, int x, int y) { // Set checker shadow color. // 设置棋子阴影的颜色 g.setColor (Color.black); // Paint checker shadow. // 绘制棋子的阴影 g.fillOval (x, y, CHECKERDIM, CHECKERDIM); // Set checker color. // 设置棋子颜色 g.setColor (Color.red); // Paint checker. // 绘制棋子 g.fillOval (x, y, CHECKERDIM - CHECKERDIM / 13, CHECKERDIM - CHECKERDIM / 13); } void paintCheckerBoard (Graphics g, int x, int y) { // Paint checkerboard outline. // 绘制棋盘轮廓线 g.setColor (Color.black); g.drawRect (x, y, 8 * SQUAREDIM + 1, 8 * SQUAREDIM + 1); // Paint checkerboard. // 绘制棋盘 for (int row = 0; row 8; row++) { g.setColor (((row 1) != 0) ? darkGreen : Color.white); for (int col = 0; col 8; col++) { g.fillRect (x + 1 + col * SQUAREDIM, y + 1 + row * SQUAREDIM, SQUAREDIM, SQUAREDIM); g.setColor ((g.getColor () == darkGreen) ? Color.white : darkGreen); } } } // The AWT invokes the update() method in response to the repaint() method // calls that are made as a checker is dragged. The default implementation // of this method, which is inherited from the Container class, clears the // applet's drawing area to the background color prior to calling paint(). // This clearing followed by drawing causes flicker. CheckerDrag overrides // update() to prevent the background from being cleared, which eliminates // the flicker. // AWT调用了update()方法来响应拖动棋子时所调用的repaint()方法。该方法从 // Container类继承的默认实现会在调用paint()之前,将applet的绘图区域清除 // 为背景色,这种绘制之后的清除就导致了闪烁。CheckerDrag重写了update()来 // 防止背景被清除,从而消除了闪烁。 public void update (Graphics g) { paint (g); }}
投篮小游戏的java代码的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于投篮小游戏链接、投篮小游戏的java代码的信息别忘了在本站进行查找喔。