简单小游戏“贪吃蛇”可运行代码

合集下载

贪吃蛇JAVA源代码完整版

贪吃蛇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);});}}。

简单的贪吃蛇游戏代码示例

简单的贪吃蛇游戏代码示例

《简单的贪吃蛇游戏代码示例,使用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语言小游戏源代码《贪吃蛇》

C语言小游戏源代码《贪吃蛇》
void main(void){/*主函数体,调用以下四个函数*/ init(); setbkcolor(7); drawk(); gameplay(); close(); }
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语言源代码

贪吃蛇游戏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实现的贪吃蛇小游戏代码

以下是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()```当您运行此代码时,将会启动一个贪吃蛇小游戏。

超简单贪吃蛇c语言代码编写

超简单贪吃蛇c语言代码编写

超简单贪吃蛇c语言代码编写贪吃蛇其实就是实现以下几步——1:蛇的运动(通过“画头擦尾”来达到蛇移动的视觉效果)2:生成食物3:蛇吃食物(实现“画头不擦尾”)4:游戏结束判断(也就是蛇除了食物,其余东西都不能碰)#include<stdio.h>#include<stdlib.h>#include<windows.h>#include<conio.h>#include<time.h>#define width 60#define hight 25#define SNAKESIZE 200//蛇身的最长长度int key=72;//初始化蛇的运动方向,向上int changeflag=1;//用来标识是否生成食物,1表示蛇还没吃到食物,0表示吃到食物int speed=0;//时间延迟struct {int len;//用来记录蛇身每个方块的坐标int x[SNAKESIZE];int y[SNAKESIZE];int speed;}snake;struct{int x;int y;}food;void gotoxy(int x,int y)//调用Windows的API函数,可以在控制台的指定位置直接操作,这里可暂时不用深究{COORD coord;coord.X = x;coord.Y = y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); }//■○void drawmap(){//打印图框for (int _y = 0; _y < hight; _y++){for (int x = 0; x < width; x+=2){if (x == 0 || _y == 0 || _y == hight - 1 || x == width - 2){gotoxy(x, _y);printf("■");}}}//打印蛇头snake.len=3;snake.x[0]=width/2;snake.y[0]=hight/2;gotoxy(snake.x[0],snake.y[0]);printf("■");//打印蛇身for(int i=1;i<snake.len;i++){snake.x[i]=snake.x[i-1];snake.y[i]=snake.y[i-1]+1;gotoxy(snake.x[i],snake.y[i]);printf("■");}//初始化食物的位置food.x=20;food.y=20;gotoxy(food.x,food.y);printf("○");}/**控制台按键所代表的数字*“↑”:72*“↓”:80*“←”:75*“→”:77*/void snake_move()//按键处理函数{int history_key=key;if (_kbhit()){fflush(stdin);key = _getch();key = _getch();}if(changeflag==1)//还没吃到食物,把尾巴擦掉{gotoxy(snake.x[snake.len-1],snake.y[snake.len-1]);printf(" ");}for(int i=snake.len-1;i>0;i--){snake.x[i]=snake.x[i-1];snake.y[i]=snake.y[i-1];}if(history_key==72&&key==80)key=72;if(history_key==80&&key==72)key=80;if(history_key==75&&key==77)key=75;if(history_key==77&&key==75)key=77;switch(key){case 72:snake.y[0]--;break;case 75:snake.x[0]-= 2;break;case 77:snake.x[0]+= 2;break;case 80:snake.y[0]++;break;}gotoxy(snake.x[0],snake.y[0]);printf("■");gotoxy(0,0);changeflag=1;}void creatfood(){if(snake.x[0] == food.x && snake.y[0] == food.y)//只有蛇吃到食物,才能生成新食物{changeflag=0;snake.len++;if(speed<=100)speed+=10;while(1){srand((unsigned int) time(NULL));food.x=rand()%(width-6)+2;//限定食物的x范围不超出围墙,但不能保证food.x 为偶数food.y=rand()%(hight-2)+1;for(int i=0;i<snake.len;i++){if(food.x==snake.x[i]&&food.y==snake.y[i])//如果产生的食物与蛇身重合则退出break;}if(food.x%2==0)break;//符合要求,退出循环}gotoxy(food.x,food.y);printf("○");}}bool Gameover(){//碰到围墙,OVERif(snake.x[0]==0||snake.x[0]==width-2)return false;if(snake.y[0]==0||snake.y[0]==hight-1) return false;//蛇身达到最长,被迫OVERif(snake.len==SNAKESIZE)return false;//头碰到蛇身,OVERfor(int i=1;i<snake.len;i++){if(snake.x[0]==snake.x[i]&&snake.y[0]==snake.y[i])return false;}return true;}int main(){system("mode con cols=60 lines=27");drawmap();while(Gameover()){snake_move();creatfood();Sleep(350-speed);//蛇的移动速度}return 0;}。

基于C语言实现的贪吃蛇游戏完整实例代码

基于C语言实现的贪吃蛇游戏完整实例代码

基于C语⾔实现的贪吃蛇游戏完整实例代码本⽂以实例的形式讲述了基于C语⾔实现的贪吃蛇游戏代码,这是⼀个⽐较常见的游戏,代码备有⽐较详细的注释,对于读者理解有⼀定的帮助。

贪吃蛇完整实现代码如下:#include <graphics.h>#include <conio.h>#include <stdlib.h>#include <dos.h>#define NULL 0#define UP 18432#define DOWN 20480#define LEFT 19200#define RIGHT 19712#define ESC 283#define ENTER 7181struct snake{int centerx;int centery;int newx;int newy;struct snake *next;};struct snake *head;int grade=60; /*控制速度的*******/int a,b; /* 背静遮的位置*/void *far1,*far2,*far3,*far4; /* 蛇⾝指针背静遮的指针⾍⼦*/int size1,size2,size3,size4; /* **全局变量**/int ch=RIGHT; /**************存按键开始蛇的⽅向为RIGHT***********/int chy=RIGHT;int flag=0; /*********判断是否退出游戏**************/int control=4; /***********判断上次⽅向和下次⽅向不冲突***/int nextshow=1; /*******控制下次蛇⾝是否显⽰***************/int scenterx; /***************随即矩形中⼼坐标***************/int scentery;int sx; /*******在a b 未改变前得到他们的值保证随机矩形也不在此出现*******/int sy;/************************蛇⾝初始化**************************/void snakede(){struct snake *p1,*p2;head=p1=p2=(struct snake *)malloc(sizeof(struct snake));p1->centerx=80;p1->newx=80;p1->centery=58;p1->newy=58;p1=(struct snake *)malloc(sizeof(struct snake));p2->next=p1;p1->centerx=58;p1->newx=58;p1->centery=58;p1->newy=58;p1->next=NULL;}/*******************end*******************/void welcome() /*************游戏开始界⾯ ,可以选择 速度**********/{int key;int size;int x=240;int y=300;int f;void *buf;setfillstyle(SOLID_FILL,BLUE);bar(98,100,112,125);setfillstyle(SOLID_FILL,RED);buf=malloc(size);getimage(98,100,112,125,buf);cleardevice();setfillstyle(SOLID_FILL,BLUE);bar(240,300,390,325);outtextxy(193,310,"speed:");setfillstyle(SOLID_FILL,RED);bar(240,312,390,314);setcolor(YELLOW);outtextxy(240,330,"DOWN");outtextxy(390,330,"UP");outtextxy(240,360,"ENTER to start..." );outtextxy(270,200,"SNAKE");fei(220,220);feiyang(280,220);yang(340,220);putimage(x,y,buf,COPY_PUT);setcolor(RED);rectangle(170,190,410,410);while(1){ if(bioskey(1)) /********8选择速度部分************/key=bioskey(0);switch(key){case ENTER:f=1;break;case DOWN:if(x>=240){ putimage(x-=2,y,buf,COPY_PUT);grade++;key=0;break;}case UP:if(x<=375){ putimage(x+=2,y,buf,COPY_PUT);grade--;key=0;break;}}if (f==1)break;} /********** end ****************/free(buf);}/*************************随即矩形*****************//***********当nextshow 为1的时候才调⽤此函数**********/void ran(){ int nx;int ny;int show; /**********控制是否显⽰***********/int jump=0;struct snake *p;p=head;if(nextshow==1) /***********是否开始随机产⽣***************/while(1){show=1;randomize();nx=random(14);ny=random(14);scenterx=nx*22+58;scentery=ny*22+58;while(p!=NULL){if(scenterx==p->centerx&&scentery==p->centery||scenterx==sx&&scentery==sy)}elsep=p->next;if(jump==1)break;}if(show==1){putimage(scenterx-11,scentery-11,far3,COPY_PUT); nextshow=0;break;}}}/***********过关动画**************/void donghua(){ int i;cleardevice();setbkcolor(BLACK);randomize();while(1){for(i=0;i<=5;i++){putpixel(random(640),random(80),13);putpixel(random(640),random(80)+80,2);putpixel(random(640),random(80)+160,3);putpixel(random(640),random(80)+240,4);putpixel(random(640),random(80)+320,1);putpixel(random(640),random(80)+400,14);}setcolor(YELLOW);settextstyle(0,0,4);outtextxy(130,200,"Wonderful!!");setfillstyle(SOLID_FILL,10);bar(240,398,375,420);feiyang(300,400);fei(250,400);yang(350,400);if(bioskey(1))if(bioskey(0)==ESC){flag=1;break;}}}/*************************end************************//***********************初始化图形系统*********************/ void init(){int a=DETECT,b;int i,j;initgraph(&a,&b,"");}/***************************end****************************//***画⽴体边框效果函数******/void tline(int x1,int y1,int x2,int y2,int white,int black) { setcolor(white);line(x1,y1,x2,y1);line(x1,y1,x1,y2);setcolor(black);line(x2,y1,x2,y2);line(x1,y2,x2,y2);}/****end*********//*************飞洋标志**********/int feiyang(int x,int y){int feiyang[18][18]={ {0,0,0,0,0,0,1,1,1,1,1,1,0,1,1,0,0,0}, {0,0,0,0,0,1,1,1,0,0,1,1,1,1,1,0,0,0},{0,0,0,0,1,1,1,0,0,0,0,0,1,1,1,0,0,0},{0,0,1,1,0,1,1,1,1,1,1,0,0,0,0,0,0,0},{0,0,1,1,1,1,1,0,0,1,0,0,1,1,0,0,0,0},{0,0,1,1,1,0,0,0,0,1,0,1,1,1,0,0,0,0},{0,0,1,1,0,1,1,1,0,1,1,1,0,0,0,0,0,0},{0,0,1,1,0,0,0,1,0,0,1,1,0,0,0,0,0,0},{0,0,1,1,0,0,0,1,1,0,0,1,1,0,0,1,0,0},{0,0,1,1,1,0,0,1,1,0,0,1,1,0,0,1,0,0},{0,0,1,1,1,1,0,1,1,1,1,1,1,0,1,1,0,0},{0,0,0,1,1,1,0,1,1,1,1,1,0,0,1,0,0,0},{0,0,0,0,1,1,1,0,0,0,0,0,0,1,1,0,0,0},{0,0,0,0,0,1,1,1,0,0,0,0,1,1,0,0,0,0},{0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,0}};int i,j;for(i=0;i<=17;i++)for(j=0;j<=17;j++){if (feiyang[i][j]==1)putpixel(j+x,i+y,RED);}}/********"飞"字*************/int fei(int x,int y){int fei[18][18]={{1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0},{0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,1,1,0,0,1,0,0,0,0},{0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0,0},{0,0,0,0,0,0,0,0,0,1,1,0,1,1,0,0,0,0},{0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,1,1,0,1,1,1,0,0,0},{0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0},{0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,0,0},{0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0},{0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,1},{0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1},{0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1},{0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0},{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0}};int i,j;for(i=0;i<=17;i++)for(j=0;j<=17;j++){if (fei[i][j]==1)putpixel(j+x,i+y,BLUE);}}/*********"洋"字**************/int yang(int x,int y){int yang[18][18]={{0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0}, {1,1,0,0,0,0,1,1,1,0,0,0,1,1,0,0,0,0},{0,1,1,1,0,0,0,1,1,1,0,1,1,0,0,0,0,0},{0,0,1,1,0,0,0,0,0,1,1,1,0,0,0,1,0,0},{0,0,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,0},{0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0},{1,1,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0},{0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0},{0,0,1,1,0,0,0,1,1,1,1,1,1,1,1,0,0,0},{0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0},{0,0,0,1,0,0,1,0,0,0,1,0,0,0,0,0,0,0},{0,0,0,0,0,1,1,0,0,0,1,0,0,0,0,1,1,0},{0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1},{0,0,0,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0},{1,1,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0},{0,1,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0},{0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0},{0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0}};int i,j;for(i=0;i<=17;i++)for(j=0;j<=17;j++)}/******************主场景**********************/int bort(){ int a;setfillstyle(SOLID_FILL,15);bar(49,49,71,71);setfillstyle(SOLID_FILL,BLUE);bar(50,50,70,70);size1=imagesize(49,49,71,71);far1=(void *)malloc(size1);getimage(49,49,71,71,far1);cleardevice();setfillstyle(SOLID_FILL,12);bar(49,49,71,71);size2=imagesize(49,49,71,71);far2=(void *)malloc(size2);getimage(49,49,71,71,far2);setfillstyle(SOLID_FILL,12);bar(49,49,71,71);setfillstyle(SOLID_FILL,GREEN);bar(50,50,70,70);size3=imagesize(49,49,71,71);far3=(void *)malloc(size3);getimage(49,49,71,71,far3);cleardevice(); /*取蛇⾝节点背景节点⾍⼦节点end*/setbkcolor(8);setfillstyle(SOLID_FILL,GREEN);bar(21,23,600,450);tline(21,23,600,450,15,8); /***开始游戏场景边框⽴体效果*******/ tline(23,25,598,448,15,8);tline(45,45,379,379,8,15);tline(43,43,381,381,8,15);tline(390,43,580,430,8,15);tline(392,45,578,428,8,15);tline(412,65,462,85,15,8);tline(410,63,464,87,15,8);tline(410,92,555,390,15,8);tline(412,94,553,388,15,8);tline(431,397,540,420,15,8);tline(429,395,542,422,15,8);tline(46,386,377,428,8,15);tline(44,384,379,430,8,15);setcolor(8);outtextxy(429,109,"press ENTER ");outtextxy(429,129,"---to start"); /*键盘控制说明*/outtextxy(429,169,"press ESC ");outtextxy(429,189,"---to quiet");outtextxy(469,249,"UP");outtextxy(429,289,"LEFT");outtextxy(465,329,"DOWN");outtextxy(509,289,"RIGHT");setcolor(15);outtextxy(425,105,"press ENTER ");outtextxy(425,125,"---to start");outtextxy(425,165,"press ESC ");outtextxy(425,185,"---to quiet");outtextxy(465,245,"UP");outtextxy(425,285,"LEFT");outtextxy(461,325,"DOWN");outtextxy(505,285,"RIGHT"); /*******end*************/setcolor(8);outtextxy(411,52,"score");outtextxy(514,52,"left");setcolor(15);outtextxy(407,48,"score");outtextxy(510,48,"left");size4=imagesize(409,62,465,88); /****分数框放到内存********/far4=(void *)malloc(size4);getimage(409,62,465,88,far4);outtextxy(415,70,"0"); /***************输⼊分数为零**********/outtextxy(512,70,"20"); /*************显⽰还要吃的⾍⼦的数⽬*********/ bar(46,46,378,378);feiyang(475,400);fei(450,400);yang(500,400);outtextxy(58,390,"mailto:************************");outtextxy(58,410,"snake game");outtextxy(200,410,"made by yefeng");while(1){ if(bioskey(1))a=bioskey(0);if(a==ENTER)break;}}/******************gameover()******************/void gameover(){ char *p="GAME OVER";int cha;setcolor(YELLOW);settextstyle(0,0,6);outtextxy(100,200,p);while(1){if(bioskey(1))cha=bioskey(0);if(cha==ESC){flag=1;break;}}}/***********显⽰蛇⾝**********************/void snakepaint(){struct snake *p1;p1=head;putimage(a-11,b-11,far2,COPY_PUT);while(p1!=NULL){putimage(p1->newx-11,p1->newy-11,far1,COPY_PUT);p1=p1->next;}}/****************end**********************//*********************蛇⾝刷新变化游戏关键部分 *******************/void snakechange(){struct snake *p1,*p2,*p3,*p4,*p5;int i,j;static int n=0;static int score;static int left=20;char sscore[5];char sleft[1];p2=p1=head;while(p1!=NULL){ p1=p1->next;if(p1->next==NULL){a=p1->newx;b=p1->newy; /************记录最后节点的坐标************/sx=a;sy=b;}p1->newx=p2->centerx;p1->newy=p2->centery;p2=p1;}p1=head;p1=p1->next;}/********判断按键⽅向*******/if(bioskey(1)){ ch=bioskey(0);if(ch!=RIGHT&&ch!=LEFT&&ch!=UP&&ch!=DOWN&&ch!=ESC) /********chy为上⼀次的⽅向*********/ ch=chy;}switch(ch){case LEFT: if(control!=4){head->newx=head->newx-22;head->centerx=head->newx;control=2;if(head->newx<47)gameover();}else{ head->newx=head->newx+22;head->centerx=head->newx;control=4;if(head->newx>377)gameover();}chy=ch;break;case DOWN:if(control!=1){ head->newy=head->newy+22;head->centery=head->newy;control=3;if(head->newy>377)gameover();}else{ head->newy=head->newy-22;head->centery=head->newy;control=1;if(head->newy<47)gameover();}chy=ch;break;case RIGHT: if(control!=2){ head->newx=head->newx+22;head->centerx=head->newx;control=4;if(head->newx>377)gameover();}else{ head->newx=head->newx-22;head->centerx=head->newx;control=2;if(head->newx<47)gameover();}chy=ch;break;case UP: if(control!=3){ head->newy=head->newy-22;head->centery=head->newy;control=1;if(head->newy<47)gameover();}else{ head->newy=head->newy+22;head->centery=head->newy;control=3;if(head->newy>377)gameover();case ESC:flag=1;break;}/* if 判断是否吃蛇*/if(flag!=1){ if(head->newx==scenterx&&head->newy==scentery){ p3=head;while(p3!=NULL){ p4=p3;p3=p3->next;}p3=(struct snake *)malloc(sizeof(struct snake));p4->next=p3;p3->centerx=a;p3->newx=a;p3->centery=b;p3->newy=b;p3->next=NULL;a=500;b=500;putimage(409,62,far4,COPY_PUT); /********** 分数框挡住**************/putimage(500,62,far4,COPY_PUT); /*********把以前的剩下⾍⼦的框挡住********/ score=(++n)*100;left--;itoa(score,sscore,10);itoa(left,sleft,10);setcolor(RED);outtextxy(415,70,sscore);outtextxy(512,70,sleft);nextshow=1;if(left==0) /************判断是否过关**********/donghua(); /*******如果过关,播放过关动画*********************/}p5=head; /*********************判断是否⾃杀***************************/p5=p5->next;p5=p5->next;p5=p5->next;p5=p5->next; /****从第五个节点判断是否⾃杀************/while(p5!=NULL){if(head->newx==p5->centerx&&head->newy==p5->centery){ gameover();break;}elsep5=p5->next;}}}/************snakechange()函数结束*******************//*****************************主函数******************************************/int main(){ int i;init(); /**********初始化图形系统**********/welcome(); /*********8欢迎界⾯**************/bort(); /*********主场景***************/snakede(); /**********连表初始化**********/while(1){ snakechange();if(flag==1)break;snakepaint();ran();for(i=0;i<=grade;i++)delay(3000);free(far3);free(far4);closegraph(); return 0;}。

JAVA小程序—贪吃蛇源代码

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 + "&#92;n&#92;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 + "&#92;n&#92;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!&#92;n&#92;n" + "Author: FinalCore&#92;n&#92;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语言贪吃蛇源代码

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语言编写)

贪吃蛇游戏代码(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++)<>。

C语言课程设计贪吃蛇源代码

C语言课程设计贪吃蛇源代码

C语言程序贪吃蛇代码#include<stdio.h>#include<windows.h>#include<time.h>#include<stdlib.h>#include<conio.h>#define N 21FILE *fp;int S;void boundary(void);//开始界面void end(void); //结束void gotoxy(int x,int y)//位置函数{COORD pos;pos.X=x;pos.Y=y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos); }void color(int a)//颜色函数{SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),a);}void init(int food[2])//初始化函数(初始化围墙、显示信息、苹果){system("cls");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(10);for(i=0;i<N+2;i++)//畵围墙{for(j=0;j<N+2;j++){if(wall[i][j])printf(" ");else printf("#") ;}printf("\n") ;}gotoxy(N+3,3);//显示信息color(14);printf("\t\t按a,b,c,d改变方向\n");gotoxy(N+3,1);color(14);printf("\t\t按任意键暂停,按1返回,按2退出\n"); gotoxy(N+5,3);color(14);printf("score:\n");food[0]=rand()%N+1;//随机出现食物food[1]=rand()%N+1;gotoxy(food[0],food[1]);color(12);printf("*\n");}void play()//具体玩的过程{system("cls");int i,j;int** snake=NULL;//定义蛇的二维指针int food[2];//食物的数组,food[0]代表横坐标,food[1]代表纵坐标int score=0;//为得分int tail[2];//此数组为了记录蛇的头的坐标int node=3;//蛇的节数char ch='p';srand((unsigned)time(NULL));//随机数发生器的初始化函数init(food);snake=(int**)realloc(snake,sizeof(int*)*node);//改变snake所指内存区域的大小为node长度for(i=0;i<node;i++)snake[i]=(int*)malloc(sizeof(int)*2);for(i=0;i<node;i++)//初始化蛇的长度{snake[i][0]=N/2;snake[i][1]=N/2+i;gotoxy(snake[i][0],snake[i][1]);color(14);printf("*\n");}while(1)//进入消息循环{gotoxy(5,0);color(10);printf("#");gotoxy(0,5);color(10);printf("#");gotoxy(0,7);color(10);printf("#");gotoxy(0,9);color(10);printf("#");tail[0]=snake[node-1][0];//将蛇的后一节坐标赋给tail数组tail[1]=snake[node-1][1];gotoxy(tail[0],tail[1]);color(0);printf(" ");for(i=node-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);printf("*\n");}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;case '1':boundary() ;break;case '2':end();break;default: break;}gotoxy(snake[0][0],snake[0][1]);color(14);printf("*\n");Sleep(abs(200-0.5*score));//使随着分数的增长蛇的移动速度越来越快if(snake[0][0]==food[0]&&snake[0][1]==food[1])//吃掉食物后蛇分数加1,蛇长加1 {score++;//分数增加S=score;node++;//节数增加snake=(int**)realloc(snake,sizeof(int*)*node);snake[node-1]=(int*)malloc(sizeof(int)*2);food[0]=rand()%N+1;//产生随机数且要在围墙内部food[1]=rand()%N+1;gotoxy(food[0],food[1]);color(12);printf("*\n");gotoxy(N+12,3);color(14);printf("%d\n",score);//输出得分}if(snake[0][1]==0||snake[0][1]==N+1||snake[0][0]==0||snake[0][0]==N+1)//撞到围墙后失败{gotoxy(N/2,N/2);color(30);printf("GAME OVER\n");for(i=0;i<node;i++)free(snake[i]);Sleep(INFINITE);exit(0);}}//从蛇的第四节开始判断是否撞到自己,因为蛇头为两节,第三节不可能拐过来for (i=3; i<node; i++){for(j=0;j<node;j++){if (snake[i][0]==snake[j][0] && snake[i][1]==snake[j][1]){gotoxy(N/2,N/2);color(30);printf("GAME OVER\n");for(i=0;i<node;i++)free(snake[i]);Sleep(INFINITE);exit(0);;}}}}void end()//结束函数{system("cls");system("cls");printf("EXIT\n");}void grade()//成绩记录函数{system("cls");int i=0;char s;if( (fp=fopen("f:\\贪吃蛇\\贪吃蛇.txt","ar") )==NULL)//打开文件{printf("\nCannot open file!\n");exit(0);}if(i<S)i=S;color(14);fwrite(&i,sizeof(i),1,fp);fclose(fp);printf("最高的分为:%d\n\n",i);printf("\t按1返回\n\n");printf("\t按2退出\n\n");s=getche();switch(s){case '1':boundary();break;case '2': end();break;}}void boundary()//开始界面{system("cls");char s;color(14);printf("\t\t欢迎来玩!!\n\n");printf("\t\t1:开始\n\n");printf("\t\t2:查看成绩\n\n");printf("\t\t3:退出\n\n");printf("\t\t请选择:");s=getche();switch(s){case '1': play();break;case '2': grade();break;case '3': end();break;}}int main(){boundary();getchar();return 0;}。

贪吃蛇源代码

贪吃蛇源代码

#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;}。

经典游戏贪吃蛇代码(c++编写)

经典游戏贪吃蛇代码(c++编写)

经典游戏贪吃蛇代码(c++编写)/* 头文件 */#include#includeusing namespace std;#ifndef SNAKE_H#define SNAKE_Hclass Cmp{friend class Csnake;int rSign; //横坐标int lSign; //竖坐标public://friend bool isDead(const Cmp& cmp); Cmp(int r,int l){setPoint(r,l);}Cmp(){}void setPoint(int r,int l){rSign=r;lSign=l;}Cmp operator-(const Cmp &m)const{return Cmp(rSign - m.rSign,lSign - m.lSign);}Cmp operator+(const Cmp &m)const{return Cmp(rSign + m.rSign,lSign + m.lSign);}};const int maxSize = 5; //初始蛇身长度class Csnake{Cmp firstSign; //蛇头坐标Cmp secondSign;//蛇颈坐标Cmp lastSign; //蛇尾坐标Cmp nextSign; //预备蛇头int row; //列数int line; //行数int count; //蛇身长度vector<vector > snakeMap;//整个游戏界面queue snakeBody; //蛇身public:int GetDirections()const;char getSymbol(const Cmp& c)const //获取指定坐标点上的字符{return snakeMap[c.lSign][c.rSign];}Csnake(int n) //初始化游戏界面大小{if(n<20)line=20+2;else if(n>30)line = 30 + 2;else line=n+2;row=line*3+2;}bool isDead(const Cmp& cmp){return ( getSymbol(cmp)=='c' || cmp.rSign == row-1 || cmp.rSign== 0 || cmp.lSign == line-1 || cmp.lSign == 0 );}void InitInstance(); //初始化游戏界面bool UpdataGame(); //更新游戏界面void ShowGame(); //显示游戏界面};#endif // SNAKE_H====================================== ==============================/* 类的实现及应用*/#include#include#include#include "snake.h"using namespace std;//测试成功void Csnake::InitInstance(){snakeMap.resize(line); // snakeMap[竖坐标][横坐标]for(int i=0;i{snakeMap[i].resize(row);for(int j=0;j{snakeMap[i][j]=' ';}}for(int m=1;m{//初始蛇身snakeMap[line/2][m]='c';//将蛇身坐标压入队列snakeBody.push(Cmp(m,(line/2)));//snakeBody[横坐标][竖坐标]}//链表头尾firstSign=snakeBody.back();secondSign.setPoint(maxSize-1,line/2);}//测试成功int Csnake::GetDirections()const{if(GetKeyState(VK_UP)<0) return 1; //1表示按下上键if(GetKeyState(VK_DOWN)<0) return 2; //2表示按下下键if(GetKeyState(VK_LEFT)<0) return 3; //3表示按下左键if(GetKeyState(VK_RIGHT)<0)return 4; //4表示按下右键return 0;}bool Csnake::UpdataGame(){//-----------------------------------------------//初始化得分0static int score=0;//获取用户按键信息int choice;choice=GetDirections();cout<<"Total score: "<<score</</score<</vector/随机产生食物所在坐标int r,l;//开始初始已经吃食,产生一个食物static bool eatFood=true;//如果吃了一个,才再出现第2个食物if(eatFood){do{//坐标范围限制在(1,1)到(line-2,row-2)对点矩型之间srand(time(0));r=(rand()%(row-2))+1; //横坐标l=(rand()%(line-2))+1;//竖坐标//如果随机产生的坐标不是蛇身,则可行//否则重新产生坐标if(snakeMap[l][r]!='c'){snakeMap[l][r]='*';}}while (snakeMap[l][r]=='c');}switch (choice){case 1://向上//如果蛇头和社颈的横坐标不相同,执行下面操作if(firstSign.rSign!=secondSign.rSign)nextSign.setPoint(firstSi gn.rSign,firstSign.lSign-1);//否则,如下在原本方向上继续移动else nextSign=firstSign+(firstSign-secondSign); break;case 2://向下if(firstSign.rSign!=secondSign.rSign)nextSign.setPoint(firstSi gn.rSign,firstSign.lSign+1);else nextSign=firstSign+(firstSign-secondSign); break;case 3://向左if(firstSign.lSign!=secondSign.lSign)nextSign.setPoint(firstSi gn.rSign-1,firstSign.lSign);else nextSign=firstSign+(firstSign-secondSign);break;case 4://向右if(firstSign.lSign!=secondSign.lSign)nextSign.setPoint(firstSi gn.rSign+1,firstSign.lSign);else nextSign=firstSign+(firstSign-secondSign);break;default:nextSign=firstSign+(firstSign-secondSign);}//----------------------------------------------------------if(getSymbol(nextSign)!='*' && !isDead(nextSign)) //如果没有碰到食物(且没有死亡的情况下),删除蛇尾,压入新的蛇头{//删除蛇尾lastSign=snakeBody.front();snakeMap[lastSign.lSign][lastSign.rSign]=' ';snakeBody.pop();//更新蛇头secondSign=firstSign;//压入蛇头snakeBody.push(nextSign);firstSign=snakeBody.back();snakeMap[firstSign.lSign][firstSign.rSign]='c';//没有吃食eatFood=false;return true;}//-----吃食-----else if(getSymbol(nextSign)=='*' && !isDead(nextSign)){secondSign=firstSign;snakeMap[nextSign.lSign][nextSign.rSign]='c';//只压入蛇头snakeBody.push(nextSign);firstSign=snakeBody.back();eatFood=true;//加分score+=20;return true;}//-----死亡-----else {cout<<"Dead"<<endl;cout<<"your "<<score<}void Csnake::ShowGame(){for(int i=0;i{for(int j=0;jcout<cout<}Sleep(1);system("cls");}======================================================================/*主函数部分 */#include#include "snake.h"#includeusing namespace std;int main(){Csnake s(20);s.InitInstance();//s.ShowGame();int noDead;do{s.ShowGame();noDead=s.UpdataGame();}while (noDead</endl;cout<<"your>);system("pause");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)```这个代码实现了一个简单的贪吃蛇游戏,包括基本的游戏循环、蛇的移动、食物的生成和碰撞检测。

