Functions to make input trigger actions on list and stack etc. etc.

  • (2 Pages)
  • +
  • 1
  • 2

15 Replies - 3146 Views - Last Post: 09 July 2012 - 02:50 PM Rate Topic: -----

#1 jayburn00  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 118
  • Joined: 05-July 12

Functions to make input trigger actions on list and stack etc. etc.

Posted 07 July 2012 - 01:35 PM

Sorry if I wasn't supposed to, but this is actually multiple questions in a single topic. I am trying to write a program that is sort of like a text based version of tetris, and I am hitting a couple of deadends. I have yet to try implimenting a timer, because I first need to get the stack, list, and functions that are used whenever the player puts in input that transfer an item from list to stack and brings the next item in the list to beginning of the list to be displayed. In my code, any line that is entirely made up of comments is actually a description of a function or group of functions that I am trying to figure out how to implement. Also, my list creation code is not correct at the moment because I am having issues figuring out what should be returned to main, whether I should be creating a new object of list type, and I need to be able to delete the list after it is used for something, so the deletion code needs to be seperate. Any suggestions on how to implement the functions that are described is appreciated. Also, read my comments, they highlight where I am having trouble or explain what something is being used for. The errors I'm getting that don't make much sense to me even though my code isn't complete are: Intellisense: list is not a template (line 40 of header file); Intellisense: name followed by '::' must be a class or namespace name.(Line 41 of header file). Also read my comments, especially the function descriptions, and whereever I put a question. Those are the questions I am trying to answer. Here is the code, consisting of two files, a header file and a cpp file:
//Header file to create linked list.
#ifndef RANDOMSHAPELISTGEN_H
#define RANDOMSHAPELISTGEN_H
#include <iostream>
#include <list>
#include <stdlib.h>
#include <ctime>


//Where should I put the code "std::"? 
class shape
{
    public:
        shape(){}
        virtual ~shape(){;}//destructor
        virtual char *getType() = 0;//does any of this actually need to be virtual?
		//need code to designate what the score value of each shape is.  All shapes are worth 2 points each
    private://don't think I need any private
};
 
class circle : public shape
{
    public:
        char *getType() {return "circle";}
};
 
class square : public shape
{
    public:
        char *getType() {return "square";}
};
 
class triangle : public shape
{
    public:
        char *getType() {return "triangle";}
};
 

typedef list<shape*> shapeList_t;//this sometimes raises an error sometimes doesn't.  Its like my computer can't make up it mind.
typedef shapeList_t::iterator shapeListIter_t;//what am I doing wrong here?

shapeList_t myList;//declared this outside functions so multiple functions could use it.
shapeListIter_t myIter;//same as above
shape *curShape;//same as above

shapeList_t makeList()//should I have defined this function perhaps in the cpp file?
{//also am I defining this function correctly?  I think eventually I will need to pass something to it, such as what level the game is on, to be passed to shapes(later though for timer.)
    int i, numItems=20;//i is a counter, and numItems is simply the number of shapes in the list.
    
    
	int seed;
	seed = time(0);
	srand(seed);//makes time the seed for randomization function
 
    // Insert
    for (i=0; i<numItems; i++)//for loop to fill list.
    {
        switch (rand() %  3)//random function here, seeded by srand.
        {
            case 0: myList.push_back(new circle); break;
            case 1: myList.push_back(new square); break;
            case 2: myList.push_back(new triangle); break;
        }
    }
 
    // Display.  Will need to be changed to keep console screen from being a mess.
	//Also will need to be changed so that only one object at a time is listed, and clears each time object is moved from list or deleted.
    for (myIter=myList.begin(); myIter!=myList.end(); myIter++)
    {
        curShape = *myIter;
        std::cout << "Shape type: " << curShape->getType() << endl;
    }
	return myList;//Not sure if this right.
}

void deleteList()//function to delete list.  Again should I put this in the cpp file?
	//Also, will this work for when the list is empty or not filled with a number different than 20?
{
	// Cleanup
		for (myIter=myList.begin(); myIter!=myList.end(); myIter++)
		{
			curShape = *myIter;
			delete curShape;        // free the memory that this list item consumes - calls curShape's destructor
		}
		myList.clear();             // free the memory that the list uses to point to each list item - empties the list
}
#endif




