拼图游戏(js,C#,java三种语言)

时间:2022-08-12 08:29:53
<html>

<head>
    <meta charset="utf-8">
    <style type="text/css">
    .haha {
        border-width: 2;
        font-size: 50;
        font-weight: bold;
        color: white;
        text-align: center;
        color: white;
        background-color: black;
    }

    .form {
        position: fixed;
    }
    </style>
</head>
<h4 id='de'></h4>
<div class='form'>
    <input type="number" name="quantity" min="1" max="5" value="3" id='xsize'>
    <input type="number" name="quantity" min="1" max="5" value="3" id='ysize'>
    <button onclick="newGame()">提交</button>
</div>
<table align='center' id="table">

</table>
<script>
var xsize = 3,
    ysize = 3;
var size = xsize * ysize;
var a = new Array(size);
var spaceX, spaceY;
var table=document.getElementById("table")
newGame();

function newGame() {
    xsize=document.getElementById('xsize').value;
    ysize=document.getElementById("ysize").value;
    size = xsize * ysize;
    a = new Array(size);
    clear();
    shuffle();
    init();
    draw();
}
onkeydown = keyDown;

function print(s) {
    document.getElementById('de').innerHTML = s;
}

function clear() {
    for (var i = 0; i < size - 1; i++)
        a[i] = i + 1;
    a[size - 1] = 0;
    spaceX = xsize - 1;
    spaceY = ysize - 1;
}

function shuffle() {
    for (var i = 0; i < 100; i++) {
        var x, y;
        do {
            x = Math.floor(Math.random() * (size - 1));
            y = Math.floor(Math.random() * (size - 1));
        } while (x == y);
        var temp = a[x];
        a[x] = a[y];
        a[y] = temp;
    }
}

function keyDown(e) {
    var x = spaceX,
        y = spaceY;
    switch (e.keyCode) {
        case 37:
            y++;
            break;
        case 38:
            x++;
            break;
        case 39:
            y--;
            break;
        case 40:
            x--;
            break;
    }
    if (x >= 0 && y >= 0 && x < xsize && y < ysize) {
        var temp = a[x * ysize + y];
        a[x * ysize + y] = a[spaceX * ysize + spaceY];
        a[spaceX * ysize + spaceY] = temp;
        spaceX = x;
        spaceY = y;
        draw();
        if (over()) {
            confirm('you win!');
            clear();
            shuffle();
            draw();
        }
    }
}

function over() {
    for (var i = 0; i < size - 1; i++) {
        if (a[i] != i + 1)
            return false;
    }
    return true;
}

function draw() {
    for (var i = 0; i < size; i++) {
        var img = document.getElementById('pic' + i);
        img.innerHTML = (a[i] == 0 ? "" : a[i]);
    }
}

function init() {
    var w = document.documentElement.clientHeight * 0.95 / xsize;
    var h = document.documentElement.clientWidth * 0.95 / ysize;
    w = h = Math.min(w, h);
    var html="";
    for (var i = 0; i < xsize; i++) {
        html+="<tr>";
        for (var j = 0; j < ysize; j++) {
            html+="<td width=" + Math.floor(w) + " height=" + Math.floor(h) + "  class='haha' id=pic" + (i * ysize + j) + "></td>";
        }
        html+="</tr>";
    }
    table.innerHTML=html;
}
</script>
<html>

==========================java版拼图游戏==============

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MenuBar;
import java.awt.Rectangle;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;

import javax.swing.*;

import java.util.Random;  

import javax.swing.*; 

public class Pintu extends JFrame {
	public static void main(String []args) {
		new Pintu();
	}

	int[][] a = new int[4][4];
	int x, y;

	void init() {
		for (int i = 0; i < 4; i++)
			for (int j = 0; j < 4; j++)
				a[i][j] = i * 4 + j;
		x=y=3;
	}

	Pintu() {
		setTitle("拼图游戏-made by weidiao.neu");
		setSize(600,600);
		addKeyListener(listenKey);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setVisible(true);
		init();
		shuffle();
	}
	@Override
	public void paint(Graphics g) {
	    Container pane=getContentPane();
		BufferedImage bit=new BufferedImage(pane.getWidth(),pane.getHeight(),BufferedImage.TYPE_INT_ARGB);
		Graphics gg=bit.getGraphics();
		gg.setColor(Color.BLUE);
		gg.fillRect(0, 0, bit.getWidth(), bit.getHeight());
		for(int i=0;i<4;i++){
			for(int j=0;j<4;j++){
				if(a[i][j]==15)continue;
				gg.drawImage(getPic(a[i][j]), j*pane.getWidth()/4, i*pane.getHeight()/4, pane.getWidth()/4-1, pane.getHeight()/4-1, null);
			}
		}
		pane.getGraphics().drawImage(bit, 0, 0, null);
	}
	private BufferedImage getPic(int i) {
		BufferedImage bit;
		Font font=new Font("Consolas",Font.BOLD,50);
		Rectangle2D rec= getFontMetrics(font).getStringBounds(i+"", getGraphics());
		bit=new BufferedImage((int)rec.getWidth(),(int)rec.getHeight(),BufferedImage.TYPE_INT_ARGB);
		Graphics gg=bit.getGraphics();
		gg.setColor(Color.BLACK);
		gg.fillRect(0, 0, bit.getWidth(), bit.getHeight());
		gg.setFont(font);
		gg.setColor(Color.RED);
		gg.drawString(i+"",0, getFontMetrics(font).getAscent());
		return bit;
	}

	private void shuffle() {
		Random r=new Random();
		for(int i=0;i<100;i++){
			int p=r.nextInt(15);
			int q=r.nextInt(15);
			if(p==q){
				i--;
			}
			else{
				int temp=a[p/4][p%4];
				a[p/4][p%4]=a[q/4][q%4];
				a[q/4][q%4]=temp;
			}
		}
	}

	KeyListener listenKey = new KeyAdapter() {

		@Override
		public void keyReleased(KeyEvent e) {
			switch (e.getKeyCode()) {
			case KeyEvent.VK_UP:
				if (x == 3)
					return;
				else {
					int temp = a[x][y];
					a[x][y] = a[x + 1][y];
					a[x + 1][y] = temp;
					x++;
				}
				break;
			case KeyEvent.VK_DOWN:
				if (x == 0)
					return;
				else {
					int temp = a[x][y];
					a[x][y] = a[x - 1][y];
					a[x - 1][y] = temp;
					x--;
				}
				break;
			case KeyEvent.VK_RIGHT:
				if (y == 0)
					return;
				else {
					int temp = a[x][y];
					a[x][y] = a[x][y - 1];
					a[x][y - 1] = temp;
					y--;
				}
				break;
			case KeyEvent.VK_LEFT:
				if (y == 3)
					return;
				else {
					int temp = a[x][y];
					a[x][y] = a[x][y + 1];
					a[x][y + 1] = temp;
					y++;
				}
				break;
			}
			repaint();
			if(checkWin()){
				JOptionPane.showMessageDialog(Pintu.this, "You win");
				init();
				shuffle();
				repaint();
			}
		}

		private boolean checkWin() {
			// TODO Auto-generated method stub
			for(int i=0;i<4;i++)
				for(int j=0;j<4;j++)
					if(a[i][j]!=i*4+j)
						return false;
			return true;
		}
	};
}

=================android版======================================

本程序没有用到图片资源。

package weidiao.pintu;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Random;

public class MainActivity extends Activity {
    class MyView extends View {
        public MyView(Context context) {
            super(context);
            init();
            shuffle();
            initPaint();
        }

        final int width = 4, height = 6;
        int a[][] = new int[width][height];
        Point last;
        Point space;
        int d[] = {-1, 0, 0, -1, 1, 0, 0, 1};
        Paint fill, stroke;

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                last = new Point((int) event.getX(), (int) event.getY());
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                double dx = event.getX() - last.x, dy = event.getY() - last.y;
                double the = Math.atan2(dy, dx);
                if (the < 0) the += Math.PI * 2;
                int min = 0;
                for (int i = 1; i < 4; i++) {
                    if (Math.abs(the - min * Math.PI / 2) > Math.abs(the - i * Math.PI / 2)) {
                        min = i;
                    }
                }
                if (move(min)) {
                    if (isWin()) {
                        Toast.makeText(getContext(), "you win!", Toast.LENGTH_LONG).show();
                        init();
                        shuffle();
                    }
                    postInvalidate();
                }
            }
            return true;
        }

        void initPaint() {
            fill = new Paint();
            fill.setColor(Color.BLACK);
            fill.setStyle(Paint.Style.FILL);
            stroke = new Paint();
            stroke.setTextSize(60);
            stroke.setStrokeWidth(3);
            stroke.setStyle(Paint.Style.STROKE);
            stroke.setColor(Color.WHITE);
        }

        void init() {
            for (int i = 0; i < width; i++) {
                for (int j = 0; j < height; j++) {
                    a[i][j] =j* width + i+1;
                }
            }
            a[width-1][height-1]=0;
            space = new Point(width-1, height-1);
        }

        boolean move(int dir) {
            int x = space.x + d[dir << 1], y = space.y + d[dir << 1 | 1];
            if (x < 0 || x >= width || y < 0 || y >= height) return false;
            a[space.x][space.y] = a[x][y];
            a[x][y] = 0;
            space = new Point(x, y);
            return true;
        }

        void shuffle() {
            Random r = new Random();
            for (int i = 0; i < 100; i++) {
                move(r.nextInt(4));
            }
        }

        boolean isWin() {
            int all = width * height;
            for (int i = 0; i < width; i++) {
                for (int j = 0; j < height; j++) {
                    if (a[i][j] != (j*width+i+1) % all) {
                        return false;
                    }
                }
            }
            return true;
        }

        @Override
        protected void onDraw(Canvas canvas) {
            float w = Math.min(getWidth() / width, getHeight() / height);
            for (int i = 0; i < width; i++) {
                for (int j = 0; j < height; j++) {
                    canvas.drawRect(i * w + 2, j * w + 2, i * w + w - 2, j * w + w - 2, fill);
                    if (a[i][j] > 0)
                        canvas.drawText(a[i][j] + "", i * w + 102, j * w + 102, stroke);
                }
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new MyView(this));
    }
}