当前位置:网站首页>Snake (C language)
Snake (C language)
2022-07-04 10:27:00 【Lol only plays Timo】
Snake project
The core algorithm : Circular array , Licensing algorithms , One dimensional transformation of two-dimensional coordinates
Compile environment :TC 2.0
preparation : Study gotoxy() function , understand bioskey() Function USES , know bioskey(1) And bioskey(0) The difference between , Understand keyboard scan code , And know how to use .
The core work :1. Understand the subscript cycle law of circular array
2. Understand the core code of licensing algorithm
3. Master how to deal with two-dimensional coordinates in one dimension , And the transformation between the two
that , First of all, let's get to know gotoxy() This function :
gotoxy (int x, int y) yes Borland C Extended function library conio.h A function declared in , The function is to move the cursor to the specified position . In Contemporary Visual C++ or GCC You can customize this function in . In the last century 80-90 The popular integrated development environment in the s Turbo C or Borland C Extended function library in conio.h Provides gotoxy function , For screen output , The function is to cursor Move to the specified position on the screen . The upper left corner of the screen is defined as the coordinate origin of the cursor (0, 0), The horizontal direction is X Axis , Vertical is Y Axis .
Because we are Turbo C Environment , So it should be written when using #include <conio.h> This header file .
Next let's look at bioskey() This function :
The function prototype :int bioskey (int cmd)
explain :bioskey() The prototype of the function is bios.h in
bioskey() Complete direct keyboard operation ,cmd The value of determines what operation to perform .
cmd = 0:
When cmd yes 0,bioskey() Returns the next value typed on the keyboard ( It will wait until a key is pressed ). It returns a 16 The binary number of bits , Include two different values . When you press a normal key , It's low 8 Number of digits to store the character ASCII code , high 8 Bit stores the scan code of the key ; For special keys ( Such as direction keys 、F1~F12 wait ), low 8 Position as 0, high 8 Bit bytes store the scan code of the key .
cmd = 1:
When cmd yes 1,bioskey() Query whether to press a key , If a key is pressed, a non-zero value is returned , Otherwise return to 0.
The important thing is bioskey() After function detection, the key value of this key is left in the keyboard buffer , If necessary, you can take it out of the keyboard buffer .
After finishing the preparatory work , We begin with the first core algorithm — Licensing algorithms
for example :
int arr[10] = {1,5,9,3,7,2,8,4,0,6};
From here 10 Select six completely random and absolutely non repeating numbers .
n Elements , Random generation 0 To n-1 The subscript , Adjust the selected elements ( In exchange for ) At the end of , Make the subscript of unselected elements , stay 0 To n-2 Between , The next round of random generation 0 To n-2 The subscript , So back and forth .
The code example is as follows :
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void swap(int *p, int *q);
void swap(int *p, int *q) {
int temp;
temp = *p;
*p = *q;
*q = temp;
}
int main() {
int arr[10] = {
3,8,1,2,0,9,6,5,7,4};
int i;
int index;
int n = 10;
srand((unsigned) time(NULL));
for(i = 0; i < 6; i++) {
index = rand()%n;
printf("%d\t",arr[index]);
swap(&arr[index],&arr[n--]);
}
}
The next core algorithm is the circular array , The purpose is to realize the movement of snakes , The reason for using arrays instead of linked lists is that there is no need , Don't bargain , Array operation is simpler and more convenient than linked list .
Compared with ordinary arrays , It is more convenient for snakes to move , The time complexity will also be reduced .
How to make subscripts cycle ? Here's a formula :
headIndex( Snake head coordinates ) = (index + Length of array + 1)% Length of array
tailIndex( Snake tail coordinates ) = (index + Length of array - The length of the snake + 1)% Length of array
Move the snake
Use a circular array to store the lines of each point of the snake's body , Column coordinates
A snake head is initially displayed , Slowly increasing , Until it is equal to the set length of the snake
The process of snake moving :
1.if( Current length < The length of the snake itself ) {
Current length ++;
} else {
Tail elimination ;
}
2. Neck modification : Draw the body of the snake on the original place of the snake's head
3. Picture head
One dimensional transformation of two-dimensional coordinates :
i,j
1,1 1,2 1,3 1,4 2*4 Two dimensional array of 4:COL_COUNT
0 1 2 3
2,1 2,2 2,3 2,4
4 5 6 7
index( Subscript ) = (i-1) *COL_COUNT+(j-1)
i = t / COL_COUNT + 1
j = t % COL_COUNT + 1
Part of the source code is as follows :
#include <stdio.h>
#include <bios.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
#include "keyValue.h"
#include "snakeValue.h"
const int delta[][2] = {
{
0, -1},
{
0, 1},
{
-1, 0},
{
1, 0},
};
void keyOperate(ARG *arg);
boolean moveSnake(ARG *arg, SIT *sit, int *map);
void printHead(ARG *arg);
void produceFood(ARG *arg, SIT *sit, int *map);
void swap(int *p, int *q);
void printMap(int *map);
void printMap(int *map) {
int i;
int x;
int y;
int j;
for(i = 0; i < 2000; i++) {
x = i % COL_COUNT + 1;
y = i / COL_COUNT + 1;
if((x == 26 || x == 55) && ((y >= 4 && y <= 8)||(y >= 18 && y <=22))) {
map[i] = 4;
for (j = 0; j < 6; j++) {
gotoxy(x,y);
printf("%c",254);
}
}
if((y == 8 || y == 18) && ((x >= 6 && x <= 26) || (x >= 55 && x <= 74))) {
map[i] = 4;
for(j = 0 ; j < 20; j++) {
gotoxy(x,y);
printf("%c",254);
}
}
if(map[i] == 3) {
gotoxy(x,y);
printf("%c",254);
}
}
}
void swap(int *p, int *q) {
int temp;
temp = *p;
*p = *q;
*q = temp;
}
void produceFood(ARG *arg, SIT *sit, int *map) {
int foodMap[2000] = {
0};
int i;
int x;
int y;
int index = 0;
int q;
srand((unsigned) time(NULL));
for (i = 0, q = 0; i < 2000; i++) {
if (map[i] == 0) {
foodMap[q] = i;
q++;
}
}
q++;
for (i = 0; i < 10; i++) {
index = rand()%q;
map[foodMap[index]] = 2;
x = foodMap[index] % COL_COUNT + 1;
y = foodMap[index] / COL_COUNT + 1;
gotoxy(x,y);
printf("%c",157);
swap(&foodMap[index],&foodMap[--q]);
}
}
void printHead(ARG *arg) {
if (arg->direct == LEFT ) {
printf("<");
}
if (arg->direct == RIGHT ) {
printf(">");
}
if (arg->direct == UP ) {
printf("^");
}
if (arg->direct == DOWN ) {
printf("v");
}
}
boolean moveSnake(ARG *arg,SIT *sit,int *map) {
int tailIndex;
int x;
int y;
int index;
tailIndex = (arg->headIndex + MAXLEN - arg->length + 1) % MAXLEN;
if(arg->curLength < arg->length) {
arg->curLength++;
} else {
gotoxy(sit[tailIndex].row,sit[tailIndex].col);
printf(" ");
index = (sit[tailIndex].row - 1) * COL_COUNT + (sit[tailIndex].col - 1);
map[index] = 0;
}
index = (sit[arg->headIndex].col - 1) * COL_COUNT + (sit[arg->headIndex].row - 1);
gotoxy(sit[arg->headIndex].row,sit[arg->headIndex].col);
printf("%c",233);
map[index] = 5;
x = sit[arg->headIndex].row;
y = sit[arg->headIndex].col;
arg->headIndex = (arg->headIndex + MAXLEN + 1) % MAXLEN;
sit[arg->headIndex].row = x + delta[arg->direct][0];
sit[arg->headIndex].col = y + delta[arg->direct][1];
index = (sit[arg->headIndex].col - 1) * COL_COUNT + (sit[arg->headIndex].row - 1);
if(map[index] == 2) {
arg->eatCount++;
arg->length++;
}
if(map[index] == 3 || map[index] == 4 || map[index] == 5) {
return FALSE;
}
map[index] = 1;
gotoxy(sit[arg->headIndex].row,sit[arg->headIndex].col);
printHead(arg);
return TRUE;
}
void keyOperate(ARG *arg) {
if (arg->key == KEY_UP) {
arg->direct = UP;
} else if (arg->key == KEY_DOWN) {
arg->direct = DOWN;
} else if (arg->key == KEY_LEFT) {
arg->direct = LEFT;
} else if (arg->key == KEY_RIGHT) {
arg->direct = RIGHT;
} else if (arg->key == KEY_ESC) {
arg->finished = TRUE;
} else if (arg->key == KEY_ADD) {
if(arg->delayTime > 1000) {
arg->judgeSpeed = -1000;
}
}else if (arg->key == KEY_SUB) {
if(arg->delayTime < 15000) {
arg->judgeSpeed = 1000;
}
} else if(arg->key == KEY_SPACE) {
arg->gameOut = !arg->gameOut;
}
}
You can leave a message below if you need the source code , If you think there is anything else you can improve the code , You can also communicate below .
边栏推荐
- Kotlin set operation summary
- IPv6 comprehensive experiment
- Delayed message center design
- 2021-08-11 function pointer
- Differences among opencv versions
- leetcode1-3
- Machine learning -- neural network (IV): BP neural network
- Basic principle of servlet and application of common API methods
- 【Day2】 convolutional-neural-networks
- The most detailed teaching -- realize win10 multi-user remote login to intranet machine at the same time -- win10+frp+rdpwrap+ Alibaba cloud server
猜你喜欢

