贪吃蛇游戏代码

本文详细介绍了如何使用C++编写贪吃蛇游戏,包括定义结构体、控制台输出、移动规则、难度调整和碰撞检测等关键部分,供初学者参考和学习。
摘要由CSDN通过智能技术生成

相信大家都玩过贪吃蛇这个游戏,但是不知道自己怎么可以编出来。下面是我学习和借鉴其他博主的开发经验以及经典作品写出来的。

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<ctime>
#include<conio.h>
#include<cmath>
#include<windows.h>
using namespace std;
HANDLE hout=GetStdHandle(STD_OUTPUT_HANDLE);
COORD coord;
void locate(int x,int y){
	coord.X=y;
	coord.Y=x;
	SetConsoleCursorPosition(hout,coord); 
}
void hide(){
	CONSOLE_CURSOR_INFO cursor_info={1,0};
	SetConsoleCursorInfo(hout,&cursor_info);
}
double random(double start,double end){
	return start+(end-start)*rand()/(RAND_MAX+1.0);
}
int m,n;
struct node{
	int x,y;
}snake[1000];
int snake_length,dir;
node food;
int direct[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
void print_wall(){
	cout<<" ";
	for(int i=1;i<=n;i++)
		cout<<"-";
	cout<<endl;
	for(int j=0;j<=m-1;j++){
		cout<<"|";
		for(int i=1;i<=n;i++) cout<<" ";
		cout<<"|"<<endl;
	}
	cout<<" ";
	for(int i=1;i<=n;i++)
		cout<<"-";
}
void print_snake(){
	locate(snake[0].x,snake[0].y);
	cout<<"@";
	for(int i=1;i<=snake_length-1;i++){
		locate(snake[i].x,snake[i].y);
		cout<<"*";
	}
}
bool is_correct(){
	if(snake[0].x==0||snake[0].y==0||snake[0].x==m+1||snake[0].y==n+1) return false;
	for(int i=1;i<=snake_length-1;i++){
		if(snake[0].x==snake[i].x&&snake[0].y==snake[i].y) return false;
	}
	return true;
}
bool print_food(){
	srand((unsigned)time(0));
	bool e;
	while(1){
		e=true;
		int i=(int) random(0,m)+1,j=(int) random(0,n)+1;
		food.x=i,food.y=j;
		for(int k=0;k<=snake_length-1;k++){
			if(snake[k].x==food.x&&snake[k].y==food.y){
				e=false;
				break;
			}
		}
		if(e) break;
	}
	locate(food.x,food.y);
	cout<<"$";
	return true;
}
bool go_ahead(){
	node temp;
	bool e=false;
	temp=snake[snake_length-1];
	for(int i=snake_length-1;i>=1;i--)
		snake[i]=snake[i-1];
	snake[0].x+=direct[dir][0];
	snake[0].y+=direct[dir][1];
	locate(snake[1].x,snake[1].y);
	cout<<"*";
	if(snake[0].x==food.x&&snake[0].y==food.y){
		snake_length++;
		e=true;
		snake[snake_length-1]=temp;
	}
	if(!e){
		locate(temp.x,temp.y);
		cout<<" ";
	}
	else 
		print_food();
	locate(snake[0].x,snake[0].y);
	cout<<"@";
	if(!is_correct()){
		system("cls");
		cout<<"你输了!"<<endl<<"长度:"<<snake_length<<endl;
		return false;
	}
	return true;
}
int main(){
	cout<<"--------------------贪吃蛇--------------------"<<endl;
	cout<<"请选择窗口大小,以免发生错位,建议将窗口调为最大。"<<endl;
	cout<<"先选择难度,请在1-10中输入一个数,1为最简单,10为最难。"<<endl;
	cout<<"然后进入游戏画面,以方向键控制方向,祝你游戏愉快!"<<endl;
	cout<<"----------------------------------------------"<<endl;
	m=25;
	n=40;
	if(m<10||n<10||m>25||n>40){
		cout<<"错误"<<endl;
		system("pause");
		return 0;
	}
	int hard;
	cin>>hard;
	if(hard<=0||hard>10){
		cout<<"错误"<<endl;
		system("pause");
		return 0;
	}
	snake_length=5;
	clock_t a,b;
	char ch;
	double hard_len;
	for(int i=0;i<=4;i++){
		snake[i].x=1;
		snake[i].y=5-i;
	}
	dir=3;
	system("cls");
	hide();
	print_wall();
	print_food();
	print_snake();
	locate(m+2,0);
	cout<<"现在的长度:";
	while(1){
		hard_len=(double)snake_length/(double)(m*n);
		a=clock();
		while(1){
			b=clock();
			if(b-a>=(int)(400-30*hard)*(1-sqrt(hard_len))) break; 
		}
		if(kbhit()){
			ch=getch();
			if(ch==-32){
				ch=getch();
				switch(ch){
					case 72:
						if(dir==2||dir==3)
							dir=0;
						break;
					case 80:
						if(dir==2||dir==3)
							dir=1;
						break;
					case 75:
						if(dir==0||dir==1)
							dir=2;
						break;
					case 77:
						if(dir==0||dir==1)
							dir=3;
						break;
				}
			}
		}
		if(!go_ahead()) break;
		locate(m+2,12);
		cout<<snake_length;
	}
	system("pause");
	return 0;
} 

欢迎大家试玩! 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
贪吃游戏是一种经典的小游戏,它通过控制一条小在屏幕上移动来吃食物,同时避免碰到墙壁或自身,直到小长度达到一定程度或者游戏失败为止。下面是一个简单的Python版贪吃游戏代码: ``` import pygame import random # 初始化游戏 pygame.init() # 定义游戏窗口大小 width = 640 height = 480 screen = pygame.display.set_mode((width, height)) pygame.display.set_caption("Snake Game") # 定义颜色 white = (255, 255, 255) black = (0, 0, 0) red = (255, 0, 0) # 定义的初始位置和速度 snake_pos = [100, 50] snake_body = [[100, 50], [90, 50], [80, 50]] direction = "RIGHT" change_to = direction speed = 10 # 定义食物的初始位置 food_pos = [random.randrange(1, width // 10) * 10, random.randrange(1, height // 10) * 10] food_spawn = True # 定义分数和字体 score = 0 font_style = pygame.font.SysFont(None, 30) # 游戏循环 while True: # 处理事件 for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: change_to = "LEFT" elif event.key == pygame.K_RIGHT: change_to = "RIGHT" elif event.key == pygame.K_UP: change_to = "UP" elif event.key == pygame.K_DOWN: change_to = "DOWN" # 判断方向是否相反 if change_to == "LEFT" and direction != "RIGHT": direction = "LEFT" elif change_to == "RIGHT" and direction != "LEFT": direction = "RIGHT" elif change_to == "UP" and direction != "DOWN": direction = "UP" elif change_to == "DOWN" and direction != "UP": direction = "DOWN" # 移动的位置 if direction == "RIGHT": snake_pos += speed elif direction == "LEFT": snake_pos -= speed elif direction == "UP": snake_pos -= speed elif direction == "DOWN": snake_pos += speed # 增加的长度和分数 snake_body.insert(0, list(snake_pos)) if snake_pos == food_pos: food_spawn = False score += 10 else: snake_body.pop() # 重新生成食物 if not food_spawn: food_pos = [random.randrange(1, width // 10) * 10, random.randrange(1, height // 10) * 10] food_spawn = True # 绘制游戏界面 screen.fill(black) for pos in snake_body: pygame.draw.rect(screen, white, pygame.Rect(pos, pos, 10, 10)) pygame.draw.rect(screen, red, pygame.Rect(food_pos, food_pos, 10, 10)) # 显示分数和更新窗口 score_font = font_style.render("Score: " + str(score), True, white) screen.blit(score_font, [5, 5]) pygame.display.update() # 判断游戏是否结束 if snake_pos < 0 or snake_pos > width - 10 or snake_pos < 0 or snake_pos > height - 10: pygame.quit() quit() for block in snake_body[1:]: if snake_pos == block: pygame.quit() quit() ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值