Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

CS 200 - Introduction to Programming Assignment 1

Welcome to your first C++ programming homework assignment. Please read this handout very thoroughly before starting your assignment. You will be seeing a lot of new terminology along the way. The information in this handout will help you understand any new terms you might encounter. Also, please go through the submission details carefully, so that you dont lose points due to any inconsistencies in your assignment submission. Tasks labeled as "Hacker's Edition" are optional and are worth bonus points that may be used to make up for shortcomings in any other graded instrument in the course. You only need to submit one file called rollnumber_Pacman.cpp, where you should replace rollnumber with your actual roll number, e.g. 14100239_Pacman.cpp. All assignment submissions will be done on LMS. All forms of plagiarism, such as the following, will be dealt in the harshest of manner: o o o o o o o Typing code for a fellow student, Debugging code for a fellow student, Having a fellow student type or debug code for you, Sharing your code with others via any means, Acquiring a copy of another student's code without his/her knowledge, Deliberately copying off another student's code from his/her monitor, Deliberately letting another student copy off code from your monitor,

For this assignment, you will use a C++ library called NCURSES.

What is a library?
You have been introduced to functions in class. Also, if you have taken CS 100 at LUMS previously, you will remember functions from your MATLAB days. Most programming languages offer a small set of constructs for essential operations such as data manipulation and console input/output. Other useful features are available as functions. Several functions serving a related purpose are grouped together into a unit called a library. There are libraries, for example, to deal with audio input and output, 2D and 3D graphics, network programming, etc. Some libraries are part of the standard C/C++ compiler, whereas many others must be downloaded or purchased separately. Some reasons for not including these libraries as part of the standard compiler package are: Not everyone using C++ needs all these functionalities. It would make the distribution package unnecessarily large. It enables users to make their own libraries. There might be different libraries for the same purpose, but on different operating systems.

What is NCURSES?
Rest assured, it doesn't print out random curse words on the screen. NCURSES is a library that will let you play around with the cursor that you see on the face of your new best friend, the Linux shell. Up till

now, the cursor on the shell hasn't been in your control much. The input that you type in the shell is pretty much pre-determined by the location of the cursor (see figure 1), which moved according to certain rules. NCURSES provides you the ability to move the cursor around the shell screen arbitrarily and display characters on the desired location on the screen. Think about it: this opens up all sorts of possibilities! The shell screen becomes your own canvas, and you can now use standard characters as 'artistic' symbols and create crude graphics, right in your very first assignment!

The cursor. This is where the next inputted text will be printed. NCURSES will let you place this anywhere on the screen.

Figure 1: Linux shell and the concept of cursor

Task 1: Testing your setup


Execute the following steps very carefully. An explanation of everything you do will follow once you have it all up and running.
1.

Open your Linux shell, and use the nano text editor to open up a new file called rollnumber_Pacman.cpp. Useful hint: Instead of typing "nano Pacman.cpp", try typing "nano i
Pacman.cpp". This enables the auto-indenting feature within nano, so your code looks way cleaner! You can Google to find more of such options such as T4 (Tab indents four spaces), c etc.

2.

Type and save the following code into that file. #include <ncurses.h> int main() { initscr(); raw(); keypad(stdscr, TRUE); noecho(); printw("Hello Curses World!\n"); getch(); endwin(); return 0; }

3. Exit nano and go back to your Linux shell. 4. Use the following command to compile your first NCURSES program: g++ -o Pacman Pacman.cpp lncurses 5. Run the programming using the command: ./Pacman If you see a blank screen with "Hello Curses World!" written at the top, congratulations! You're all set to write and compile your own NCURSES programs. Explanation: Now, the promised explanation for everything we told you to do above. It's very important to understand what's going on, and what every line of code that you typed is doing. The #include <ncurses.h> line should be at the very top of every NCURSES program that you write. This tells the C++ compiler that your file is going to use functions that are defined in the ncurses.h file, which is somewhere you dont have to worry about. But trust us, its there. The initscr() function call initializes the screen and paves the way for using various other ncurses function calls. The Linux shell is line buffered, meaning that keyboard input is not given to your program until the enter key is pressed. In games, however, we often want to respond immediately to the keys

(such as the arrow keys) as they are typed. The call to the function raw(), indicates to the shell that we want to receive keyboard input immediately, without waiting for the enter key. The keypad() function call tells the ncurses library that we wish to handle keypad keys such as the arrow keys. Since the ncurses library allows us to create multiple windows, we must mention the specific window whose keypad input we wish to receive in our program. The first argument to keypad(), stdscr, does exactly that. In our program, we havent created any windows. In such cases, a window is created for us by the library, and it is called stdscr, which stands for standard screen. Recall that when you use cin statements to solicit user input, whatever you type is echoed on the screen. In games, we dont want this happening. The noecho () call instructs the ncurses library to disable echoing of user input on to the screen. The printw() line displays the string "Hello Curses World!" at the current cursor position. When your program starts running, this is the very top-left corner of the screen. The \n at the end of the string is, of course, the newline character. It moves the cursor to line below it. If this character was not at the end of your screen, subsequent calls to printw would display its argument in front of the "Hello Curses World!" string without starting a new line. The getch() function waits for the user to press a key on the keyboard. Until the user presses a key, this function does not terminate, and halts the program. This is why your program does not quit until you press a key. If this line were not there, you would probably not even see your output, since the program would terminate before you could see the output. Endwin(). This function must be called at the end of your NCURSES program, just before returning from the main function. THIS IS VERY IMPORTANT! Missing this will cause your shell to behave very weirdly, which could cause troubles, so please be careful. Do not miss out this line!

