게시판 즐겨찾기
편집
드래그 앤 드롭으로
즐겨찾기 아이콘 위치 수정이 가능합니다.
c언어 버그 재질문 메모리해제 부분에서 프로그램이 정지합니다.
게시물ID : computer_132285짧은주소 복사하기
작성자 : 익명15885588
추천 : 0
조회수 : 348회
댓글수 : 5개
등록시간 : 2013/12/03 23:45:42
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

#define LEFT   75
#define RIGHT  77
#define UP       72
#define DOWN  80

struct POINT {
short x;
short y;
};

void main()
{
struct POINT player; //플레이어 좌표
short **maze; //미로 배열
short i,j, width, height; //for문 제어변수(i, j), 배열 크기(width, height)
int key; //사용자의 키를 입력받을 변수
FILE* loadfile; //파일을 불러올 파일포인터
/*
maze.txt 파일
첫 줄에 미로의 너비와 높이 값이 기록되어 있으며, 그 다음 줄부터는 미로데이터들이 입력되어 있다.
아래는 데이터가 의미하는 바이다.
0: 공백
1: 벽
2: 출발지점
3: 도착지점
*/
loadfile = fopen("maze.txt","r");

//maze.txt파일이 없을 시 실행 불가
if(loadfile == NULL)
{
fprintf(stderr, "ERROR: \"maze.txt\" does not exist");
return;
}

fscanf(loadfile, "%d %d", &width, &height);
/*
2차원 배열 할당 알고리즘
포인터 배열 행의 크기만큼 할당하여 더블포인터변수에 주소를 받은 뒤
데이터 배열을 행*열의 크기만큼 할당하여 방금 할당한 포인터 배열의 첫칸에 주소를 넣는다.
포인터 배열 나머지 칸에는 첫칸 주소를 이용해 열의 크기만큼 건너뛰어 주소를 잡아준다.
*/
maze = (short**)malloc(sizeof(short*)*width);
*maze = (short*)malloc(sizeof(short)*width*height);
for(i=1;i<width;i++) *(maze+i) = *(maze+i-1)+height;
for(i=0;i<width;i++)
for(j=0;j<height;j++)
fscanf(loadfile, "%d", &maze[i][j]);
fclose(loadfile);
//플레이어의 시작위치를 찾는다.
for(i=0;i<width;i++)
for(j=0;j<height;j++)
if(maze[i][j] == 2)
{
player.x = i;
player.y = j;
}

while(1)
{
system("cls");
//화면을 그린다.
for(i=0;i<width;i++)
{
for(j=0;j<height;j++)
{
if(player.x == i && player.y == j) //플레이어
printf("◎");
else if(maze[i][j] == 3) //도착지점
printf("★");
else if(maze[i][j] == 1) //벽
printf("■");
else //공백
printf("  ");
}
printf("\n");
}

if(maze[player.x][player.y] == 3)
{
printf("\n\n\a클리어!!!\n");
break;
}
//키를 입력받는다.
key = getch();
switch(key)
{
case UP:
if(!(maze[player.x-1][player.y] == 1))
player.x--;
break;
case DOWN:
if(!(maze[player.x+1][player.y] == 1))
player.x++;
break;
case LEFT:
if(!(maze[player.x][player.y-1] == 1))
player.y--;
break;
case RIGHT:
if(!(maze[player.x][player.y+1] == 1))
player.y++;
}
}
free(*maze);
free(maze);
}
꼬릿말 보기
전체 추천리스트 보기
새로운 댓글이 없습니다.
새로운 댓글 확인하기
글쓰기
◀뒤로가기
PC버전
맨위로▲
공지 운영 자료창고 청소년보호