5_23_贪吃蛇(成功)

Posted wlxdaydayup

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了5_23_贪吃蛇(成功)相关的知识,希望对你有一定的参考价值。

修复上一篇中的bug

1.蛇的尾巴删除后,更新地图

2.设计链表使得蛇链接起来,从而在尾部删除之后更新新的尾部节点,即tail=tail->next;

function.h

#pragma once
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
#include<Windows.h>
#include<conio.h>
#include<iostream>
#include<map>
#include<string>
using namespace std;
#define WIDTH 80
#define HEIGHT 25//地图的宽和高
#define SPEED 100

typedef enum 
	WALL,
	EMPTY,
	SNAKE_BODY,
	FOOD
Mapelement;//定义一个枚举类型Mapelement

typedef struct 
public:
	Mapelement **elements;
Map;//Map的结构体成员是一个Mapelement数组

typedef struct Snake
	int x, y;//记录蛇的位置
	int flag;//记录蛇是否死亡
	struct Snake* next;//记录蛇移动方向
	int len;//记录得分
	char way;
Snake;

void initmap(Map*& map);//初始化地图

void mapdisplay(Map*& map);//地图打印函数

void drawFood(Map*& map);//生成食物

void initSnake(Snake*& head,Snake*& tail); //初始化蛇身

void updateSnake(Map*& map,Snake*& head,Snake*& tail); //更新绘制地图上的蛇

void ctrlSnake(Snake*& head);//控制蛇移动

function.cpp

#include"function.h"

void initmap(Map*& map)

    for (int i = 0; i < HEIGHT; i++) 
        for (int j = 0; j < WIDTH; j++)
        
            if (i == 0 || j == 0 || i == HEIGHT - 1 || j == WIDTH - 1)
            
                map->elements[i][j] = WALL;

            
            else
            
                map->elements[i][j] = EMPTY;
            
        
    
    map->elements[1][1] = SNAKE_BODY;
    map->elements[1][2] = SNAKE_BODY;


void mapdisplay(Map*& map)

    system("cls");
    for (int i = 0; i < HEIGHT; i++) 
        for (int j = 0; j < WIDTH; j++) 
            switch (map->elements[i][j]) 
            case EMPTY:
                printf(" ");
                break;
            case SNAKE_BODY:
                printf("*");
                break;
            case FOOD:
                printf("#");
                break;
            case WALL:
                printf("+");
            
        
        printf("\\n");
    


void drawFood(Map*& map)

    int res = 1;
    srand((unsigned)time(NULL));
    
    while (res)
    
        int x, y;
        x = rand() % (HEIGHT - 3) + 1;
        y = rand() % (WIDTH - 3) + 1;
        if (map->elements[x][y] != SNAKE_BODY)
        
            map->elements[x][y] = FOOD;
            res = 0;
        
    
    


void initSnake(Snake*& head,Snake*& tail)

    head->x = 1;
    head->y = 2;
    tail->flag = head->flag = 1;
    head->way = \'d\';
    tail->next = head;


    tail->len = head->len = 2;
    head->next = NULL;
    tail->x = 1;
    tail->y = 1;
    tail->way = \'d\';


void updateSnake(Map*& map, Snake*& head, Snake*& tail)

    Snake* snake = (Snake*)malloc(sizeof(Snake));
    switch (head->way) 
    case \'a\':
        snake->y = head->y - 1;
        snake->x = head->x;
        break;
    case \'d\':
        snake->y = head->y + 1;
        snake->x = head->x;
        break;
    case \'s\':
        snake->y = head->y;
        snake->x = head->x + 1;
        break;
    case\'w\':
        snake->y = head->y;
        snake->x = head->x - 1;
        break;
    
    snake->way = head->way;
    snake->len = head->len;
    head->next = snake;
    head = snake;
    head->next = NULL;
    if (head->y >= WIDTH || head->x >= HEIGHT || head->x <= 0 || head->y <= 0)
    
        head->flag = 0;
        return;
    
    if (map->elements[head->x][head->y] == WALL || map->elements[head->x][head->y] == SNAKE_BODY)
    
        head->flag = 0;
        return;
    
    if (map->elements[head->x][head->y] == FOOD)
    
        map->elements[head->x][head->y] = SNAKE_BODY;
        head->len++;
        drawFood(map);
    
    else 
        map->elements[head->x][head->y] = SNAKE_BODY;
        map->elements[tail->x][tail->y] = EMPTY;
        Snake* a = tail;
        tail = tail->next;
        free(a);
    