// char input
//for gameover=false
//run game(will call all functions at some point, probably multiple times.
//if input = s execute save
//if input = j execute join
//if input = d execute drop
//if input = e execute redeem
//gameover conditions met:  go to main menu.
//cout totalScore
//
#include <iostream>
//May need to include another header file.
#include "RandomShapeListGen.h"
using namespace std;

int main()
{
	bool stackFull = false;  //initial value, changes based on return of a function. Controls level loop.
	bool listEmpty = false;	//initial value, changes based on return of a function. Controls level loop.
	bool gameOver = false;//initial value, controls main loop.
	bool levelEndCondition= false; //controls level loop.
	int userScore, totalScore=0; //initial values, totalScore is found at the end of every level.  userScore is determined by user functions. 
	int commonShapeScore;
	int level;

	while (gameOver==false)
	{
		for (level=1; level<=3; level++)//I haven't been able to quite test this, but will it start at level 1 or automatically move to level 2?
			//Do I need to change the initialization to level=0?
		{
			//Code to create new list using resources from header file.
			//code to create stack using resources from a header file(not done yet, not sure how my code for this will look.)
			//commonShapeScore=//Code to find number of most abundant shape and multiply by 2.  A function.
			while (levelEndCondition==false)
			{
				userScore=0;
				/*[Display contents of the top of the stack and contents at the beginning of list.];
				[perform user functions on stack and list:
					parameters of functions:  
						Shape score: 2
						redeemableScore X = 5*level (if score is greater than this, it is redeemable);
						user controlled function to move shape at beginning of list to top of stack and next shape in list becomes shape at beginning;
						automated function that scores points whenever enough shapes of the same type are placed consecutively on top eachother in stack];
				[Change displayed representation of stack and list based on what user functions were called (without multiple displays appearing for each time a change is made if possible)];
				stackFull=[function to test if stack is full, returns bool];
				listEmpty=[function to test if list is empty, returns bool];*/
				if (stackFull==true)
				{
					levelEndCondition=true;
				}
				else if (listEmpty==true)
				{
					levelEndCondition=true;
				}
				else
				{
					cout<<""<<endl;
				}
			}
			totalScore+=userScore;
			//Code to delete list.
			//Code to delete stack.
			if (userScore < (3/4 * commonShapeScore))
			{
				gameOver=true;
				cout<<3/4*commonShapeScore<<" was the minimum score to proceed.  You did not reach it."<<endl;
				cout<<"Game Over"<<endl;
				break;
			}
			else
			{
				if (level==3)
				{
					cout<<"You beat all the levels!"<<endl;
					gameOver=true;
				}
				else
				{
					cout<<"Going to next level... Press enter to continue:"<<endl;
					//code to make program wait for enter to be pressed before continuing.
				}
			}
		}
	}
	cout<<totalScore<<" is your final score."<<endl;
	return 0;
}





Oh and ignore the text above the include statement in the cpp file, the bottom file, that was some pseudocode I was using earlier. Sorry about that.

Is This A Good Question/Topic? 0
  • +

Replies To: Functions to make input trigger actions on list and stack etc. etc.

#2 jimblumberg  Icon User is online

  • member icon


Reputation: 4098
  • View blog
  • Posts: 12,682
  • Joined: 25-December 09

Re: Functions to make input trigger actions on list and stack etc. etc.

Posted 07 July 2012 - 01:45 PM

In the future please post the complete error messages, exactly as they appear in your development environment.

For the following two lines:
typedef list<shape*> shapeList_t;//this sometimes raises an error sometimes doesn't.  Its like my computer can't make up it mind.
typedef shapeList_t::iterator shapeListIter_t;//what am I doing wrong here?


Part of the problem is that you should be properly scoping the std namespace when using the std::list class.

Jim
Was This Post Helpful? 1
  • +
  • -

#3 Aphex19  Icon User is offline

  • Born again Pastafarian.
  • member icon

