贪吃蛇小游戏源代码
贪吃蛇JAVA源代码完整版
游戏贪吃蛇的JAVA源代码一.文档说明a)本代码主要功能为实现贪吃蛇游戏,GUI界面做到尽量简洁和原游戏相仿。
目前版本包含计分,统计最高分,长度自动缩短计时功能。
b)本代码受计算机系大神指点,经许可后发布如下,向Java_online网致敬c)运行时请把.java文件放入default package 即可运行。
二.运行截图a)文件位置b)进入游戏c)游戏进行中三.JAVA代码import java.awt.*;import java.awt.event.*;import static ng.String.format;import java.util.*;import java.util.List;import javax.swing.*;public class Snake extends JPanel implements Runnable { enum Dir {up(0, -1), right(1, 0), down(0, 1), left(-1, 0);Dir(int x, int y) {this.x = x; this.y = y;}final int x, y;}static final Random rand = new Random();static final int WALL = -1;static final int MAX_ENERGY = 1500;volatile boolean gameOver = true;Thread gameThread;int score, hiScore;int nRows = 44;int nCols = 64;Dir dir;int energy;int[][] grid;List<Point> snake, treats;Font smallFont;public Snake() {setPreferredSize(new Dimension(640, 440));setBackground(Color.white);setFont(new Font("SansSerif", Font.BOLD, 48));setFocusable(true);smallFont = getFont().deriveFont(Font.BOLD, 18);initGrid();addMouseListener(new MouseAdapter() {@Overridepublic void mousePressed(MouseEvent e) {if (gameOver) {startNewGame();repaint();}}});addKeyListener(new KeyAdapter() {@Overridepublic void keyPressed(KeyEvent e) {switch (e.getKeyCode()) {case KeyEvent.VK_UP:if (dir != Dir.down)dir = Dir.up;break;case KeyEvent.VK_LEFT:if (dir != Dir.right)dir = Dir.left;break;case KeyEvent.VK_RIGHT:if (dir != Dir.left)dir = Dir.right;break;case KeyEvent.VK_DOWN:if (dir != Dir.up)dir = Dir.down;break;}repaint();}});}void startNewGame() {gameOver = false;stop();initGrid();treats = new LinkedList<>();dir = Dir.left;energy = MAX_ENERGY;if (score > hiScore)hiScore = score;score = 0;snake = new ArrayList<>();for (int x = 0; x < 7; x++)snake.add(new Point(nCols / 2 + x, nRows / 2));doaddTreat();while(treats.isEmpty());(gameThread = new Thread(this)).start();}void stop() {if (gameThread != null) {Thread tmp = gameThread;gameThread = null;tmp.interrupt();}}void initGrid() {grid = new int[nRows][nCols];for (int r = 0; r < nRows; r++) {for (int c = 0; c < nCols; c++) {if (c == 0 || c == nCols - 1 || r == 0 || r == nRows - 1)grid[r][c] = WALL;}}}@Overridepublic void run() {while (Thread.currentThread() == gameThread) {try {Thread.sleep(Math.max(75 - score, 25));} catch (InterruptedException e) {return;}if (energyUsed() || hitsWall() || hitsSnake()) {gameOver();} else {if (eatsTreat()) {score++;energy = MAX_ENERGY;growSnake();}moveSnake();addTreat();}repaint();}}boolean energyUsed() {energy -= 10;return energy <= 0;}boolean hitsWall() {Point head = snake.get(0);int nextCol = head.x + dir.x;int nextRow = head.y + dir.y;return grid[nextRow][nextCol] == WALL;}boolean hitsSnake() {Point head = snake.get(0);int nextCol = head.x + dir.x;int nextRow = head.y + dir.y;for (Point p : snake)if (p.x == nextCol && p.y == nextRow)return true;return false;}boolean eatsTreat() {Point head = snake.get(0);int nextCol = head.x + dir.x;int nextRow = head.y + dir.y;for (Point p : treats)if (p.x == nextCol && p.y == nextRow) {return treats.remove(p);}return false;}void gameOver() {gameOver = true;stop();}void moveSnake() {for (int i = snake.size() - 1; i > 0; i--) {Point p1 = snake.get(i - 1);Point p2 = snake.get(i);p2.x = p1.x;p2.y = p1.y;}Point head = snake.get(0);head.x += dir.x;head.y += dir.y;}void growSnake() {Point tail = snake.get(snake.size() - 1);int x = tail.x + dir.x;int y = tail.y + dir.y;snake.add(new Point(x, y));}void addTreat() {if (treats.size() < 3) {if (rand.nextInt(10) == 0) { // 1 in 10if (rand.nextInt(4) != 0) { // 3 in 4int x, y;while (true) {x = rand.nextInt(nCols);y = rand.nextInt(nRows);if (grid[y][x] != 0)continue;Point p = new Point(x, y);if (snake.contains(p) || treats.contains(p))continue;treats.add(p);break;}} else if (treats.size() > 1)treats.remove(0);}}}void drawGrid(Graphics2D g) {g.setColor(Color.lightGray);for (int r = 0; r < nRows; r++) {for (int c = 0; c < nCols; c++) {if (grid[r][c] == WALL)g.fillRect(c * 10, r * 10, 10, 10);}}}void drawSnake(Graphics2D g) {g.setColor(Color.blue);for (Point p : snake)g.fillRect(p.x * 10, p.y * 10, 10, 10);g.setColor(energy < 500 ? Color.red : Color.orange);Point head = snake.get(0);g.fillRect(head.x * 10, head.y * 10, 10, 10);}void drawTreats(Graphics2D g) {g.setColor(Color.green);for (Point p : treats)g.fillRect(p.x * 10, p.y * 10, 10, 10);}void drawStartScreen(Graphics2D g) {g.setColor(Color.blue);g.setFont(getFont());g.drawString("Snake", 240, 190);g.setColor(Color.orange);g.setFont(smallFont);g.drawString("(click to start)", 250, 240);}void drawScore(Graphics2D g) {int h = getHeight();g.setFont(smallFont);g.setColor(getForeground());String s = format("hiscore %d score %d", hiScore, score);g.drawString(s, 30, h - 30);g.drawString(format("energy %d", energy), getWidth() - 150, h - 30); }@Overridepublic void paintComponent(Graphics gg) {super.paintComponent(gg);Graphics2D g = (Graphics2D) gg;g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);drawGrid(g);if (gameOver) {drawStartScreen(g);} else {drawSnake(g);drawTreats(g);drawScore(g);}}public static void main(String[] args) {SwingUtilities.invokeLater(() -> {JFrame f = new JFrame();f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);f.setTitle("Snake");f.setResizable(false);f.add(new Snake(), BorderLayout.CENTER);f.pack();f.setLocationRelativeTo(null);f.setVisible(true);});}}。
JAVA程序源代码(贪吃蛇)
贪吃蛇源代码将Location、LocationRO、SnakeFrame、SnakeModel、SnakePanel放到命名为snake的文件夹里,主函数MainApp放到外面运行主函数即可实现。
主函数package snake;import javax.swing.*;import snake.*;public class MainApp {public static void main(String[] args) {JFrame.setDefaultLookAndFeelDecorated(true);SnakeFrame frame=new SnakeFrame();frame.setSize(350,350);frame.setResizable(false);frame.setLocation(330,220);frame.setTitle("贪吃蛇");frame.setV isible(true);}}package snake;public class Location {private int x;private int y;Location(int x,int y){this.x=x;this.y=y;}int getX(){return x;}int getY(){return y;}void setX(int x){this.x=x;}void setY(int y){this.y=y;}public boolean equalOrRev(Location e){return ((e.getX()==getX())&&(e.getY()==getY()))||((e.getX()==getX())&&(e.getY()==-1*getY()))||((e.getX()==-1*getX())&&(e.getY()==getY()));}public boolean equals(Location e){return(e.getX()==getX())&&(e.getY()==getY());}public boolean reverse(Location e){return ((e.getX()==getX())&&(e.getY()==-1*getY()))||((e.getX()==-1*getX())&&(e.getY()==getY()));}}package snake;public class LocationRO{private int x;private int y;LocationRO(int x,int y){this.x=x;this.y=y;}int getX(){return x;}int getY(){return y;}public boolean equalOrRev(LocationRO e){return ((e.getX()==getX())&&(e.getY()==getY()))||((e.getX()==getX())&&(e.getY()==-1*getY()))||((e.getX()==-1*getX())&&(e.getY()==getY()));}public boolean equals(LocationRO e){return(e.getX()==getX())&&(e.getY()==getY());}public boolean reverse(LocationRO e){return ((e.getX()==getX())&&(e.getY()==-1*getY()))||((e.getX()==-1*getX())&&(e.getY()==getY()));}}package snake;import java.awt.*;import java.awt.event.*;import javax.swing.*;class SnakeFrame extends JFrame implements ActionListener{final SnakePanel p=new SnakePanel(this);JMenuBar menubar=new JMenuBar();JMenu fileMenu=new JMenu("文件");JMenuItem newgameitem=new JMenuItem("开始");JMenuItem stopitem=new JMenuItem("暂停");JMenuItem runitem=new JMenuItem("继续");JMenuItem exititem=new JMenuItem("退出");//"设置"菜单JMenu optionMenu=new JMenu("设置");//等级选项ButtonGroup groupDegree = new ButtonGroup();JRadioButtonMenuItem oneItem= new JRadioButtonMenuItem("初级");JRadioButtonMenuItem twoItem= new JRadioButtonMenuItem("中级");JRadioButtonMenuItem threeItem= new JRadioButtonMenuItem("高级");JMenu degreeMenu=new JMenu("等级");JMenu helpMenu=new JMenu("帮助");JMenuItem helpitem=new JMenuItem("操作指南");final JCheckBoxMenuItem showGridItem = new JCheckBoxMenuItem("显示网格");JLabel scorelabel;public JTextField scoreField;private long speedtime=200;private String helpstr = "游戏说明:\n1 :方向键控制蛇移动的方向."+"\n2 :单击菜单'文件->开始'开始游戏."+"\n3 :单击菜单'文件->暂停'或者单击键盘空格键暂停游戏."+"\n4 :单击菜单'文件->继续'继续游戏."+"\n5 :单击菜单'设置->等级'可以设置难度等级."+"\n6 :单击菜单'设置->显示网格'可以设置是否显示网格."+ "\n7 :红色为食物,吃一个得10分同时蛇身加长."+"\n8 :蛇不可以出界或自身相交,否则结束游戏.";SnakeFrame(){setJMenuBar(menubar);fileMenu.add(newgameitem);fileMenu.add(stopitem);fileMenu.add(runitem);fileMenu.add(exititem);menubar.add(fileMenu);oneItem.setSelected(true);groupDegree.add(oneItem);groupDegree.add(twoItem);groupDegree.add(threeItem);degreeMenu.add(oneItem);degreeMenu.add(twoItem);degreeMenu.add(threeItem);optionMenu.add(degreeMenu);// 风格选项showGridItem.setSelected(true);optionMenu.add(showGridItem);menubar.add(optionMenu);helpMenu.add(helpitem);menubar.add(helpMenu);Container contentpane=getContentPane();contentpane.setLayout(new FlowLayout());contentpane.add(p);scorelabel=new JLabel("得分: ");scoreField=new JTextField("0",15);scoreField.setEnabled(false);scoreField.setHorizontalAlignment(0);JPanel toolPanel=new JPanel();toolPanel.add(scorelabel);toolPanel.add(scoreField);contentpane.add(toolPanel);oneItem.addActionListener(this);twoItem.addActionListener(this);threeItem.addActionListener(this);newgameitem.addActionListener(this);stopitem.addActionListener(this);runitem.addActionListener(this);exititem.addActionListener(this);helpitem.addActionListener(this);showGridItem.addActionListener(this);}public void actionPerformed(ActionEvent e){try{if(e.getSource()==helpitem){JOptionPane.showConfirmDialog(p,helpstr,"操纵说明",JOptionPane.PLAIN_MESSAGE);}else if(e.getSource()==exititem)System.exit(0);else if(e.getSource()==newgameitem)p.newGame(speedtime);else if(e.getSource()==stopitem)p.stopGame();else if(e.getSource()==runitem)p.returnGame();else if(e.getSource()==showGridItem){if(!showGridItem.isSelected()){p.setBackground(Color.lightGray);}else{p.setBackground(Color.darkGray);}}else if(e.getSource()==oneItem) speedtime=200;else if(e.getSource()==twoItem) speedtime=100;else if(e.getSource()==threeItem) speedtime=50;}catch(Exception ee){ee.printStackTrace();}}}package snake;import java.util.*;import javax.swing.JOptionPane;public class SnakeModel {private int rows,cols;//行列数private Location snakeHead,runingDiriction;//运行方向private LocationRO[][] locRO;//LocationRO类数组private LinkedList snake,playBlocks;//蛇及其它区域块private LocationRO snakeFood;//目标食物private int gameScore=0; //分数private boolean AddScore=false;//加分// 获得蛇头public LocationRO getSnakeHead(){return (LocationRO)(snake.getLast());}//蛇尾public LocationRO getSnakeTail(){return (LocationRO)(snake.getFirst());}//运行路线public Location getRuningDiriction(){return runingDiriction;}//获得蛇实体区域public LinkedList getSnake(){return snake;}//其他区域public LinkedList getOthers(){return playBlocks;}//获得总分public int getScore(){return gameScore;}//获得增加分数public boolean getAddScore(){return AddScore;}//设置蛇头方向private void setSnakeHead(Location snakeHead){ this.snakeHead=snakeHead;}//获得目标食物public LocationRO getSnakeFood(){return snakeFood;}//随机设置目标食物private void setSnakeFood(){snakeFood=(LocationRO)(playBlocks.get((int)(Math.random()*playBlocks.size()))); }//移动private void moveTo(Object a,LinkedList fromlist,LinkedList tolist){fromlist.remove(a);tolist.add(a);}//初始设置public void init(){playBlocks.clear();snake.clear();gameScore=0;for(int i=0;i<rows;i++){for(int j=0;j<cols;j++){playBlocks.add(locRO[i][j]);}}//初始化蛇的形状for(int i=4;i<7;i++){moveTo(locRO[4][i],playBlocks,snake);}//蛇头位置snakeHead=new Location(4,6);//设置随机块snakeFood=new LocationRO(0,0);setSnakeFood();//初始化运动方向runingDiriction=new Location(0,1);}//Snake构造器public SnakeModel(int rows1,int cols1){rows=rows1;cols=cols1;locRO=new LocationRO[rows][cols];snake=new LinkedList();playBlocks=new LinkedList();for(int i=0;i<rows;i++){for(int j=0;j<cols;j++){locRO[i][j]=new LocationRO(i,j);}}init();}/**定义布尔型move方法,如果运行成功则返回true,否则返回false*参数direction是Location类型,*direction 的值:(-1,0)表示向上;(1,0)表示向下;*(0,-1)表示向左;(0,1)表示向右;**/public boolean move(Location direction){//判断设定的方向跟运行方向是不是相反if (direction.reverse(runingDiriction)){snakeHead.setX(snakeHead.getX()+runingDiriction.getX());snakeHead.setY(snakeHead.getY()+runingDiriction.getY());}else{snakeHead.setX(snakeHead.getX()+direction.getX());snakeHead.setY(snakeHead.getY()+direction.getY());}//如果蛇吃到了目标食物try{if ((snakeHead.getX()==snakeFood.getX())&&(snakeHead.getY()==snakeFood.getY())){moveTo(locRO[snakeHead.getX()][snakeHead.getY()],playBlocks,snake);setSnakeFood();gameScore+=10;AddScore=true;}else{AddScore=false;//是否出界if((snakeHead.getX()<rows)&&(snakeHead.getY()<cols)&&(snakeHead.getX()>=0&&(snak eHead.getY()>=0))){//如果不出界,判断是否与自身相交if(snake.contains(locRO[snakeHead.getX()][snakeHead.getY()])){//如果相交,结束游戏JOptionPane.showMessageDialog(null, "Game Over!", "游戏结束",RMA TION_MESSAGE);return false;}else{//如果不相交,就把snakeHead加到snake里面,并且把尾巴移出moveTo(locRO[snakeHead.getX()][snakeHead.getY()],playBlocks,snake);moveTo(snake.getFirst(),snake,playBlocks);}}else{//出界,游戏结束JOptionPane.showMessageDialog(null, "Game Over!", "游戏结束", RMA TION_MESSAGE);return false;}}}catch(ArrayIndexOutOfBoundsException e){return false;}//设置运行方向if (!(direction.reverse(runingDiriction)||direction.equals(runingDiriction))){runingDiriction.setX(direction.getX());runingDiriction.setY(direction.getY());}return true;}}package snake;import javax.swing.*;import java.awt.*;import java.awt.event.*;import java.util.*;public class SnakePanel extends JPanel implements Runnable,KeyListener{JFrame parent=new JFrame();private int row=20; //网格行数private int col=30; //列数private JPanel[][] gridsPanel; //面板网格private Location direction;//方向定位private SnakeModel snake; //贪吃蛇private LinkedList snakeBody; //蛇的身体private LinkedList otherBlocks; //其他区域private LocationRO snakeHead; //蛇的头部private LocationRO snakeFood; //目标食物private Color bodyColor=Color.orange;//蛇的身体颜色private Color headColor=Color.black; //蛇的头部颜色private Color foodColor=Color.red; //目标食物颜色private Color othersColor=Color.lightGray;//其他区域颜色private int gameScore=0; //总分private long speed; //速度(难度设置)private boolean AddScore; //加分private Thread t; //线程private boolean isEnd; //暂停private static boolean notExit;// 构造器,初始化操作public SnakePanel(SnakeFrame parent){this.parent=parent;gridsPanel=new JPanel[row][col];otherBlocks=new LinkedList();snakeBody=new LinkedList();snakeHead=new LocationRO(0,0);snakeFood=new LocationRO(0,0);direction=new Location(0,1);// 布局setLayout(new GridLayout(row,col,1,1));for(int i=0;i<row;i++){for(int j=0;j<col;j++){gridsPanel[i][j]=new JPanel();gridsPanel[i][j].setBackground(othersColor);add(gridsPanel[i][j]);}}addKeyListener(this);}// 开始游戏public void newGame(long speed){this.speed=speed;if (notExit) {snake.init();}else{snake=new SnakeModel(row,col);notExit=true;t=new Thread(this);t.start();}requestFocus();direction.setX(0);direction.setY(1);gameScore=0;updateTextFiled(""+gameScore);isEnd=false;}// 暂停游戏public void stopGame(){requestFocus();isEnd=true;}// 继续public void returnGame(){requestFocus();isEnd=false;}// 获得总分public int getGameScore(){return gameScore;}//更新总分private void updateTextFiled(String str){((SnakeFrame)parent).scoreField.setText(str); }//更新各相关单元颜色private void updateColors(){// 设定蛇身颜色snakeBody=snake.getSnake();Iterator i =snakeBody.iterator();while(i.hasNext()){LocationRO t=(LocationRO)(i.next());gridsPanel[t.getX()][t.getY()].setBackground(bodyColor);}//设定蛇头颜色snakeHead=snake.getSnakeHead();gridsPanel[snakeHead.getX()][snakeHead.getY()].setBackground(headColor);//设定背景颜色otherBlocks=snake.getOthers();i =otherBlocks.iterator();while(i.hasNext()){LocationRO t=(LocationRO)(i.next());gridsPanel[t.getX()][t.getY()].setBackground(othersColor);}//设定临时块的颜色snakeFood=snake.getSnakeFood();gridsPanel[snakeFood.getX()][snakeFood.getY()].setBackground(foodColor); }public boolean isFocusTraversable(){return true;}//实现Runnable接口public void run(){while(true){try{Thread.sleep(speed);}catch (InterruptedException e){}if(!isEnd){isEnd=!snake.move(direction);updateColors();if(snake.getAddScore()){gameScore+=10;updateTextFiled(""+gameScore);}}}}//实现KeyListener接口public void keyPressed(KeyEvent event){int keyCode = event.getKeyCode();if(notExit){if (keyCode == KeyEvent.VK_LEFT) { //向左direction.setX(0);direction.setY(-1);}else if (keyCode == KeyEvent.VK_RIGHT) { //向右direction.setX(0);direction.setY(1);}else if (keyCode == KeyEvent.VK_UP) { //向上direction.setX(-1);direction.setY(0);}else if (keyCode == KeyEvent.VK_DOWN) { //向下direction.setX(1);direction.setY(0);}else if (keyCode == KeyEvent.VK_SPACE){ //空格键isEnd=!isEnd;}}}public void keyReleased(KeyEvent event){}public void keyTyped(KeyEvent event){}}。
贪吃蛇游戏源代码(C++)
贪吃蛇游戏源代码(C++)#include <windows.h>#include <stdlib.h>#include <conio.h>#include <time.h>#include <cstring>#include <cstdio>#include <iostream>#define N 22using namespace std;int gameover;int x1, y1; // 随机出米int x,y;long start;//===================================== ==//类的实现与应用initialize//===================================== ==//下面定义贪吃蛇的坐标类class snake_position{public:int x,y; //x表示行,y表示列snake_position(){};void initialize(int &);//坐标初始化};snake_position position[(N-2)*(N-2)+1]; //定义贪吃蛇坐标类数组,有(N-2)*(N-2)个坐标void snake_position::initialize(int &j){x = 1;y = j;}//下面定义贪吃蛇的棋盘图class snake_map{private:char s[N][N];//定义贪吃蛇棋盘,包括墙壁。
int grade, length;int gamespeed; //前进时间间隔char direction; // 初始情况下,向右运动int head,tail;int score;bool gameauto;public:snake_map(int h=4,int t=1,int l=4,char d=77,int s=0):length(l),direction(d),head(h),tail(t),score(s){}void initialize(); //初始化函数void show_game();int updata_game();void setpoint();void getgrade();void display();};//定义初始化函数,将贪吃蛇的棋盘图进行初始化void snake_map::initialize(){int i,j;for(i=1;i<=3;i++)s[1][i] = '*';s[1][4] = '#';for(i=1;i<=N-2;i++)for(j=1;j<=N-2;j++)s[i][j]=' '; // 初始化贪吃蛇棋盘中间空白部分for(i=0;i<=N-1;i++)s[0][i] = s[N-1][i] = '-'; //初始化贪吃蛇棋盘上下墙壁for(i=1;i<=N-2;i++)s[i][0] = s[i][N-1] = '|'; //初始化贪吃蛇棋盘左右墙壁}//===================================== =======//输出贪吃蛇棋盘信息void snake_map::show_game(){system("cls"); // 清屏int i,j;cout << endl;for(i=0;i<N;i++){cout << '\t';for(j=0;j<N;j++)cout<<s[i][j]<<' '; // 输出贪吃蛇棋盘if(i==2) cout << "\t等级:" << grade;if(i==6) cout << "\t速度:" << gamespeed;if(i==10) cout << "\t得分:" << score << "分" ;if(i==14) cout << "\t暂停:按一下空格键" ;if(i==18) cout << "\t继续:按两下空格键" ;cout<<endl;}}//输入选择等级void snake_map::getgrade(){cin>>grade;while( grade>7 || grade<1 ){cout << "请输入数字1-7选择等级,输入其他数字无效" << endl;cin >> grade;}switch(grade){case 1: gamespeed = 1000;gameauto = 0;break;case 2: gamespeed = 800;gameauto = 0;break;case 3: gamespeed = 600;gameauto = 0;break;case 4: gamespeed = 400;gameauto = 0;break;case 5: gamespeed = 200;gameauto = 0;break;case 6: gamespeed = 100;gameauto = 0;break;case 7: grade = 1;gamespeed = 1000;gameauto = 1;break; }}//输出等级,得分情况以及称号void snake_map::display(){cout << "\n\t\t\t\t等级:" << grade;cout << "\n\n\n\t\t\t\t速度:" << gamespeed;cout << "\n\n\n\t\t\t\t得分:" << score << "分" ;}//随机产生米void snake_map::setpoint(){srand(time(0));do{x1 = rand() % (N-2) + 1;y1 = rand() % (N-2) + 1;}while(s[x1][y1]!=' ');s[x1][y1]='*';}char key;int snake_map::updata_game(){gameover = 1;key = direction;start = clock();while((gameover=(clock()-start<=gamespeed))&&!kbhit()); //如果有键按下或时间超过自动前进时间间隔则终止循环if(gameover){getch();key = getch();}if(key == ' '){while(getch()!=' '){};//这里实现的是按空格键暂停,按空格键继续的功能,但不知为何原因,需要按两下空格才能继续。
贪吃蛇游戏安卓源代码
附录1.SnakeView类package com.example.android_snake.view;import java.util.ArrayList;import java.util.List;import java.util.Random;import java.util.Timer;import java.util.TimerTask;import com.example.android_snake.R;import com.example.android_snake.food.Food;import com.example.android_snake.snake.Body;import com.example.android_snake.snake.Head;import com.example.android_snake.snake.Snake;import com.example.android_snake.snake.SnakeDirection; import com.example.android_snake.stone.Stone;import android.annotation.SuppressLint;import android.content.Context;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.graphics.Paint.Style;import android.os.Handler;import android.util.DisplayMetrics;import android.view.Display;import android.view.MotionEvent;import android.view.View;import android.view.ViewManager;import android.view.WindowManager;import android.widget.Toast;public class SnakeView extends View {private Context context;private Bitmap headBitmap;private Bitmap bodyBitmap;private Bitmap foodBitmap;private Bitmap stoneBitmap;// 屏幕的高度和宽度private int screenHeight;private int screenWidth;// 每个小格子的高度和宽度private int eachHeight;private int eachWidth;private Snake snake;private Food food;private Stone stone;private int [] listx;private int [] listy;private Timer timer = new Timer();Handler handler = new Handler() {public void handleMessage(android.os.Message msg) {moveSnake();invalidate();}};public SnakeView(Context context) {super(context);this.context = context;listx =new int[100];listy =new int[100];// 获得屏幕的高和宽DisplayMetrics metrics = new DisplayMetrics();WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);windowManager.getDefaultDisplay().getMetrics(metrics);screenHeight = metrics.heightPixels;screenWidth = metrics.widthPixels;eachHeight = screenHeight / 32;eachWidth = screenWidth / 20;// 初始化图片headBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.head);bodyBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.body);foodBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.food);stoneBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.stone);this.initSnake();this.initFood();this.initstone();gameRun();}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);Paint paint = new Paint();// 定义画笔paint.setColor(Color.GRAY);// 设置画笔颜色paint.setAntiAlias(true);// 去除锯齿paint.setStyle(Style.STROKE);// 设置空心实心paint.setTextSize(40);drawLines(canvas, paint);drawStone(canvas, paint);if(isCollide()){canvas.drawText("Game Over!", screenWidth/4, screenHeight/3, paint);canvas.drawText("得分", screenWidth/4, screenHeight/2, paint);timer.cancel();}else{this.drawSnake(canvas, paint);}boolean flag = IsRectCollision(snake.getHead().getPointX(), snake.getHead().getPointY(), eachWidth, eachHeight,food.getPointX(), food.getPointY(), eachWidth, eachHeight);if (flag) {food = null;snake.getBodyList().add(new Body());this.initFood();this.initstone();} else {this.drawFood(canvas, paint);this.drawStone(canvas, paint);}}//方向控制@Overridepublic boolean onTouchEvent(MotionEvent event) {int x = (int) event.getX();int y = (int) event.getY();SnakeDirection nowDir = snake.getSnakeDirection();int m = -screenHeight * x + screenHeight * screenWidth - screenWidth * y;int n = screenHeight * x - screenWidth * y;if ((m > 0 && n > 0) && (nowDir != SnakeDirection.DOWN)) {snake.setSnakeDirection(SnakeDirection.UP);} else if ((m > 0 && n < 0) && (nowDir != SnakeDirection.RIGHT)) { snake.setSnakeDirection(SnakeDirection.LEFT);} else if ((m < 0 && n > 0) && (nowDir != SnakeDirection.LEFT)) { snake.setSnakeDirection(SnakeDirection.RIGHT);} else if ((m < 0 && n < 0) && (nowDir != SnakeDirection.UP)) { snake.setSnakeDirection(SnakeDirection.DOWN);}return super.onTouchEvent(event);}public void gameRun() {timer.scheduleAtFixedRate(new TimerTask() {public void run() {handler.obtainMessage().sendToTarget();}}, 100, 400);}/** 画网格线*/public void drawLines(Canvas canvas, Paint paint) {int startX = 0, startY = 0;for (int i = 0; i < 100; i++) {canvas.drawLine(0, startY, screenWidth, startY, paint);startY = startY + eachHeight;}for (int i = 0; i < 100; i++) {canvas.drawLine(startX, 0, startX, screenHeight, paint);startX = startX + eachWidth;}canvas.drawLine(0, 0, screenWidth, screenHeight, paint);canvas.drawLine(0, screenHeight, screenWidth, 0, paint);}// 初始化蛇public void initSnake() {List<Body> bodies = new ArrayList<Body>();Head head = new Head(eachWidth * 4, eachHeight * 2, headBitmap);Body body1 = new Body(eachWidth * 3, eachHeight * 2, bodyBitmap);Body body2 = new Body(eachWidth * 2, eachHeight * 2, bodyBitmap);Body body3 = new Body(eachWidth * 1, eachHeight * 2, bodyBitmap);Body body4 = new Body(eachWidth * 0, eachHeight * 2, bodyBitmap);bodies.add(body1);bodies.add(body2);bodies.add(body3);bodies.add(body4);snake = new Snake(head, bodies, SnakeDirection.RIGHT);}// 画蛇public void drawSnake(Canvas canvas, Paint paint) {canvas.drawBitmap(headBitmap, snake.getHead().getPointX(), snake .getHead().getPointY(), paint);for (int i = 0; i < snake.getBodyList().size(); i++) {canvas.drawBitmap(bodyBitmap, snake.getBodyList().get(i).getPointX(), snake.getBodyList().get(i).getPointY(), paint);}}// 改变蛇身的位置public void changSnakePosition(int pointX, int pointY) {for (int i = snake.getBodyList().size() - 1; i > 0; i--) {snake.getBodyList().get(i).setPointX(snake.getBodyList().get(i - 1).getPointX());snake.getBodyList().get(i).setPointY(snake.getBodyList().get(i - 1).getPointY());}snake.getBodyList().get(0).setPointX(snake.getHead().getPointX());snake.getBodyList().get(0).setPointY(snake.getHead().getPointY());}// 移动蛇public void moveSnake() {int nowPointX = snake.getHead().getPointX();int nowPointY = snake.getHead().getPointY();if (snake.getSnakeDirection() == SnakeDirection.RIGHT) {changSnakePosition(nowPointX, nowPointY);if (nowPointX >= screenWidth - eachWidth) {snake.getHead().setPointX(0);} else {snake.getHead().setPointX(nowPointX + eachWidth);}} else if (snake.getSnakeDirection() == SnakeDirection.DOWN) { changSnakePosition(nowPointX, nowPointY);if (nowPointY >= screenHeight - eachHeight) {snake.getHead().setPointY(0);} else {snake.getHead().setPointY(nowPointY + eachHeight);}} else if (snake.getSnakeDirection() == SnakeDirection.LEFT) {changSnakePosition(nowPointX, nowPointY);if (nowPointX <= 0) {snake.getHead().setPointX(screenWidth - eachWidth);} else {snake.getHead().setPointX(nowPointX - eachWidth);}} else if (snake.getSnakeDirection() == SnakeDirection.UP) {changSnakePosition(nowPointX, nowPointY);if (nowPointY <= 0) {snake.getHead().setPointY(screenHeight - eachHeight);} else {snake.getHead().setPointY(nowPointY - eachHeight);}}}// 初始化foodpublic void initFood() {int x = new Random().nextInt(19);int y = new Random().nextInt(29);food = new Food(eachWidth * x, eachHeight * y, foodBitmap);}// 在界面上画出Foodpublic void drawFood(Canvas canvas, Paint paint) {if (food != null) {canvas.drawBitmap(foodBitmap, food.getPointX(), food.getPointY(),paint);}}// 初始化stonepublic void initstone() {int x = new Random().nextInt(17);int y = new Random().nextInt(23);stone = new Stone(eachWidth * x, eachHeight * y, stoneBitmap);int i=0,j=0;listx[i++]=x;listy[j++]=y;}// 在界面上画出Stonepublic void drawStone(Canvas canvas, Paint paint) {if (true) {canvas.drawBitmap(stoneBitmap, stone.getPointX(), stone.getPointY(),paint);for(int k=0;k<100;k++){//food = new Food(eachWidth * listx[k], eachHeight * listy[k], foodBitmap);//canvas.drawBitmap(stoneBitmap,listx[k], listy[k],paint);}}}/*** 矩形碰撞检测参数为x,y,width,height** @param x1* 第一个矩形的x* @param y1* 第一个矩形的y* @param w1* 第一个矩形的w* @param h1* 第一个矩形的h* @param x2* 第二个矩形的x* @param y2* 第二个矩形的y* @param w2* 第二个矩形的w* @param h2* 第二个矩形的h* @return是否碰撞*/public boolean IsRectCollision(int x1, int y1, int w1, int h1, int x2, int y2, int w2, int h2) {if (x2 > x1 && x2 >= x1 + w1) {return false;} else if (x2 < x1 && x2 <= x1 - w2) {return false;} else if (y2 > y1 && y2 >= y1 + h1) {return false;} else if (y2 < y1 && y2 <= y1 - h2) {return false;} else {return true;}}//检测蛇头是否与蛇身碰撞//检测蛇头与墙的碰撞//public boolean isCollide() {boolean flag = false;for (int i = 0; i < snake.getBodyList().size(); i++) {flag = IsRectCollision(snake.getHead().getPointX(),snake.getHead().getPointY(), eachWidth, eachHeight,snake.getBodyList().get(i).getPointX(),snake.getBodyList().get(i).getPointY(),eachWidth,eachHeight);for(int j=0;j<100;j++){flag = IsRectCollision(snake.getHead().getPointX(),snake.getHead().getPointY(), eachWidth, eachHeight,listx[j],listy[j], eachWidth,eachHeight);if(flag){break;}}if ((snake.getHead().getPointX() < 1) ||(snake.getHead().getPointY() < 1) ||(snake.getHead().getPointX() > screenWidth - 1)||(snake.getHead().getPointY() > screenHeight - 1)){flag = true;}if(flag){break;}}return flag;}}2.MainActivity类package com.example.android_snake;import com.example.android_snake.R;import com.example.android_snake.view.SnakeView;//Downloads By import android.os.Bundle;import android.app.Activity;import android.view.Menu;import android.view.MenuItem;import android.view.Window;import android.view.WindowManager;public class MainActivity extends Activity {@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_NO_TITLE);//设置全屏getWindow().setFlags(youtParams.FLAG_FULLSCREEN, youtParams.FLAG_FULLSCREEN);SnakeView view = new SnakeView(this);setContentView(view);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu);return true;}}3.Food类package com.example.android_snake.food;import android.graphics.Bitmap;public class Food {private int pointX;private int pointY;private Bitmap foodBitmap;public Food() {super();}public Food(int pointX, int pointY, Bitmap foodBitmap) { super();this.pointX = pointX;this.pointY = pointY;this.foodBitmap = foodBitmap;}public int getPointX() {return pointX;}public void setPointX(int pointX) {this.pointX = pointX;}public int getPointY() {return pointY;}public void setPointY(int pointY) {this.pointY = pointY;}public Bitmap getFoodBitmap() {return foodBitmap;}public void setFoodBitmap(Bitmap foodBitmap) {this.foodBitmap = foodBitmap;}}4.Body类package com.example.android_snake.snake;import android.graphics.Bitmap;public class Body {private int pointX;private int pointY;private Bitmap bodyBitMap;public Body() {super();}public Body(int pointX, int pointY, Bitmap bodyBitMap) { super();this.pointX = pointX;this.pointY = pointY;this.bodyBitMap = bodyBitMap;}public int getPointX() {return pointX;}public void setPointX(int pointX) {this.pointX = pointX;}public int getPointY() {return pointY;}public void setPointY(int pointY) {this.pointY = pointY;}public Bitmap getBodyBitMap() {return bodyBitMap;}public void setBodyBitMap(Bitmap bodyBitMap) {this.bodyBitMap = bodyBitMap;}}5.Head类package com.example.android_snake.snake;import android.graphics.Bitmap;public class Head {private int pointX;private int pointY;private Bitmap headBitMap;public Head() {super();}public Head(int pointX, int pointY, Bitmap headBitMap) {super();this.pointX = pointX;this.pointY = pointY;this.headBitMap = headBitMap;}public int getPointX() {return pointX;}public void setPointX(int pointX) {this.pointX = pointX;}public int getPointY() {return pointY;}public void setPointY(int pointY) {this.pointY = pointY;}public Bitmap getHeadBitMap() {return headBitMap;}public void setHeadBitMap(Bitmap headBitMap) {this.headBitMap = headBitMap;}}6.Snake类package com.example.android_snake.snake;import java.util.ArrayList;import java.util.List;import android.graphics.Bitmap;public class Snake {private Head head;private Body body;private List<Body> bodyList;private SnakeDirection snakeDirection;public Snake(){}public Snake(Head head,List<Body> bodyList,SnakeDirection snakeDirection){ super();this.head = head;this.bodyList = bodyList;this.snakeDirection = snakeDirection;}public Head getHead() {return head;}public void setHead(Head head) {this.head = head;}public Body getBody() {return body;}public void setBody(Body body) {this.body = body;}public List<Body> getBodyList() {return bodyList;}public void setBodyList(List<Body> bodyList) {this.bodyList = bodyList;}public SnakeDirection getSnakeDirection() {return snakeDirection;}public void setSnakeDirection(SnakeDirection snakeDirection) { this.snakeDirection = snakeDirection;}}7.SnakeDirection类package com.example.android_snake.snake;public enum SnakeDirection {UP,DOWN,LEFT,RIGHT;}8.Stone类package com.example.android_snake.stone;import android.graphics.Bitmap;public class Stone {private int pointX;private int pointY;private Bitmap stoneBitmap;public Stone() {super();}public Stone(int pointX, int pointY, Bitmap foodBitmap) { super();this.pointX = pointX;this.pointY = pointY;this.stoneBitmap = stoneBitmap;}public int getPointX() {return pointX;}public void setPointX(int pointX) {this.pointX = pointX;}public int getPointY() {return pointY;}public void setPointY(int pointY) {this.pointY = pointY;}public Bitmap getStoneBitmap() {return stoneBitmap;}public void setFoodBitmap(Bitmap foodBitmap) { this.stoneBitmap = stoneBitmap;}}。
C语言小游戏源代码《贪吃蛇》
void init(void){/*构建图形驱动函数*/ int gd=DETECT,gm; initgraph(&gd,&gm,""); cleardevice(); }
欢迎您阅读该资料希望该资料能给您的学习和生活带来帮助如果您还了解更多的相关知识也欢迎您分享出来让我们大家能共同进步共同成长
C 语言小游戏源代码《贪吃பைடு நூலகம்》
#define N 200/*定义全局常量*/ #define m 25 #include <graphics.h> #include <math.h> #include <stdlib.h> #include <dos.h> #define LEFT 0x4b00 #define RIGHT 0x4d00 #define DOWN 0x5000 #define UP 0x4800 #define Esc 0x011b int i,j,key,k; struct Food/*构造食物结构体*/ { int x; int y; int yes; }food; struct Goods/*构造宝贝结构体*/ { int x; int y; int yes; }goods; struct Block/*构造障碍物结构体*/ { int x[m]; int y[m]; int yes; }block; struct Snake{/*构造蛇结构体*/ int x[N]; int y[N]; int node; int direction; int life; }snake; struct Game/*构建游戏级别参数体*/ { int score; int level; int speed;
贪吃蛇游戏c语言源代码
#include <stdlib.h>#include <graphics.h>#include <bios.h>#include <dos.h>#include <conio.h>#define Enter 7181#define ESC 283#define UP 18432#define DOWN 20480#define LEFT 19200#define RIGHT 19712#ifdef __cplusplus#define __CPPARGS ...#else#define __CPPARGS#endifvoid interrupt (*oldhandler)(__CPPARGS);void interrupt newhandler(__CPPARGS);void SetTimer(void interrupt (*IntProc)(__CPPARGS));void KillTimer(void);void Initgra(void);void TheFirstBlock(void);void DrawMap(void);void Initsnake(void);void Initfood(void);void Snake_Headmv(void);void Flag(int,int,int,int);void GameOver(void);void Snake_Bodymv(void);void Snake_Bodyadd(void);void PrntScore(void);void Timer(void);void Win(void);void TheSecondBlock(void);void Food(void);void Dsnkorfd(int,int,int);void Delay(int);struct Snake{int x;int y;int color;}Snk[12];struct Food{int x;int y;int color;}Fd;int flag1=1,flag2=0,flag3=0,flag4=0,flag5=0,flag6=0,checkx,checky,num,key=0,Times,Score,Hscore,Snkspeed,TimerCounter,TureorFalse; char Sco[2],Time[6];void main(){ Initgra();SetTimer(newhandler);TheFirstBlock();while(1){DrawMap();Snake_Headmv();GameOver();Snake_Bodymv();Snake_Bodyadd();PrntScore();Timer();Win();if(key==ESC)break;if(key==Enter){cleardevice();TheFirstBlock();}TheSecondBlock();Food();Delay(Snkspeed);}closegraph();KillTimer();}void interrupt newhandler(__CPPARGS){TimerCounter++;oldhandler();}void SetTimer(void interrupt (*IntProc)(__CPPARGS)) {oldhandler=getvect(0x1c);disable();setvect(0x1c,IntProc);enable();}void KillTimer(){disable();setvect(0x1c,oldhandler);enable();}void Initgra(){int gd=DETECT,gm;initgraph(&gd,&gm,"d:\\tc");}void TheFirstBlock(){setcolor(11);settextstyle(0,0,4);outtextxy(100,220,"The First Block");loop:key=bioskey(0);if(key==Enter){cleardevice();Initsnake();Initfood();Score=0;Hscore=1;Snkspeed=10;num=2;Times=0;key=0;TureorFalse=1;TimerCounter=0;Time[0]='0';Time[1]='0';Time[2]=':';Time[3]='1';Time[4]='0';Time[5]='\0'; }else if(key==ESC) cleardevice();else goto loop;}void DrawMap(){line(10,10,470,10);line(470,10,470,470);line(470,470,10,470);line(10,470,10,10);line(480,20,620,20);line(620,20,620,460);line(620,460,480,460);line(480,460,480,20);}void Initsnake(){randomize();num=2;Snk[0].x=random(440);Snk[0].x=Snk[0].x-Snk[0].x%20+50;Snk[0].y=random(440);Snk[0].y=Snk[0].y-Snk[0].y%20+50;Snk[0].color=4;Snk[1].x=Snk[0].x;Snk[1].y=Snk[0].y+20;Snk[1].color=4;}void Initfood(){randomize();Fd.x=random(440);Fd.x=Fd.x-Fd.x%20+30;Fd.y=random(440);Fd.y=Fd.y-Fd.y%20+30;Fd.color=random(14)+1;}void Snake_Headmv(){if(bioskey(1)){key=bioskey(0);switch(key){case UP:Flag(1,0,0,0);break;case DOWN:Flag(0,1,0,0);break;case LEFT:Flag(0,0,1,0);break;case RIGHT:Flag(0,0,0,1);break;default:break;}}if(flag1){checkx=Snk[0].x;checky=Snk[0].y;Dsnkorfd(Snk[0].x,Snk[0].y,0);Snk[0].y-=20;Dsnkorfd(Snk[0].x,Snk[0].y,Snk[0].color); }if(flag2){checkx=Snk[0].x;checky=Snk[0].y;Dsnkorfd(Snk[0].x,Snk[0].y,0);Snk[0].y+=20;Dsnkorfd(Snk[0].x,Snk[0].y,Snk[0].color); }if(flag3){checkx=Snk[0].x;checky=Snk[0].y;Dsnkorfd(Snk[0].x,Snk[0].y,0);Snk[0].x-=20;Dsnkorfd(Snk[0].x,Snk[0].y,Snk[0].color);}if(flag4){checkx=Snk[0].x;checky=Snk[0].y;Dsnkorfd(Snk[0].x,Snk[0].y,0);Snk[0].x+=20;Dsnkorfd(Snk[0].x,Snk[0].y,Snk[0].color);}}void Flag(int a,int b,int c,int d){flag1=a;flag2=b;flag3=c;flag4=d;}void GameOver(){int i;if(Snk[0].x<20||Snk[0].x>460||Snk[0].y<20||Snk[0].y>460) {cleardevice();setcolor(11);settextstyle(0,0,4);outtextxy(160,220,"Game Over");loop1:key=bioskey(0);if(key==Enter){cleardevice();TheFirstBlock();}elseif(key==ESC)cleardevice();elsegoto loop1;}for(i=3;i<num;i++){if(Snk[0].x==Snk[i].x&&Snk[0].y==Snk[i].y) {cleardevice();setcolor(11);settextstyle(0,0,4);outtextxy(160,220,"Game Over");loop2:key=bioskey(0);if(key==Enter){cleardevice();TheFirstBlock();}elseif(key==ESC)cleardevice();else goto loop2;}}}void Snake_Bodymv(){int i,s,t;for(i=1;i<num;i++){Dsnkorfd(checkx,checky,Snk[i].color); Dsnkorfd(Snk[i].x,Snk[i].y,0);s=Snk[i].x;t=Snk[i].y;Snk[i].x=checkx;Snk[i].y=checky;checkx=s;checky=t;}}void Food(){if(flag5){randomize();Fd.x=random(440);Fd.x=Fd.x-Fd.x%20+30;Fd.y=random(440);Fd.y=Fd.y-Fd.y%20+30;Fd.color=random(14)+1;flag5=0;}Dsnkorfd(Fd.x,Fd.y,Fd.color);}void Snake_Bodyadd(){if(Snk[0].x==Fd.x&&Snk[0].y==Fd.y) {if(Snk[num-1].x>Snk[num-2].x){num++;Snk[num-1].x=Snk[num-2].x+20;Snk[num-1].y=Snk[num-2].y;Snk[num-1].color=Fd.color;}elseif(Snk[num-1].x<Snk[num-2].x){num++;Snk[num-1].x=Snk[num-2].x-20;Snk[num-1].y=Snk[num-2].y;Snk[num-1].color=Fd.color;}elseif(Snk[num-1].y>Snk[num-2].y) {num++;Snk[num-1].x=Snk[num-2].x; Snk[num-1].y=Snk[num-2].y+20; Snk[num-1].color=Fd.color;}elseif(Snk[num-1].y<Snk[num-2].y) {num++;Snk[num-1].x=Snk[num-2].x; Snk[num-1].y=Snk[num-2].y-20; Snk[num-1].color=Fd.color;}flag5=1;Score++;}}void PrntScore(){if(Hscore!=Score){setcolor(11);settextstyle(0,0,3); outtextxy(490,100,"SCORE"); setcolor(2);setfillstyle(1,0);rectangle(520,140,580,180); floodfill(530,145,2);Sco[0]=(char)(Score+48);Sco[1]='\0';Hscore=Score;setcolor(4);settextstyle(0,0,3); outtextxy(540,150,Sco);}}void Timer(){if(TimerCounter>18){Time[4]=(char)(Time[4]-1); if(Time[4]<'0'){Time[4]='9';Time[3]=(char)(Time[3]-1);}if(Time[3]<'0'){Time[3]='5';Time[1]=(char)(Time[1]-1);}if(TureorFalse){setcolor(11);settextstyle(0,0,3);outtextxy(490,240,"TIMER");setcolor(2);setfillstyle(1,0);rectangle(490,280,610,320);floodfill(530,300,2);setcolor(11);settextstyle(0,0,3);outtextxy(495,290,Time);TureorFalse=0;}if(Time[1]=='0'&&Time[3]=='0'&&Time[4]=='0') {setcolor(11);settextstyle(0,0,4);outtextxy(160,220,"Game Over");loop:key=bioskey(0);if(key==Enter){cleardevice();TheFirstBlock();}else if(key==ESC) cleardevice();else goto loop;}TimerCounter=0;TureorFalse=1;}}void Win(){if(Score==3)Times++;if(Times==2){cleardevice();setcolor(11);settextstyle(0,0,4);outtextxy(160,220,"You Win");loop:key=bioskey(0);if(key==Enter){cleardevice();TheFirstBlock();key=0;}else if(key==ESC) cleardevice();else goto loop;}}void TheSecondBlock(){if(Score==3){cleardevice();setcolor(11);settextstyle(0,0,4);outtextxy(100,220,"The Second Block"); loop:key=bioskey(0);if(key==Enter){cleardevice();Initsnake();Initfood();Score=0;Hscore=1;Snkspeed=8;num=2;key=0;}else if(key==ESC) cleardevice();else goto loop;}}void Dsnkorfd(int x,int y,int color) {setcolor(color);setfillstyle(1,color);circle(x,y,10);floodfill(x,y,color);}void Delay(int times){int i;for(i=1;i<=times;i++)delay(15000);}。
Python实现的贪吃蛇小游戏代码
以下是Python实现的贪吃蛇小游戏代码:```pythonimport pygameimport random# 初始化Pygamepygame.init()# 设置游戏窗口大小和标题screen_width = 480screen_height = 480game_display = pygame.display.set_mode((screen_width, screen_height))pygame.display.set_caption('贪吃蛇游戏')# 定义颜色white = (255, 255, 255)black = (0, 0, 0)red = (255, 0, 0)green = (0, 255, 0)# 定义蛇的初始位置和尺寸snake_block_size = 20snake_speed = 10initial_snake_pos = {'x': screen_width/2, 'y': screen_height/2}snake_list = [initial_snake_pos]# 定义食物的尺寸和位置food_block_size = 20food_pos = {'x': round(random.randrange(0, screen_width - food_block_size) / 20.0) * 20.0, 'y': round(random.randrange(0, screen_height - food_block_size) / 20.0) * 20.0}# 定义分数、字体和大小score = 0font_style = pygame.font.SysFont(None, 30)# 刷新分数def refresh_score(score):score_text = font_style.render("Score: " + str(score), True, black)game_display.blit(score_text, [0, 0])# 绘制蛇def draw_snake(snake_block_size, snake_list):for pos in snake_list:pygame.draw.rect(game_display, green, [pos['x'], pos['y'], snake_block_size, snake_block_size])# 显示消息def message(msg, color):message_text = font_style.render(msg, True, color)game_display.blit(message_text, [screen_width/6, screen_height/3])# 主函数循环def game_loop():game_over = Falsegame_close = False# 设置蛇头的初始移动方向x_change = 0y_change = 0# 处理事件while not game_over:while game_close:game_display.fill(white)message("You lost! Press Q-Quit or C-Play Again", red)refresh_score(score)pygame.display.update()# 处理重新开始和退出事件for event in pygame.event.get():if event.type == pygame.KEYDOWN:if event.key == pygame.K_q:game_over = Truegame_close = Falseelif event.key == pygame.K_c:game_loop()# 处理按键事件for event in pygame.event.get():if event.type == pygame.QUIT:game_over = Trueif event.type == pygame.KEYDOWN:if event.key == pygame.K_LEFT:x_change = -snake_block_sizey_change = 0elif event.key == pygame.K_RIGHT:x_change = snake_block_sizey_change = 0elif event.key == pygame.K_UP:y_change = -snake_block_sizex_change = 0elif event.key == pygame.K_DOWN:y_change = snake_block_sizex_change = 0# 处理蛇的移动位置if snake_list[-1]['x'] >= screen_width or snake_list[-1]['x'] < 0 or snake_list[-1]['y'] >= screen_height or snake_list[-1]['y'] < 0:game_close = Truesnake_list[-1]['x'] += x_changesnake_list[-1]['y'] += y_change# 处理食物被吃掉的情况if snake_list[-1]['x'] == food_pos['x'] and snake_list[-1]['y'] == food_pos['y']:score += 10food_pos = {'x': round(random.randrange(0, screen_width -food_block_size) / 20.0) * 20.0,'y': round(random.randrange(0, screen_height -food_block_size) / 20.0) * 20.0}else:snake_list.pop(0)# 处理蛇撞到自身的情况for pos in snake_list[:-1]:if pos == snake_list[-1]:game_close = True# 刷新游戏窗口game_display.fill(white)draw_snake(snake_block_size, snake_list)pygame.draw.rect(game_display, red, [food_pos['x'], food_pos['y'], food_block_size, food_block_size])refresh_score(score)pygame.display.update()# 设置蛇移动的速度clock = pygame.time.Clock()clock.tick(snake_speed)pygame.quit()quit()game_loop()```当您运行此代码时,将会启动一个贪吃蛇小游戏。
贪吃蛇游戏源代码
begin();
}
//----------------------------------------------------------------------
//keyPressed():按键检测
//----------------------------------------------------------------------
void begin()
{
if(snakeModel==null||!snakeModel.running)
{
snakeModel=new SnakeModel(this,canvasWidth/nodeWidth,
this.canvasHeight/nodeHeight);
(new Thread(snakeModel)).start();
//GreedSnake():初始化游戏界面
//----------------------------------------------------------------------
public GreedSnake()
{
//设置界面元素
mainFrame=new JFrame("GreedSnake");
*要点分析:
*1)数据结构:matrix[][]用来存储地图上面的信息,如果什么也没有设置为false,
* 如果有食物或蛇,设置为true;nodeArray,一个LinkedList,用来保存蛇的每
* 一节;food用来保存食物的位置;而Node类是保存每个位置的信息。
贪吃蛇C语言源代码
#include <stdio.h>#include <stdlib.h>#include <Windows.h>//windows编程头文件#include <time.h>#include <conio.h>//控制台输入输出头文件#ifndef __cplusplustypedef char bool;#define false 0#define true 1#endif//将光标移动到控制台的(x,y)坐标点处void gotoxy(int x, int y){COORD coord;coord.X = x;coord.Y = y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); }#define SNAKESIZE 100//蛇的身体最大节数#define MAPWIDTH 78//宽度#define MAPHEIGHT 24//高度//食物的坐标struct {int x;int y;}food;//蛇的相关属性struct {int speed;//蛇移动的速度int len;//蛇的长度int x[SNAKESIZE];//组成蛇身的每一个小方块中x的坐标int y[SNAKESIZE];//组成蛇身的每一个小方块中y的坐标}snake;//绘制游戏边框void drawMap();//随机生成食物void createFood();//按键操作void keyDown();//蛇的状态bool snakeStatus();//从控制台移动光标void gotoxy(int x, int y);int key = 72;//表示蛇移动的方向,72为按下“↑”所代表的数字//用来判断蛇是否吃掉了食物,这一步很重要,涉及到是否会有蛇身移动的效果以及蛇身增长的效果int changeFlag = 0;int sorce = 0;//记录玩家的得分int i;void drawMap(){//打印上下边框for (i = 0; i <= MAPWIDTH; i += 2)//i+=2是因为横向占用的是两个位置{//将光标移动依次到(i,0)处打印上边框gotoxy(i, 0);printf("■");//将光标移动依次到(i,MAPHEIGHT)处打印下边框gotoxy(i, MAPHEIGHT);printf("■");}//打印左右边框for (i = 1; i < MAPHEIGHT; i++){//将光标移动依次到(0,i)处打印左边框gotoxy(0, i);printf("■");//将光标移动依次到(MAPWIDTH, i)处打印左边框gotoxy(MAPWIDTH, i);printf("■");}//随机生成初试食物while (1){srand((unsigned int)time(NULL));food.x = rand() % (MAPWIDTH - 4) + 2;food.y = rand() % (MAPHEIGHT - 2) + 1;//生成的食物横坐标的奇偶必须和初试时蛇头所在坐标的奇偶一致,因为一个字符占两个字节位置,若不一致//会导致吃食物的时候只吃到一半if (food.x % 2 == 0)break;}//将光标移到食物的坐标处打印食物gotoxy(food.x, food.y);printf("*");//初始化蛇的属性snake.len = 3;snake.speed = 200;//在屏幕中间生成蛇头snake.x[0] = MAPWIDTH / 2 + 1;//x坐标为偶数snake.y[0] = MAPHEIGHT / 2;//打印蛇头gotoxy(snake.x[0], snake.y[0]);printf("■");//生成初试的蛇身for (i = 1; i < snake.len; i++){//蛇身的打印,纵坐标不变,横坐标为上一节蛇身的坐标值+2snake.x[i] = snake.x[i - 1] + 2;snake.y[i] = snake.y[i - 1];gotoxy(snake.x[i], snake.y[i]);printf("■");}//打印完蛇身后将光标移到屏幕最上方,避免光标在蛇身处一直闪烁gotoxy(MAPWIDTH - 2, 0);return;}void keyDown(){int pre_key = key;//记录前一个按键的方向if (_kbhit())//如果用户按下了键盘中的某个键{fflush(stdin);//清空缓冲区的字符//getch()读取方向键的时候,会返回两次,第一次调用返回0或者224,第二次调用返回的才是实际值key = _getch();//第一次调用返回的不是实际值key = _getch();//第二次调用返回实际值}/**蛇移动时候先擦去蛇尾的一节*changeFlag为0表明此时没有吃到食物,因此每走一步就要擦除掉蛇尾,以此营造一个移动的效果*为1表明吃到了食物,就不需要擦除蛇尾,以此营造一个蛇身增长的效果*/if (changeFlag == 0){gotoxy(snake.x[snake.len - 1], snake.y[snake.len - 1]);printf(" ");//在蛇尾处输出空格即擦去蛇尾}//将蛇的每一节依次向前移动一节(蛇头除外)for (i = snake.len - 1; i > 0; i--){snake.x[i] = snake.x[i - 1];snake.y[i] = snake.y[i - 1];}//蛇当前移动的方向不能和前一次的方向相反,比如蛇往左走的时候不能直接按右键往右走//如果当前移动方向和前一次方向相反的话,把当前移动的方向改为前一次的方向if (pre_key == 72 && key == 80)key = 72;if (pre_key == 80 && key == 72)key = 80;if (pre_key == 75 && key == 77)key = 75;if (pre_key == 77 && key == 75)key = 77;/***控制台按键所代表的数字*“↑”:72*“↓”:80*“←”:75*“→”:77*///判断蛇头应该往哪个方向移动switch (key){case 75:snake.x[0] -= 2;//往左break;case 77:snake.x[0] += 2;//往右break;case 72:snake.y[0]--;//往上break;case 80:snake.y[0]++;//往下break;}//打印出蛇头gotoxy(snake.x[0], snake.y[0]);printf("■");gotoxy(MAPWIDTH - 2, 0);//由于目前没有吃到食物,changFlag值为0changeFlag = 0;return;}void createFood(){if (snake.x[0] == food.x && snake.y[0] == food.y)//蛇头碰到食物{//蛇头碰到食物即为要吃掉这个食物了,因此需要再次生成一个食物while (1){int flag = 1;srand((unsigned int)time(NULL));food.x = rand() % (MAPWIDTH - 4) + 2;food.y = rand() % (MAPHEIGHT - 2) + 1;//随机生成的食物不能在蛇的身体上for (i = 0; i < snake.len; i++){if (snake.x[i] == food.x && snake.y[i] == food.y){flag = 0;break;}}//随机生成的食物不能横坐标为奇数,也不能在蛇身,否则重新生成if (flag && food.x % 2 == 0)break;}//绘制食物gotoxy(food.x, food.y);printf("*");snake.len++;//吃到食物,蛇身长度加1sorce += 10;//每个食物得10分snake.speed -= 5;//随着吃的食物越来越多,速度会越来越快changeFlag = 1;//很重要,因为吃到了食物,就不用再擦除蛇尾的那一节,以此来造成蛇身体增长的效果}return;}bool snakeStatus(){//蛇头碰到上下边界,游戏结束if (snake.y[0] == 0 || snake.y[0] == MAPHEIGHT)return false;//蛇头碰到左右边界,游戏结束if (snake.x[0] == 0 || snake.x[0] == MAPWIDTH)return false;//蛇头碰到蛇身,游戏结束for (i = 1; i < snake.len; i++){if (snake.x[i] == snake.x[0] && snake.y[i] == snake.y[0])return false;}return true;}int main(){drawMap();while (1){keyDown();if (!snakeStatus())break;createFood();Sleep(snake.speed);}gotoxy(MAPWIDTH / 2, MAPHEIGHT / 2);printf("Game Over!\n");gotoxy(MAPWIDTH / 2, MAPHEIGHT / 2 + 1);printf("本次游戏得分为:%d\n", sorce);Sleep(5000);return 0;}。
贪吃蛇源代码(需要easy x,vc6.0可以成功编译运行)
#include <graphics.h>#include <stdlib.h>#include <time.h>//#include <dos.h>#include <conio.h>#include <stdio.h>//#include <winnt.h>#define MAX_JOINTS 200#define LEFT 0x4b00#define RIGHT 0x4d00#define DOWN 0x5000#define UP 0x4800#define ESC 0x011b#define MV_RIGHT 1#define MV_LEFT 2#define MV_UP 3#define MV_DOWN 4void InitGraph(void); /*图形驱动初始化函数*/void DrawFence(void); /*绘制游戏场景*/void GameOver(int score); /*结束游戏*/void GamePlay(void); /*玩游戏具体过程*/void PrScore(int score); /*输出成绩*/struct Food /*食物的结构体定义*/{int x; /*食物的横坐标*/int y; /*食物的纵坐标*/int addFood; /*判断是否要出现食物的变量*/};struct Snake /*蛇的结构体定义*/{int x[MAX_JOINTS]; /*保存蛇身每一节位于屏幕上的列坐标*/ int y[MAX_JOINTS]; /*保存蛇身每一节位于屏幕上的行坐标*/ int joint; /*蛇的节数*/int direction; /*蛇移动方向*/int life; /*蛇的生命,0活着,1死亡*/};/*主函数*/void main(void){InitGraph(); /*图形驱动*/DrawFence(); /*游戏场景*/GamePlay(); /*玩游戏具体过程*/closegraph(); /*图形结束*/}/*图形驱动初始化函数*/void InitGraph(void){int gd = DETECT, gm;initgraph(&gd, &gm, "");cleardevice();setbkcolor(BLUE);cleardevice();setcolor(WHITE);//settextstyle(DEFAULT_FONT, HORIZ_DIR, 3);setfont(32, 0, "宋体");outtextxy(170, 150, "Greedy Snake");outtextxy(219, 254, "Ready?");setcolor(BLUE);cleardevice();}/*游戏开始画面,左上角坐标为(50,40),右下角坐标为(610,460)的围墙*/ void DrawFence(void){int i;setbkcolor(LIGHTGREEN);setcolor(11);//setlinestyle(SOLID_LINE, 0, THICK_WIDTH);setlinestyle(PS_SOLID, 0, 3);/*画围墙*/for (i=50; i<=600; i+=10){rectangle(i, 40, i+10, 49); /*上边*/rectangle(i, 451, i+10, 460); /*下边*/}for (i=40; i<=450; i+=10){rectangle(50, i, 59, i+10); /*左边*/rectangle(601, i, 610, i+10); /*右边*/}}/*控制贪吃蛇吃食物*/void GamePlay(void){int i, key;//int gamespeed = 22000; /*控制游戏速度*/int gamespeed = 200;int score = 0; /*记录游戏得分*/struct Food food; /*食物结构体变量*/struct Snake snake; /*蛇结构体变量*/food.addFood = 1; /*1表示需要出现新食物,0表示已经存在食物*/ snake.life = 0; /*置蛇的生命状态为活着*/snake.direction = MV_RIGHT; /*置蛇头方向往右*/snake.x[0] = 100; snake.y[0] = 100; /*置蛇头初始位置*/snake.x[1] = 110; snake.y[1] = 100;snake.joint = 2; /*置蛇的初始节数为2*/PrScore(score); /*显示游戏得分*//*重复玩游戏,直到按Esc键结束*/srand(time(NULL));while (1){while (!kbhit())/*在没有按键的情况下,蛇自己移动身体*/{if (food.addFood == 1) /*需要出现新食物*/{food.x = rand() % 400 + 60;food.y = rand() % 350 + 60;/*食物出现后必须在整格内才能让蛇吃到*/while (food.x%10 != 0){food.x++;}while (food.y%10 != 0){food.y++;}food.addFood = 0; /*画面上有食物*/}if (food.addFood == 0) /*画面上有食物,则显示*/{setcolor(GREEN);rectangle(food.x, food.y, food.x+10, food.y-10);}for (i=snake.joint-1; i>0; i--) /*蛇的每个节往前移动*/{snake.x[i] = snake.x[i-1];snake.y[i] = snake.y[i-1];}/*1,2,3,4 表示右,左,上,下四个方向,来决定蛇头的移动*/switch(snake.direction){case MV_RIGHT: snake.x[0] += 10; break;case MV_LEFT: snake.x[0] -= 10; break;case MV_UP: snake.y[0] -= 10; break;case MV_DOWN: snake.y[0] += 10; break;}/*从蛇的第四节开始判断是否撞到自己,因为蛇头为两节,第三节不可能拐过来*/for (i=3; i<snake.joint; i++){if (snake.x[i]==snake.x[0] && snake.y[i]==snake.y[0]){GameOver(score); /*显示失败*/snake.life = 1; /*蛇死*/break;}}/*判断蛇是否撞到墙壁*/if (snake.x[0]<55 || snake.x[0]>595|| snake.y[0]<55 || snake.y[0]>455){GameOver(score); /*本次游戏结束*/snake.life = 1; /*蛇死*/}/*以上两种判断以后,如果蛇死就跳出内循环,重新开始*/if (snake.life == 1) break;if (snake.x[0]==food.x && snake.y[0]==food.y) /*吃到食物后*/{/*把画面上的食物清除*/setcolor(0);rectangle(food.x, food.y, food.x+10, food.y-10);/*新的一节先放在看不见的位置,下次循环就取前一节的位置*/snake.x[snake.joint] =-20; snake.y[snake.joint] =-20;snake.joint++; /*蛇的身体长一节*/food.addFood = 1; /*画面上需要出现新食物*/score += 10;PrScore(score); /*输出新得分*/}/*画蛇*/setcolor(4);for (i=0; i<snake.joint; i++){rectangle(snake.x[i], snake.y[i],snake.x[i]+10, snake.y[i]-10);}//delay(gamespeed); /*延时控制蛇的速度*/Sleep(gamespeed);/*去除蛇的最后一节*/setcolor(BLUE);rectangle(snake.x[snake.joint-1], snake.y[snake.joint-1],snake.x[snake.joint-1]+10,snake.y[snake.joint-1]-10);} /*end of while(!kbhit)*/if (snake.life == 1) break; /*如果蛇死,则跳出循环*///key = bioskey(0); /*接收按键*/key = getch();/*if (kbhit()){key = getch();}*//*判断按键,是否往相反方向移动,按Esc键则退出*/ /* if (key == ESC) break;else if (key==UP && snake.direction!=4)snake.direction = MV_UP;else if (key==RIGHT && snake.direction!= MV_LEFT)snake.direction = MV_RIGHT;else if (key==LEFT && snake.direction!= MV_RIGHT)snake.direction = MV_LEFT;else if (key==DOWN && snake.direction!= MV_UP)snake.direction = MV_DOWN;*/if (key == ESC) break;else if (key=='W' && snake.direction!=4)snake.direction = MV_UP;else if (key=='D' && snake.direction!= MV_LEFT)snake.direction = MV_RIGHT;else if (key=='A' && snake.direction!= MV_RIGHT)snake.direction = MV_LEFT;else if (key=='S' && snake.direction!= MV_UP)snake.direction = MV_DOWN;} /*end of while(1)*/ }/*结束游戏*/void GameOver(int score){cleardevice();PrScore(score);setcolor(RED);//settextstyle(0, 0, 4);setfont(60, 0,"黑体");outtextxy(200, 200, "GAME OVER");getch();}/*输出成绩*/void PrScore(int score){char str[10];setfillstyle(SOLID_FILL, YELLOW);bar(50, 15, 220, 35);setcolor(6);//settextstyle(0, 0, 2);setfont(16, 0,"宋体");sprintf(str, "score:%d", score);outtextxy(55, 20, str);}。
JAVA小程序—贪吃蛇源代码
JAVA贪吃蛇源代码SnakeGame.javapackage SnakeGame;import javax.swing.*;public class SnakeGame{public static void main( String[] args ){JDialog.setDefaultLookAndFeelDecorated( true ); GameFrame temp = new GameFrame();}}Snake.javapackage SnakeGame;import java.awt.*;import java.util.*;class Snake extends LinkedList{public int snakeDirection = 2;public int snakeReDirection = 4;public Snake(){this.add( new Point( 3, 3 ) );this.add( new Point( 4, 3 ) );this.add( new Point( 5, 3 ) );this.add( new Point( 6, 3 ) );this.add( new Point( 7, 3 ) );this.add( new Point( 8, 3 ) );this.add( new Point( 9, 3 ) );this.add( new Point( 10, 3 ) );}public void changeDirection( Point temp, int direction ) {this.snakeDirection = direction;switch( direction ){case 1://upthis.snakeReDirection = 3;this.add( new Point( temp.x, temp.y - 1 ) );break;case 2://rightthis.snakeReDirection = 4;this.add( new Point( temp.x + 1, temp.y ) );break;case 3://downthis.snakeReDirection = 1;this.add( new Point( temp.x, temp.y + 1 ) );break;case 4://leftthis.snakeReDirection = 2;this.add( new Point( temp.x - 1, temp.y ) );break;}}public boolean checkBeanIn( Point bean ){Point temp = (Point) this.getLast();if( temp.equals( bean ) ){return true;}return false;}public void removeTail(){this.remove( 0 );}public void drawSnake( Graphics g, int singleWidthX, int singleHeightY, int cooPos ) {g.setColor( ColorGroup.COLOR_SNAKE );Iterator snakeSq = this.iterator();while ( snakeSq.hasNext() ){Point tempPoint = (Point)snakeSq.next();this.drawSnakePiece( g, tempPoint.x, tempPoint.y,singleWidthX, singleHeightY, cooPos );}}public void drawSnakePiece( Graphics g, int temp1, int temp2,int singleWidthX, int singleHeightY, int cooPos ){g.fillRoundRect( singleWidthX * temp1 + 1,singleHeightY * temp2 + 1,singleWidthX - 2,singleHeightY - 2,cooPos,cooPos );}public void clearEndSnakePiece( Graphics g, int temp1, int temp2, int singleWidthX, int singleHeightY, int cooPos ){g.setColor( ColorGroup.COLOR_BACK );g.fillRoundRect( singleWidthX * temp1 + 1,singleHeightY * temp2 + 1,singleWidthX - 2,singleHeightY - 2,cooPos,cooPos );}}GameFrame.javapackage SnakeGame;import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.util.*;import java.awt.geom.*;class GameFrame extends JFrame{private Toolkit tempKit;private int horizontalGrid, verticalGrid;private int singleWidthX, singleHeightY;private int cooPos;private Snake mainSnake;private LinkedList eatedBean;{eatedBean = new LinkedList();}private Iterator snakeSq;public javax.swing.Timer snakeTimer;private int direction = 2;private int score;private String info;private Point bean, eatBean;{bean = new Point();}private boolean flag;private JMenuBar infoMenu;private JMenu[] tempMenu;private JMenuItem[] tempMenuItem;private JRadioButtonMenuItem[] levelMenuItem, versionMenuItem;private JLabel scoreLabel;{scoreLabel = new JLabel();}private Graphics2D g;private ImageIcon snakeHead;{snakeHead = new ImageIcon( "LOGO.gif" );}private ConfigMenu configMenu;private boolean hasStoped = true;public GameFrame(){this.tempKit = this.getToolkit();this.setSize( tempKit.getScreenSize() );this.setGrid( 60, 40, 5 );this.getContentPane().setBackground( ColorGroup.COLOR_BACK );this.setUndecorated( true );this.setResizable( false );this.addKeyListener( new KeyHandler() );GameFrame.this.snakeTimer = new javax.swing.Timer( 80, new TimerHandler() ); this.getContentPane().add( scoreLabel, BorderLayout.SOUTH );this.scoreLabel.setFont( new Font( "Fixedsys", Font.BOLD, 15 ) );this.scoreLabel.setText( "Pause[SPACE] - Exit[ESC]" );this.configMenu = new ConfigMenu( this );this.setVisible( true );}public void setGrid( int temp1, int temp2, int temp3 ){this.horizontalGrid = temp1;this.verticalGrid = temp2;this.singleWidthX = this.getWidth() / temp1;this.singleHeightY = this.getHeight() / temp2;this.cooPos = temp3;}private class KeyHandler extends KeyAdapter{public void keyPressed( KeyEvent e ){if( e.getKeyCode() == 27 ){snakeTimer.stop();if( JOptionPane.showConfirmDialog( null, "Are you sure to exit?" ) == 0 ) {System.exit( 0 );}snakeTimer.start();}else if( e.getKeyCode() == 37 && mainSnake.snakeDirection != 2 )//left {direction = 4;}else if( e.getKeyCode() == 39 && mainSnake.snakeDirection != 4 )//right {direction = 2;}else if( e.getKeyCode() == 38 && mainSnake.snakeDirection != 3 )//up {direction = 1;}else if( e.getKeyCode() == 40 && mainSnake.snakeDirection != 1 )//down {direction = 3;}else if( e.getKeyCode() == 32 ){if( !hasStoped ){if( !flag ){snakeTimer.stop();configMenu.setVisible( true );configMenu.setMenuEnable( false );flag = true;}else{snakeTimer.start();configMenu.setVisible( false );configMenu.setMenuEnable( true );flag = false;}}}}}private class TimerHandler implements ActionListener{public synchronized void actionPerformed( ActionEvent e ){Point temp = (Point) mainSnake.getLast();snakeSq = mainSnake.iterator();while ( snakeSq.hasNext() ){Point tempPoint = (Point)snakeSq.next();if( temp.equals( tempPoint ) && snakeSq.hasNext() != false ){snakeTimer.stop();stopGame();JOptionPane.showMessageDialog( null,"Your Score is " + score + "\n\nYou Loss!" );}}System.out.println( temp.x + " " + temp.y );if( (temp.x == 0 && direction == 4) ||(temp.x == horizontalGrid-1 && direction == 2) ||(temp.y == 0 && direction == 1) ||(temp.y == verticalGrid-1 && direction == 3) ){snakeTimer.stop();stopGame();JOptionPane.showMessageDialog( null,"Your Score is " + score + "\n\nYou Loss!" );}if( direction != mainSnake.snakeReDirection ){moveSnake( direction );}mainSnake.drawSnake( getGraphics(), singleWidthX, singleHeightY, cooPos ); drawBeanAndEBean( getGraphics() );}}public void stopGame(){this.hasStoped = true;this.snakeTimer.stop();Graphics2D g = (Graphics2D) GameFrame.this.getGraphics();g.setColor( ColorGroup.COLOR_BACK );super.paint( g );configMenu.setVisible( true );}public void resetGame(){System.gc();this.hasStoped = false;Graphics2D g = (Graphics2D) GameFrame.this.getGraphics();g.setColor( ColorGroup.COLOR_BACK );super.paint( g );this.mainSnake = new Snake();this.createBean( bean );this.eatedBean.clear();mainSnake.drawSnake( getGraphics(), singleWidthX, singleHeightY, cooPos ); this.snakeTimer.start();this.direction = 2;this.score = 0;this.scoreLabel.setText( "Pause[SPACE] - Exit[ESC]" );}private void moveSnake( int direction ){if( mainSnake.checkBeanIn( this.bean ) ){this.score += 100;this.scoreLabel.setText( + " Current Score:" + this.score );this.eatedBean.add( new Point(this.bean) );this.createBean( this.bean );}mainSnake.changeDirection( (Point) mainSnake.getLast(), direction );Point temp = (Point) mainSnake.getFirst();if( eatedBean.size() != 0 ){if( eatedBean.getFirst().equals( temp ) ){eatedBean.remove( 0 );}else{mainSnake.clearEndSnakePiece( getGraphics(), temp.x, temp.y, singleWidthX, singleHeightY, cooPos );mainSnake.removeTail();}}else{mainSnake.clearEndSnakePiece( getGraphics(), temp.x, temp.y, singleWidthX, singleHeightY, cooPos );mainSnake.removeTail();}}private void drawBeanAndEBean( Graphics g ){g.setColor( ColorGroup.COLOR_BEAN );this.drawPiece( g, this.bean.x, this.bean.y );g.setColor( ColorGroup.COLOR_EATEDBEAN );snakeSq = eatedBean.iterator();while ( snakeSq.hasNext() ){Point tempPoint = (Point)snakeSq.next();this.drawPiece( g, tempPoint.x, tempPoint.y );}}private void drawPiece( Graphics g, int x, int y ){g.fillRoundRect( this.singleWidthX * x + 1,this.singleHeightY * y + 1,this.singleWidthX - 2,this.singleHeightY - 2,this.cooPos,this.cooPos );}private void createBean( Point temp ){LP:while( true ){temp.x = (int) (Math.random() * this.horizontalGrid);temp.y = (int) (Math.random() * this.verticalGrid);snakeSq = mainSnake.iterator();while ( snakeSq.hasNext() ){if( snakeSq.next().equals( new Point( temp.x, temp.y ) ) ){continue LP;}}break;}}}ConfigMenu.javapackage SnakeGame;import java.awt.*;import java.awt.event.*;import javax.swing.*;public class ConfigMenu extends JMenuBar{GameFrame owner;JMenu[] menu;JMenuItem[] menuItem;JRadioButtonMenuItem[] speedItem, modelItem, standardItem; private UIManager.LookAndFeelInfo looks[];public ConfigMenu( GameFrame owner ){this.owner = owner;owner.setJMenuBar( this );String[] menu_name = {"Snake Game", "Game Configure", "Game Help"}; menu = new JMenu[menu_name.length];for( int i = 0; i < menu_name.length; i++ ){menu[i] = new JMenu( menu_name[i] );menu[i].setFont( new Font( "Courier", Font.PLAIN, 12 ) );this.add( menu[i] );}String[] menuItem_name = {"Start Game", "Stop Game", "Exit Game", "Game Color","About..."};menuItem = new JMenuItem[menuItem_name.length];for( int i = 0; i < menuItem_name.length; i++ ){menuItem[i] = new JMenuItem( menuItem_name[i] );menuItem[i].setFont( new Font( "Courier", Font.PLAIN, 12 ) ); menuItem[i].addActionListener( new ActionHandler() );}menu[0].add( menuItem[0] );menu[0].add( menuItem[1] );menu[0].addSeparator();menu[0].add( menuItem[2] );menu[1].add( menuItem[3] );menu[2].add( menuItem[4] );String[] inner_menu_name = {"Game Speed", "Window Model", "Game Standard "}; JMenu[] inner_menu = new JMenu[inner_menu_name.length];for( int i = 0; i < inner_menu_name.length; i++ ){inner_menu[i] = new JMenu( inner_menu_name[i] );inner_menu[i].setFont( new Font( "Courier", Font.PLAIN, 12 ) );menu[1].add( inner_menu[i] );}ButtonGroup temp1 = new ButtonGroup();String[] speedItem_name = {"Speed-1", "Speed-2", "Speed-3", "Speed-4", "Speed-5"}; speedItem = new JRadioButtonMenuItem[speedItem_name.length];for( int i = 0; i < speedItem_name.length; i++ ){speedItem[i] = new JRadioButtonMenuItem( speedItem_name[i] );inner_menu[0].add( speedItem[i] );speedItem[i].setFont( new Font( "Courier", Font.PLAIN, 12 ) );speedItem[i].addItemListener( new ItemHandler() );temp1.add( speedItem[i] );}ButtonGroup temp2 = new ButtonGroup();String[] modelItem_name = { "Linux", "Mac", "Windows" };modelItem = new JRadioButtonMenuItem[modelItem_name.length];for( int i = 0; i < modelItem_name.length; i++ ){modelItem[i] = new JRadioButtonMenuItem( modelItem_name[i] );inner_menu[1].add( modelItem[i] );modelItem[i].setFont( new Font( "Courier", Font.PLAIN, 12 ) );modelItem[i].addItemListener( new ItemHandler() );temp2.add( modelItem[i] );}ButtonGroup temp3 = new ButtonGroup();String[] standardItem_name = { "60 * 40", "45 * 30", "30 * 20" };standardItem = new JRadioButtonMenuItem[standardItem_name.length];for( int i = 0; i < standardItem_name.length; i++ ){standardItem[i] = new JRadioButtonMenuItem( standardItem_name[i] );inner_menu[2].add( standardItem[i] );standardItem[i].setFont( new Font( "Courier", Font.PLAIN, 12 ) );standardItem[i].addItemListener( new ItemHandler() );temp3.add( standardItem[i] );}looks = UIManager.getInstalledLookAndFeels();}private class ActionHandler implements ActionListener{public void actionPerformed( ActionEvent e ){if( e.getSource() == menuItem[0] ){owner.resetGame();ConfigMenu.this.setVisible( false );}else if( e.getSource() == menuItem[1] ){owner.stopGame();ConfigMenu.this.setVisible( true );ConfigMenu.this.setMenuEnable( true );}else if( e.getSource() == menuItem[2] ){System.exit( 0 );}else if( e.getSource() == menuItem[3] ){ConfigDialog temp = new ConfigDialog( owner );temp.setVisible( true );}else if( e.getSource() == menuItem[4] ){JOptionPane.showMessageDialog( null, "Sanke Game 2.0 Version!\n\n" + "Author: FinalCore\n\n" );}}}private class ItemHandler implements ItemListener{public void itemStateChanged( ItemEvent e ){for( int i = 0; i < speedItem.length; i++ ){if( e.getSource() == speedItem[i] ){owner.snakeTimer.setDelay( 150 - 30 * i );}}if( e.getSource() == standardItem[0] ){owner.setGrid( 60, 40, 5 );}else if( e.getSource() == standardItem[1] ){owner.setGrid( 45, 30, 10 );}else if( e.getSource() == standardItem[2] ){owner.setGrid( 30, 20, 15 );}for( int i = 0; i < modelItem.length; i++ ){if( e.getSource() == modelItem[i] ){try{UIManager.setLookAndFeel( looks[i].getClassName() ); }catch(Exception ex){}}}}}public void setMenuEnable( boolean temp ){menu[1].setEnabled( temp );}}。
微信小程序之贪吃蛇小游戏开发(完整代码)
微信⼩程序之贪吃蛇⼩游戏开发(完整代码)1:⾸先是index.wxml⽂件代码:<!--index.wxml--><canvas canvas-id='snakeCanvas' style='width:100%;height:100%;background-color:#ccc;'bindtouchstart='canvasStart' bindtouchmove='canvasMove' bindtouchend='canvasEnd'></canvas>2:然后是index.js⽂件代码//index.js//⼿指按下时的坐标var startX = 0;var startY = 0;//⼿指在canvas上移动的坐标var moveX = 0;var moveY = 0;//移动位置跟开始位置差值var X =0;var Y = 0;//⼿指⽅向var direction = null;//蛇移动⽅向var snakeDirection = "right";//⾝体对象(数组)var snakeBodys = [];//⾷物对象(数组)var foods = [];//窗⼝的宽⾼var windowWidth = 0;var windowHeight = 0;//⽤来获取屏幕⼤⼩wx.getSystemInfo({success: function (res) {windowWidth = res.windowWidth;windowHeight = res.windowHeight;}});//蛇头对象var snakeHead = {x: parseInt(Math.random() * (windowWidth-20)),y: parseInt(Math.random() * (windowHeight-20)),color: '#ff0000', //这⾥只能接受16进制没法写red这样w: 20,h: 20,reset:function(){this.x = parseInt(Math.random() * (windowWidth - 20));this.y = parseInt(Math.random() * (windowHeight - 20));}}//⽤于确定是否删除var collideBol = true;Page({canvasStart:function(e){startX = e.touches[0].x;startY = e.touches[0].y;},canvasMove:function(e){moveX = e.touches[0].x;moveY = e.touches[0].y;X = moveX - startX;Y = moveY - startY;if(Math.abs(X) > Math.abs(Y) && X > 0){direction = "right";}else if(Math.abs(X) > Math.abs(Y) && X < 0){direction = "left";}else if (Math.abs(Y) > Math.abs(X) && Y > 0) {direction = "down"; //这⾥很奇怪,是我数学坐标系没学好吗?明明Y轴正坐标是向上才对啊 }else if (Math.abs(Y) > Math.abs(X) && Y < 0) {direction = "top";}},canvasEnd:function(){snakeDirection = direction;},onReady:function(){var context = wx.createContext();//帧数var frameNum = 0;function draw(obj){context.setFillStyle(obj.color);context.beginPath();context.rect(obj.x, obj.y, obj.w, obj.h);context.closePath();context.fill();}//蛇头与⾷物碰撞函数function collide(obj1,obj2){var l1 = obj1.x;var r1 = obj1.w + l1;var t1 = obj1.y;var b1 = obj1.h+t1;var l2 = obj2.x;var r2 = obj2.w + l2;var t2 = obj2.y;var b2 = obj2.h + t2;//这⾥1是蛇头⽅块的上下左右边框 2是⾷物,同样是上下左右//(当蛇头⼜边框撞到⾷物左边框也就是⼤于左边框时就是碰撞了)if(r1>l2 && l1<r2 && b1 > t2 && t1< b2){return true;}else{return false;}}//蛇头与墙壁碰撞函数function collide2(obj1){var l1 = obj1.x;var r1 = obj1.w + l1;var t1 = obj1.y;var b1 = obj1.h + t1;if (l1 <=snakeHead.w || r1 >=windowWidth || t1 <=snakeHead.h || b1 >= windowHeight){ return true;}else{return false;}}function directionSet(){switch (snakeDirection) {case"left":snakeHead.x -= snakeHead.w;break;case"right":snakeHead.x += snakeHead.w;break;case"down":snakeHead.y += snakeHead.h;break;case"top":snakeHead.y -= snakeHead.h;break;}}function animate(){frameNum++;if (frameNum % 20 == 0){//蛇⾝体数组添加⼀个上⼀个的位置(⾝体对象)snakeBodys.push({x: snakeHead.x,y: snakeHead.y,w: 20,h: 20,color: "#00ff00"});if (snakeBodys.length > 4) {//移除不⽤的⾝体位置if (collideBol){snakeBodys.shift();}else{collideBol = true;}}directionSet();}//绘制蛇头draw(snakeHead);if (collide2(snakeHead)) {collideBol = false;snakeHead.reset();snakeBodys=[];draw(snakeHead);}//绘制蛇⾝for(var i=0;i<snakeBodys.length;i++){var snakeBody = snakeBodys[i];draw(snakeBody);}//绘制⾷物for(var i=0;i<foods.length;i++){var foodObj = foods[i];draw(foodObj);if (collide(snakeHead,foodObj)){//console.log("撞上了");collideBol = false;foodObj.reset();}}wx.drawCanvas({canvasId:"snakeCanvas",actions:context.getActions()});requestAnimationFrame(animate);}function rand(min,max){return parseInt(Math.random()*(max-min))+min;}//构造⾷物对象function Food() {var w = rand(10,20);this.w = w;this.h = w;this.x = rand(this.w, windowWidth - this.w);this.y = rand(this.h, windowHeight - this.h);this.color = "rgb("+rand(0,255)+","+rand(0,255)+","+rand(0,255)+")";//内部⽅法(重置⾷物位置颜⾊)this.reset = function (){this.x = rand(0,windowWidth);this.y = rand(0,windowHeight);this.color = "rgb(" + rand(0, 255) + "," + rand(0, 255) + "," + rand(0, 255) + ")"; }}for (var i = 0; i < 20; i++) {var foodObj = new Food();foods.push(foodObj);}animate();}})。
C语言贪吃蛇源代码
C语言贪吃蛇源代码 TTA standardization office【TTA 5AB- TTAK 08- TTA 2C】#include<stdio.h>#include<process.h>#include<windows.h>#include<conio.h>#include<time.h>#include<stdlib.h>#define WIDTH 40#define HEIGH 12enum direction{//方向LEFT,RIGHT,UP,DOWN};struct Food{//食物int x;int y;};struct Node{//画蛇身int x;int y;struct Node *next;};struct Snake{//蛇属性int lenth;//长度enum direction dir;//方向};struct Food *food; //食物struct Snake *snake;//蛇属性struct Node *snode,*tail;//蛇身int SPEECH=200;int score=0;//分数int smark=0;//吃食物标记int times=0;int STOP=0;void Initfood();//产生食物void Initsnake();//构造snakevoid Eatfood();//头部前进void Addnode(int x, int y);//增加蛇身void display(struct Node *shead);//显示蛇身坐标void move();//蛇移动void draw();//画蛇void Homepage();//主页void keybordhit();//监控键盘按键void Addtail();//吃到食物void gotoxy(int x, int y)//定位光标{COORD pos;pos.X = x - 1;pos.Y = y - 1;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos); }void Initsnake()//构造snake{int i;snake=(struct Snake*)malloc(sizeof(struct Snake));tail=(struct Node*)malloc(sizeof(struct Node));food = (struct Food*)malloc(sizeof(struct Food));snake->lenth=5;//初始长度 5snake->dir=RIGHT;//初始蛇头方向右for(i=2;i<=snake->lenth 2;i )//增加 5 个结点{Addnode(i,2);}}void Initfood()//产生食物{struct Node *p=snode;int mark=1;srand((unsigned)time(NULL));//以时间为种子产生随机数while(1){food->x=rand()%(WIDTH-2) 2;//食物X坐标food->y=rand()%(HEIGH-2) 2;//食物Y坐标while(p!=NULL){if((food->x==p->x)&&(food->y==p->y))//如果食物产生在蛇身上{//则重新生成食物mark=0;//食物生成无效break;}p=p->next;if(mark==1)//如果食物不在蛇身上,生成食物,否则重新生成食物{gotoxy(food->x,food->y);printf("%c",3);break;}mark=1;p=snode;}}void move()//移动{struct Node *q, *p=snode;if(snake->dir==RIGHT){Addnode(p->x 1,p->y);if(smark==0){while(p->next!=NULL){q=p;p=p->next;}q->next=NULL;free(p);}}if(snake->dir==LEFT){Addnode(p->x-1,p->y);if(smark==0){while(p->next!=NULL){q=p;p=p->next;}q->next=NULL;free(p);}if(snake->dir==UP){Addnode(p->x,p->y-1);if(smark==0){while(p->next!=NULL){q=p;p=p->next;}q->next=NULL;free(p);}}if(snake->dir==DOWN){Addnode(p->x,p->y 1);if(smark==0){while(p->next!=NULL){q=p;p=p->next;}q->next=NULL;free(p);}}}void Addnode(int x, int y)//增加蛇身{struct Node *newnode=(struct Node *)malloc(sizeof(struct Node)); struct Node *p=snode;newnode->next=snode;newnode->x=x;newnode->y=y;snode=newnode;//结点加到蛇头if(x<2||x>=WIDTH||y<2||y>=HEIGH)//碰到边界{STOP=1;gotoxy(10,19);printf("撞墙,游戏结束,任意键退出!\n");//失败_getch();free(snode);//释放内存free(snake);exit(0);}while(p!=NULL)//碰到自身{if(p->next!=NULL)if((p->x==x)&&(p->y==y)){STOP=1;gotoxy(10,19);printf("撞到自身,游戏结束,任意键退出!\n");//失败_getch();free(snode);//释放内存free(snake);exit(0);}p=p->next;}}void Eatfood()//吃到食物{Addtail();score ;}void Addtail()//增加蛇尾{struct Node *newnode=(struct Node *)malloc(sizeof(struct Node)); struct Node *p=snode;tail->next=newnode;newnode->x=50;newnode->y=20;newnode->next=NULL;//结点加到蛇头tail=newnode;//新的蛇尾}void draw()//画蛇{struct Node *p=snode;int i,j;while(p!=NULL){gotoxy(p->x,p->y);printf("%c",2);tail=p;p=p->next;}if(snode->x==food->x&&snode->y==food->y)//蛇头坐标等于食物坐标{smark=1;Eatfood();//增加结点Initfood();//产生食物}if(smark==0){gotoxy(tail->x,tail->y);//没吃到食物清除之前的尾结点printf("%c",' ');//如果吃到食物,不清楚尾结点}else{times=1;}if((smark==1)&&(times==1)){gotoxy(tail->x,tail->y);//没吃到食物清除之前的尾结点printf("%c",' ');//如果吃到食物,不清楚尾结点smark=0;}gotoxy(50,12);printf("食物: %d,%d",food->x,food->y);gotoxy(50,5);printf("分数: %d",score);gotoxy(50,7);printf("速度: %d",SPEECH);gotoxy(15,14);printf("按o键加速");gotoxy(15,15);printf("按p键减速");gotoxy(15,16);printf("按空格键暂停");}void HideCursor()//隐藏光标{CONSOLE_CURSOR_INFO cursor_info = {1, 0};SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info); }void Homepage()//绘主页{int x,y;HideCursor();//隐藏光标printf("----------------------------------------\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("----------------------------------------\n");gotoxy(5,13);printf("任意键开始游戏!按W.A.S.D控制方向");_getch();Initsnake();Initfood();gotoxy(5,13);printf(" ");}void keybordhit()//监控键盘{char ch;if(_kbhit()){ch=getch();switch(ch){case 'W':case 'w':if(snake->dir==DOWN)//如果本来方向是下,而按相反方向无效{break;}elsesnake->dir=UP;break;case 'A':case 'a':if(snake->dir==RIGHT)//如果本来方向是右,而按相反方向无效{break;}elsesnake->dir=LEFT;break;case 'S':case 's':if(snake->dir==UP)//如果本来方向是上,而按相反方向无效{break;}elsesnake->dir=DOWN;break;case 'D':case 'd':if(snake->dir==LEFT)//如果本来方向是左,而按相反方向无效{break;}elsesnake->dir=RIGHT;break;case 'O':case 'o':if(SPEECH>=150)//速度加快{SPEECH=SPEECH-50;}break;case 'P':case 'p':if(SPEECH<=400)//速度减慢{SPEECH=SPEECH 50;}break;case ' '://暂停gotoxy(15,18);printf("游戏已暂停,按任意键恢复游戏"); system("pause>nul");gotoxy(15,18);printf(" "); break;default:break;}}}int main(void)//程序入口{Homepage();while(!STOP){keybordhit();//监控键盘按键move();//蛇的坐标变化draw();//蛇的重绘Sleep(SPEECH);//暂时挂起线程}return 0;}。
贪吃蛇游戏代码(C语言编写)
贪吃蛇游戏代码(C语言编写)#include "graphics.h"#include "stdio.h"#define MAX 200#define MAXX 30#define MAXY 30#define UP 18432#define DOWN 20480#define LEFT 19200#define RIGHT 19712#define ESC 283#define ENTER 7181#define PAGEUP 18688#define PAGEDOWN 20736#define KEY_U 5749#define KEY_K 9579#define CTRL_P 6512#define TRUE 1#define FALSE 0#define GAMEINIT 1#define GAMESTART 2#define GAMEHAPPY 3#define GAMEOVER 4struct SPlace{int x;int y;int st;} place[MAX];int speed;int count;int score;int control;int head;int tear;int x,y;int babyx,babyy;int class;int eat;int game;int gamedelay[]={5000,4000,3000,2000,1000,500,250,100}; int gamedelay2[]={1000,1};static int hitme=TRUE,hit = TRUE; void init(void);void nextstatus(void);void draw(void);void init(void){int i;for(i=0;i<max;i++)< p="">{place[i].x = 0;place[i].y = 0;place[i].st = FALSE;}place[0].st = TRUE;place[1].st = TRUE;place[1].x = 1;speed = 9;count = 0;score = 0;control = 4;head = 1;tear = 0;x = 1;y = 0;babyx = rand()%MAXX;babyy = rand()%MAXY;eat = FALSE;game = GAMESTART;}void nextstatus(void){int i;int exit;int xx,yy;xx = x;yy = y;switch(control){case 1: y--; yy = y-1; break;case 2: y++; yy = y+1; break;case 3: x--; xx = x-1; break;case 4: x++; xx = x+1; break;}hit = TRUE;if ( ((control == 1) || (control ==2 )) && ( (y < 1) ||(y >= MAXY-1)) || (((control == 3) || (control == 4)) && ((x < 1) ||(x >= MAXX-1) ) ) ){}if ( (y < 0) ||(y >= MAXY) ||(x < 0) ||(x >= MAXX) ){game = GAMEOVER;control = 0;return;}for (i = 0; i < MAX; i++){if ((place[i].st) &&(x == place[i].x) &&(y == place[i].y) ){game = GAMEOVER;control = 0;return;}if ((place[i].st) &&(xx == place[i].x) &&(yy == place[i].y) ){hit = FALSE;goto OUT;}}OUT:if ( (x == babyx) && (y == babyy) ) {count ++;score += (1+class) * 10;}head ++;if (head >= MAX) head = 0;place[head].x = x;place[head].y = y;place[head].st= TRUE;if (eat == FALSE){place[tear].st = FALSE;tear ++;if (tear >= MAX) tear = 0;}else{eat = FALSE;exit = TRUE;while(exit){babyx = rand()%MAXX;babyy = rand()%MAXY;exit = FALSE;for( i = 0; i< MAX; i++ )if( (place[i].st)&&( place[i].x == babyx) && (place[i].y == babyy))exit ++;}}if (head == tear) game = GAMEHAPPY;}void draw(void){char temp[50];int i,j;for (i = 0; i < MAX; i++ ){setfillstyle(1,9);if (place[i].st)bar(place[i].x*15+1,place[i].y*10+1,place[i].x*15+14,place[i]. y*10+9);}setfillstyle(1,4);bar(babyx*15+1,babyy*10+1,babyx*15+14,babyy*10+9);setcolor(8);setfillstyle(1,8);bar(place[head].x*15+1,place[head].y*10+1,place[head].x*1 5+14,place[head].y*10+9); /* for( i = 0; i <= MAXX; i++ ) line( i*15,0, i*15, 10*MAXY);for( j = 0; j <= MAXY; j++ )line( 0, j*10, 15*MAXX, j*10); */rectangle(0,0,15*MAXX,10*MAXY);sprintf(temp,"Count: %d",count);settextstyle(1,0,2);setcolor(8);outtextxy(512,142,temp);setcolor(11);outtextxy(510,140,temp);sprintf(temp,"1P: %d",score);settextstyle(1,0,2);setcolor(8);outtextxy(512,102,temp); setcolor(12);outtextxy(510,100,temp); sprintf(temp,"Class: %d",class); setcolor(8);outtextxy(512,182,temp); setcolor(11);outtextxy(510,180,temp);}main(){int pause = 0;char temp[50];int d,m;int key;int p;static int keydown = FALSE; int exit = FALSE;int stchange = 0;d = VGA;m = VGAMED;initgraph( &d, &m, "" ); setbkcolor(3);class = 3;init();p = 1;while(!exit){if (kbhit()){key = bioskey(0);switch(key){case UP: if( (control != 2)&& !keydown)control = 1;keydown = TRUE;break;case DOWN: if( (control != 1)&& !keydown)control = 2;keydown = TRUE;break;case LEFT: if( (control != 4)&& !keydown)control = 3;keydown = TRUE;break;case RIGHT: if( (control != 3)&& !keydown)control = 4;keydown = TRUE;break;case ESC: exit = TRUE;break;case ENTER: init();break;case PAGEUP: class --; if (class<0) class = 0; break;case PAGEDOWN: class ++;if (class>7) class = 7; break;case KEY_U: if( ( (control ==1) ||(control ==2))&& !keydown) control = 3;else if(( (control == 3) || (control == 4))&& !keydown)control = 1;keydown = TRUE;break;case KEY_K: if( ( (control ==1) ||(control ==2))&& !keydown) control = 4;else if(( (control == 3) || (control == 4))&& !keydown)control = 2;keydown = TRUE;break;case CTRL_P:pause = 1 - pause; break;}}stchange ++ ;putpixel(0,0,0);if (stchange > gamedelay[class] + gamedelay2[hit]){stchange = 0;keydown = FALSE;p = 1 - p;setactivepage(p);cleardevice();if (!pause)nextstatus();else{settextstyle(1,0,4);setcolor(12);outtextxy(250,100,"PAUSE");}draw();if(game==GAMEOVER){settextstyle(0,0,6);setcolor(8);outtextxy(101,101,"GAME OVER"); setcolor(15);outtextxy(99,99,"GAME OVER"); setcolor(12);outtextxy(100,100,"GAME OVER"); sprintf(temp,"Last Count: %d",count); settextstyle(0,0,2);outtextxy(200,200,temp);}if(game==GAMEHAPPY){settextstyle(0,0,6);setcolor(12);outtextxy(100,300,"YOU WIN"); sprintf(temp,"Last Count: %d",count); settextstyle(0,0,2);outtextxy(200,200,temp);}setvisualpage(p);}}closegraph();}</max;i++)<>。
贪吃蛇源代码
#include<stdio.h>#include <stdlib.h>#include <windows.h>#include<time.h>#include <conio.h>struct snake{int x, y;snake *next;};snake *head;static int direction=1;//1,2,3,4分别代表左上右下int food_x, food_y;int foodflag = false;int count = 0;int manu();void init();int gamerun();//游戏开始void move();//移动void printframe();//画界面void paint();//打印蛇身int check();//检测int food();//产生实物int setposition(int x, int y);//设置光标位置int check(){if (head->x == 2 || head->x == 63 || head->y == 1 || head->y == 25) return 0;elsereturn 1;}int food(){srand(unsigned int(time(0)));if (!foodflag){food_x = rand() % 60 + 3;food_y = rand() % 23 + 2;foodflag = true;}setposition(food_x, food_y);printf("*");return 0;}int setposition(int x,int y){HANDLE hOut;hOut = GetStdHandle(STD_OUTPUT_HANDLE);COORD pos = { x-1, y-1 }; /* 光标的起始位(第1列,第3行)0是第1列2是第3行*/SetConsoleCursorPosition(hOut, pos);return 0;}void printframe(){HANDLE consolehwnd;//创建句柄consolehwnd =GetStdHandle(STD_OUTPUT_HANDLE);//实例化句柄SetConsoleTextAttribute(consolehwnd, BACKGROUND_GREEN );//设置字体颜色for (int i = 1; i <40;i++){printf(" ");}setposition(1, 25);for (int i = 1; i < 41; i++){printf(" ");}for (int i = 1; i < 25; i++){setposition(1, i);printf(" ");}for (int i = 1; i < 25; i++){setposition(79, i);printf(" ");}for (int i = 1; i < 25;i++){setposition(63, i);printf(" ");}setposition(67, 5);SetConsoleTextAttribute(consolehwnd, 0x07);//设置字体颜色printf("你的分数:%d\n",count);setposition(66, 8);printf("暂停请按回车");}void init(){snake *temp1, *temp2;head = new snake;temp1 = new snake;temp2 = new snake;head->x = 26;head->y = 12;head->next = temp1;temp1->x = 27;temp1->y = 12;temp1->next = temp2;temp2->x = 28;temp2->y = 12;temp2->next = NULL;}void paint(){snake *p;p = head;while (p){setposition(p->x, p->y);printf("*");p = p->next;}}void move(){snake * newHead;newHead = new snake;newHead->next = head;if (direction==1){newHead->x = head->x - 1;newHead->y = head->y;}if (direction == 2){newHead->x = head->x ;newHead->y = head->y-1;}if (direction == 3){newHead->x = head->x +1;newHead->y = head->y;}if (direction == 4){newHead->x = head->x;newHead->y = head->y+1;}head = newHead;}int gamerun(){char c;setposition(30, 13);printf("按任意键开始");_getch();system("cls");printframe();init();while (1){food();paint();if (_kbhit()){c = _getch();if (c ==-32){c = _getch();if (c ==75 && direction != 3){direction = 1;}if (c == 72 && direction != 4){direction = 2;}if (c == 77 && direction != 1){direction = 3;}if (c == 80 && direction != 2){direction = 4;}}if (c==' '){c = _getch();}if ((c == 'a' || c == 'A')&&direction !=3){direction = 1;}if ((c == 'w' || c == 'W')&&direction != 4){direction = 2;}if ((c == 'd' || c == 'D')&&direction != 1){direction = 3;}if ((c == 's' || c == 'S')&&direction != 2){direction = 4;}}move();paint();if (head->x!=food_x||head->y!=food_y) {snake *t;t = head;while (t->next->next){t = t->next;}setposition(t->next->x, t->next->y);printf(" ");delete t->next;t->next = NULL;}else{foodflag = false;count++;HANDLE consolehwnd;//创建句柄consolehwnd = GetStdHandle(STD_OUTPUT_HANDLE);//实例化句柄setposition(67, 5);SetConsoleTextAttribute(consolehwnd, 0x07);//设置字体颜色printf("你的分数:%d\n", count);}if (!check()){system("cls");setposition(20, 10);printf("你的最终分数为:%d", count);break;}Sleep(200);}return 1;}int main(){gamerun();_getch();return 0;}。
贪吃蛇游戏代码
贪吃蛇游戏代码贪吃蛇是一个经典的小游戏,可以在很多平台和设备上找到。
如果你想自己开发一个贪吃蛇游戏,这里有一个简单的Python版本,使用pygame库。
首先,确保你已经安装了pygame库。
如果没有,可以通过pip来安装:bash复制代码pip install pygame然后,你可以使用以下代码来创建一个简单的贪吃蛇游戏:python复制代码import pygameimport random# 初始化pygamepygame.init()# 颜色定义WHITE = (255, 255, 255)RED = (213, 50, 80)GREEN = (0, 255, 0)BLACK = (0, 0, 0)# 游戏屏幕大小WIDTH, HEIGHT = 640, 480screen = pygame.display.set_mode((WIDTH, HEIGHT))pygame.display.set_caption("贪吃蛇")# 时钟对象来控制帧速度clock = pygame.time.Clock()# 蛇的初始位置和大小snake = [(5, 5), (6, 5), (7, 5)]snake_dir = (1, 0)# 食物的初始位置food = (10, 10)food_spawn = True# 游戏主循环running = Truewhile running:for event in pygame.event.get():if event.type == pygame.QUIT:running = Falseelif event.type == pygame.KEYDOWN:if event.key == pygame.K_UP:snake_dir = (0, -1)elif event.key == pygame.K_DOWN:snake_dir = (0, 1)elif event.key == pygame.K_LEFT:snake_dir = (-1, 0)elif event.key == pygame.K_RIGHT:snake_dir = (1, 0)# 检查蛇是否吃到了食物if snake[0] == food:food_spawn = Falseelse:del snake[-1]if food_spawn is False:food = (random.randint(1, (WIDTH // 20)) * 20, random.randint(1, (HEIGHT // 20)) * 20)food_spawn = Truenew_head = ((snake[0][0] + snake_dir[0]) % (WIDTH // 20), (snake[0][1] + snake_dir[1]) % (HEIGHT // 20))snake.insert(0, new_head)# 检查游戏结束条件if snake[0] in snake[1:]:running = False# 清屏screen.fill(BLACK)# 绘制蛇for segment in snake:pygame.draw.rect(screen, GREEN, (segment[0], segment[1], 20, 20))# 绘制食物pygame.draw.rect(screen, RED, (food[0], food[1], 20, 20))# 更新屏幕显示pygame.display.flip()# 控制帧速度clock.tick(10)pygame.quit()这个代码实现了一个基本的贪吃蛇游戏。
贪吃蛇游戏代码
贪吃蛇游戏可以使用Python的pygame库来实现。
以下是一份完整的贪吃蛇游戏代码:```pythonimport pygameimport sysimport random#初始化pygamepygame.init()#设置屏幕尺寸和标题screen_size=(800,600)screen=pygame.display.set_mode(screen_size)pygame.display.set_caption('贪吃蛇')#设置颜色white=(255,255,255)black=(0,0,0)#设置蛇和食物的大小snake_size=20food_size=20#设置速度clock=pygame.time.Clock()speed=10snake_pos=[[100,100],[120,100],[140,100]]snake_speed=[snake_size,0]food_pos=[random.randrange(1,(screen_size[0]//food_size))*food_size,random.randrange(1,(screen_size[1]//food_size))*food_size]food_spawn=True#游戏主循环while True:for event in pygame.event.get():if event.type==pygame.QUIT:pygame.quit()sys.exit()keys=pygame.key.get_pressed()for key in keys:if keys[pygame.K_UP]and snake_speed[1]!=snake_size:snake_speed=[0,-snake_size]if keys[pygame.K_DOWN]and snake_speed[1]!=-snake_size:snake_speed=[0,snake_size]if keys[pygame.K_LEFT]and snake_speed[0]!=snake_size:snake_speed=[-snake_size,0]if keys[pygame.K_RIGHT]and snake_speed[0]!=-snake_size:snake_speed=[snake_size,0]snake_pos[0][0]+=snake_speed[0]snake_pos[0][1]+=snake_speed[1]#碰撞检测if snake_pos[0][0]<0or snake_pos[0][0]>=screen_size[0]or\snake_pos[0][1]<0or snake_pos[0][1]>=screen_size[1]or\snake_pos[0]in snake_pos[1:]:pygame.quit()sys.exit()#蛇吃食物if snake_pos[0]==food_pos:food_spawn=Falseelse:snake_pos.pop()if not food_spawn:food_pos=[random.randrange(1,(screen_size[0]//food_size))*food_size,random.randrange(1,(screen_size[1]//food_size))*food_size] food_spawn=True#绘制screen.fill(black)for pos in snake_pos:pygame.draw.rect(screen,white,pygame.Rect(pos[0],pos[1],snake_size,snake_size)) pygame.draw.rect(screen,white,pygame.Rect(food_pos[0],food_pos[1],food_size, food_size))pygame.display.flip()clock.tick(speed)```这个代码实现了一个简单的贪吃蛇游戏,包括基本的游戏循环、蛇的移动、食物的生成和碰撞检测。
贪吃蛇游戏源代码
import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.util.*;public class GreedSnake implements KeyListener{JFrame mainFrame;Canvas paintCanvas;JLabel labelScore;SnakeModel snakeModel = null;public static final int canvasWidth = 200;public static final int canvasHeight = 300;public static final int nodeWidth = 10;public static final int nodeHeight = 10;public GreedSnake() {mainFrame = new JFrame("GreedSnake");Container cp = mainFrame.getContentPane();labelScore = new JLabel("Score:");cp.add(labelScore, BorderLayout.NORTH);paintCanvas = new Canvas();paintCanvas.setSize(canvasWidth+1,canvasHeight+1);paintCanvas.addKeyListener(this);cp.add(paintCanvas, BorderLayout.CENTER);JPanel panelButtom = new JPanel();panelButtom.setLayout(new BorderLayout());JLabel labelHelp;labelHelp = new JLabel("PageUp, PageDown for speed;", JLabel.CENTER);panelButtom.add(labelHelp, BorderLayout.NORTH);labelHelp = new JLabel("ENTER or R or S for start;", JLabel.CENTER); panelButtom.add(labelHelp, BorderLayout.CENTER);labelHelp = new JLabel("SPACE or P for pause",JLabel.CENTER);panelButtom.add(labelHelp, BorderLayout.SOUTH);cp.add(panelButtom,BorderLayout.SOUTH);mainFrame.addKeyListener(this);mainFrame.pack();mainFrame.setResizable(false);mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainFrame.setVisible(true);begin();}public void keyPressed(KeyEvent e){int keyCode = e.getKeyCode();if (snakeModel.running)switch(keyCode){case KeyEvent.VK_UP:snakeModel.changeDirection(SnakeModel.UP);break;case KeyEvent.VK_DOWN:snakeModel.changeDirection(SnakeModel.DOWN);break;case KeyEvent.VK_LEFT:snakeModel.changeDirection(SnakeModel.LEFT);break;case KeyEvent.VK_RIGHT:snakeModel.changeDirection(SnakeModel.RIGHT);break;case KeyEvent.VK_ADD:case KeyEvent.VK_PAGE_UP:snakeModel.speedUp();break;case KeyEvent.VK_SUBTRACT:case KeyEvent.VK_PAGE_DOWN:snakeModel.speedDown();break;case KeyEvent.VK_SPACE:case KeyEvent.VK_P:snakeModel.changePauseState();break;default:}if (keyCode == KeyEvent.VK_R ||keyCode == KeyEvent.VK_S ||keyCode == KeyEvent.VK_ENTER){snakeModel.running = false;begin();}}public void keyReleased(KeyEvent e){}public void keyTyped(KeyEvent e){}void repaint(){Graphics g = paintCanvas.getGraphics();//draw backgroundg.setColor(Color.WHITE);g.fillRect(0,0,canvasWidth,canvasHeight);// draw the snakeg.setColor(Color.BLACK);LinkedList na = snakeModel.nodeArray;Iterator it = na.iterator();while(it.hasNext()){Node n = (Node)it.next();drawNode(g,n);}// draw the foodg.setColor(Color.RED);Node n = snakeModel.food;drawNode(g,n);updateScore();}private void drawNode(Graphics g, Node n){ g.fillRect(n.x*nodeWidth,n.y*nodeHeight,nodeWidth-1,nodeHeight-1);}public void updateScore(){String s = "Score: " + snakeModel.score; labelScore.setText(s);}void begin(){if (snakeModel == null || !snakeModel.running){snakeModel = new SnakeModel(this,canvasWidth/nodeWidth,canvasHeight/nodeHeight);(new Thread(snakeModel)).start();}}public static void main(String[] args){GreedSnake gs = new GreedSnake();}}/////////////////////////////////////////////////// // Îļþ2///////////////////////////////////////////////////import java.util.*;import javax.swing.*;class SnakeModel implements Runnable{GreedSnake gs;boolean[][] matrix;LinkedList nodeArray = new LinkedList();Node food;int maxX;int maxY;int direction = 2;boolean running = false;int timeInterval = 200;double speedChangeRate = 0.75;boolean paused = false;int score = 0;int countMove = 0;// UP and DOWN should be even// RIGHT and LEFT should be oddpublic static final int UP = 2;public static final int DOWN = 4;public static final int LEFT = 1;public static final int RIGHT = 3;public SnakeModel(GreedSnake gs, int maxX, int maxY){ this.gs = gs;this.maxX = maxX;this.maxY = maxY;// initial matirxmatrix = new boolean[maxX][];for(int i=0; i<maxX; ++i){matrix = new boolean[maxY];Arrays.fill(matrix,false);}// initial the snakeint initArrayLength = maxX > 20 ? 10 : maxX/2;for(int i = 0; i < initArrayLength; ++i){int x = maxX/2+i;int y = maxY/2;nodeArray.addLast(new Node(x, y));matrix[x][y] = true;}food = createFood();matrix[food.x][food.y] = true;}public void changeDirection(int newDirection){if (direction % 2 != newDirection % 2){direction = newDirection;}}public boolean moveOn(){Node n = (Node)nodeArray.getFirst();int x = n.x;int y = n.y;switch(direction){case UP:y--;break;case DOWN:y++;break;case LEFT:x--;break;case RIGHT:x++;break;}if ((0 <= x && x < maxX) && (0 <= y && y < maxY)){if (matrix[x][y]){if(x == food.x && y == food.y){nodeArray.addFirst(food);int scoreGet = (10000 - 200 * countMove) / timeInterval; score += scoreGet > 0? scoreGet : 10;countMove = 0;food = createFood();matrix[food.x][food.y] = true;return true;}elsereturn false;}else{nodeArray.addFirst(new Node(x,y));matrix[x][y] = true;n = (Node)nodeArray.removeLast();matrix[n.x][n.y] = false;countMove++;return true;}}。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
}
tail=(tail+1)%80;
qipan[zuobiao[0][head]][zuobiao[1][head]]='*';
head=(head+1)%80;
zuobiao[0][head]=x;
zuobiao[1][head]=y;
qipan[zuobiao[0][head]][zuobiao[1][head]]='#';
/*处理棋盘*/
char qipan[20][80];//定义棋盘
for(i=0;i<20;i++)
for(j=0;j<80;j++)
qipan[i][j]=' ';//初始化棋盘
for(i=0;i<80;i++)
qipan[0][i]='_';
for(i=0;i<20;i++)
qipan[i][0]='|';
printf("Input your game speed,please.(e.g.300)\n");
scanf("%d",&gamespeed);
while(direction!='q')
{
system("cls");
for(i=0;i<20;i++)//打印出棋盘
for(j=0;j<80;j++)
direction='q';
system("cls");
printf("GAME OVER!\n");
}
}
return 0;
}
int change(char qipan[20][80],int zuobiao[2][80],char direction)
{
int x,y;
if(direction==72)
printf("%c",qipan[i][j]);
timeover=1;
start=clock();
while(!kbhit()&&(timeover=clock()-start<=gamespeed));
if(timeover)
{
getch();
direction=getch();
}
else
direction=direction;
if(direction==77)
x=zuobiao[0][head];y=zuobiao[1][head]+1;
if(x==0||x==18||y==78||y==0)
return 0;
if(qipan[x][y]!=' ')
return 0;
qipan[zuobiao[0][tail]][zuobiao[1][tail]]=' ';
if(!(direction==72||direction==80||direction==75||direction==77))
{
return 0;
system("cls");
printf("GAME OVER!\n");
}
if(!change(qipan,zuobiao,direction))
{
int gamespeed;
int timer qipan[20][80],int zuobiao[2][80],char direction);
zuobiao[0][tail]=1;zuobiao[1][tail]=1;zuobiao[0][1]=1;zuobiao[1][1]=2;zuobiao[0][2]=1;zuobiao[1][2]=3;zuobiao[0][head]=1;zuobiao[1][head]=4;
/*贪吃蛇*/
#include<stdio.h>
#include<time.h>
#include<conio.h>
#include<stdlib.h>
int head=3 ,tail=0;
int main()
{
int i,j,k=0;
int zuobiao[2][80];
long start;
int direction=77;
for(i=0;i<20;i++)
qipan[i][79]='|';
for(i=0;i<80;i++)
qipan[19][i]='_';
qipan[1][1]=qipan[1][2]=qipan[1][3]='*';//初始化蛇的位置
qipan[1][4]='#';
printf("This is a game of a SNAKE.\nGOOD LUCK TO YOU !\n");
x=zuobiao[0][head]-1;y=zuobiao[1][head];
if(direction==80)
x=zuobiao[0][head]+1;y=zuobiao[1][head];
if(direction==75)
x=zuobiao[0][head];y=zuobiao[0][head]-1;