Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > IT форум > Помощь студентам
Регистрация

Восстановить пароль

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 12.08.2011, 12:58   #1
Neo151
 
Регистрация: 18.05.2011
Сообщений: 8
По умолчанию Змейка в C++

Есть змейка, помогите пожалуйста написать к ней меню, 2 пункта: Начать игру и выход, а то игра сразу начинается, как только скомпилируется...
Код:
// zm.cpp: определяет точку входа для консольного приложения.
//
 
#include "stdafx.h"
 
 
#include <iostream>  //стандартная библиотека
#include <time.h> //случайные числа
#include <stdio.h> //для printf
#include <windows.h> // для HANDLE, курсора, цвета
#include <conio.h>  //для kbhit
 
using namespace std;
 
 
 
HANDLE hConsole;
//HANDLE hStdout, hStdin;
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
 
void GotoXY(int X, int Y)
{
    COORD coord = { X, Y };
    SetConsoleCursorPosition(hStdOut, coord);
} 
//Цвет
enum ConsoleColor
{
    Black         = 0,
        Blue          = 1,
        Green         = 2,
        Cyan          = 3,
        Red           = 4,
        Magenta       = 5,
        Brown         = 6,
        LightGray     = 7,
        DarkGray      = 8,
        LightBlue     = 9,
        LightGreen    = 10,
        LightCyan     = 11,
        LightRed      = 12,
        LightMagenta  = 13,
        Yellow        = 14,
        White         = 15
};
int numer;
void SetColor(ConsoleColor text, ConsoleColor background)
{
    SetConsoleTextAttribute(hStdOut, (WORD)((background << 4) | text));
}
 
 
struct Zmeja  // структура змейка 
{
    COORD *t; //точки
    int PCount; //количество яблок
};
enum uprawlenie{LEFT,UP,RIGHT,DOWN}; //направление змейки
struct Game //даные-точности: змейки, яблок, передвижение по X и Y, задержка, направление
{
    Zmeja gaduka; //змейка
    COORD jabloko; //яблоко
    int dx,dy, //передвижение
        pause; //задержка
    int nap; //направление
    
};
 
//Функция разброски яблок
void PlusJabloko(Game &g)
{
    int i,x,y;
        numer = rand() % 5+1;
    int n = g.gaduka.PCount;
    do
    {
        x = rand() % 16+3; //
        y = rand() % 16+3; //кординаты яблока
        for(i = 0; i < n; i++)
        {
            if(x == g.gaduka.t[i].X && y == g.gaduka.t[i].Y) // проверка чтоб яблоко не бросить на змею
                break;
        }
    }
    while(i < n);
    g.jabloko.X = x; //
    g.jabloko.Y = y; //запоминаем позицию яблока
    SetConsoleCursorPosition(hConsole, g.jabloko); //переносим курсор в эту позицию
    SetConsoleTextAttribute(hConsole,0x0c); //цвет яблока  
    printf("%d", numer); //рисуем яблоко каким хотим символом
    
}
// Функцыя старта змейки ее координат и скорости
void skorostGame(Game &g)
{
    system("cls");
    g.gaduka.PCount = 3; //сколько точек в змейки
    g.gaduka.t = new COORD [3];//создали точки
    for(int i = 0; i < 3; i++)
    {
        g.gaduka.t[i].X = 10 + i;
        g.gaduka.t[i].Y = 10;
        
    }
    g.dx = 1;
    g.dy = 0;
    g.pause = 100;//скорость передвижение змеи
    PlusJabloko(g);//рисуем яблока
}
 
