汇编语言写的贪吃蛇小游戏源代码
贪吃蛇小游戏源代码
}
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");
贪吃蛇游戏安卓源代码
附录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;}}。
简单的贪吃蛇游戏代码示例
《简单的贪吃蛇游戏代码示例,使用Python语言和pygame库实现:》import pygameimport random# 初始化pygamepygame.init()# 设置窗口大小和标题screen_width = 640screen_height = 480screen = pygame.display.set_mode((screen_width, screen_height))pygame.display.set_caption("Snake Game")# 设置颜色white = (255, 255, 255)black = (0, 0, 0)red = (255, 0, 0)# 定义蛇的初始位置和长度snake_pos = [[100, 50], [90, 50], [80, 50]]snake_len = len(snake_pos)# 定义游戏结束标志和得分game_over = Falsescore = 0# 定义蛇的移动方向和速度direction = "right"speed = 10# 定义食物的初始位置和大小food_pos = [random.randint(1, screen_width-1), random.randint(1, screen_height-1)]food_size = 20# 定义边界和障碍物的大小和位置border = 10obstacle_size = 200obstacle_pos = [random.randint(border, screen_width-border), random.randint(border, screen_height-border)]obstacle_speed = 2# 游戏循环while not game_over:# 处理事件for event in pygame.event.get():if event.type == pygame.QUIT:game_over = Trueelif event.type == pygame.KEYDOWN:if event.key == pygame.K_UP and direction != "down":direction = "up"elif event.key == pygame.K_DOWN and direction != "up":direction = "down"elif event.key == pygame.K_LEFT and direction != "right":direction = "left"elif event.key == pygame.K_RIGHT and direction != "left":direction = "right"elif event.type == pygame.KEYUP:if event.key == pygame.K_UP and direction == "up":direction = "right" if random.randint(0, 1) else "left"elif event.key == pygame.K_DOWN and direction == "down": direction = "right" if random.randint(0, 1) else "left"elif event.key == pygame.K_LEFT and direction == "left":direction = "up" if random.randint(0, 1) else "down"elif event.key == pygame.K_RIGHT and direction == "right": direction = "up" if random.randint(0, 1) else "down"。
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;
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类是保存每个位置的信息。
汇编贪吃蛇课程设计附源码
目录1程序简介 (1)2程序设计 (1)2.1程序分析程序初始化: (1)2.2游戏流程 (2)2.3程序流程图 (3)2.4数据定义及重要函数 (4)3系统测试及改进 (12)3.1程序测试 (12)3.2系统改进 (14)4源码 (15)1程序简介贪吃蛇游戏是一个经典小游戏,在封闭的围墙里面,通过键盘的上下左右控制蛇的方向,寻找随机出现的食物。
蛇头撞到食物,则食物被吃掉,蛇身体长度+1,同时记100分,蛇的身子越吃越长,身子越长玩的难度就越大,如果蛇在移动中撞到墙或身体交叉蛇头撞倒自己身体游戏结束。
2程序设计2.1程序分析程序初始化:加载在数据段定义好相关的提示信息以及储存蛇身的数组,主要是如何开始游戏的提示信息蛇的移动:程序的关键是表示蛇的图形以及蛇的移动。
一开始用4个小矩形表示蛇的身体,每吃一个食物,身体增加一个矩形,移动时必须从蛇头开始,所以蛇不能向相反方向移动,蛇头的前进方向也就是蛇的方向,蛇尾不能改作蛇头。
设置一个等待时间,如果不按任何按键,蛇在当前方向上前进。
按了有效的方向键后,先确定蛇头的位置然后蛇身体随着蛇头移动,图形的实现是从蛇头的新位置开始画出蛇,这时由于没有清屏的原因,原来蛇的位置和新蛇的位置相差一个单位,所以看起来蛇会多一节身体。
食物的产生:通过一系列运算产生在要求范围内的的随机数,此时的随机数便是随即点,可以通过产生的随即点的坐标画出随即点,也就是食物了。
蛇吃食物:蛇头的位置可以与随即点的位置坐标判断,如果此时两点的坐标是相同的,那么该食物被蛇吃掉,蛇的长度+1。
判断游戏结束的条件:当蛇的头部位置坐标与边界坐标重合或者蛇头的位置与自身相重合,游戏结束暂停:游戏过程中,按空格键可以使游戏暂停,在按空格键进入被暂停的游戏2.2游戏流程由程序分析知,该游戏是用方向键实现贪吃蛇的移动,游戏大概流程分为:游戏初始化(描绘围墙、蛇体、食物等及其颜色),游戏过程(通过四个方向键控制蛇头带动身体移动),游戏结束(显示总分并判断是否重新游戏)。
使用汇编语言编写一条简单的贪吃蛇的实现
使⽤汇编语⾔编写⼀条简单的贪吃蛇的实现本⽂中的汇编语⾔是基于x86芯⽚,下⾯给出代码:;TITLE GAME4THPAGE 60,132STSEG SEGMENTDB 64 DUP (0)STSEG ENDS;-----------------------------------DTSEG SEGMENTDATAH DB 10H,10H,10H,10H,10H,10H,10H,10H,10HDATAL DB 20H,21H,22H,23H,24H,25H,26H,27H,28HDTSEG ENDSCR EQU 0DHLF EQU 0AH;------------------------------------CDSEG SEGMENTMAIN PROC FARASSUME CS:CDSEG,DS:DTSEG,SS:STSEGMOV AX,DTSEGMOV DS,AXMOV AX,0600HMOV BH,00011110BMOV CX,0MOV DH,18HMOV DL,04FHINT 10HFISH: MOV AX,0600HMOV BH,00011110BMOV CX,0MOV DH,18HMOV DL,04FHINT 10HMOV AH,02MOV BH,00MOV SI,OFFSET DATAHMOV DI,OFFSET DATALMOV DH,[SI]MOV DL,[DI]INT 10HMOV AX,0201HMOV DL,'+'INT 21HMOV AH,02MOV BH,00MOV DH,[SI]+1MOV DL,[DI]+1INT 10HMOV AX,0201HMOV DL,'#'INT 21HMOV AH,02MOV BH,00MOV DH,[SI]+2MOV DL,[DI]+2INT 10HMOV AX,0201HMOV DL,'#'INT 21HMOV AH,02MOV BH,00MOV DH,[SI]+3MOV DL,[DI]+3INT 10HMOV AX,0201HMOV DL,'#'INT 21HMOV AH,02MOV BH,00MOV DH,[SI]+4MOV DL,[DI]+4INT 10HMOV AX,0201HMOV DL,'#'INT 21HMOV AH,02MOV BH,00MOV DH,[SI]+5MOV DL,[DI]+5INT 10HMOV AX,0201HMOV DL,'#'INT 21HMOV AH,02MOV BH,00MOV DH,[SI]+6MOV DL,[DI]+6INT 10HMOV AX,0201HMOV DL,'#'INT 21HMOV AH,02MOV BH,00MOV DH,[SI]+7MOV DL,[DI]+7INT 10HMOV AX,0201HMOV DL,'#'INT 21HMOV AH,02MOV BH,00MOV DH,[SI]+8MOV DL,[DI]+8INT 10HMOV AX,0201HMOV DL,'>'INT 21HLOOP1:MOV AH,0 ;循环输⼊MOV AL,0INT 16HCMP AH,72JE UPCMP AH,80JE DOWNCMP AH,77JE RIGHTCMP AH,75JE LEFTUP: MOV SI,OFFSET DATAH MOV DI,OFFSET DATALMOV DH,[SI]+8MOV DL,[DI]+8MOV CH,DHMOV CL,DLDEC DHMOV [SI]+8,DHMOV [DI]+8,DLJMP BACKDOWN: MOV SI,OFFSET DATAH MOV DI,OFFSET DATALMOV DH,[SI]+8MOV DL,[DI]+8MOV CH,DHMOV CL,DLINC DHMOV [SI]+8,DHMOV [DI]+8,DLJMP BACKLEFT: MOV SI,OFFSET DATAH MOV DI,OFFSET DATALMOV DH,[SI]+8MOV DL,[DI]+8MOV CH,DHMOV CL,DLDEC DLMOV [SI]+8,DHMOV [DI]+8,DLJMP BACKRIGHT:MOV SI,OFFSET DATAHMOV DI,OFFSET DATALMOV DH,[SI]+8MOV DL,[DI]+8MOV CH,DHMOV CL,DLINC DLMOV [SI]+8,DHMOV [DI]+8,DLJMP BACKBACK: MOV DH,[SI]+7MOV DL,[DI]+7MOV [SI]+7,CHMOV [DI]+7,CLMOV CH,DHMOV CL,DLMOV DH,[SI]+6MOV DL,[DI]+6MOV [SI]+6,CHMOV [DI]+6,CLMOV CH,DHMOV CL,DLMOV DH,[SI]+5MOV DL,[DI]+5MOV [SI]+5,CHMOV [DI]+5,CLMOV CH,DHMOV CL,DLMOV DH,[SI]+4MOV DL,[DI]+4MOV [SI]+4,CHMOV [DI]+4,CLMOV CH,DHMOV CL,DLMOV DH,[SI]+3MOV DL,[DI]+3MOV [SI]+3,CHMOV [DI]+3,CLMOV CH,DHMOV CL,DLMOV DH,[SI]+2MOV DL,[DI]+2MOV [SI]+2,CHMOV [DI]+2,CLMOV CH,DHMOV CL,DLMOV DH,[SI]+1MOV DL,[DI]+1MOV [SI]+1,CHMOV [DI]+1,CLMOV CH,DHMOV CL,DLMOV DH,[SI]MOV DL,[DI]MOV [SI],CHMOV [DI],CLMOV CH,DHMOV CL,DLJMP FISHMAIN ENDPCDSEG ENDSEND MAIN以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
贪吃蛇游戏源代码
//主函数# include <windows.h># include <time.h># include "resource.h"#include "snake.h"#include "table.h"#define GAME_STATE_W AIT 0//游戏等待状态#define GAME_STATE_RUN 1//游戏运行状态#define GAME_STATE_END 2//游戏结束状态//界面相关物件尺寸的定义#define WALL_WIDTH 80//外墙左部到游戏区的宽度#define WALL_HEIGHT 80//外墙顶部到游戏区的高度#define BMP_W ALL_WIDTH 16//墙位图的宽度#define BMP_W ALL_HEIGHT 16//墙位图的高度LRESULT CALLBACK WndProc(HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam);void DrawGame(void);void ShellDraw( HDC hdc );void GameAreaDraw(HDC hdc);void OnTimer(UINT uTIMER_ID);void StartGame( void );void EndGame( void );//创建一个桌子CTable table;int tableBlockWidth = 0; //桌子的格子的宽度int tableBlockHeight = 0; //桌子的格子的高度int iScores = 0; //游戏的得分UINT uGameState = GAME_STATE_W AIT; //当前游戏状态HDC windowDC = NULL; //windows屏幕设备HDC bufferDC = NULL; //缓冲设备环境HDC picDC = NULL; //snake图像内存设备HDC endDC = NULL; //游戏终结图像内存设备HDC scoreDC = NULL; //分数板内存设备HWND hAppWnd = NULL; //本application窗口句柄HBITMAP picBMP = NULL; //snake图像位图句柄HBITMAP bufferBMP = NULL; //缓冲位图句柄HBITMAP endBMP = NULL; //游戏终结hAppWnd图像内存句柄HBITMAP hbmpWall = NULL; //墙位图句柄HBITMAP hbmpScore = NULL; //分数板位图句柄HBRUSH hbrushWall = NULL; //墙画刷//定时器标识UINT uSnakeMoveTimer; //蛇的移动UINT uFoodAddTimer; //水果的产生//框架的位置数据定义//GDI RECT 而不是MFC CRectRECT g_ClientRect;int g_iClientWidth;int g_iClientHeight;int WINAPI WinMain(HINSTANCE hInstance, // handle to current instanceHINSTANCE hPrevInstance, // handle to previous instanceLPSTR lpCmdLine, // command lineint nCmdShow // show state){WNDCLASS wndClass;UINT width,height;//定义窗口wndClass.cbClsExtra = 0;wndClass.cbWndExtra = 0;wndClass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);wndClass.hIcon = LoadIcon(NULL,MAKEINTRESOURCE(IDI_MAIN));wndClass.hCursor = LoadCursor(NULL,IDC_ARROW);wndClass.hInstance = hInstance;wndClass.lpfnWndProc = WndProc;wndClass.lpszClassName = "Snake";wndClass.lpszMenuName = NULL;wndClass.style = CS_HREDRAW | CS_VREDRAW;//注册窗口RegisterClass(&wndClass);width = GetSystemMetrics(SM_CXSCREEN);height = GetSystemMetrics(SM_CYSCREEN);HWND hWnd;hWnd = CreateWindow("Snake","贪吃蛇游戏",WS_POPUP,0,0,width,height,NULL,NULL,hInstance,NULL);hAppWnd = hWnd;//显示窗口ShowWindow(hWnd,SW_SHOWNORMAL);UpdateWindow(hWnd);GetClientRect(hWnd,&g_ClientRect);g_iClientWidth = g_ClientRect.right - g_ClientRect.left;g_iClientHeight = g_ClientRect.bottom - g_ClientRect.top;//将游戏区域分成横纵均匀的20小块tableBlockWidth = (g_ClientRect.right - 2 * WALL_WIDTH) / 20;tableBlockHeight = (g_ClientRect.bottom - 2 * WALL_HEIGHT) / 20;//获取当前主设备与windowDC相连windowDC = GetDC(NULL);//创建与windowDC兼容的内存设备环境bufferDC = CreateCompatibleDC(windowDC);picDC = CreateCompatibleDC(windowDC);endDC = CreateCompatibleDC(windowDC);scoreDC =CreateCompatibleDC(windowDC);//位图的初始化与载入位图bufferBMP = CreateCompatibleBitmap(windowDC,g_iClientWidth,g_iClientHeight);picBMP = (HBITMAP)LoadImage(NULL,"snake.bmp",IMAGE_BITMAP,160,80,LR_LOADFROMFILE);hbmpWall = (HBITMAP)LoadImage(NULL,"brick.bmp",IMAGE_BITMAP,16,16,LR_LOADFROMFILE);endBMP = (HBITMAP)LoadImage(NULL,"end.bmp",IMAGE_BITMAP,369,300,LR_LOADFROMFILE);hbmpScore = (HBITMAP)LoadImage(NULL,"scoreboard.bmp",IMAGE_BITMAP,265,55,LR_LOADFROMFILE);//生声明位图与设备环境的关联SelectObject(bufferDC,bufferBMP);SelectObject(picDC,picBMP);SelectObject(endDC,endBMP);SelectObject(scoreDC,hbmpScore);hbrushWall = CreatePatternBrush(hbmpWall);StartGame();MSG Msg;while (GetMessage(&Msg,NULL,0,0)){TranslateMessage(&Msg);DispatchMessage(&Msg);}return Msg.wParam;}LRESULT CALLBACK WndProc(HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam){switch (message){case WM_TIMER:OnTimer((UINT)wParam);break;case WM_KEYDOWN:switch (wParam){case VK_ESCAPE:KillTimer(hAppWnd,uSnakeMoveTimer);KillTimer(hAppWnd,uFoodAddTimer);uGameState = GAME_STATE_W AIT;if (IDYES == MessageBox(hWnd,"真的要退出吗?","贪吃蛇",MB_YESNO | MB_ICONQUESTION)){exit(0);}uSnakeMoveTimer = SetTimer(hAppWnd,500,100,NULL);uFoodAddTimer = SetTimer(hAppWnd,600,7000,NULL);uGameState = GAME_STATE_RUN;break;case VK_UP:table.ChangeSnakeDirect(S_UP);break;case VK_DOWN:table.ChangeSnakeDirect(S_DOWN);break;case VK_LEFT:table.ChangeSnakeDirect(S_LEFT);break;case VK_RIGHT:table.ChangeSnakeDirect(S_RIGHT);break;case VK_SPACE:if (GAME_STATE_END == uGameState){StartGame();}else if (GAME_STATE_RUN == uGameState){KillTimer(hAppWnd,uSnakeMoveTimer);KillTimer(hAppWnd,uFoodAddTimer);uGameState = GAME_STATE_W AIT;}else{uSnakeMoveTimer = SetTimer(hAppWnd,500,100,NULL);uFoodAddTimer = SetTimer(hAppWnd,600,7000,NULL);uGameState = GAME_STATE_RUN;}break;}break;case WM_SETCURSOR:SetCursor(NULL);break;case WM_DESTROY:ReleaseDC(hWnd,picDC);ReleaseDC(hWnd,bufferDC);ReleaseDC(hWnd,windowDC);PostQuitMessage(0);break;}return DefWindowProc(hWnd,message,wParam,lParam);}void DrawGame(){ShellDraw(bufferDC);GameAreaDraw(bufferDC);BitBlt(windowDC,0,0,g_iClientWidth,g_iClientHeight,bufferDC,0,0,SRCCOPY);}void OnTimer(UINT uTIMER_ID){if (uTIMER_ID == uSnakeMoveTimer){//移动蛇table.SnakeMove();//检测蛇是否碰到自己的身体if (table.GetSnake() ->IsHeadTouchBody(table.GetSnake() ->GetPos()[0].x,table.GetSnake() ->GetPos()[0].y)){EndGame();}//根据蛇头所在区域做相应的处理switch (table.GetData(table.GetSnake() ->GetPos()[0].x,table.GetSnake() ->GetPos()[0].y)){case TB_STATE_FOOD:table.ClearFood(table.GetSnake() ->GetPos()[0].x,table.GetSnake() ->GetPos()[0].y);table.AddBlock((rand())%tableBlockWidth,rand()%tableBlockHeight);table.GetSnake() ->AddBody();iScores++;break;case TB_STATE_BLOCK:case TB_STATE_SBLOCK:EndGame();break;}//xianshiDrawGame();}else if (uTIMER_ID == uFoodAddTimer){//定时加食物table.AddFood((rand())%tableBlockWidth,rand()%tableBlockHeight);}}//开始游戏void StartGame(){iScores = 0;int iFoodNumber;//桌面初始化table.InitialTable(tableBlockWidth,tableBlockHeight);table.GetSnake() ->ChangeDirect(S_RIGHT);table.GetSnake() ->SetHeadPos(tableBlockWidth / 2,tableBlockHeight / 2);//预先随机产生一些食物srand( (unsigned)time(NULL));for (iFoodNumber = 0; iFoodNumber < 400; iFoodNumber++){table.AddFood((rand())%tableBlockWidth,(rand())%tableBlockHeight);}//打开定时器DrawGame();uSnakeMoveTimer = SetTimer(hAppWnd,500,100,NULL);uFoodAddTimer = SetTimer(hAppWnd,600,7000,NULL);uGameState = GAME_STATE_RUN;}void EndGame(){//关计时器KillTimer(hAppWnd,uSnakeMoveTimer);KillTimer(hAppWnd,uFoodAddTimer);uGameState = GAME_STATE_END;}void ShellDraw(HDC hdc){char szText[30] = "Score: ";char szNum[20];int iNowScores = iScores * 100;itoa(iNowScores,szNum,10);strcat(szText,szNum);RECT rt,rect;GetClientRect(hAppWnd,&rt);//墙的绘制SelectObject(hdc,hbrushWall);PatBlt(hdc,rt.left,rt.top,rt.right,rt.bottom,PATCOPY);//内部游戏区为白色底平面rect.left = rt.left + WALL_WIDTH;rect.top = rt.top + WALL_HEIGHT;rect.right = rt.right - WALL_WIDTH;rect.bottom = rt.bottom - WALL_HEIGHT;FillRect(hdc,&rect,(HBRUSH)(COLOR_WINDOW + 1));BitBlt(hdc,GetSystemMetrics(SM_CXSCREEN) / 3 ,10,256,55,scoreDC,0,0,SRCCOPY);SetBkMode(hdc,TRANSPARENT);TextOut(hdc,GetSystemMetrics(SM_CXSCREEN) / 3 + 50,30,szText,strlen(szText));}void GameAreaDraw(HDC hdc){int i,j;int x, y, x_pos, y_pos;BitmapState state;//绘制水果与毒果for (i = 0; i < tableBlockHeight; i++){for (j = 0; j < tableBlockWidth; j++){x_pos = j * 20 + WALL_WIDTH;y_pos = i * 20 + WALL_HEIGHT;switch (table.GetData(j,i)){case TB_STATE_FOOD:BitBlt(hdc,x_pos,y_pos,20,20,picDC,100,0,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,20,0,SRCAND);break;case TB_STATE_BLOCK:BitBlt(hdc,x_pos,y_pos,20,20,picDC,80,0,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,0,0,SRCAND);break;}}}//根据当前的形状绘制蛇头x = table.GetSnake()->GetPos()[0].x;y = table.GetSnake()->GetPos()[0].y;x_pos = x * 20 + WALL_WIDTH;y_pos = y * 20 + WALL_HEIGHT;state = table.GetSnake()->GetStateArray()[0];switch (state){case M_UP_UP:BitBlt(hdc,x_pos,y_pos,20,20,picDC,80,20,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,0,20,SRCAND);break;case M_DOWN_DOWN:BitBlt(hdc,x_pos,y_pos,20,20,picDC,140,20,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,60,20,SRCAND);break;case M_LEFT_LEFT:BitBlt(hdc,x_pos,y_pos,20,20,picDC,100,20,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,20,20,SRCAND);break;case M_RIGHT_RIGHT:BitBlt(hdc,x_pos,y_pos,20,20,picDC,120,20,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,40,20,SRCAND);break;}//根据蛇身各节点的状态绘制蛇身for (i = 1; i < table.GetSnake()->GetLength() - 1; i++){x = table.GetSnake()->GetPos()[i].x;y = table.GetSnake()->GetPos()[i].y;x_pos = x * 20 + WALL_WIDTH;y_pos = y * 20 + WALL_HEIGHT;state = table.GetSnake()->GetStateArray()[i];switch (state){case M_UP_UP:case M_DOWN_DOWN:BitBlt(hdc,x_pos,y_pos,20,20,picDC,80,40,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,0,40,SRCAND);break;case M_LEFT_LEFT:case M_RIGHT_RIGHT:BitBlt(hdc,x_pos,y_pos,20,20,picDC,100,40,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,20,40,SRCAND);break;case M_RIGHT_DOWN:case M_UP_LEFT:BitBlt(hdc,x_pos,y_pos,20,20,picDC,100,60,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,20,60,SRCAND);break;case M_RIGHT_UP:case M_DOWN_LEFT:BitBlt(hdc,x_pos,y_pos,20,20,picDC,140,40,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,60,40,SRCAND);break;case M_LEFT_DOWN:case M_UP_RIGHT:BitBlt(hdc,x_pos,y_pos,20,20,picDC,80,60,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,0,60,SRCAND);break;case M_LEFT_UP:case M_DOWN_RIGHT:BitBlt(hdc,x_pos,y_pos,20,20,picDC,120,40,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,40,40,SRCAND);break;}}//绘制蛇尾巴x = table.GetSnake()->GetPos()[table.GetSnake()->GetLength()-1].x;y = table.GetSnake()->GetPos()[table.GetSnake()->GetLength()-1].y;x_pos = x * 20 + WALL_WIDTH;y_pos = y * 20 + WALL_HEIGHT;state = table.GetSnake()->GetStateArray()[table.GetSnake()->GetLength()-1];switch (state){case M_UP_UP:BitBlt(hdc,x_pos,y_pos,20,20,picDC,120,60,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,40,60,SRCAND);break;case M_DOWN_DOWN:BitBlt(hdc,x_pos,y_pos,20,20,picDC,120,0,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,40,0,SRCAND);break;case M_LEFT_LEFT:BitBlt(hdc,x_pos,y_pos,20,20,picDC,140,60,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,60,60,SRCAND);break;case M_RIGHT_RIGHT:BitBlt(hdc,x_pos,y_pos,20,20,picDC,140,0,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,60,0,SRCAND);break;}//绘制游戏结束图案if (uGameState == GAME_STA TE_END){x_pos = g_iClientWidth / 3;y_pos = g_iClientHeight / 4;BitBlt(hdc,x_pos,y_pos,369,300,endDC,0,0,SRCCOPY);}}# include "snake.h"CSnake::CSnake(int x_pos,int y_pos,int len){if (len < 1){len = 1;}int i;m_length = len;//蛇的身体体长//初始化蛇的坐标位置m_pPos = new SPoint[m_length+2];m_pPos[0].x = x_pos;m_pPos[0].y = y_pos;for (i = 1; i < m_length +2; i++){m_pPos[i].x = 0;m_pPos[i].y = 0;}//初始化蛇的运动状态m_newSnake.head = S_NONE;m_oldSnake.head = S_NONE;m_newSnake.body = new MoveState[m_length];m_oldSnake.body = new MoveState[m_length];for(i = 0; i < m_length; i++){m_oldSnake.body[i] = S_NONE;m_newSnake.body[i] = S_NONE;}m_newSnake.tail = S_NONE;m_oldSnake.tail = S_NONE;//初始化蛇的位图显示状态;m_pStateArray = new BitmapState[m_length+2];for (i = 0; i < m_length + 2; i++){m_pStateArray[i] = M_NONE;}}CSnake::~CSnake(){SAFE_DELETE_ARRAY(m_pPos);SAFE_DELETE_ARRAY(m_pStateArray);}//根据新旧两蛇的运动状态,确定当前显示的运动状态BitmapState CSnake::GetRightState(MoveState oldDirect,MoveState newDirect) {BitmapState re;switch(oldDirect){case S_NONE:switch(newDirect){case S_NONE:re = M_NONE;break;case S_UP:re = M_UP_UP;break;case S_DOWN:re = M_DOWN_DOWN;break;case S_LEFT:re = M_LEFT_LEFT;break;case S_RIGHT:re = M_RIGHT_RIGHT;break;}break;case S_UP:switch(newDirect){case S_UP:re = M_UP_UP;break;case S_LEFT:re = M_UP_LEFT;break;case S_RIGHT:re = M_UP_RIGHT;break;}break;case S_DOWN:switch(newDirect){case S_DOWN:re = M_DOWN_DOWN;break;case S_LEFT:re = M_DOWN_LEFT;break;case S_RIGHT:re = M_DOWN_RIGHT;break;}break;case S_LEFT:switch(newDirect){case S_UP:re = M_LEFT_UP;break;case S_LEFT:re = M_LEFT_LEFT;break;case S_DOWN:re = M_LEFT_DOWN;break;}break;case S_RIGHT:switch(newDirect){case S_UP:re = M_RIGHT_UP;break;case S_DOWN:re = M_RIGHT_DOWN;break;case S_RIGHT:re = M_RIGHT_RIGHT;break;}break;}return re;}//改变方向void CSnake::ChangeDirect(MoveState d) {//方向不能为其对立方switch(d){case S_NONE:m_newSnake.head = S_NONE;break;case S_UP:if(m_newSnake.head != S_DOWN)m_newSnake.head = S_UP;break;case S_DOWN:if(m_newSnake.head != S_UP)m_newSnake.head = S_DOWN;break;case S_LEFT:if(m_newSnake.head != S_RIGHT)m_newSnake.head = S_LEFT;break;case S_RIGHT:if(m_newSnake.head != S_LEFT)m_newSnake.head = S_RIGHT;break;}}//蛇移动void CSnake::Move(){int i;//1.计算各节点的新状态//保存蛇身体各部位的形状for (i = 0; i < m_length; i++){m_oldSnake.body[i] = m_newSnake.body[i];}m_newSnake.tail = m_newSnake.body[m_length-1];for(i = m_length - 1; i > 0; i--){m_newSnake.body[i] = m_newSnake.body[i-1];}m_newSnake.body[0] = m_newSnake.head;//根据新旧状态获取新的状态m_pStateArray[0] = GetRightState(m_oldSnake.head,m_newSnake.head);for(i = 0; i < m_length; i++){m_pStateArray[i+1] = GetRightState(m_oldSnake.body[i],m_newSnake.body[i]);}m_pStateArray[m_length+1] = GetRightState(m_oldSnake.tail,m_newSnake.tail);//2、整个蛇坐标移动,除蛇头外其他为原状态的前一位置for(i = m_length + 1; i > 0; i--){m_pPos[i] = m_pPos[i-1];}//蛇头根据新位置进行偏移switch(m_newSnake.head){case S_UP:m_pPos[0].y -= SNAKE_MOVE;break;case S_DOWN:m_pPos[0].y += SNAKE_MOVE;break;case S_LEFT:m_pPos[0].x -= SNAKE_MOVE;break;case S_RIGHT:m_pPos[0].x += SNAKE_MOVE;break;}}//蛇身体的增长void CSnake::AddBody(int n){//分配变量作为保存各种数据状态int i;Snake_Struct saveOldSnake,saveNewSnake;BitmapState *saveStateArray;SPoint *savePos;//保存蛇的位置信息savePos = new SPoint[m_length+2];for(i = 0; i < m_length + 2; i++){savePos[i] = m_pPos[i];}//保存蛇的状态信息saveOldSnake.head = m_oldSnake.head;saveOldSnake.body = new MoveState[m_length];for(i = 0; i < m_length; i++){saveOldSnake.body[i] = m_oldSnake.body[i];}saveOldSnake.tail = m_oldSnake.tail;saveNewSnake.head = m_newSnake.head;saveNewSnake.body = new MoveState[m_length];for(i = 0; i < m_length; i++){saveNewSnake.body[i] = m_newSnake.body[i];}saveNewSnake.tail = m_newSnake.tail;saveStateArray = new BitmapState[m_length+2];for (i = 0; i < m_length + 2; i++){saveStateArray[i] = m_pStateArray[i];}//将长度增长m_length += n;//释放所有存储蛇状态数据的存储空间SAFE_DELETE_ARRAY(m_newSnake.body); SAFE_DELETE_ARRAY(m_oldSnake.body); SAFE_DELETE_ARRAY(m_pPos);SAFE_DELETE_ARRAY(m_pStateArray);//创建并初始化蛇增长后的存储空间m_pPos = new SPoint[m_length+2];for (i = 0; i < m_length +2; i++){m_pPos[i].x = 0;m_pPos[i].y = 0;}//初始化蛇的运动状态m_newSnake.head = S_NONE;m_oldSnake.head = S_NONE;m_newSnake.body = new MoveState[m_length]; m_oldSnake.body = new MoveState[m_length];for(i = 0; i < m_length; i++){m_oldSnake.body[i] = S_NONE;m_newSnake.body[i] = S_NONE;}m_newSnake.tail = S_NONE;m_oldSnake.tail = S_NONE;//初始化蛇的位图显示状态;m_pStateArray = new BitmapState[m_length+2]; for (i = 0; i < m_length + 2; i++){m_pStateArray[i] = M_NONE;}//恢复原来的长度数据m_newSnake.head = saveNewSnake.head;m_oldSnake.head = saveOldSnake.head;for(i = 0; i < m_length - n; i++){m_newSnake.body[i] = saveNewSnake.body[i];m_oldSnake.body[i] = saveOldSnake.body[i];}m_newSnake.tail = saveNewSnake.tail;m_oldSnake.tail = saveOldSnake.tail;m_pStateArray = new BitmapState[m_length+2];for (i = 0; i < m_length + 2 - n; i++)m_pStateArray[i] = saveStateArray[i];m_pPos = new SPoint[m_length+2];for(i = 0; i < m_length + 2 - n; i++)m_pPos[i] = savePos[i];}//设置蛇头坐标void CSnake::SetHeadPos(int x, int y){m_pPos[0].x = x;m_pPos[0].y = y;}//取蛇状态的标志数组BitmapState* CSnake::GetStateArray(){return m_pStateArray;}//取蛇的位置信息SPoint* CSnake::GetPos(){return m_pPos;}//取蛇长度int CSnake::GetLength()return m_length + 2;}//检测蛇头是否碰到身体bool CSnake::IsHeadTouchBody(int x, int y){int i;for(i = 1; i < m_length + 2; i++){if (m_pPos[i].x == x && m_pPos[i].y == y)return true;}return false;}//初始化,用作游戏结束后重新开始void CSnake::Initial(){//释放以前的存储空间SAFE_DELETE_ARRAY(m_pPos);SAFE_DELETE_ARRAY(m_pStateArray);SAFE_DELETE_ARRAY(m_newSnake.body);SAFE_DELETE_ARRAY(m_oldSnake.body);int i;int x_pos = 0;int y_pos = 0;m_length = 1;//蛇的身体体长//初始化蛇的坐标位置m_pPos = new SPoint[m_length+2];m_pPos[0].x = x_pos;m_pPos[0].y = y_pos;for (i = 1; i < m_length +2; i++){m_pPos[i].x = 0;m_pPos[i].y = 0;}//初始化蛇的运动状态m_newSnake.head = S_NONE;m_oldSnake.head = S_NONE;m_newSnake.body = new MoveState[m_length];m_oldSnake.body = new MoveState[m_length];for(i = 0; i < m_length; i++){m_oldSnake.body[i] = S_NONE;m_newSnake.body[i] = S_NONE;}m_newSnake.tail = S_NONE;m_oldSnake.tail = S_NONE;//初始化蛇的位图显示状态;m_pStateArray = new BitmapState[m_length+2];for (i = 0; i < m_length + 2; i++){m_pStateArray[i] = M_NONE;}}#ifndef __SNAKE_H_H#define __SNAKE_H_H#define SNAKE_MOVE 1#define SAFE_DELETE_ARRAY(p) {delete [](p);(p)=NULL;}#include <stdio.h>//节点图像显示位图状态enumBitmapState{M_NONE,M_UP_UP,M_DOWN_DOWN,M_LEFT_LEFT,M_RIGHT_RIGHT, M_UP_LEFT,M_UP_RIGHT,M_DOWN_LEFT,M_DOWN_RIGHT,M_LEFT_UP,M_LEFT_DOWN,M_RIGHT_UP,M_RIGHT_DOWN};//节点运动状态enum MoveState{S_NONE,S_UP,S_DOWN,S_LEFT,S_RIGHT};//节点位置坐标struct SPointint x;int y;};//定义蛇体状态struct Snake_Struct{MoveState head;//头部MoveState *body;//身体MoveState tail;//尾部};class CSnake{private:int m_length; //蛇的长度Snake_Struct m_newSnake; //蛇的新态的所有节点的运动状态Snake_Struct m_oldSnake; //蛇的原态的所有节点的坐标的运动状态BitmapState *m_pStateArray; //蛇的所有节点显示位图的状态SPoint *m_pPos; //蛇体坐标BitmapState GetRightState(MoveState oldDirect,MoveState newDirect);public:void Move(void);void ChangeDirect(MoveState d);void AddBody(int n=1);void SetHeadPos(int x, int y);BitmapState * GetStateArray(void);SPoint * GetPos(void);bool IsHeadTouchBody(int x, int y);int GetLength(void);void Initial(void);CSnake(int x_pos = 0, int y_pos = 0, int len = 1);~CSnake();};#endif#include "table.h"CTable::CTable()m_width = 0;m_height = 0;m_foodNumber = 0;m_blockNumber = 0;m_board = NULL;}CTable::~CTable(){if (m_board != NULL){SAFE_DELETE_ARRAY(m_board);}}//初始化面板void CTable::InitialTable(int w,int h){int i, j;m_width = w;m_height = h;m_snake.Initial();if (m_board != NULL){SAFE_DELETE_ARRAY(m_board);}//根据高度和宽度设置新的桌子m_board = new int * [m_height];for (i = 0; i < m_height; i++){m_board[i] = new int[m_width];for (j = 0; j < m_width; j++){m_board[i][j] = 0;}}//将桌子四周设置为墙for (i = 0; i < m_height; i++){m_board[i][0] = TB_STATE_SBLOCK;m_board[i][m_width-1] = TB_STA TE_SBLOCK;}for (i = 0; i < m_width; i++){m_board[0][i] = TB_STATE_SBLOCK;m_board[m_height-1][i] = TB_STA TE_SBLOCK;}}//食物的操作bool CTable::AddBlock(int x, int y){if( (x > 0) && (x < m_width) && (y > 0) && (y < m_height) && (m_board[y][x] == TB_STATE_OK)){m_board[y][x] = TB_STA TE_BLOCK;m_blockNumber++;return true;}return false;}bool CTable::AddFood(int x, int y){if( (x > 0) && (x < m_width) && (y > 0) && (y < m_height) && (m_board[y][x] == TB_STATE_OK)){m_board[y][x] = TB_STA TE_FOOD;m_foodNumber++;return true;}return false;}bool CTable::ClearFood(int x, int y){m_board[y][x] = TB_STA TE_OK;return true;}//取蛇对象CSnake * CTable::GetSnake(void){return &m_snake;}//取桌子对象int ** CTable::GetBoard(void){return m_board;}//获取数据信息int CTable::GetData(int x, int y){return m_board[y][x];}//蛇的操作void CTable::SnakeMove(void){m_snake.Move();}bool CTable::ChangeSnakeDirect(MoveState d){m_snake.ChangeDirect(d);return true;}#ifndef __TABLE_H_H#define __TABLE_H_H#define TB_STATE_OK 0 //正常#define TB_STATE_FOOD 1 //食物#define TB_STATE_BLOCK 2 //障碍-毒果#define TB_STATE_SBLOCK 3 //障碍-墙#include "snake.h"class CTable{private:int m_width;//桌子的宽度int m_height;//桌子的宽度int m_foodNumber;//桌子上食物的数量int m_blockNumber;//毒果的数量CSnake m_snake;//桌上的蛇int ** m_board;//桌的面板public:CTable();~CTable();//初始化面板void InitialTable(int w,int h);//食物的操作bool AddBlock(int x, int y);bool AddFood(int x, int y);bool ClearFood(int x, int y);//物件获取CSnake * GetSnake(void);int ** GetBoard(void);int GetData(int x, int y);//蛇的操作void SnakeMove(void);bool ChangeSnakeDirect(MoveState d); };#endif。
贪吃蛇游戏c语言源代码
outtextxy(160,220,"Game Over");
loop1:key=bioskey(0);
if(key==Enter)
{cleardevice();
TheFirstBlock();
}
else
if(key==ESC)
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);
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);
{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)
void Snake_Bodyadd(void);
汇编语言写的贪吃蛇小游戏源代码
DATA SEGMENTdw 0,0snk db 1blk db 32food db 3tal1 db 4tal2 db 2adrs db 5len db ?pst db ?addrs dw ?frow db ?fcol db ?hwrt db ?gmov db 'game over press r to restart press q to quit $'score1 db 'score :$'score2 db ?score0 db 1zero db 48writer db 'Developer: Geniusdot $'email db ': geniusdotgmail.$'msg1 db 'The way to play the game:$'way db ' press w to up ,press s to down,press a to left,press d to right$' msg db 'Press any key(except a,s,d,w) to start$'DATA ENDSSTACK SEGMENT stackdb 200 dup(0)STACK ENDSCODE SEGMENTASSUME CS:CODE,DS:DATA,SS:STACKstart:mov ax,datamov ds,axmov ax,0mov es,axmov frow,10mov fcol,6mov dh,10mov dl,26mov ah,2int 10hmov ah,9lea dx,msg1 int 21hmov dh,11 mov dl,7mov ah,2mov bh,0int 10hmov ah,9lea dx,wayint 21hmov dh,12 mov dl,20 mov ah,2mov bh,0int 10hmov ah,9lea dx,msgint 21hmov ah,0int 16hmov ah,6mov al,0mov ch,0mov cl,0mov dh,24 mov dl,79 mov bh,10int 10hmov dh,0mov dl,0mov ah,2mov bh,0int 10hmov ah,9lea dx,score1 int 21hmov dl,15 mov ah,2mov bh,0int 10hlea dx,writerint 21hmov ah,9lea dx,emailint 21hmov score2,48push es:[9*4] ;将原int9入口地址保存pop ds:[0]push es:[9*4+2]pop ds:[2]mov word ptr es:[9*4],offset int9 ;更改中断向量表mov es:[9*4+2],csjmp aawrite macro row,col,cnt ;宏定义用于向当前光标处输出字符push bxpush cxpush dxmov dh,rowmov dl,colmov ah,2mov bh,0int 10hmov ah,9mov bl,11mov cx,1lea di,cnt ;50mov al,[di]int 10hpop dxpop cxpop bxendmreadh macro row,col ;宏定义用于读出当前光标处字符push dxpush bxmov dh,rowmov dl,colmov ah,2mov bh,0int 10hmov ah,08hint 10hmov pst,alpop bxpop axpop dxendmwnear macro ;宏定义只用在readcg宏中当readcg的所有判断都不成立调用此宏local wnext1local wnext2local wnext3local wnext4push dxdec dhreadh dh,dlcmp pst,1jne wnext1write dh,dl,tal2jmp wnext4wnext1:inc dhdec dlreadh dh,dlcmp pst,1jne wnext2write dh,dl,tal2jmp wnext4wnext2:inc dhinc dlreadh dh,dlcmp pst,1jne wnext3write dh,dl,tal2jmp wnext4dec dhinc dlreadh dh,dlcmp pst,1jne wnext4write dh,dl,tal2wnext4:pop dxendmreadcg macro row,col ;宏定义用于改变判断出来的字符local tnup,tnup1,tnup2,tnlf,tnlf1,tnlf2,tndn,tndn1,tndn2,tnrt,tnrt1,tnrt2,goout push bxpush axpush dxwrite dh,dl,tal1dec rowreadh dh,dlcmp pst,4jne tnup1jmp tnup2tnup1:jmp near ptr tnuptnup2:write dh,dl,blkinc dhinc dhreadh dh,dlcmp pst,1jne tnupwrite dh,dl,tal2jmp near ptr goouttnup:pop dxpush dxdec colreadh dh,dlcmp pst,4jne tnlf1jmp tnlf2tnlf1:jmp near ptr tnlf tnlf2:write dh,dl,blk inc dlinc dlreadh dh,dlcmp pst,1jne tnlfwrite dh,dl,tal2 jmp near ptr goout tnlf:pop dxpush dxinc rowreadh dh,dlcmp pst,4jne tndn1jmp tndn2tndn1:jmp near ptr tndn tndn2:write dh,dl,blk dec dhdec dhreadh dh,dlcmp pst,1jne tndnwrite dh,dl,tal2 jmp near ptr goout tndn:pop dxpush dxinc colreadh dh,dlcmp pst,4jne tnrt1jmp tnrt2tnrt1:jmp near ptr tnrt tnrt2:write dh,dl,blk dec dldec dlreadh dh,dlcmp pst,1jne tnrtwrite dh,dl,tal2jmp near ptr goouttnrt:pop dxpush dxwneargoout:pop dxpop axpop bxendmaddone: ;此标号功能是将蛇身增加一push dxinc score2mov dh,1mov dl,0mov cx,23cmpad1:push cxmov cx,79cmpad2:readh dh,dlcmp pst,2jne nextad3jmp nextad4nextad3:jmp near ptr nextadnextad4:write dh,dl,snkdec dhreadh dh,dlcmp pst,4jne natupwrite dh,dl,tal2dec dhwrite dh,dl,tal1jmp outonatup:inc dhreadh dh,dlcmp pst,4jne natlfwrite dh,dl,tal2 dec dlwrite dh,dl,tal1 jmp outonatlf:inc dhinc dlreadh dh,dlcmp pst,4jne natdnwrite dh,dl,tal2 inc dhwrite dh,dl,tal1 jmp outonatdn:dec dhinc dlreadh dh,dlcmp pst,4jne natrtwrite dh,dl,tal2 inc dlwrite dh,dl,tal1 natrt:outo:pop cxjmp near ptr endad nextad:inc dljmp nextad2chgad2:jmp near ptr cmpad2 nextad2:loop chgad2sub dl,79inc dhpop cxjmp nextad1chgad1:jmp near ptr cmpad1loop chgad1endad:pop dxjmp near ptr crtfaa: ;从这开始产生最原始的蛇mov addrs,offset turnrightmov dh,10mov dl,1mov cx,3write dh,dl,tal1inc dlwrite dh,dl,tal2wrt:inc dlwrite dh,dl,snkloop wrtmov len,6mov ax,0jmp wrt1ovflw: ;当蛇碰壁或自身转到此游戏结束mov ah,6mov al,0mov ch,0mov cl,0mov dh,24mov dl,79mov bh,7int 10hmov dh,17mov dl,17mov ah,2mov bh,0int 10hmov ah,9lea dx,gmovint 21hmov ax,0 ;恢复int9中断mov es,axpush ds:[0]pop es:[9*4]push ds:[2]pop es:[9*4+2]stop:mov ah,0int 16hcmp al,'r'je aa1jmp aa2aa1:jmp near ptr startaa2:cmp al,'q'jne stopjmp near ptr exitwrt1: ;此处蛇行走过程的无限循环call dlypush dxinc dhcmp dh,25je ovflwinc dlcmp dl,80je ovflwpop dxpush dxdec dhcmp dh,0je ovflwdec dlcmp dl,-1je ovflwpop dxpush dxlea ax,turnrightcmp addrs,axjne tonxt2inc dlreadh dh,dlcmp pst,1je tonxt1cmp pst,2je tonxt1cmp pst,4je tonxt1jmp tonxt2 tonxt1:jmp ovflwtonxt2:pop dxpush dxlea ax,turnup cmp addrs,ax jne tonxt4dec dhreadh dh,dl cmp pst,1je tonxt3cmp pst,2je tonxt3cmp pst,4je tonxt3jmp tonxt4 tonxt3:jmp ovflwtonxt4:pop dxpush dxlea ax,turndown cmp addrs,ax jne tonxt6inc dhreadh dh,dl cmp pst,1je tonxt5cmp pst,2je tonxt5cmp pst,4je tonxt5jmp tonxt6 tonxt5:jmp ovflwtonxt6:pop dxpush dxlea ax,turnback cmp addrs,axjne tonxt8dec dlreadh dh,dlcmp pst,1je tonxt7cmp pst,2je tonxt7cmp pst,4je tonxt7jmp tonxt8tonxt7:jmp ovflwtonxt8:pop dxjmp nextacrtf1:jmp near ptr addone crtf:call rand1call rand2inc frowmov ah,frowmov al,fcolpush dxmov dh,1mov dl,0push cxmov cx,23check1:push cxmov cx,79check2:readh dh,dlcmp pst,1je nextncmp pst,2je nextncmp pst,4je nextnjmp nextnnnextn:cmp ax,dxje crtfnextnn:inc dlloop check2inc dhsub dl,79pop cxloop check1pop cxpop dxwrite frow,fcol,food nexta:mov ah,frowmov al,fcolcmp ax,dxje crtf12jmp crtf13crtf12:jmp near ptr crtf1 crtf13:push dxcmp score2,58jl normalmov score2,49inc score0normal:mov dh,0mov dl,8write dh,dl,score2 add dl,score0write dh,dl,zeropop dxcmp adrs,17je jmp1cmp adrs,145je jmp1cmp adrs,31je jmp2cmp adrs,159je jmp2cmp adrs,32je jmp3cmp adrs,160je jmp3cmp adrs,30je jmp4cmp adrs,158je jmp4jmp addrsjmp1:lea ax, turndowncmp ax,addrsje jmp2mov addrs,offset turnupjmp near ptr turnupjmp2:lea ax,turnupcmp ax,addrsje jmp1mov addrs,offset turndownjmp near ptr turndownjmp3:lea ax,turnbackcmp ax,addrsje jmp4mov addrs,offset turnrightjmp near ptr turnrightjmp4:lea ax,turnrightcmp ax,addrsje jmp3mov addrs,offset turnbackjmp near ptr turnbackturnright: ;此处实现蛇向左走push dxmov dh,1mov dl,0mov cx,23cmpr1:push cxmov cx,79cmpr2:readh dh,dlcmp pst,2je nextr4jmp near ptr nextrnextr4:readcg dh,dlpop cxjmp near ptr endrnextr:inc dljmp nextr2chgr2:jmp near ptr cmpr2nextr2:loop chgr2sub dl,79inc dhpop cxjmp nextr1chgr1:jmp near ptr cmpr1nextr1:loop chgr1endr:pop dxinc dlwrite dh,dl,snkjmp near ptr wrt1turnup: ;此处实现蛇向上走push dxmov dh,1mov dl,0mov cx,23cmpu1:push cxmov cx,79cmpu2:readh dh,dlcmp pst,2jne nextu3jmp nextu4nextu3:jmp near ptr nextunextu4:readcg dh,dlpop cxjmp near ptr endunextu:inc dljmp nextu2chgu2:jmp near ptr cmpu2nextu2:loop chgu2sub dl,79inc dhpop cxjmp nextu1chgu1:jmp near ptr cmpu1nextu1:loop chgu1endu:pop dxdec dhwrite dh,dl,snkjmp near ptr wrt1turndown: ;此处实现蛇向下走push dxmov dh,1mov dl,0mov cx,23cmpd1:push cxmov cx,79cmpd2:readh dh,dlcmp pst,2jne nextd3jmp nextd4nextd3:jmp near ptr nextdnextd4:readcg dh,dlpop cxjmp near ptr enddnextd:inc dljmp nextd2chgd2:jmp near ptr cmpd2nextd2:loop chgd2sub dl,79inc dhpop cxjmp nextd1chgd1:jmp near ptr cmpd1nextd1:loop chgd1endd:pop dxinc dhwrite dh,dl,snkjmp near ptr wrt1turnback: ;此处实现蛇向右走push dxmov dh,1mov dl,0mov cx,23cmpb1:push cxmov cx,79cmpb2:readh dh,dlcmp pst,2jne nextb3jmp nextb4nextb3:jmp near ptr nextbnextb4:readcg dh,dlpop cxjmp near ptr endbnextb:jmp nextb2chgb2:jmp near ptr cmpb2nextb2:loop chgb2sub dl,79inc dhpop cxjmp nextb1chgb1:jmp near ptr cmpb1nextb1:loop chgb1endb:pop dxdec dlwrite dh,dl,snkjmp near ptr wrt1exit:mov ax,0 ;恢复int9中断mov es,axpush ds:[0]pop es:[9*4]push ds:[2]pop es:[9*4+2]mov ah,4chint 21hint9: ;更改后的中断服务程序push axin al,60hmov adrs,almov al,20hout 20h,aliretDLY PROC near ;延时子程序PUSH CXPUSH DXMOV DX,10000DL1: MOV CX,9801DL2: LOOP DL2DEC DXJNZ DL1POP DXPOP CXRETDLY ENDPRAND1 PROCPUSH CXPUSH DXPUSH AXSTIMOV AH,0 ;读时钟计数器值INT 1AHMOV AX,DX ;清高6位AND AH,3MOV DL,23 ;除23,产生0~23余数DIV DLMOV frow,AH ;余数存frow,作随机行数 POP AXPOP DXPOP CXRETRAND1 ENDPRAND2 PROCPUSH CXPUSH DXPUSH AXSTIMOV AH,0 ;读时钟计数器值INT 1AHMOV AX,DX ;清高6位AND AH,3MOV DL,79 ;除79,产生0~79余数DIV DLMOV fcol,AH ;余数存fcol,作随机列数 POP AXPOP DXPOP CXRETRAND2 ENDPCODE ENDSEND start。
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 );}}。
贪吃蛇源代码
以下是贪吃蛇源代码:#include<iostream.h>#include<windows.h>#include<time.h>#include<stdlib.h>#include<conio.h>#define N 21void gotoxy(int x,int y)//位置函数{COORD pos;pos.X=2*x;pos.Y=y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos); }void color(int a)//颜色函数{SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),a);}void init(int apple[2])//初始化函数(初始化围墙、显示信息、苹果){int i,j;//初始化围墙int wall[N+2][N+2]={{0}};for(i=1;i<=N;i++){for(j=1;j<=N;j++)wall[i][j]=1;}color(11);for(i=0;i<N+2;i++){for(j=0;j<N+2;j++){if(wall[i][j])cout<<"■";else cout<<"□" ;}cout<<endl;}gotoxy(N+3,1);//显示信息color(20);cout<<"按W S A D 移动方向"<<endl;gotoxy(N+3,2);color(20);cout<<"按任意键暂停"<<endl;gotoxy(N+3,3);color(20);cout<<"得分:"<<endl;apple[0]=rand()%N+1;//苹果apple[1]=rand()%N+1;gotoxy(apple[0],apple[1]);color(12);cout<<"●"<<endl;}int main(){int i,j;int** snake=NULL;int apple[2];int score=0;int tail[2];int len=3;char ch='p';srand((unsigned)time(NULL));init(apple);snake=(int**)realloc(snake,sizeof(int*)*len); for(i=0;i<len;i++)snake[i]=(int*)malloc(sizeof(int)*2);for(i=0;i<len;i++){snake[i][0]=N/2;snake[i][1]=N/2+i;gotoxy(snake[i][0],snake[i][1]);color(14);cout<<"★"<<endl;}while(1)//进入消息循环{tail[0]=snake[len-1][0];tail[1]=snake[len-1][1];gotoxy(tail[0],tail[1]);color(11);cout<<"■"<<endl;for(i=len-1;i>0;i--)snake[i][0]=snake[i-1][0];snake[i][1]=snake[i-1][1];gotoxy(snake[i][0],snake[i][1]);color(14);cout<<"★"<<endl;}if(kbhit()){gotoxy(0,N+2);ch=getche();}switch(ch){case 'w':snake[0][1]--;break;case 's':snake[0][1]++;break;case 'a':snake[0][0]--;break;case 'd':snake[0][0]++;break;default: break;}gotoxy(snake[0][0],snake[0][1]);color(14);cout<<"★"<<endl;Sleep(abs(200-0.5*score));if(snake[0][0]==apple[0]&&snake[0][1]==apple[1])//吃掉苹果后蛇分数加1,蛇长加1{score++;len++;snake=(int**)realloc(snake,sizeof(int*)*len);snake[len-1]=(int*)malloc(sizeof(int)*2);apple[0]=rand()%N+1;apple[1]=rand()%N+1;gotoxy(apple[0],apple[1]);color(12);cout<<"●"<<endl;gotoxy(N+5,3);color(20);cout<<score<<endl;}if(snake[0][1]==0||snake[0][1]==N||snake[0][0]==0||snake[0][0]==N)//撞到围墙后失败gotoxy(N/2,N/2);color(30);cout<<"失败!!!"<<endl; for(i=0;i<len;i++)free(snake[i]);Sleep(INFINITE);exit(0);}}return 0;}。
用汇编语言实现贪吃蛇游戏
moc.yrellagemeht.www
。示展家大为里本事记在将们我�示 展中TPP在便不�长太序程子的们我于由
moc.yrellagemeht.www
!uoY knahT
O/G/O/L
moc.yrellagemeht.www
• • • • • • • • • • • • • •
c.yrellagemeht.www sdnemo a tad • 物食生产来用,数机随; 0 BD DEES • 04 BD 3N • 712 BD 2N • 92 BD 1N • 命 生 次 几 有; 1 b d dro l • 度长的kcans; 4 bd sl • 向 方 的 前 当; thgir bd pmetd • 向 方; thgir bd d • 02 bd y • )y,x(置位前当的头的kcans; 02 b d x • 0 bd y f • )yf,xf(置位的物食; 0 bd xf • )0(pud 002 bd ys • )ys,xs(置位的蛇; )0(pud 002 bd xs • 单菜 ; '$',':level ruoy esoohC' bd • hd0,ha0,'redraH.5 ' bd •
moc.yrellagemeht.www
色 黑置 设 景背 为;
h01 tni 0 , h b v om h01 tnI 0,lb vom 1 , hb v o m
)式模形图的色颜种4、002×023(板色调�LB�H10 �HB�板色调择选�色颜�LB�H00�HB�色颜 置设�框边或色景背、板色调置设�能功HB0用调; 4*002*023:幕屏置设次再; 码制进二为换转码IICSA;
• • • • • • •
贪吃蛇游戏代码
贪吃蛇游戏代码贪吃蛇是一个经典的小游戏,可以在很多平台和设备上找到。
如果你想自己开发一个贪吃蛇游戏,这里有一个简单的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)```这个代码实现了一个简单的贪吃蛇游戏,包括基本的游戏循环、蛇的移动、食物的生成和碰撞检测。
《贪吃蛇》游戏程序代码
《贪吃蛇》游戏程序代码1. 游戏初始化:设置游戏窗口、蛇的初始位置和长度、食物的初始位置等。
2. 蛇的移动:根据用户输入的方向键,更新蛇的位置。
确保蛇的移动不会超出游戏窗口的边界。
3. 食物的:在游戏窗口中随机食物的位置。
确保食物不会出现在蛇的身体上。
4. 碰撞检测:检测蛇头是否撞到食物或自己的身体。
如果撞到食物,蛇的长度增加;如果撞到自己的身体,游戏结束。
5. 游戏循环:不断更新游戏画面,直到游戏结束。
6. 游戏结束:显示游戏结束的提示,并询问用户是否重新开始游戏。
import random游戏窗口大小WIDTH, HEIGHT = 800, 600蛇的初始位置和长度snake = [(WIDTH // 2, HEIGHT // 2)]snake_length = 1食物的初始位置food = (random.randint(0, WIDTH // 10) 10,random.randint(0, HEIGHT // 10) 10)蛇的移动方向direction = 'RIGHT'游戏循环while True:更新蛇的位置if direction == 'UP':snake.insert(0, (snake[0][0], snake[0][1] 10)) elif direction == 'DOWN':snake.insert(0, (snake[0][0], snake[0][1] + 10)) elif direction == 'LEFT':snake.insert(0, (snake[0][0] 10, snake[0][1])) elif direction == 'RIGHT':snake.insert(0, (snake[0][0] + 10, snake[0][1]))检测碰撞if snake[0] == food:food = (random.randint(0, WIDTH // 10) 10, random.randint(0, HEIGHT // 10) 10)else:snake.pop()检测游戏结束条件if snake[0] in snake[1:] or snake[0][0] < 0 or snake[0][0] >= WIDTH or snake[0][1] < 0 or snake[0][1] >= HEIGHT:break游戏画面更新(这里使用print代替实际的游戏画面更新) print(snake)用户输入方向键direction = input("请输入方向键(WASD): ").upper() print("游戏结束!")。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
DATA SEGMENTdw 0,0snk db 1blk db 32food db 3tal1 db 4tal2 db 2adrs db 5len db ?pst db ?addrs dw ?frow db ?fcol db ?hwrt db ?gmov db 'game over press r to restart press q to quit $'score1 db 'score :$'score2 db ?score0 db 1zero db 48writer db 'Developer: Geniusdot $'email db ': geniusdotgmail.$'msg1 db 'The way to play the game:$'way db ' press w to up ,press s to down,press a to left,press d to right$' msg db 'Press any key(except a,s,d,w) to start$'DATA ENDSSTACK SEGMENT stackdb 200 dup(0)STACK ENDSCODE SEGMENTASSUME CS:CODE,DS:DATA,SS:STACKstart:mov ax,datamov ds,axmov ax,0mov es,axmov frow,10mov fcol,6mov dh,10mov dl,26mov ah,2int 10hmov ah,9lea dx,msg1 int 21hmov dh,11 mov dl,7mov ah,2mov bh,0int 10hmov ah,9lea dx,wayint 21hmov dh,12 mov dl,20 mov ah,2mov bh,0int 10hmov ah,9lea dx,msgint 21hmov ah,0int 16hmov ah,6mov al,0mov ch,0mov cl,0mov dh,24 mov dl,79 mov bh,10int 10hmov dh,0mov dl,0mov ah,2mov bh,0int 10hmov ah,9lea dx,score1 int 21hmov dl,15 mov ah,2mov bh,0int 10hlea dx,writerint 21hmov ah,9lea dx,emailint 21hmov score2,48push es:[9*4] ;将原int9入口地址保存pop ds:[0]push es:[9*4+2]pop ds:[2]mov word ptr es:[9*4],offset int9 ;更改中断向量表mov es:[9*4+2],csjmp aawrite macro row,col,cnt ;宏定义用于向当前光标处输出字符push bxpush cxpush dxmov dh,rowmov dl,colmov ah,2mov bh,0int 10hmov ah,9mov bl,11mov cx,1lea di,cnt ;50mov al,[di]int 10hpop dxpop cxpop bxendmreadh macro row,col ;宏定义用于读出当前光标处字符push dxpush bxmov dh,rowmov dl,colmov ah,2mov bh,0int 10hmov ah,08hint 10hmov pst,alpop bxpop axpop dxendmwnear macro ;宏定义只用在readcg宏中当readcg的所有判断都不成立调用此宏local wnext1local wnext2local wnext3local wnext4push dxdec dhreadh dh,dlcmp pst,1jne wnext1write dh,dl,tal2jmp wnext4wnext1:inc dhdec dlreadh dh,dlcmp pst,1jne wnext2write dh,dl,tal2jmp wnext4wnext2:inc dhinc dlreadh dh,dlcmp pst,1jne wnext3write dh,dl,tal2jmp wnext4dec dhinc dlreadh dh,dlcmp pst,1jne wnext4write dh,dl,tal2wnext4:pop dxendmreadcg macro row,col ;宏定义用于改变判断出来的字符local tnup,tnup1,tnup2,tnlf,tnlf1,tnlf2,tndn,tndn1,tndn2,tnrt,tnrt1,tnrt2,goout push bxpush axpush dxwrite dh,dl,tal1dec rowreadh dh,dlcmp pst,4jne tnup1jmp tnup2tnup1:jmp near ptr tnuptnup2:write dh,dl,blkinc dhinc dhreadh dh,dlcmp pst,1jne tnupwrite dh,dl,tal2jmp near ptr goouttnup:pop dxpush dxdec colreadh dh,dlcmp pst,4jne tnlf1jmp tnlf2tnlf1:jmp near ptr tnlf tnlf2:write dh,dl,blk inc dlinc dlreadh dh,dlcmp pst,1jne tnlfwrite dh,dl,tal2 jmp near ptr goout tnlf:pop dxpush dxinc rowreadh dh,dlcmp pst,4jne tndn1jmp tndn2tndn1:jmp near ptr tndn tndn2:write dh,dl,blk dec dhdec dhreadh dh,dlcmp pst,1jne tndnwrite dh,dl,tal2 jmp near ptr goout tndn:pop dxpush dxinc colreadh dh,dlcmp pst,4jne tnrt1jmp tnrt2tnrt1:jmp near ptr tnrt tnrt2:write dh,dl,blk dec dldec dlreadh dh,dlcmp pst,1jne tnrtwrite dh,dl,tal2jmp near ptr goouttnrt:pop dxpush dxwneargoout:pop dxpop axpop bxendmaddone: ;此标号功能是将蛇身增加一push dxinc score2mov dh,1mov dl,0mov cx,23cmpad1:push cxmov cx,79cmpad2:readh dh,dlcmp pst,2jne nextad3jmp nextad4nextad3:jmp near ptr nextadnextad4:write dh,dl,snkdec dhreadh dh,dlcmp pst,4jne natupwrite dh,dl,tal2dec dhwrite dh,dl,tal1jmp outonatup:inc dhreadh dh,dlcmp pst,4jne natlfwrite dh,dl,tal2 dec dlwrite dh,dl,tal1 jmp outonatlf:inc dhinc dlreadh dh,dlcmp pst,4jne natdnwrite dh,dl,tal2 inc dhwrite dh,dl,tal1 jmp outonatdn:dec dhinc dlreadh dh,dlcmp pst,4jne natrtwrite dh,dl,tal2 inc dlwrite dh,dl,tal1 natrt:outo:pop cxjmp near ptr endad nextad:inc dljmp nextad2chgad2:jmp near ptr cmpad2 nextad2:loop chgad2sub dl,79inc dhpop cxjmp nextad1chgad1:jmp near ptr cmpad1loop chgad1endad:pop dxjmp near ptr crtfaa: ;从这开始产生最原始的蛇mov addrs,offset turnrightmov dh,10mov dl,1mov cx,3write dh,dl,tal1inc dlwrite dh,dl,tal2wrt:inc dlwrite dh,dl,snkloop wrtmov len,6mov ax,0jmp wrt1ovflw: ;当蛇碰壁或自身转到此游戏结束mov ah,6mov al,0mov ch,0mov cl,0mov dh,24mov dl,79mov bh,7int 10hmov dh,17mov dl,17mov ah,2mov bh,0int 10hmov ah,9lea dx,gmovint 21hmov ax,0 ;恢复int9中断mov es,axpush ds:[0]pop es:[9*4]push ds:[2]pop es:[9*4+2]stop:mov ah,0int 16hcmp al,'r'je aa1jmp aa2aa1:jmp near ptr startaa2:cmp al,'q'jne stopjmp near ptr exitwrt1: ;此处蛇行走过程的无限循环call dlypush dxinc dhcmp dh,25je ovflwinc dlcmp dl,80je ovflwpop dxpush dxdec dhcmp dh,0je ovflwdec dlcmp dl,-1je ovflwpop dxpush dxlea ax,turnrightcmp addrs,axjne tonxt2inc dlreadh dh,dlcmp pst,1je tonxt1cmp pst,2je tonxt1cmp pst,4je tonxt1jmp tonxt2 tonxt1:jmp ovflwtonxt2:pop dxpush dxlea ax,turnup cmp addrs,ax jne tonxt4dec dhreadh dh,dl cmp pst,1je tonxt3cmp pst,2je tonxt3cmp pst,4je tonxt3jmp tonxt4 tonxt3:jmp ovflwtonxt4:pop dxpush dxlea ax,turndown cmp addrs,ax jne tonxt6inc dhreadh dh,dl cmp pst,1je tonxt5cmp pst,2je tonxt5cmp pst,4je tonxt5jmp tonxt6 tonxt5:jmp ovflwtonxt6:pop dxpush dxlea ax,turnback cmp addrs,axjne tonxt8dec dlreadh dh,dlcmp pst,1je tonxt7cmp pst,2je tonxt7cmp pst,4je tonxt7jmp tonxt8tonxt7:jmp ovflwtonxt8:pop dxjmp nextacrtf1:jmp near ptr addone crtf:call rand1call rand2inc frowmov ah,frowmov al,fcolpush dxmov dh,1mov dl,0push cxmov cx,23check1:push cxmov cx,79check2:readh dh,dlcmp pst,1je nextncmp pst,2je nextncmp pst,4je nextnjmp nextnnnextn:cmp ax,dxje crtfnextnn:inc dlloop check2inc dhsub dl,79pop cxloop check1pop cxpop dxwrite frow,fcol,food nexta:mov ah,frowmov al,fcolcmp ax,dxje crtf12jmp crtf13crtf12:jmp near ptr crtf1 crtf13:push dxcmp score2,58jl normalmov score2,49inc score0normal:mov dh,0mov dl,8write dh,dl,score2 add dl,score0write dh,dl,zeropop dxcmp adrs,17je jmp1cmp adrs,145je jmp1cmp adrs,31je jmp2cmp adrs,159je jmp2cmp adrs,32je jmp3cmp adrs,160je jmp3cmp adrs,30je jmp4cmp adrs,158je jmp4jmp addrsjmp1:lea ax, turndowncmp ax,addrsje jmp2mov addrs,offset turnupjmp near ptr turnupjmp2:lea ax,turnupcmp ax,addrsje jmp1mov addrs,offset turndownjmp near ptr turndownjmp3:lea ax,turnbackcmp ax,addrsje jmp4mov addrs,offset turnrightjmp near ptr turnrightjmp4:lea ax,turnrightcmp ax,addrsje jmp3mov addrs,offset turnbackjmp near ptr turnbackturnright: ;此处实现蛇向左走push dxmov dh,1mov dl,0mov cx,23cmpr1:push cxmov cx,79cmpr2:readh dh,dlcmp pst,2je nextr4jmp near ptr nextrnextr4:readcg dh,dlpop cxjmp near ptr endrnextr:inc dljmp nextr2chgr2:jmp near ptr cmpr2nextr2:loop chgr2sub dl,79inc dhpop cxjmp nextr1chgr1:jmp near ptr cmpr1nextr1:loop chgr1endr:pop dxinc dlwrite dh,dl,snkjmp near ptr wrt1turnup: ;此处实现蛇向上走push dxmov dh,1mov dl,0mov cx,23cmpu1:push cxmov cx,79cmpu2:readh dh,dlcmp pst,2jne nextu3jmp nextu4nextu3:jmp near ptr nextunextu4:readcg dh,dlpop cxjmp near ptr endunextu:inc dljmp nextu2chgu2:jmp near ptr cmpu2nextu2:loop chgu2sub dl,79inc dhpop cxjmp nextu1chgu1:jmp near ptr cmpu1nextu1:loop chgu1endu:pop dxdec dhwrite dh,dl,snkjmp near ptr wrt1turndown: ;此处实现蛇向下走push dxmov dh,1mov dl,0mov cx,23cmpd1:push cxmov cx,79cmpd2:readh dh,dlcmp pst,2jne nextd3jmp nextd4nextd3:jmp near ptr nextdnextd4:readcg dh,dlpop cxjmp near ptr enddnextd:inc dljmp nextd2chgd2:jmp near ptr cmpd2nextd2:loop chgd2sub dl,79inc dhpop cxjmp nextd1chgd1:jmp near ptr cmpd1nextd1:loop chgd1endd:pop dxinc dhwrite dh,dl,snkjmp near ptr wrt1turnback: ;此处实现蛇向右走push dxmov dh,1mov dl,0mov cx,23cmpb1:push cxmov cx,79cmpb2:readh dh,dlcmp pst,2jne nextb3jmp nextb4nextb3:jmp near ptr nextbnextb4:readcg dh,dlpop cxjmp near ptr endbnextb:jmp nextb2chgb2:jmp near ptr cmpb2nextb2:loop chgb2sub dl,79inc dhpop cxjmp nextb1chgb1:jmp near ptr cmpb1nextb1:loop chgb1endb:pop dxdec dlwrite dh,dl,snkjmp near ptr wrt1exit:mov ax,0 ;恢复int9中断mov es,axpush ds:[0]pop es:[9*4]push ds:[2]pop es:[9*4+2]mov ah,4chint 21hint9: ;更改后的中断服务程序push axin al,60hmov adrs,almov al,20hout 20h,aliretDLY PROC near ;延时子程序PUSH CXPUSH DXMOV DX,10000DL1: MOV CX,9801DL2: LOOP DL2DEC DXJNZ DL1POP DXPOP CXRETDLY ENDPRAND1 PROCPUSH CXPUSH DXPUSH AXSTIMOV AH,0 ;读时钟计数器值INT 1AHMOV AX,DX ;清高6位AND AH,3MOV DL,23 ;除23,产生0~23余数DIV DLMOV frow,AH ;余数存frow,作随机行数 POP AXPOP DXPOP CXRETRAND1 ENDPRAND2 PROCPUSH CXPUSH DXPUSH AXSTIMOV AH,0 ;读时钟计数器值INT 1AHMOV AX,DX ;清高6位AND AH,3MOV DL,79 ;除79,产生0~79余数DIV DLMOV fcol,AH ;余数存fcol,作随机列数 POP AXPOP DXPOP CXRETRAND2 ENDPCODE ENDSEND start。