void ctrlSnake(Snake*& head)

    char key = 0;
    if (_kbhit())
    
        key = _getch();
    
    switch (key) 
    case \'a\':
        if (head->way == \'d\')
        
            break;
        
        head->way = \'a\';
        break;
    case \'d\':
        if (head->way == \'a\')
        
            break;
        
        head->way = \'d\';
        break;
    case \'s\':
        if (head->way == \'w\')
        
            break;
        
        head->way = \'s\';
        break;
    case\'w\':
        if (head->way == \'s\')
        
            break;
        
        head->way = \'w\';
        break;
    



main.cpp

#include"function.h"

int main()

	printf("欢迎来到贪吃蛇小游戏,请输入用户名\\n");
	string users;
	cin >> users;
	map<int, string>bangdan;
	bangdan.insert(pair<int, string>(1000, "wanglingxiao"));
	printf("请输入1开始游戏\\n");
	int res;
	scanf_s("%d", &res);
	if (res != 1)  return 0; 
	while (1)
	
		Snake* head = (Snake*)malloc(sizeof(Snake));
		Snake* tail = (Snake*)malloc(sizeof(Snake));
		Map* map = (Map*)malloc(sizeof(Map));
		map->elements = (Mapelement**)malloc(HEIGHT * sizeof(Mapelement*));
		if (map->elements == NULL) 
			// 内存分配失败的处理
			free(map); // 释放先前分配的内存
			return 1;
		
		for (int i = 0; i < HEIGHT; i++) 
			map->elements[i] = (Mapelement*)malloc(WIDTH * sizeof(Mapelement));
			if (map->elements[i] == NULL) 
				// 内存分配失败的处理
				// 释放先前分配的内存
				for (int j = 0; j < i; j++) 
					free(map->elements[j]);
				
				free(map);
				return 1;
			
		
		initSnake(head, tail);
		initmap(map);
		drawFood(map);
		while (head->flag)
		
			mapdisplay(map);
			Sleep(SPEED);
			ctrlSnake(head);
			updateSnake(map, head, tail);
		

		// 现在 a->elements 可以正常使用了
		
		// 释放内存
		for (int i = 0; i < HEIGHT; i++) 
			free(map->elements[i]);
		
		free(map);

		system("cls");
		std::cout << "本次得分:" << head->len - 2 << std::endl;
		bangdan.insert(pair<int, string>(head->len - 2, users));
		cout << "按a查看得分榜:" << endl;
		char a;
		cin >> a;
		if (a == \'a\')
		
			for (const auto& pair : bangdan) 
				std::cout << "姓名: " << pair.second << "得分: " << pair.first << std::endl;
			
		
		Sleep(3000);
		char yes;
		printf("还想继续玩吗?,输入y或者n\\n");
		std::cin >> yes;
		if (yes == \'n\')break;
	
	return 0;

python贪吃蛇

 1 class point:
 2     row=0
 3     col=0
 4     def __init__(self,row,col):
 5         self.row=row
 6         self.col=col
 7     def copy(self):
 8         return point(row=self.row,col=self.col)
 9 #初始化框架
10 import pygame
11 import random
12 pygame.init()
13 width=800
14 height=600
15 ROW=30
16 COL=40
17 size=(width,height)
18 window=pygame.display.set_mode(size)
19 pygame.display.set_caption(mlhj)
20 head=point(row=random.randint(0,ROW-1),col=random.randint(0,COL-1))
21 food=point(row=random.randint(0,ROW-1),col=random.randint(0,COL-1))
22 quit=True
23 clock =pygame.time.Clock()
24 back_color=(255,255,255)
25 head_color=(255,0,0)
26 snake_color=(128,128,128)
27 food_color=(0,128,128)
28 snakes=[]
29 def rect(point,color):
30     cell_width=width/COL
31     cell_height=height/ROW
32     left=point.col*(cell_width)
33     top=point.row*(cell_height)
34     pygame.draw.rect(window, color, (left, top, cell_width, cell_height))
35     pass

36 dir=left 37 while quit: 38 for event in pygame.event.get(): 39 print(event) 40 if event.type==pygame.QUIT: 41 quit = False 42 elif event.type==pygame.KEYDOWN: 43 if event.key==273: 44 if dir==left or dir==right: 45 dir=up 46 elif event.key==274: 47 if dir == left or dir == right: 48 dir=down 49 elif event.key == 275: 50 if dir == up or dir == down: 51 dir = right 52 elif event.key == 276: 53 if dir == up or dir == down: 54 dir = left 55 eat = (head.row==food.row and head.col==food.col) 56 snakes.insert(0,point.copy(head)) 57 if not eat: #如果没吃到,移动的时候就把尾巴给‘扔了’,如果迟到了食物,则会增加一节,这一节刚好就是需要pop的那一个位置 58 snakes.pop() 59 if eat: 60 food = point(row=random.randint(0, ROW - 1), col=random.randint(0, COL - 1)) 61 #碰到边界死亡 62 if head.col>40 or head.row<0 or head.row>30or head.col<0: 63 quit=False 64 #碰到自己的身体死亡 65 for snake in snakes: 66 if snake.row==head.row and snake.col==head.col: 67 quit=False 68 if dir==left: 69 head.col-=1 70 elif dir==right: 71 head.col+=1 72 elif dir==up: 73 head.row-=1 74 elif dir == down: 75 head.row += 1 76 #渲染,将舌头蛇身食物等在界面上画出来 77 pygame.display.flip() 78 pygame.draw.rect(window,back_color,(0,0,width,height)) 79 rect(head,head_color) 80 rect(food,food_color) 81 for snake in snakes: 82 rect(snake,snake_color) 83 84 85 86 #设置帧频 87 clock.tick(10)

 

以上是关于5_23_贪吃蛇(成功)的主要内容,如果未能解决你的问题,请参考以下文章

命令贪吃蛇2_0

Python贪吃蛇

python贪吃蛇

Unity3D_(游戏)贪吃蛇

酷炫 贪吃蛇——由“前端“实现___效果 + 全部代码

贪吃蛇(贪心&Matrix)