Jump to content
  • Revista PROGRAMAR: Já está disponível a edição #60 da revista programar. Faz já o download aqui!

CoimbraPT

Space Invaders

Recommended Posts

CoimbraPT

Boa noite a todos,

Chamo-me Ricardo Campos sou de Portugal, e estou a frequentar uma cadeira de Linguagem C

O trabalho final consiste em fazer o jogo do "Space Invaders", como o conhecemos, aquele bem antigo.

Mas, eu gostava fazer uma pequena alteração, que era, fazer um ciclo, em que a nave ao disparar um tiro, iria aparecer na nossa tela um circulo, que explodia de dentro para fora.

Isto é possível? É muito difícil de fazer?

Atenciosamente,

Ricardo Campos

Edited by CoimbraPT

Share this post


Link to post
Share on other sites
HappyHippyHippo

depende da maneira como estás a trabalhar a apresentação "na tela"


IRC : sim, é algo que ainda existe >> #p@p

Share this post


Link to post
Share on other sites
CoimbraPT

Boa noite

O que eu queria era fazer um ciclo com o "char InV6[88] e char InV7[88]" colocando-os no meio do ecran, para dar a ideia que o míssil está a explodir,

ou seja, alterna-los, de maneira que a que apareça char InV6[88] primeiro e depois char InV7[88] mas na mesma possição, para parecer que o míssil está a estoirar.