Reputation: 615
  • View blog
  • Posts: 1,873
  • Joined: 02-August 09

Re: Functions to make input trigger actions on list and stack etc. etc.

Posted 07 July 2012 - 01:57 PM

You need to tell the compiler that list is part of the std namespace.

e.g.
typedef std::list<a*> shapeList_t;
typedef shapeList_t::iterator shapeListIter_t;


Quote

//does any of this actually need to be virtual?

Only if you want your classes to be polymorphic and for the relevant methods to be overridden in derived classes.

Quote

//should I have defined this function perhaps in the cpp file?
//also am I defining this function correctly? I think eventually I will need to pass something to it, such as what level the game is on, to be passed to shapes(later though for timer.)

Yes. As a general rule, declarations go in to header files, definitions go in to source files. There are exceptions, but not many.

Are you defining it properly? Well, that's a design choice and it's up to you. Syntactically, it looks fine.

In makeList, you're returning a global variable. This isn't necessarily objectively wrong (there may be cause for it in some situations), but since your program is written in an object orientated way, it's best to try to avoid global variables (since they tend to go against OOP somewhat (especially data encapsulation)).

Quote

//function to delete list. Again should I put this in the cpp file?
//Also, will this work for when the list is empty or not filled with a number different than 20?

It should be in the source file, yes. The function itself looks okay, but I don't know why you have the iterator declared globally. It's needless. It's common to declare these throw away variables as locally as you can. In other words, don't declare them where they won't be used. In this case, just declare it as part of the for statement and get rid of your global variable(s).

e.g.
for (shapeListIter_t myIter=myList.begin(); myIter!=myList.end(); myIter++)


Quote

for (level=1; level<=3; level++)//I haven't been able to quite test this, but will it start at level 1 or automatically move to level 2?
//Do I need to change the initialization to level=0?

The increments in the for loop are applied at the end of each iteration.

This post has been edited by Aphex19: 07 July 2012 - 02:02 PM

Was This Post Helpful? 1
  • +
  • -

#4 jayburn00  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 118
  • Joined: 05-July 12

Re: Functions to make input trigger actions on list and stack etc. etc.

Posted 07 July 2012 - 06:17 PM

Thanks both of you for clearing up the std issue me. There is one other problem I am having with my program, but not related directly to my code, it is a problem understanding part of the directions for this assignment; I know its not C++ exactly, but its relevant to the program being written. Here are the instructions for what this program would do that I don't understand:

1. The Game: Given an empty stack and a random finite list of shapes and a list of operations, the player will try to accumulate the most scores by removing the shape from the list, in order, and applying an operation to the shapes as fast as he/she can.
There are three types of shapes: triangle, rectangle, and circle
These are the valid operations: push/save, pop/join, ignore/drop, and redeem
2. Scoring: each shape has a score and a timer associate with it
+ A Pop/Join operation of a shape that has the same type as the one on the input will result in the same shape on the top of the stack with the combine scores, and the shape from the input is removed.
+ A Pop/Join operation of a shape that has different type as the one on the input will result in losing both of these shapes
+ A Push/Save operation will move the shape from the input list to the top of the stack
+ An Ignore/Drop operation will remove a shape from the input list

