Thursday, April 16, 2009

Simple Game with C++

I tried to make a better code for simple game (quiz in my class last 2 weeks). And, I failed TT.TT. Well, i've tried to remake it and i'm sure there is NO ZOMBIE! (no minus hp to be printed ^^)

#include "stdafx.h"
#include "stdlib.h"
#include "time.h"
#include "string.h"

struct musuh{
int hp;
char nama[11];
struct musuh *next,*prev;
}*curr,*head,*tail,*temp;

void push()
{
char name[11];
curr=(struct musuh*)malloc(sizeof(struct musuh));
do{
printf("Insert your enemy's name [3-10 character]: ");
scanf("%s",&name);fflush(stdin);
}while(strlen(name)<3||strlen(name)>10);
strcpy(curr->nama,name);
curr->hp=100;
if(head==NULL) head=tail=curr;
else
{//back push
curr->prev=tail; tail->next=curr; tail=curr;
}head->prev=NULL;tail->next=NULL;
}

void pop()
{
printf("\nYou've killed %s!!\n",curr->nama);
if(head==tail){free(head);head=curr=tail=NULL;printf("\nYou killed all of your enemies!\nYou win!\n");}
else if(curr==head&&head!=NULL)
{//front pop
head=curr->next;
free(curr);
head->prev=NULL;
}
else if(curr==tail&&head!=NULL)
{//back pop
tail=curr->prev;
free(curr);
tail->next=NULL;
}
else if(head!=NULL)
{
curr->prev->next=curr->next;
curr->next->prev=curr->prev;
free(curr);
}
}

void attack()
{
char att[11];
int spl,dmg;
srand(time(NULL));
do{
printf("Insert the name of your enemy who you want to punish [3-10 char]: ");
scanf("%s",&att);fflush(stdin);
}while(strlen(att)<3||strlen(att)>10);
curr=head;
if(head==NULL)printf("\nYou don't have any enemy(s) yet!\n");
while(strcmp(curr->nama,att)!=0)
{
curr=curr->next;
if(curr==NULL) break;
}
if(curr==NULL) {printf("\nYou have input the wrong name!\n\n");attack();}
else if(strcmp(curr->nama,att)==0){
dmg=rand()%11+10; spl=dmg/2;
curr->hp=curr->hp-dmg;
if(curr->prev!=NULL)
curr->prev->hp=curr->prev->hp-spl;
if(curr->next!=NULL)
curr->next->hp=curr->next->hp-spl;
}
curr=head;
while(curr)
{if(curr->hp<1){pop();curr=head;}
else curr=curr->next;}
}

void cetak()
{
printf("\n");
curr=head;
while(curr)
{printf("%-10s",curr->nama); curr=curr->next;}
printf("\n");
curr=head;
while(curr)
{printf("%-10d",curr->hp);curr=curr->next;}
printf("\n");
}

void menu(){
printf("\n\nSimple Game by Yuri\n-------------------\n1.Insert enemy\n2.Attack!\n3.Quit game\n-------------------\n");
}

int _tmain(int argc, _TCHAR* argv[])
{
int pilih;
do{
menu();
do{
printf("Insert option : ");
scanf("%d",&pilih);}while(pilih<1||pilih>3);
switch(pilih)
{
case 1:{push();break;}
case 2:{attack();break;}
}cetak();
}while(pilih!=3);
printf("\nThanks for Playing!!\n\n---You are the ONLY edition(Ps.Jeffrey Rachmat)---\n\n");
getchar();
return 0;
}

i used visual c++, and i hope this time its right answer!
correction are appreciated ^^v! thx!

No comments: