공부/C
[C] 기억력 게임/문자열 전광판
래울
2020. 12. 13. 11:39
conIo.h
windows.h
기억력 게임
#include <stdio.h>
#include <windows.h>
#include <conIo.h> //getch()
#include <stdlib.h>
#include <time.h>
#define ENTER 0x0d //ENTER의 ASCII_CODE
#define ESC 0x1b //ESC의 ASCII_CODE
// 80 25 size
char screen[24][80];
void initailize();
void gotoxy(int x, int y);
void cursor_off();
char get_alphabet();
void display_screen();
void clear_screen();
void play_game();
void clear_array();
void main(){
char ch = 0;
initailize();
while(ch != ESC){
gotoxy(0, 24);
printf("게임을 시작하려면 엔터, 종료하려면 ESC를 누르세요.");
ch = _getch();
if(ch == ENTER){
gotoxy(0,24);
printf("점수 : ");
play_game();
}
}
}
void initailize(){
srand(time(NULL));
cursor_off();
}
void gotoxy(int x, int y){
COORD Pos = {x, y};
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), Pos);
}
void cursor_off(){
CONSOLE_CURSOR_INFO Coff = {100, 0};
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &Coff);
}
char get_alphabet(){
int x, y;
do{
x = rand()%80;
y = rand()%25;
}while(screen[y][x] != 0);
screen[y][x] = rand()%26 + 65; //65~90
return screen[y][x];
}
void display_screen(){
int x,y;
for(y=0; y<24; y++){
for(x=0; x<80; x++){
if(screen[y][x] != 0){
gotoxy(x,y);
_putch(screen[y][x]);
}
}
}
}
void clear_screen(){
int x,y;
for(y=0; y<24; y++){
for(x=0; x<80; x++){
if(screen[y][x] != 0){
gotoxy(x,y);
_putch(' ');
}
}
}
}
void play_game(){
int score = 0;
char keyin, alphabet;
clear_array();
do{
clear_screen();
Sleep(1000);
alphabet = get_alphabet();
display_screen();
keyin = _getch();
keyin = toupper(keyin);
if(keyin == alphabet){
score += 1;
gotoxy(7, 24);
printf("%2d", score);
}
}while(keyin == alphabet);
}
void clear_array(){
clear_screen(); //clear_screen을 한뒤, 배열screen을 지워야 과거 값이 지워진다.
int i,j;
for(i=0; i<24; i++){
for(j=0; j<80; j++)
screen[i][j] = '\0';
}
}
문자열 전광판
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#include <conIo.h>
#include <time.h>
#define SPACE 0x20 //ESC
#define ESC 0x1b //Space bar
#define REFRESH_TIME 500
void gotoxy(int x, int y);
void print_string(int x, int y, const char *str, int length, int pos);
char screen[25][80];
int main()
{
const char *str = "C programming is easy.";
int length = strlen(str);
int dx = (80-strlen(str))/2;
int dy = 12;
int dir = 1;
int pos = 0;
clock_t refresh_time = 0;
char ch;
for(;;){
if(clock() > refresh_time){
print_string(dx, dy, str, length, pos);
refresh_time = clock() + REFRESH_TIME;
pos = pos + dir;
if(pos == length)
pos = 0;
if(pos < 0)
pos = length-1;
}
if(_kbhit()){
ch = _getch();
if(ch == SPACE)
dir = (dir == 1) ? -1 : 1;
if(ch == ESC)
break;
}
}
}
void gotoxy(int x, int y){
COORD Pos = {x, y};
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), Pos);
}
void print_string(int x, int y, const char *str, int length, int pos){
int n, index;
gotoxy(x, y);
for(n=0; n<length; n++){
index = (pos + n)%length;
_putch(str[index]);
}
}