void Level()
{
    GotoXY(10,10);cout <<"Wu nikogda ne wuigraete "<<endl;
    GotoXY(10,11);cout <<"eslu ne bydete bdutelnu!!!"<<endl;
}
void ZmejaStart()
{
    GotoXY(10,15);cout <<"Soberite 75 Jablok togda posmotrim"<<endl;
}
void STENA_2()
{
    SetColor(LightBlue , Black);GotoXY(20,0);
    GotoXY(64,2);cout <<  "Danue:" << endl ;
    GotoXY(64,3);cout <<  "Jablok:0" << endl ;
    GotoXY(64,4); cout <<  "Dlina:3"<< endl;
    GotoXY(64,5); cout <<  "Speed:0" << endl;
    GotoXY(64,7); cout << "Uprawlenie:" <<  endl;
                GotoXY(64,8); cout << "Esc:Wuxod" <<  endl;
                GotoXY(64,9); cout << "P:Pause" <<  endl;
                GotoXY(64,10); cout <<"S:Start" <<  endl;
                GotoXY(64,11); cout <<"L:Level" <<  endl;
                GotoXY(64,13);printf("%c",24);cout <<":Wwerx"<<endl;
                GotoXY(64,14);printf("%c",25);cout<<":Wniz"<<endl;
                GotoXY(64,15);printf("%c",27);cout<<":Wlewo"<<endl;
                GotoXY(64,16);printf("%c",26);cout<<":Wprawo"<<endl;
                SetColor(LightMagenta , Black);
                GotoXY(2,2);
                int m = 0;
                for(m = 0; m < 20; m++)
                {
                    printf("*");
                }
                
                {
                    GotoXY(2,20);
                    for(m = 0; m < 20;m++)
                    {
                        printf("*");
                    }
                }
                {
                    for(m = 2; m < 20;m++)
                    {
                                                GotoXY(2,m);
                        printf("*");
                    }
                }
                {
                    for(m = 2; m < 21;m++)
                    {
                                                GotoXY(22,m);
                        printf("*");
                    }
                }
}

Последний раз редактировалось Neo151; 12.08.2011 в 13:00.
Neo151 вне форума Ответить с цитированием
Старый 12.08.2011, 12:59   #2
Neo151
 
Регистрация: 18.05.2011
Сообщений: 8
По умолчанию

Продолжение кода
Код:
enum {KONEC, STENA,  PLUS, MOVE};
int Move(Game &g)
{
    int & n = g.gaduka.PCount;
    COORD head = g.gaduka.t[n - 1]; 
    COORD tail = g.gaduka.t[0]; 
    COORD next;
    next.X = head.X + g.dx;
    next.Y = head.Y + g.dy; 
    if(next.X < 3 || next.Y < 3 || next.X > 20 || next.Y > 19)
        
        
        return STENA;
    if(n > 4)
    {
        for(int i = 0; i < n; i++)
            if(next.X == g.gaduka.t[i].X && next.Y == g.gaduka.t[i].Y)
                return KONEC;
    }
    
    if(next.X == g.jabloko.X && next.Y == g.jabloko.Y)
    {
                n+=numer;
        COORD*temp = new COORD[ n ];
        for(int i = 0; i < n; i++)
            temp[i] = g.gaduka.t[i];
        temp[n - 1] = next;
        delete [] g.gaduka.t;
        g.gaduka.t = temp;
        
        SetConsoleCursorPosition(hConsole,head);
        SetConsoleTextAttribute(hConsole, 0x0a);
        printf("*");
        SetConsoleCursorPosition(hConsole,next);
        SetConsoleTextAttribute(hConsole,0x0a);
        printf("%c",1);
        PlusJabloko(g);
        return PLUS;
    }
    
    for(int i = 0; i < n - 1; i++)
        g.gaduka.t[i] = g.gaduka.t[i + 1];
    g.gaduka.t[n - 1] = next;
    SetConsoleCursorPosition(hConsole,tail);
    printf(" ");
    
    SetConsoleCursorPosition(hConsole,head);
    SetConsoleTextAttribute(hConsole, 0x0a);зелений цвет
    printf("*");
    SetConsoleCursorPosition(hConsole,next);
    SetConsoleTextAttribute(hConsole,0x0f);
    printf("%c",1);
    
    return MOVE;
}
 
 
 