Architecture introduction

对于程序员来说,伤害力度最大的话。。。

From programmers to large-scale distributed architects, where are you (I)

Software sharing: the best PDF document conversion tool and PDF Suite Enterprise version sharing | with sharing

How do microservices aggregate API documents? This wave of show~

Today's sleep quality record 78 points

入职中国平安三周年的一些总结

uniapp 小于1000 按原数字显示 超过1000 数字换算成10w+ 1.3k+ 显示

leetcode1-3

Basic principle of servlet and application of common API methods
随机推荐
The bamboo shadow sweeps the steps, the dust does not move, and the moon passes through the marsh without trace -- in-depth understanding of the pointer
Ruby时间格式转换strftime毫秒匹配格式
Introduction to tree and binary tree
Es entry series - 6 document relevance and sorting
MPLS: multi protocol label switching
Write a program to judge whether the two arrays are equal, and then write a similar program to compare the two vectors.
System. Currenttimemillis() and system Nanotime (), which is faster? Don't use it wrong!
BGP ---- border gateway routing protocol ----- basic experiment
VLAN part of switching technology
The future education examination system cannot answer questions, and there is no response after clicking on the options, and the answers will not be recorded
Tables in the thesis of latex learning
Work order management system OTRs
View CSDN personal resource download details
Linked list operation can never change without its roots
【OpenCV 例程200篇】218. 多行倾斜文字水印
7-17 crawling worms (15 points)
Exercise 7-2 finding the maximum value and its subscript (20 points)
Native div has editing ability
Write a program to define an array with 10 int elements, and take its position in the array as the initial value of each element.
Button wizard business running learning - commodity quantity, price reminder, judgment Backpack