贪吃蛇

作者在 2010-12-08 14:23:12 发布以下内容
#include <iostream.h>
#include <time.h>
#include <conio.h>
#include <windows.h>
#include <stdio.h>

const int LENGTH = 25;//最大的图


class SNAKE
{
public:
    SNAKE():size(10),s1(1),s2(1){}
    int step();
    int init();
    int show();
    int change();
private:
    int size;
    int table[LENGTH][LENGTH];
    int s1, s2;//初始位置
    int x, y;//食物
};
int SNAKE::init()
{
    int i=0, j=0;
    for(i=0; i<=size; ++i)
        for( j=0; j<=size; ++j )
            table[i][j] = 0;
            
    for( i=0; i<=size; ++i )
    {
        table[0][i] = 1;
        table[i][size] = 1;
        table[i][0] = 1;
        table[size][i] = 1;
    }
    
    return 0;
}
int SNAKE::change()
{
    x = rand()%(size-1) + 1;
    y = rand()%(size-1) + 1;
    table[x][y] = 2;
    return 0;
}
int SNAKE::step()
{
    int m;
    while( s2!=y || s1!=x )
    {
        system("cls");
        table[s1][s2] = 'S';
        show();
        m = getch();    
        if( m=='w' )
        {
            table[s1][s2] = 0;
            --s1;
            if( s1==0 )
            {
                s1 = size-1;
            }
            table[s1][s2] = 'S';
        }
        else if( m=='s' )
        {
            table[s1][s2] = 0;
            ++s1;
            if( s1==size )
            {
                s1 = 1;
            }
            table[s1][s2] = 'S';
        }
        else if( m=='a' )
        {
            table[s1][s2] = 0;
            --s2;
            if( s2==0 )
            {
                s2 = size-1;
            }
            table[s1][s2] = 'S';
        }
        else if( m=='d' )
        {
            table[s1][s2] = 0;
            ++s2;
            if( s2==size )
            {
                s2 = 1;
            }
            table[s1][s2] = 'S';
        }
        system("cls");
        show();
    }
    return 0;
}
int SNAKE::show()
{
    int i, j;
    for(i=0; i<=size; ++i)
    {
        for( j=0; j<=size; ++j )
            printf("%c", table[i][j]);
        printf("\n");
    }

    return 0;
}
int main()
{
    SNAKE s;
    s.init();
    srand(time(0));
    s.change();
    while(1)
    {
        if(!s.step())
        {    
            s.change();
        }
    }
    return 0;
}
程序 | 阅读 649 次
文章评论,共0条
游客请输入验证码
浏览31547次