简单贪吃蛇c语言代码,一个C语言写简单贪吃蛇源代码.doc

简单贪吃蛇c语言代码,一个C语言写简单贪吃蛇源代码.doc

简单贪吃蛇c语⾔代码,⼀个C语⾔写简单贪吃蛇源代码.doc ⼀个C语⾔写简单贪吃蛇源代码#include#include#include#include#include#includeint grade=5,point=0,life=3;voidset(),menu(),move_head(),move_body(),move(),init_insect(),left(),upon(),right(),down(),init_graph(),food_f(),ahead(),crate(); struct bug{int x;int y;struct bug *last;struct bug *next;};struct fd{int x;int y;int judge;}food={0,0,0};struct bug *head_f=NULL,*head_l,*p1=NULL,*p2=NULL;void main(){char ch;initgraph(800,600);set();init_insect();while(1){food_f();Sleep(grade*10);setcolor(BLACK);circle(head_l->x,head_l->y,2);setcolor(WHITE);move_body();if(kbhit()){ch=getch();if(ch==27){ahead();set();}else if(ch==-32){switch(getch()){case 72:upon();break;case 80:down();break;case 75:left();break;case 77:right();break;}}else ahead();}else{ahead();}if(head_f->x==food.x&&head_f->y==food.y) {Sleep(100);crate();food.judge=0;point=point+(6-grade)*10;if(food.x<30||food.y<30||food.x>570||food.y>570)life++;menu();}if(head_f->x<5||head_f->x>595||head_f->y<5||head_f->y>595) {Sleep(1000);life--;food.judge=0;init_graph();init_insect();menu();}for(p1=head_f->next;p1!=NULL;p1=p1->next){if(head_f->x==p1->x&&head_f->y==p1->y){Sleep(1000);life--;food.judge=0;init_graph();init_insect();menu();break;}}if(life==0){outtextxy(280,300,"游戏结束!");getch();return;}move();};}void init_graph(){clearviewport();setlinestyle(PS_SOLID,1,5);rectangle(2,2,600,598);setlinestyle(PS_SOLID,1,1);}void set(){init_graph();outtextxy(640,50,"1、开始 / 返回");outtextxy(640,70,"2、退出");outtextxy(640,90,"3、难度");outtextxy(640,110,"4、重新开始");switch(getch()){case '1': menu();setcolor(GREEN);circle(food.x,food.y,2);setcolor(WHITE);return; case '2': exit(0);break;。