Eu queria colocar aqui um ficheiro.h, mas não o sei fazer :(

Atenciosamente,

Ricardo Campos

// space invaders simple game can be palyed at : http://www.pacxon4u.com/space-invaders/
// in http://cecilsunkure.blogspot.pt/  its possible to see how to use the windows console with ascii chars to
// build simple console games
#include <stdio.h>  
#include <stdlib.h>
#include <time.h>
#include <conio.h>
#include <math.h>
#include <windows.h> // WinApi header. Here are functions to acess and change the console interface
#include "numeros.h" // this header has number maps to write "char" made with the 219 char

// the  windows console is defined in character lines and colons
// colors of text and background can be changed with the function;

// SetConsoleTextAttribute(wHnd, background color*16+ foreground color );

// The different color codes are:   0->BLACK, 1->BLUE, 2->GREEN, 3->CYAN, 4->RED, 5->MAGENTA, 6->BROWN, 7->LIGHTGRAY
//								  8->DARKGRAY, 9->LIGHTBLUE, 10->LIGHTGREEN, 11->LIGHTCYAN, 12->LIGHTRED, 13->LIGHTMAGENTA, 14->YELLOW, 15->WHITE
// entities for the space invader game:
// Core Cannon- He is the player and the hero of the earth
// Large Invader
// Medium Invader
// Small Invader
// UFO

// define constants to define the width and height of a "invader"
#define MediumInvaderW 11
#define MediumInvaderH 8

// define constants to use to set the Console size in "pixels" -  Definição do tamanho da consola em "pixeis"
// a pixel is a char 219 that we can change the color.
#define WIDTH 100
#define HEIGHT 80

HANDLE wHnd; // write (output) handle https://en.wikipedia.org/wiki/Handle_(computing)
 // handle to the console
typedef struct
{
 int tipo; //Invader form, for example : Canon, Large Invader and so on.
 int px;
 int py;
 int estado; //For example: 1 the invader is "alive"; 0 - the invader is dead; more options if you want
}SpaceBug;


void gotoxy( int column, int line ) // esta função seleciona a posição de escrita na consola
  {
  COORD coord;
  coord.X = column;
  coord.Y = line;
  SetConsoleCursorPosition(GetStdHandle( STD_OUTPUT_HANDLE ),coord);
  }

void hidecursor()  // hides the console cursor
{
   HANDLE consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
   CONSOLE_CURSOR_INFO info;
   info.dwSize = 100;
   info.bVisible = FALSE;
   SetConsoleCursorInfo(consoleHandle, &info);
}

// a logic map to draw a example of an invader...
char InV1[88]=  {0,0,1,0,0,0,0,0,1,0,0,
  0,0,0,1,0,0,0,1,0,0,0,
  0,0,1,1,1,1,1,1,1,0,0,
  0,1,1,0,1,1,1,0,1,1,0,
  1,1,1,1,1,1,1,1,1,1,1,
  1,0,1,1,1,1,1,1,1,0,1,
  1,0,1,0,0,0,0,0,1,0,1,
  0,0,0,1,1,0,1,1,0,0,0};//Posição boneco braços para baixo
char InV2[88]=  {0,0,1,0,0,0,0,0,1,0,0,
  1,0,0,1,0,0,0,1,0,0,1,
  1,0,1,1,1,1,1,1,1,0,1,
  1,1,1,0,1,1,1,0,1,1,1,
  0,1,1,1,1,1,1,1,1,1,0,
  0,1,1,1,1,1,1,1,1,1,0,
  0,0,1,0,0,0,0,0,1,0,0,
  0,1,0,0,0,0,0,0,0,1,0};//Posição boneco braços para cima
char InV3[88]= { 0,0,0,0,0,1,0,0,0,0,0,
  0,0,0,1,1,0,1,1,0,0,0,
  0,0,1,0,0,1,0,0,1,0,0,
  0,1,0,0,1,0,1,0,0,1,0,
  0,1,0,1,0,0,0,1,0,1,0,
  0,1,0,0,0,0,0,0,0,1,0};//Nave_ISEC
char InV5[88]=  {0,0,0,0,1,0,1,0,0,0,0,
  0,0,0,1,0,1,0,1,0,0,0,
  0,0,1,0,1,0,1,0,1,0,0,
  0,0,1,0,1,0,1,0,1,0,0,
  0,1,0,1,0,1,0,1,0,1,0,
  0,1,0,1,0,1,0,1,0,1,0,
  0,0,1,0,1,0,1,0,1,0,0,
  0,0,0,1,0,1,0,1,0,0,0,};//Nave 2
char InV6[88]=  {0,0,0,1,0,1,0,1,0,0,0,
  0,0,1,0,1,0,1,0,1,0,0,
  0,1,0,1,0,1,0,1,0,1,0,
  1,0,1,0,1,0,1,0,1,0,1,
  0,1,0,1,0,1,0,1,0,1,0,
  0,0,1,0,1,0,1,0,1,0,0,
  0,0,0,1,0,1,0,1,0,0,0,
  0,0,0,0,1,0,1,0,0,0,0};//Missil a explodir
char InV7[88]=  {0,0,0,0,1,0,1,0,0,0,0,
  0,0,0,1,0,1,0,1,0,0,0,
  0,0,1,0,1,0,1,0,1,0,0,
  0,1,0,1,0,1,0,1,0,1,0,
  1,0,1,0,1,0,1,0,1,0,1,
  0,1,0,1,0,1,0,1,0,1,0,
  0,0,1,0,1,0,1,0,1,0,0,
  0,0,0,1,0,1,0,1,0,0,0,};//Missil a explodir 2


   // setConsole uses a vector that will be used to store a image with the size of the console
// that will be sent to the console
// this function initializes all the elements of the vector with the char 219
void setConsole(CHAR_INFO * conbuf){
int y, x;
  for (y = 0; y < HEIGHT; ++y)   // for all the console lines adressed by y
  {
 for (x = 0; x < WIDTH; ++x)  // for all console line colons
 {
   conbuf[x + WIDTH * y].Char.AsciiChar = (unsigned char)219; // the char 219 is writen in all elements of the console vector
   conbuf[x + WIDTH * y].Attributes = 0;	   // attributes register the color of the char 0-> black
 }
  }
}

// print_invader - is a function to print an invader with the 219 ASCII char
// conbuf is a pointer to the buffer of data that is copied to the console.
// (px, py) top left coordinate of the invader

void print_invader(CHAR_INFO *conbuf,int  px, int py, int show){//AQUI MUDAMOS A COR AOS INVADERS, CLOLOCANDO OS ATTRIBUTES DE 0 A 15
 int y, x;    // console coordinates
 int j=0;	  // invader index

  for (y = py, j=0; y <py+MediumInvaderH; y++) // for each line of the invader
  {
 for (x = px; x < px+MediumInvaderW ; j++, x++) // for each colun of the invader
 {
  if(InV7[j]==1)
  {
   //conbuf[x + WIDTH * y].Char.AsciiChar = (unsigned char)219;
   if ( show==1)
   conbuf[x + WIDTH * y].Attributes = rand_color(); // se show é 1 é usado a cor branca para os caracteres que representam um pixel a "1"
   else
   conbuf[x + WIDTH * y].Attributes = 0;  // caso contrario é usado a cor preta para os caracteres que representam um pixel a "1" , apaga.
  } 
 }
  }
}

// function to print with the 219 ASCII char a number

int rand_color(void);
/***************************************************************************************************/
/********** Muda as cores dos invaders baseado no relógio do PC ************************************/
/***************************************************************************************************/

int rand_color(void)
{
srand(time(NULL));
return rand() % 15;
}
/*
Linhas 1 e 2 - bibliotecas que tens que adicionar no início do code
Linha 4 - cabeçalho da função
Linha 6 - definição da função. Esta devolve um 'int' e não recebe qualquer parâmetro
Linha 7 - Seed para a função rand(). Usamos a função built-in 'time(NULL)' para gerar uma seed, baseada no clock do sistema.
Linha 8 - A função retorna um valor inteiro (pseudo) aleatório entre 0 e 15

Como a função devolve um valor, ou usamos directamente a função ou em alternativa, usamos uma variável para guardar o valor devolvido

cor_aleatoria = rand_color();
*/
/***************************************************************************************************/
/***************************    Muda a cor dos invaders  *******************************************/
/***************************************************************************************************/


void print_chr(CHAR_INFO * conbuf, int  px, int py, int num){
 int y,x,j=0;
 num=num*20; // each char uses 20 pixels

 for (y = py; y < py+5; y++) // each char has 5 pixels in height
   {
  for (x = px; x < px+ 4; x++,j++) // cada caracter tem 4 pixels em largura
  {
    if( numap[num+j]== 1) conbuf[x + WIDTH * y].Attributes = 9;//15
   else conbuf[x + WIDTH * y].Attributes = 0;
  }
   }
}
/***************************************************************************************************/
/***************************************************************************************************/

//the number is divided in digits that are printed in the print_chr function
void  PrintNumber(CHAR_INFO * conbuf, int posx,int posy, int number){
int newdig=0;
 while(number>=10){
  print_chr(conbuf, posx - 5*newdig, posy,number%10); //take a digit px recua 5 "pixes" a cada escrita: px - 5*nl
	 number=number/10;		    //or numero2screen/=10 if you like brevity
  newdig++;
 }
  print_chr(conbuf, posx - 5*newdig, posy,number); //print the last digit
  newdig++;
  print_chr(conbuf, posx - 5*newdig, posy,15); //print a blank space
}

/***************************************************************************************************/
// ###########################    MAIN  ############################################################/
/***************************************************************************************************/
int main()
{

int x,y, contador_ciclos=0, tempo_ciclo, numero2screen;
int nl;
srand((unsigned) time(NULL)); /* Intializes random number generator */
char ch, nome[100];
char score_to_print[10];
time_t t;//time_t t;<---------------------------------------------------------------------------------------------------------------------------------MUDAR

/***************************************************************************************************/
// ###########################    console setup   ##################################################/
/***************************************************************************************************/


  SMALL_RECT windowSize = {0, 0, WIDTH - 1, HEIGHT - 1}; /* Window size coordinates, be sure to start index at zero! */
  COORD bufferSize = {WIDTH, HEIGHT}; /* A COORD struct for specificying the console's screen buffer dimensions */
  COORD characterBufferSize = {WIDTH, HEIGHT};/* Setting up different variables for passing to WriteConsoleOutput */
  COORD characterPosition = {0, 0};
  SMALL_RECT consoleWriteArea = {0, 0, WIDTH - 1, HEIGHT - 1};

  CHAR_INFO consoleBuffer[WIDTH * HEIGHT];
 // The variable for the console buffer
 // A CHAR_INFO structure containing data about a single character */
 // https:msdn.microsoft.com/en-us/library/windows/desktop/ms682013(v=vs.85).aspx

  wHnd = GetStdHandle(STD_OUTPUT_HANDLE);/* initialize handles */
  SetConsoleTitle("ISEC-DEE SPACE INVADERS");/* Set the console's title */
  SetConsoleWindowInfo(wHnd, TRUE, &windowSize);/* Set the window size */
  SetConsoleScreenBufferSize(wHnd, bufferSize);/* Set the screen's buffer size */

 CONSOLE_FONT_INFOEX info = {0};
 info.cbSize	   = sizeof(info);
 info.dwFontSize.Y = 18; //
 info.FontWeight   = FW_NORMAL;
 wcscpy(info.FaceName,L"Lucida Console");
 SetCurrentConsoleFontEx(wHnd, 0, &info);

SetConsoleWindowInfo(wHnd, TRUE, &windowSize);


SetConsoleTextAttribute(wHnd,  14); 
printf("\t TRABALHO DE PROGRAMACAO DE COMPUTADORES \n");   
printf("\t UTILIZACAO DA CONSOLA \n"); 
printf("\t COM CARACTERES ASCII EXTENDIDOS\n"); 
printf("\t	   PROGRAMACAO DO JOGO SPACE INVADERS \n\n");

SetConsoleTextAttribute(wHnd, 15);  // colocar texto a cor branco

printf("\n\n\n\tQual e o seu nome?  ");

gets(nome);
printf("\n\n \t");
// printf("\007");Sleep(500);  // makes a bip
printf("\n \t");

SetConsoleTextAttribute(wHnd,  14); // colocar texto a cor amarela

printf("\n\n\tBoa sorte para o trabalho pratico %s ", nome);
hidecursor();

Sleep(2000); // wait for 2000 miliseconds



 info.cbSize	   = sizeof(info);
 info.dwFontSize.Y = 12; //
 SetCurrentConsoleFontEx(wHnd, 0, &info);

// ################################################################################


 setConsole(consoleBuffer);

 x=0; //  initial position
 y=20;

 tempo_ciclo=20;

// create an invader

SpaceBug invader_example; // creates a variable of type SpaceBug

 invader_example.px=0;
 invader_example.py=0;


 srand((unsigned) time(NULL)); /* Intializes random number generator *//*<----------------------------------------------------------------------------AQUI*/



 print_invader(consoleBuffer ,invader_example.px+x,invader_example.py+y,1);

 WriteConsoleOutput(wHnd, consoleBuffer, characterBufferSize, characterPosition, &consoleWriteArea);		  

 SetConsoleWindowInfo(wHnd, TRUE, &windowSize);

 Sleep(2000);

 while(1)
 {
   if(contador_ciclos==0)
  {
	 print_invader(consoleBuffer ,invader_example.px+x,invader_example.py+y,0);
		  x++;

 if(x>40)
 {
 x=rand() % 40;  // next x will be a random position from 0 to 39
 }

 PrintNumber(consoleBuffer,30, 0, x);
 print_invader(consoleBuffer ,invader_example.px+x,invader_example.py+y,1);

  }

  contador_ciclos++;

  if(contador_ciclos==tempo_ciclo) {
  contador_ciclos=0;
  }
  // ################	  teclado	 ##########################
  WriteConsoleOutput(wHnd, consoleBuffer, characterBufferSize, characterPosition, &consoleWriteArea);  
  //in each cicle the console is updated, this takes some time .... enougth to see de bug moving whitout the use of time delay 




 }// fim while

return 0;
}

Share this post


Link to post
Share on other sites
HappyHippyHippo

o teu ciclo já está feito :

while(1)
{
 // ..

  WriteConsoleOutput(wHnd, consoleBuffer, characterBufferSize, characterPosition, &consoleWriteArea);  
} // fim while

agora é controlar o que aparece na posição pretendida

  • Vote 1

IRC : sim, é algo que ainda existe >> #p@p

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.