I understand most of it, except for anything regarding the "valid operations". I understand redeem and ignore/drop(though I don't understand what the '/' means or why they have two words there) but the push and pop part I don't understand at all, other than them being the name of operations that can be done on a stack and list, but I don't think that is all it is in this case, I think they are supposed to do some other things in addition to the C++ container operations of push and pop.
Was This Post Helpful? 0
  • +
  • -

#5 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3589
  • View blog
  • Posts: 11,159
  • Joined: 05-May 12

Re: Functions to make input trigger actions on list and stack etc. etc.

Posted 07 July 2012 - 06:47 PM

As I understand the assignment, push just the same as the C++ container operation. Pop involves a little bit more. In pseudo code:
Pop/Join:
    fromStack = stack.Pop;
    fromQueue = queue.Deque;
    if (fromStack.Shape == fromQueue.Shape)
    {
        fromStack.Score += fromQueue.Score;
        stack.Push(fromStack);
    }



What's the deal with the timer? If an item in the list has a timer expire is it considered an Ignore/Drop, or is it Push/Save, or a Pop/Join? If two items are joined, does the timer get reset to the original value, or to the sum of the two combined items original times, or to the sum of the two combined items remaining times, or to some random value? Or does the timer not matter for items on the stack? If an item on the stack expires, does it automatically get redeemed, or pop/joined?
Was This Post Helpful? 0
  • +
  • -

#6 #define  Icon User is offline

  • Duke of Err
  • member icon

Reputation: 1353
  • View blog
  • Posts: 4,659
  • Joined: 19-February 09

Re: Functions to make input trigger actions on list and stack etc. etc.

Posted 07 July 2012 - 06:59 PM

You are using classes. Would it be possible to create a class for your shape list?
Was This Post Helpful? 0
  • +
  • -

#7 jayburn00  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 118
  • Joined: 05-July 12

Re: Functions to make input trigger actions on list and stack etc. etc.

Posted 07 July 2012 - 09:02 PM

View PostSkydiver, on 07 July 2012 - 06:47 PM, said:

As I understand the assignment, push just the same as the C++ container operation. Pop involves a little bit more. In pseudo code:
Pop/Join:
    fromStack = stack.Pop;
    fromQueue = queue.Deque;
    if (fromStack.Shape == fromQueue.Shape)
    {
        fromStack.Score += fromQueue.Score;
        stack.Push(fromStack);
    }



What's the deal with the timer? If an item in the list has a timer expire is it considered an Ignore/Drop, or is it Push/Save, or a Pop/Join? If two items are joined, does the timer get reset to the original value, or to the sum of the two combined items original times, or to the sum of the two combined items remaining times, or to some random value? Or does the timer not matter for items on the stack? If an item on the stack expires, does it automatically get redeemed, or pop/joined?

The timer is only for the shape that is next to be used in the list. That would be whatever shape is now in the first position. The timer is only used while the shape is in the list waiting for user input. There is another timer, it is the sum of all the shape timers/level or something like that. So, if a shape was in the first position of the list, its timer would be running, and then if time ran out, the shape would be deleted and the next shape moved to the position. Then that shape's timer would start. So on and so forth. Once in the stack, the timer would no longer be used. Personally I think our teacher is asking a little much of us. This timer thing would need the program to be able to do multi-threads or multi-tasks, and I never learned how to do that, and he never even taught us. He gave us a sample timer program, telling us to figure out how to use it to make timers for the shapes, but even this timer program doesn't do multitasking. His program is next to useless, it would only work if you had the timer notify you of time running out after the user gave input. Here is the timer program he gave us though, maybe one of you will have a suggestion:

/* 
Purpose: timer example 
Author: Ken Nguyen
Written: July 3, 2012
Language/compiler: C++ VS Studio 2010
*/


#include <time.h>
#include <iostream>

using namespace std;
//======================= UTILITY FUNCTIONS ============================================
/*
@Name: timer
@pParameters: reset (optional). The timer is set to current time on the first call or when reset=true
@Return: milliseconds since the last reset time
*/
int timer(bool reset = false){
	static unsigned int start = clock(); //one time initialization
	if(reset)
		start = clock(); //reset the timer
	return clock() - start; //time since last clock
}

//=====================================================================================================

/* Driver */

int main () {
    char  i;
	//the timer will reset to current time on the first call
	cout<<"\nStart clock: " << timer() <<endl;
	cout<<"\nEnter a character: ";
	cin>>i;
	cout<<"\nElapsed: " << timer() << " ms "<< endl;

	cout<<"\nElapsed: " << timer() << " ms ater printing"<< endl;
    cout<<"\nEnter a character: ";
    cin>>i;

	cout<<"\nElapsed: " << timer() << " ms"<< endl;
	cout<<"\nEnter a character: ";
    cin>>i;
	cout<<"\nElapsed: " << timer() << " ms "<< endl;

	//reseting the timer
    cout<<"\nLet's reset the timer . . . "<<timer(true)<<endl;
	cout<<"\nElapsed: " << timer() << " ms "<< endl;

	cout<<"\nEnter a character: ";
	cin>>i;
	cout<<"\nElapsed: " << timer() << " ms "<< endl;
  return 0;
}


He doesn't want us to use this, but to borrow from it to make the shape timers and list timer. But I don't see how without multi-whatevering. Sorry, a bit frustrated.
Was This Post Helpful? 0
  • +
  • -

#8 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3589
  • View blog
  • Posts: 11,159
  • Joined: 05-May 12

Re: Functions to make input trigger actions on list and stack etc. etc.

Posted 07 July 2012 - 10:21 PM

Actually, that timer your teacher presented is in the classic style of timers. It is in the same company as the Windows GetTickCount() or the UNIX time() function. Even OpenGL library call glutGet(GLUT_ELAPSED_TIME) acts on the same principle. Programs written in the past have managed to work with that style of timer and they've done amazing things.

I think, though, that you are thinking in terms of of ticking time bomb timer that throws a notification when time is up.
Was This Post Helpful? 0
  • +
  • -

#9 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3589
  • View blog
  • Posts: 11,159
  • Joined: 05-May 12

Re: Functions to make input trigger actions on list and stack etc. etc.

Posted 07 July 2012 - 10:51 PM

I'm guessing, but I think that one of the thoughts weighing on the back of your mind is how to get the input from the user without blocking. If only the program doesn't block, then you can poll the timer/current time/tick count. If you have to wait for the user to press enter after every move, then a timer can have long expired by the time you process some input.

So, I think you have to make some key decisions:
What is your target platform(s)?
  • Windows?
  • Linux?
  • Mac?
  • Other?
  • All of the above?
  • Only one (or two) of the above?

What will your UI look like?
  • ASCII art
  • Windows graphics
  • OpenGL
  • Other


Answers to these will help you make a choice whether to use a platform independent library to do you UI and input, or if you'll a platform specific set of APIs. Some API or library choices may also give you access to the "live" timer with notifications that you seem to actually be thinking of.
Was This Post Helpful? 0
  • +
  • -

#10 jayburn00  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 118
  • Joined: 05-July 12

Re: Functions to make input trigger actions on list and stack etc. etc.

Posted 08 July 2012 - 11:02 AM

View PostSkydiver, on 07 July 2012 - 10:51 PM, said:

I'm guessing, but I think that one of the thoughts weighing on the back of your mind is how to get the input from the user without blocking. If only the program doesn't block, then you can poll the timer/current time/tick count. If you have to wait for the user to press enter after every move, then a timer can have long expired by the time you process some input.

So, I think you have to make some key decisions:
What is your target platform(s)?
  • Windows?
  • Linux?
  • Mac?
  • Other?
  • All of the above?
  • Only one (or two) of the above?

What will your UI look like?
  • ASCII art
  • Windows graphics
  • OpenGL
  • Other


Answers to these will help you make a choice whether to use a platform independent library to do you UI and input, or if you'll a platform specific set of APIs. Some API or library choices may also give you access to the "live" timer with notifications that you seem to actually be thinking of.

Target OS is windows, though it would be good to be able to do other OS's as well, but not necessary. As for the UI, it is text based as I said, just using the good old command prompt window.
Was This Post Helpful? 0
  • +
  • -

#11 jayburn00  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 118
  • Joined: 05-July 12

Re: Functions to make input trigger actions on list and stack etc. etc.

Posted 08 July 2012 - 01:11 PM

Also got an email from the teacher explaining things a bit more. I think the way this works is you use the pop/join function/operation to combine the shape on top of the stack and the shape from the list into one shape, and combining their scores. That shape created from joining those two shapes remains on top of the stack, unless another shape is pushed/saved on top of it. If another shape of the same type is popped/joined to the the shape resulting from those 2 previous shapes, its score is also combined. So, if all shapes are worth 2 points to begin with, when the first two shapes are joined, the shape now on top of the stack is worth 4 points. If another shape of the same type is joined/popped from the list, the score becomes 6 points. Thats how I understand it anyway.
Was This Post Helpful? 0
  • +
  • -

#12 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3589
  • View blog
  • Posts: 11,159
  • Joined: 05-May 12

Re: Functions to make input trigger actions on list and stack etc. etc.

Posted 08 July 2012 - 06:15 PM

If your target is only Windows Console. Take a look at _kbhit() and _getch() in the conio.h of VS2010. The former will tell you if there was a keypressed, and the _getch() lets you get that keypressed. You can also look directly at the Win32 Console APIs, but I think these two functions will be sufficient for your needs.

Why is _kbhit() important? Instead of being blocked by a cin.get() or getchar() call, you can now loop tightly and check your timer. In pseudo code:
lastTime = timer();
while (!quit)
{
    currentTime = timer();
    elapsedTime = currentTime - lastTime;

    currentShape.Time -= elapsedTime;
    if (shape.Time < 0)
    {
        // handle expired shape
    }

    if (_kbhit())
    {
        process_input(_getch());
    }

    lastTime = currentTime;
}


This post has been edited by Skydiver: 08 July 2012 - 06:15 PM

Was This Post Helpful? 0
  • +
  • -

#13 jayburn00  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 118
  • Joined: 05-July 12

Re: Functions to make input trigger actions on list and stack etc. etc.

Posted 09 July 2012 - 02:08 PM

View PostSkydiver, on 08 July 2012 - 06:15 PM, said:

If your target is only Windows Console. Take a look at _kbhit() and _getch() in the conio.h of VS2010. The former will tell you if there was a keypressed, and the _getch() lets you get that keypressed. You can also look directly at the Win32 Console APIs, but I think these two functions will be sufficient for your needs.

Why is _kbhit() important? Instead of being blocked by a cin.get() or getchar() call, you can now loop tightly and check your timer. In pseudo code:
lastTime = timer();
while (!quit)
{
    currentTime = timer();
    elapsedTime = currentTime - lastTime;

    currentShape.Time -= elapsedTime;
    if (shape.Time < 0)
    {
        // handle expired shape
    }

    if (_kbhit())
    {
        process_input(_getch());
    }

    lastTime = currentTime;
}



You say this is pseudocode. What would be the difference in C++? Where exactly would I put it in my code?
Was This Post Helpful? 0
  • +
  • -

#14 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3589
  • View blog
  • Posts: 11,159
  • Joined: 05-May 12

Re: Functions to make input trigger actions on list and stack etc. etc.

Posted 09 July 2012 - 02:28 PM

Lots of things: You'll have to declare the appropriate types for the variables. You'll need to figure out whether currentShape should be present at that level of the code (eg. the main loop) or some place else. you'll need to figure out if the mythical process_input() function also needs the current time or the elapsed time or not. There is some hand waving with regards to determining when quit becomes true.

The point of the pseudo code was that you could have the timer advancing, and you have the ability to watch the timer advance while still being able to get input from the user. This is a big change from the previous state you were in where you were stuck waiting for the user's input, and then needing to figure out what to do with the timer.

This post has been edited by Skydiver: 09 July 2012 - 02:30 PM

Was This Post Helpful? 0
  • +
  • -

#15 jayburn00  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 118
  • Joined: 05-July 12

Re: Functions to make input trigger actions on list and stack etc. etc.

Posted 09 July 2012 - 02:39 PM

View PostSkydiver, on 09 July 2012 - 02:28 PM, said:

Lots of things: You'll have to declare the appropriate types for the variables. You'll need to figure out whether currentShape should be present at that level of the code (eg. the main loop) or some place else. you'll need to figure out if the mythical process_input() function also needs the current time or the elapsed time or not. There is some hand waving with regards to determining when quit becomes true.

The point of the pseudo code was that you could have the timer advancing, and you have the ability to watch the timer advance while still being able to get input from the user. This is a big change from the previous state you were in where you were stuck waiting for the user's input, and then needing to figure out what to do with the timer.

I understand most of your post, but not the hand waving part. What do you mean?
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2