《贪吃蛇》游戏程序代码

《贪吃蛇》游戏程序代码

《贪吃蛇》游戏程序代码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("游戏结束!")。

贪吃蛇简易代码

贪吃蛇简易代码

贪吃蛇简易代码文件编码(GHTU-UITID-GGBKT-POIU-WUUI-8968)#include<windows.h>#include"resource1.h"#include<stdio.h>#include<stdlib.h>#include<time.h>//蛇的结构体typedefstructSNAKE{intx;inty;structSNAKE*pNext;}Snake;//豆的结构体typedefstructBEAN{intx;inty;structBEAN*pNext;}Bean;//函数原型voidCreateSnake(Snake**pSnake); voiddeleteAll(Snake**pSnake);voidShowSnake(Snake*pSnake);voidCreateBean(Bean**pBean,Snake*pSnake);voidShowBean(Bean*pBean);voidDeleteBean(Bean**pBean);voidSnakeRun(Snake**pSnake);voidSnakeGrowUp(Snake*pSnake);intCanEatBean(Snake*pSnake,Bean*pBean);intCanDie(Snake*pSnake);////////////////////////////////////////////////////////////////////////////// ///////charg_ClassName[20]="ClassName";LRESULTCALLBACKWndProc(HWNDhwnd,UINTnMsg,WPARAMwParam,LPARAMlParam); HBITMAPhBitMap;intCALLBACKWinMain(HINSTANCEhInstance,HINSTANCEhPreInstance,LPSTRpCmdLine,intnCmdShow){HBRUSHhBrush=CreateSolidBrush(RGB(100,100,410));HICONhIcon=LoadIcon(hInstance,MAKEINTRESOURCE(IDI_wnd_icon));HICONhIconsm=LoadIcon(hInstance,MAKEINTRESOURCE(IDI_wnd_iconsm));hBitMap=LoadBitmap(hInstance,MAKEINTRESOURCE(IDB_wdnbitmap));//设计类WNDCLASSEXwndClass;wndClass.cbClsExtra=NULL;wndClass.cbSize=sizeof(wndClass);wndClass.cbWndExtra=NULL;wndClass.hbrBackground=hBrush;wndClass.hCursor=LoadCursor(hInstance,IDC_ARROW); wndClass.hIcon=hIcon;wndClass.hIconSm=hIconsm;wndClass.hInstance=hInstance;wndClass.lpfnWndProc=WndProc;wndClass.lpszClassName=g_ClassName;wndClass.style=CS_HREDRAW|CS_VREDRAW;wndClass.lpszMenuName=NULL;//注册if(!RegisterClassEx(&wndClass)){MessageBox(NULL,"注册失败","消息",MB_OK);}//创建HWNDhwnd=CreateWindow(g_ClassName,"贪吃蛇",WS_OVERLAPPEDWINDOW,200,50,600+16,600+38,NULL,NULL,hInstance,NULL);if(!hwnd){MessageBox(NULL,"创建失败!","消息",MB_OK);}//显示ShowWindow(hwnd,nCmdShow);//消息循环MSGmsg;while(GetMessage(&msg,NULL,0,0)){TranslateMessage(&msg); //翻译DispatchMessage(&msg); //回调函数}return0;}HDCdc=NULL;Bean*pBean=NULL;Snake*pSnake=NULL;intVK=VK_RIGHT;LRESULTCALLBACKWndProc(HWNDhwnd,UINTnMsg,WPARAMwParam,LPARAMlParam) {switch(nMsg){caseWM_CREATE:{CreateSnake(&pSnake); //创建蛇CreateBean(&pBean,pSnake);dc=GetDC(hwnd);}break;caseWM_KEYDOWN:{switch(wParam){caseVK_RETURN://按下后就开始SetTimer(hwnd,1,150,NULL);break;caseVK_UP:VK=VK_UP;break;caseVK_DOWN:VK=VK_DOWN;break;caseVK_LEFT:VK=VK_LEFT;break;caseVK_RIGHT:VK=VK_RIGHT;break;case'':KillTimer(hwnd,1);break;}break;}caseWM_TIMER:{/*创建背景*/RECTrect;GetWindowRect(hwnd,&rect);HDChmeDc=CreateCompatibleDC(dc);SelectObject(hmeDc,hBitMap);StretchBlt(dc,0,0,rect.right-rect.left,rect.bottom-rect.top,hmeDc,0,0,500,600,SRCCOPY);DeleteDC(hmeDc);/*背景创建结束*///各种函数if(CanDie(pSnake)){KillTimer(hwnd,1);MessageBox(NULL,"笨蛋,撞到自己身上,我死啦!","消息",MB_OK);}if(CanEatBean(pSnake,pBean)){SnakeGrowUp(pSnake);DeleteBean(&pBean);CreateBean(&pBean,pSnake);SnakeRun(&pSnake);}else{SnakeRun(&pSnake);}ShowSnake(pSnake);ShowBean(pBean);}caseWM_PAINT:{/*创建背景*/RECTrect;GetWindowRect(hwnd,&rect);HDChmeDc=CreateCompatibleDC(dc);SelectObject(hmeDc,hBitMap);StretchBlt(dc,0,0,rect.right-rect.left,rect.bottom-rect.top,hmeDc,0,0,500,600,SRCCOPY);/*背景创建结束*/ShowSnake(pSnake); //显示蛇ShowBean(pBean); //显示豆DeleteDC(hmeDc);break;}caseWM_CLOSE:deleteAll(&pSnake);DeleteBean(&pBean);DestroyWindow(hwnd);break;caseWM_DESTROY:ReleaseDC(hwnd,dc);PostQuitMessage(0);break;caseWM_QUIT:break;}returnDefWindowProc(hwnd,nMsg,wParam,lParam);}/////////////////////////////////函数/////////////////////////////////////////////////////////// //创建蛇CreateSnake()voidCreateSnake(Snake**pSnake){Snake*u=NULL,*w=NULL;inti=3; //开始的蛇有三截intx=0; //蛇头的初始位置inty=0; //蛇尾的初始位置while(i--){u=(Snake*)malloc(sizeof(Snake));u->pNext=NULL;u->x=x;u->y=y;x+=20;if(NULL==*pSnake){*pSnake=u;}else{w->pNext=u;}w=u;}/*蛇的三届创建完毕*/}//创建豆voidCreateBean(Bean**pBean,Snake*pSnake) {Snake*ji;intx=0; //随机的位置x坐标inty=0; //随机的位置y坐标srand(time(NULL));x=((unsigned)rand()%29)*20;y=((unsigned)rand()%29)*20;ji=pSnake;while(pSnake){if((x==pSnake->x)&&(y==pSnake->y)){x=((unsigned)rand()%29)*20;y=((unsigned)rand()%29)*20;pSnake=ji;}pSnake=pSnake->pNext;}Bean*u;u=(Bean*)malloc(sizeof(Bean));u->pNext=NULL;u->x=x;u->y=y;*pBean=u;}//删掉全部蛇voiddeleteAll(Snake**pSnake){Snake*del;while(*pSnake){del=*pSnake;(*pSnake)=(*pSnake)->pNext;free(del);}}//删掉豆voidDeleteBean(Bean**pBean){free(*pBean);*pBean=NULL;}//显示蛇voidShowSnake(Snake*pSnake){while(pSnake){Rectangle(dc,pSnake->x,pSnake->y,pSnake->x+20,pSnake->y+20);pSnake=pSnake->pNext;}}//显示豆voidShowBean(Bean*pBean){Rectangle(dc,pBean->x,pBean->y,pBean->x+20,pBean->y+20); }//贪吃蛇移动voidSnakeRun(Snake**pSnake){Snake*ji, //记录变化的蛇头*round; //循环遍历intx, //蛇头的当前位置x坐标y; //蛇头的当前位置y坐标ji=*pSnake;round=*pSnake;while(round->pNext){round=round->pNext;}x=round->x;y=round->y;switch(VK){caseVK_UP:if(y==0)y=600;}y-=20;break; caseVK_DOWN:if(y==600){y=0;}y+=20;break; caseVK_LEFT:if(x==0){x=600;}x-=20;break; caseVK_RIGHT:if(x==600){x=0;x+=20;break;}*pSnake=(*pSnake)->pNext;ji->x=x;ji->y=y;ji->pNext=NULL;round->pNext=ji;}//下一步能吃到豆吗?返回1吃到intCanEatBean(Snake*pSnake,Bean*pBean){while(pSnake->pNext){pSnake=pSnake->pNext;}if((pSnake->x==pBean->x)&&(pSnake->y==pBean->y)){return1;}return0;}//长大voidSnakeGrowUp(Snake*pSnake){Snake*u;u=(Snake*)malloc(sizeof(Snake));u->pNext=NULL;u->x=pBean->x;u->y=pBean->y;while(pSnake->pNext){pSnake=pSnake->pNext;}pSnake->pNext=u;}//蛇会死吗返回1会死intCanDie(Snake*pSnake){Snake*ji=NULL;intx=0,y=0;ji=pSnake;while(pSnake->pNext){pSnake=pSnake->pNext;}x=pSnake->x;y=pSnake->y;switch(VK){caseVK_UP:y-=20;break;caseVK_DOWN:y+=20;break;caseVK_LEFT:x-=20;break;caseVK_RIGHT:x+=20;break;}while(ji->pNext){if((x==ji->x)&&(y==ji->y)){return1;}ji=ji->pNext;}return0;}。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
setcolor(WHITE);rectangle(snake.crd[snake.node-1].x,snake.crd[snake.node-1].y,snake.crd[snake.node-1].x+SNAKELEN,snake.crd[snake.node-1].y+SNAKELEN);
outtextxy(280,100,"感谢您的支持");
outtextxy(320,150,"谢谢");
Sleep(2000);
}
void judgeslod()
{
int i;
if(snake.crd[0].x<0||snake.crd[0].x>=640||snake.crd[0].y<0||snake.crd[0].y>=480)
}
void snakemove()
{
int i;for(i=snake.node;i>0;i--)
{
snake.crd[i].x=snake.crd[i-1].x;
snake.crd[i].y=snake.crd[i-1].y;
}
switch(snake.dir)
{
#include <stdio.h>
#include <stdlib.h>
#include <graphics.h>
#include <conio.h>
#include <time.h>
#define SIZEMAX 100
#define SNAKELEN 10
#define SPEED 100
food.flag=1;
}
void showfood()
{
rectangle(food.crd.x,food.crd.y,food.crd.x+SNAKELEN,food.crd.y+SNAKELEN);
}
void showsnake()
{
int i;
for(i=snake.node-1;i>=0;i--)
int node;
DIR dir;
}snake;
int speed=SPEED;
void init()
{
initgraph(640,480);
srand(time(NULL));
food.flag=0;
snake.crd[0].x=0+SNAKELEN;
snake.crd[0].y=0;
typedef enum
{
left,right,up,down
}DIR;
typedef struct
{
int x;
int y;
}COOR;
struct FOOD
{
COOR crd;
int flag;
}food;
struct SNAKE
{
COOR crd[SIZEMAX];
}showsnake();
}
void changeskdir() /*改变蛇的方向*/
{
char key;
key=getch();
switch(key)
{
case'w': case'W': if(snake.dir!=down)snake.dir=up;break;
case up:snake.crd[0].y-=SNAKELEN;break;
case down:snake.crd[0].y+=SNAKELEN;break;
case left:snake.crd[0].x-=SNAKELEN;break;
case right:snake.crd[0].x+=SNAKELEN;
gameover();
for(i=snake.node-1;i>0;i--)
if(i=snake.crd[0].x==snake.crd[i].x&&snake.crd[0].y==snake.crd[i].y)
gameover;
}
void judgefood() /*判断蛇是否吃到食物*/
setcolor(WHITE); food.flag=0;
}
}
void main()
{
init();
while(1){
while(!kbhit())
{
if (!food.flag) setfoodcrd();
showfood();
judgeslod();
snake.crd[1].x=0;
snake.crd[1].y=0;
snake.node=2;
snake.dir=right;
}
void setfoodcrd()
{
food.crd.x=rand()%(600/SNAKELEN)*SNAKELEN;
food.crd.y=rand()%(480/SNAKELEN)*SNAKELEN;
}
}
void gameover() /*游戏结束函数*/
{
IMAGE img;
loadimage(&img,"6.jpg");
putimage(0,0,&img);
setcolor(BLUE);
setfont(30,0,"宋体");
settextcolor(YELLOW);
rectangle(snake.crd[i].x,snake.crd[i].y,snake.crd[i].x+SNAKELEN,snake.crd[i].y+SNAKELEN);
setcolor(BLACK);
rectangle(snake.crd[snake.node].x,snake.crd[snake.node].y,snake.crd[snake.node].x+SNAKELEN,snake.crd[snake.node].y+SNAKELEN);
judgefood();
snakemove();
Sleep(speed);
}
changeskdir();
}
}
case's': case'S': if(snake.dir!=up) snake.dir=down;break;
case'a': case'A': if(snake.dir!=right)snake.dir=left;break;
case'd': case'D': if(snake.dir!=left) snake.dir=right;bx==food.crd.x&&snake.crd[0].y==food.crd.y)
{
snake.node++;
setcolor(BLACK);
rectangle(food.crd.x,food.crd.y,food.crd.x+SNAKELEN,food.crd.y+SNAKELEN);
相关文档
最新文档