void main()
{
 
    hConsole = GetStdHandle(STD_OUTPUT_HANDLE); //получаем дескриптор консоли
    int key = 0, count = 0;
    bool Pause=false;
    Game g;
    skorostGame(g);
    STENA_2();
    srand(time(0));
//      numer = rand() % 5;
    bool pause = false;
    while(key != 27)
    {
        while(!kbhit()) //ждет пока нажмем
        {
            if(Pause==true)
            {
                Sleep(1); 
                continue;
            }
            
            switch (Move(g))//движение
            {
                
            case PLUS:
                ++count;
                g.pause-=1;
                GotoXY(64,2);cout <<  "Danue:" << endl ;
                GotoXY(64,3); cout << "Jablok:" <<count << endl;
                GotoXY(64,4); cout << "Dlina:" <<g.gaduka.PCount << endl;
                GotoXY(64,5); cout << "Speed:" <<g.pause<< endl;
                GotoXY(64,7); cout << "Uprawlenie:" <<  endl;
                GotoXY(64,8); cout << "Esc:Wuxod" <<  endl;
                GotoXY(64,9); cout << "P:Pause" <<  endl;
                GotoXY(64,10); cout <<"S:Start" <<  endl;
                GotoXY(64,11); cout <<"L:Level" <<  endl;
                GotoXY(64,13);printf("%c",24);cout <<":Wwerx"<<endl;
                GotoXY(64,14);printf("%c",25);cout<<":Wniz"<<endl;
                GotoXY(64,15);printf("%c",27);cout<<":Wlewo"<<endl;
                GotoXY(64,16);printf("%c",26);cout<<":Wprawo"<<endl;
                if (count == 75) 
                {
                    GotoXY(15,1); cout << "Wu wuigrali(maladec!!!)" << endl;
                   
                    GotoXY(15,6);printf( "Esli wi wiigrali prihlite mne kluh ukazanie wihe\n\t\t\t" );
                    GotoXY(15,7);printf( "Nazmi 5 raz\n\t\t\t" );
                    getch();
                    getch();
                    getch();
                    getch();
                    getch();
                    return;
                }
                break;
                
            case STENA:
                
            case KONEC:
                GotoXY(23,1); printf("Wu proigrali(xa-xa-xa!!!)\n\n\t\t\t");
                getch();
                return;
                break;
            }
            
            Sleep(g.pause); //Задержка
        }
        key = getch();
        
        if(key=='P'||key=='p')
            Pause=!Pause;
        else if(key=='S'||key=='s')
            ZmejaStart();
        else if(key=='L'||key=='l')
            Level();
        else if(key==0||key==224)
        {
            key=getch();
            
            if(key == 72 && g.nap != DOWN)
            {
                g.nap = UP;
                g.dx = 0;
                g.dy = -1;
            }
            else if(key == 80 && g.nap != UP)
            {
                g.nap = DOWN;
                g.dx = 0;
                g.dy = 1;
            }
            else if(key == 75 && g.nap != RIGHT)
            {
                g.nap = LEFT;
                g.dx = -1;
                g.dy = 0;
            }
            else if(key == 77 && g.nap != LEFT)
            {
                g.nap = RIGHT;
                g.dx = 1;
                g.dy = 0;
            }
        }
    }
}
Neo151 вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
змейка на с++ danzel1 Gamedev - cоздание игр: Unity, OpenGL, DirectX 6 30.07.2011 09:06
Змейка на c++ Banner Помощь студентам 1 14.05.2011 16:21
Змейка на с++ Banner Помощь студентам 5 26.02.2011 16:42
змейка =) romiccccc Помощь студентам 0 12.05.2010 11:08
ЗМЕЙКА(((( mizantrop32 Общие вопросы C/C++ 2 07.04.2010 17:10