这个游戏大家小时候应该都玩过,我就不多做介绍了。
这个游戏我运用到了LinkedList的知识点
import java.util.LinkedList;
import java.util.Scanner;
public class GameStart {
public static void main(String[] args){
//1.创建节点 因为一条蛇是通过接点组成的
Point head=new Point(2,2);
Point p1=new Point(3,2);
Point p2=new Point(3,3);
Point p3=new Point(4,3);
Point p4=new Point(5,3);
//2.创建链表
LinkedList<Point> list=new LinkedList<Point>();
//3.将节点放入到链表
list.add(head);
list.add(p1);
list.add(p2);
list.add(p3);
list.add(p4);
//4.创建一条蛇
Snake snake=new Snake(list);
//5.创建一个游戏面板
GamePanel gamepanel=new GamePanel(snake);
//6.打印游戏面板
gamepanel.printPanel();
//7.蛇行走
System.out.println("游戏开始!");
for(;;){
Scanner sca=new Scanner(System.in); 从键盘开始控制
String s=sca.nextLine();
if(s.equals("W")){ //w代表向上
snake.go(snake.SNAKE_UP);
}else if(s.equals("A")){ //A代表向左
snake.go(snake.SNAKE_LEFT);
}else if(s.equals("S")){ //S代表向右
snake.go(snake.SNAKE_DOWN);
}else if(s.equals("D")){ //D代表向右
snake.go(snake.SNAKE_RIGHT);
}else if(s.equals("E")){ //E代表向下
break;
}
gamepanel.printPanel();//重新生成游戏画板
}
}
}
//这个是节点,因为在游戏中,蛇是有节点组成,我这里用坐标代替了它的接点位置
public class Point {
public int x;
public int y;
public Point(){
}
public Point(int x,int y){
this.x=x;
this.y=y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
import java.util.LinkedList;
import java.util.Iterator;
public class Snake {
private LinkedList<Point> points;
//通过计算,向上时,X的坐标要-10.其余的类推
public static final int SNAKE_UP=-10;
public static final int SNAKE_DOWN=10;
public static final int SNAKE_LEFT=-1;
public static final int SNAKE_RIGHT=1;
public Snake(){
}
public Snake(LinkedList<Point> points){
this.points=points;
}
public void setPoint(LinkedList<Point> points){
this.points=points;
}
public LinkedList<Point> getPoint(){
return points;
}
//行走方法
public void go(int dir){
Point head=points.getFirst();//获取第一个点
int x=head.getX()+dir/10;
int y=head.getY()+dir%10;
Point dest=new Point(x,y);//获取目标坐标
points.addFirst(dest);
points.removeLast();
}
public boolean contains(int x,int y){
Iterator<Point> p=this.points.iterator();
while(p.hasNext()){
Point point=p.next();
if(point.getX()==x&&point.getY()==y){
return true;
}
}return false;
}
}
//游戏的画板
public class GamePanel {
private Snake snake;
public GamePanel(){
}
public GamePanel(Snake snake){
this.snake=snake;
}
public Snake getSnake() {
return snake;
}
public void setSnake(Snake snake) {
this.snake = snake;
}
//打印画板,我用#代表了蛇身,*代表了边界
public void printPanel(){
for(int x=0;x<=16;x++){
for(int y=0;y<=16;y++){
if(x==0||x==16){
System.out.print("*");
}else if(y==0||y==16){
System.out.print("|");
}else if(snake.contains(x,y)){
System.out.print("#");
}else{
System.out.print(" ");
}
}System.out.println("");
}
}
}
由于知识学得不够同车,这个还不能实现蛇吃食物和撞墙就结束游戏的功能,希望哪位大神赐教!
|