You might have noticed the peculiar -lncurses line at the end of our compilation command. The l switch tell g++ that it should link our program with the ncurses library. This effectively integrates our code with that of the ncurses library.

Task 2: Get comfortable with NCURSES


NCURSES has many convenient functions for you to use the shell as your canvas and draw anything you want. However, there are certain functions that you will probably need to use a lot, so we will go over them briefly here: int ch = getch(); This function waits for the user to enter a keystroke, and then returns an int value which represents the character the user entered. wtimeout(stdscr, 100); This function sets a limit on the amount of time the program will wait for a keystroke. If this function is called at the start of the program, all subsequent calls to getch() will wait for a maximum of 100 ms for a keystroke. If timeout occurs before the user presses any key, getch() will return an integer value which is symbolized as ERR. You can edit the second argument in this function to specify a different waiting time. A negative value means that getch() will be a blocking call, whereas a 0 means that getch() will return immediately if no keyboard input is waiting in the keyboard buffer. printw("Hello"); You already know what this does. mvprintw(2, 3, "Hello"); This is a variation of printw. The above function call means that the cursor is first moved to the 2nd row and the 3rd column, and then the string "Hello" is displayed there. This enables you to print whatever you want, wherever you want. getmaxyx(stdscr, r, c); Assuming that r and c are int variables previously declared, after the above function call, r will contain the number of rows on the screen, and c will contain the number of columns on the screen. Further reading: Weve listed just a few ncurses functions with a brief description. You should really play around with these, and more, on your shell. Some comprehensive tutorials, complete with code samples, are given here: http://tldp.org/HOWTO/NCURSES-Programming-HOWTO/index.html http://www.cs.ukzn.ac.za/~hughm/os/notes/ncurses.html For those looking for more extensive and precise documentation: http://pubs.opengroup.org/onlinepubs/7908799/xcurses/curses.h.html Also, get in the habit of Googling up things you dont understand. This is vital. Please try your hardest to look up concepts you dont fully grasp, because you are your own best teacher. If that fails, or if you need help with reading the documentation, please feel free to harass your TAs with your queries. They're getting paid to help you, after all

HINT: You will now be starting the game. To get a feel of what you are making check this link out to play Pacman in its full form: www.thepcmanwebsite.com/media/Pacman_flash/

Task 3: Setting up your game environment


In this task, your job is to set up the game environment which will include: Mr Pacman The food he eats!

Step 1: Draw Pacman using the mvprintw command in the middle of the screen. Here use the < character at first. Well be going into the animation of him later! It should look something like this:

Step2: Draw the food around the screen. Try placing them all over the screen and spread them around. Step3: The animation: Here is where things get really interesting. You will have to make a game loop. In this we will make the animation for Pacmans movement. For now assume that he starts off going towards the right. You will also have to work on Pacmans animation. Use the < and O characters alternatively in each iteration of the loop to give the effect that hes opening and closing his mouth. Here are some points to think about while coding this:

This is not MATLAB. Your programming training wheels have now come off. C++ variables must be declared before they can be used. So be careful to avoid compilation errors resulting from lack of declaration of variables. Learn to read compiler errors. TAs will not be debugging for you. The first major hint is the line number returned by the compiler in which the error occurred. You should immediately go to that line in your code and see what the problem is. Think very carefully about the variables you will need to maintain during the animation. Also give them easy, practical names that would make sense. As obvious as it may seem, it really helps the thought process (and may not seem like it but helps in debugging). Think very carefully about the conditions of the main animation loop, when it should start, and when it should break. Make a plan or write a step-wise approach on paper to help you break this problem (and others in the future) to easy bite-size chunks Every animation needs a time-step. You display one frame, pause for a short time period, and then display the next frame. How do you think you would implement the time-step in this case?

Once you have this basic animation running, go on to the next task!

Task 4: The Ravenous Maze Trolling Pacman


Using your basic animation loop, it is now time to get keyboard input from the user and move Pacman around. You need to implement the basic arrow keys control scheme for this game. Get comfortable with moving your Pacman around in different directions. However be careful. When Pacman changes direction, then you must change the character you use for him as well. For example use v as the character when Pacman is moving up. Treat the border of the page as boundaries in the real Pacman. The next step is to form a maze for the Pacman. Be creative! Make a fun filled maze with some twists and turns. Start off with a simple maze, perhaps a few parallel lines or a rectangle. Try making the maze on paper first, so that when creating the maze on the screen you have a good idea of what exactly you are trying to achieve. The rules of Pacman are simple. Pacman navigates his way through the maze and eats the food he comes across. When all the food is eaten, the level is cleared. When Pacman hits a wall, he just stares at it until you tell him to go in any free direction. Youll have to think in terms of collision detection so its best to try out with a simple maze at first and then get adventurous. The next part gets tricky, you have to create ghosts that appear after every little while , randomly on any part of the screen, and stay there for a about ten iterations of your animation and then disappear. While they are there on the screen, a collision with them means certain death for Pacman. You will have to make 3 of them. For simplicitys sake, make all 3 appear at the same time in different parts of the screen.

Task 5: The Ghost Hunting Pacman (Hackers Edition)


The more adventurous students may implement a better version of this game. In addition to the rule stated in Task 4, the following rules will also apply: The Ghosts move randomly around the maze. If they come into collision with Pacman, its game over.

In a special duration of time, Pacman can eat the Ghosts, which for now would disappear for the game. You can have special items of food, perhaps fruit that give the Pacman these gluttonous powers! The game should have an aesthetically pleasing color scheme, perhaps with an animated background as well. In addition to this, we would expect you to implement a much more intricate maze for this part of the assignment.

Good Luck!

You might also like