当前位置:网站首页>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 .
边栏推荐
- Evolution from monomer architecture to microservice architecture
- Realsense of d435i, d435, d415, t265_ Matching and installation of viewer environment
- Dynamic memory management
- Map container
- 用数据告诉你高考最难的省份是哪里!
- Latex arranges single column table pictures in double column format articles
- Jianzhi offer 04 (implemented in C language)
- uniapp 小于1000 按原数字显示 超过1000 数字换算成10w+ 1.3k+ 显示
- Two way process republication + routing policy
- Devop basic command
猜你喜欢

Advanced technology management - how to design and follow up the performance of students at different levels

What is an excellent architect in my heart?
Si vous ne connaissez pas ces quatre modes de mise en cache, vous osez dire que vous connaissez la mise en cache?

Hands on deep learning (III) -- Torch Operation (sorting out documents in detail)

Tables in the thesis of latex learning

Servlet基本原理与常见API方法的应用

Devop basic command

Rhcsa day 9

Summary of several job scheduling problems

DCL statement of MySQL Foundation
随机推荐
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 time format conversion strftime MS matching format
Batch distribution of SSH keys and batch execution of ansible
DCL statement of MySQL Foundation
Check 15 developer tools of Alibaba
Debug:==42==ERROR: AddressSanitizer: heap-buffer-overflow on address
Some summaries of the third anniversary of joining Ping An in China
Si vous ne connaissez pas ces quatre modes de mise en cache, vous osez dire que vous connaissez la mise en cache?
Realsense of d435i, d435, d415, t265_ Matching and installation of viewer environment
用数据告诉你高考最难的省份是哪里!
如果不知道這4種緩存模式,敢說懂緩存嗎?
Exercise 7-8 converting strings to decimal integers (15 points)
Read a piece of text into the vector object, and each word is stored as an element in the vector. Convert each word in the vector object to uppercase letters. Output the converted elements in the vect
MongoDB数据日期显示相差8小时 原因和解决方案
leetcode1229. Schedule the meeting
RHCE day 3
How can Huawei online match improve the success rate of player matching
If you don't know these four caching modes, dare you say you understand caching?
PHP代码审计3—系统重装漏洞
Advanced technology management - how to design and follow up the performance of students at different levels