Assignment #2: Connect Four

Due: Monday, December 9 at 4pm.

Design Due: in class on or before Tuesday, November 19th

No late work will be accepted for a grade.

Motivation | Goals | Overview | Rules | Requirements | At Home | Hints | Announcements | Hand-in | Solution

 


Motivation: Why do this?

It is getting close to the end of the semester and since you and your friends are so busy with classes, you have not had the opportunity to hang out together. Therefore, you have set yourself to the task of finding a bonding activity. Inspiration has just struck: a game! A challenge requiring thought and at least two people. The game to rule all games: a connect four tournament has been scheduled at the end of the semester. To ensure that your team has the best chance of winning, you have the inspiration to create a practice connect four game so that you and your friends will be the champions at the tournament.  As an aspiring programmer, you've decided to implement a Java program so that everyone on your hall can practice with each other. Your program allows the user to choose the size of the board and pit their talents against another player.  This task is described in more detail below. In this project you will design, code, and test your connect four database program.

Required Reading

Read Chapters 8, 9, 12 (sections 12.1 and 12.2), the Java IO web page, and the Exceptions web page.

Back to Top

 

Goals: What we hope to learn

The goals of this assignment are:

Back to Top

 

Game Overview: What's Going to Be Involved?

In this assignment, you will be writing a program called ConnectFour that will let users play games of connect four. As games are played, the win/loss/draw records of all the players will be updated. Furthermore, you will be saving games to files so that you can postpone them and continue bonding with your friends later.

The medium for these games will be the black console window, where you will be prining out a character representation of a connect four game. Here is an example of a game in progress:
| x - x o o - o | | o - o x o - x | | o - x o x x o | | o - o x o o x | | x - o o x x x | | x - o x x o x | ----------------- 1 2 3 4 5 6 7
In other words, we you not be using any javabook packae classes. Instead, you'll use many of the provided JAVA standard utility and input/output classes.

Back to Top

 

Game Rules: What Is Connect Four?

  • Connect Four is a two player game.
  • The board game is a two-dimensional grid of points where playing chips may be placed.
  • Each player has a different color (or symbol for) their chips.
  • The board game starts out empty.
  • Players take turns placing their chips on the board, one at a time.
  • A playing chip is placed on the board by choosing a column into which to "drop" the chip. The chip starts in the highest row and then then "falls" down to the lowest point available in that column.
  • A column may become full and then no more playing chips may be dropped into that column.
  • A player wins the game as soon as four of his playing chips occupy consecutive horizontal, vertical, or diagonal points on the game board.
  • If all of the points on the board fill up without any player winning, then the game ends in a draw.

End Game Examples:


| - - - - - - - |
| - - - - - - - |
| - - - o x x - |
| - - o x x o - |
| - X X X X o - |
| - o o x o o - |
-----------------
  1 2 3 4 5 6 7  

| - - - - - - - |
| - - - - X - - |
| - - - o X x - |
| - - o x X o - |
| - - x x X o - |
| - o o x o o - |
-----------------
  1 2 3 4 5 6 7  

| - - - - - - - |
| - - - - o - - |
| - - - o X x - |
| - - o X x o - |
| - - X x x o - |
| - X o x o o - |
-----------------
  1 2 3 4 5 6 7  

| x o x o x o x |
| o x o x o x o |
| x o x o x o x |
| x o x o x o x |
| o x o x o x o |
| x o x o x o x |
-----------------
  1 2 3 4 5 6 7  
horizontal
win
vertical
win
diagonal
win
draw


Really Pretty Online Example: Here is an online game with six rows and seven columns. The opponent is quite tough but beatable.
Play Connect Four Online

Back to Top


Requirements: Here's What will Get You Full Credit

Game Basics

  • Each game will have a name.
  • The game will be played on the input/output (black window) console. This means that the game board will be redrawn (printed to the console) as a bunch of characters.
  • The users will also use this console window for input.
  • WE WILL NOT BE USING ANY JAVABOOK CLASSES IN THIS ASSIGNMNET.
  • Each Player will have a unique name.
  • For each game, each player will choose a unique character to represent their chips on the console board.
  • The character for an empty space must be the dash, '-', so players may not use this as their own.
  • Your program, once running, will be using several files as a means of persistent (long-term) storage.


The Players Statistics File
  • As games of connect four are played, you will keep a record of all of the players. This will include the player's name, their number of wins, their number of losses, and their number of draws (in that order) up until that point.
  • The file name should be "statistics.txt".
  • Each line of the file should contain all the information for one single player.
  • Separate the player's information with the pipe character, '|', and also end each line with the pipe character.
    Here is an example of stored information from a hypothetical a statistics file:
       statistics.txt   
    --------------------
    |                  |
    |   Ellen|13|6|2|  |
    |   Marie|2|21|6|  |
    |   Thomas|0|1|0|  |
    |                  |
    --------------------
    
    This file shows that three players have played games so far. The first player's name is "Ellen," and Ellen so far has won 13 games, lost 6 games, and drew 2 games. Marie has won 2 games, lost 21 games, and drew 6 times. Thomas has won no games, lost one game, and drew no games.
Saved Games Files
  • Every time a new peice is added during a game, the state of that game (what the board looks like) should be saved in a file, so that you can later retreive that game's information, and continue playing.
  • The name of the text file saving that game's state should have the same name, and have a cn4 extension (end with the string ".cn4". For example, if a new game is started called "myFirstGame", then the file that always saves the state of that game should be a file called "myFirstGame.cn4".
  • In addition to where peices are, you should also save the names of the players, their own board chip characters, whose turn it is, and the dimensions of the board.
  • Becasue the file names depend upon the game's name, it will be possible to overrite a game file by starting a new game with the same name.
    Here is an example of what could work:
       myFirstGame.cnc4   
    ----------------------
    |                    |
    |   Ellen|*|turn|    |
    |   Marie|&|         |
    |   6|7|             |
    |   -|-|-|-|-|-|-|   |
    |   -|-|-|-|-|-|-|   |
    |   -|-|-|&|-|-|-|   |
    |   -|-|-|*|*|-|-|   |
    |   -|-|-|&|*|&|-|   |
    |   -|*|-|&|&|*|-|   |
    |                    |
    ----------------------
    
    This file coild be interpretes as, Ellen and Marie are playing a game that was called myFirstGame. Ellen's chip character is * and Marie's chip character is &. It will be Ellen's turn as soon as the game is resumed. The game board has 6 rows and 7 columns, and the current chips are as shown.
  • There is no required format for this file. However, it is recommended that you "chunk" your information in some logical or practical way, and always end each information "chunk" with the pipe character, '|'.


Program Start
  • The program will start by verifying that the players statistics file exists. If it does not, then you must create a new, blank statistics file.
  • Then the program will print out a main menu of options to the console window, and get the user's selection. In effect, you are making a console version of a ListBox.


The Main Menu
  • The main menu will have the following options:
    Display Player Statistics
    Start New Game
    Continue Saved Game
    Exit


  • If Display Player Statistics is selected, then all of the informatino in the statistics file should be printed, in some clear and logical format, to the console window.
  • After the statistics are shown, you should reprint the main menu.


  • If Start New Game is slected, the you should prompt the users for the name of the new game, the names of each of the players, their chip characters, and the number of rows and coloumns of the game board.
  • For each input, you should make sure that the values entered are valid, and immediately repeat a prompt whenever an invalid value is entered.
  • Player names must be unique from each other, must not contain any numbers in it, and must not contain the pipe character '|'.
  • Player chip characters, for each individual game, must be unique, and must be neither the empty space character '-', nor the pipe character '|'.
  • The number of rows and columns of the game board must each be greater than or equal to 4 and less than or equal to 99.
  • A new game file should be created with the appropriate name and with all the appropriate values.
  • Normal game play should then ensue.


  • If Continue Saved Game is selected, the users should be prompted to enter in the name of the game to be continued.
  • If the game file does not exist, you should print a message to the console saying that the file was not found, and then reprint the main menu.
  • If the game file was found, you should read the game file, grabbing all data in it, and normal game play should unsue.


  • If Exit is selected, you should execute the method System.exit(0);.


Normal Game Play
  • The first step in normal game play is to print out to the console the current game board. While there is no required format for this beyond displaying the chips and empty spaces, "prettier" outputs are always nicer. For example, it is sometimes hard to determine which column a chip is in if the columns aren't numbered on the screen. An example of output is shown below for six rows and seven columns:
    | - - - - - - - |
    | - - - - - - - |
    | - - - - - - - |
    | - - - - - - - |
    | - - - - - - - |
    | - - - - - - - |
    -----------------
      1 2 3 4 5 6 7  
    
  • After displaying the game board, you should check if the game is over.
  • If the game is over, you should first print the result of the game, and then reprint the main menu.
  • If the game is not yet over, then print out the name of the player whose turn it is to place a chip.
  • Prompt the user for a selection. There should be a choice for every column and also a choice to quit the current game.
  • If the selection made is to quit the current game, you should reprint the main menu.
  • If the selection is a column choice, then proceed to place that chip, and update the game file with the current game state.
  • If the slection made is invalid for any reason at all, then print out a message telling why the choice is invalid. Then reprint the game board, the current player whose turn it is, and the options.


Style


Provided Classes
  • You are not allowed to use any classes from the javabook package.
  • You are not allowed to use any classes from the galapagos package.
  • You are not allowed to use the java.util.Vector class, nor any of its subclasses (desccendents).
  • You must use the java.lang.System class (for console i/o).
  • You must use a java.io.BufferedReader object.
  • You must use java.io.FileReader objects.
  • You must use java.io.File objects.
  • You must use java.io.PrintWriter objects.
  • You must use java.io.FileWriter objects.
  • You must use java.util.StringTokenizer objects.
  • You must use FileFormatVerifier objects.

Back to Top


Requirements:

Here's what you need to do to get full credit.
Analysis | Design | Game Design | Coding | Testing | Back to Top

Analysis

The analysis phase is an essential first step in software development. Read and understand this document before proceeding.

Back to Requirements

Design

Once you understand the problem you can start designing a solution. During the design phase you determine the classes needed to be used and/or created. For this assignment, follow the requirements in Assignment 2 Design.

Use the following Java API classes to complete this program. Click on links below for Java API documentation. Useful classes in the Java I/O package (import java.io.*):

Useful classes in the Java util package: (import java.util.*):

Useful class in your project stationery (no import needed):

Useful objects (see the Java API documentation for System):

  • System.out
  • System.in

DO NOT USE ANY OF THE JAVABOOK2 CLASSES!
One of the goals of this assignment is for you to learn how to do console-based input/output.

DO NOT USE THE VECTOR CLASS!
One of the goals of this assignment is for you to learn how to do basic array operations.

To help you with your design, answer these questions, but your design must answer more than just these questions:

  1. How can I obtain information from the user (i.e. what menus are needed)?
  2. What classes will I need (i.e. what kind of objects do I need to represent)?
  3. What data values do the objects need (i.e. what is the state of the objects)?
  4. What methods will each class need (i.e. what is the behavior of the objects)?
  5. How will the objects interact with each other?
  6. How can I implement the functionality described in this document?

Back to Requirements

Game Design

Add Book | Find Book | Process Book | Show All Books | Load From File | Save To File | Quit

The GamePlayer class that you write must contain the main method that starts your program. Your program must use only one instance of the BufferedReader class for user input, i.e. console input (more may be used for file input). While the program is running, the book review database is stored in memory by using instances of your instantiable classes to store the data. This game can be saved to a file so that it may be used at a later time. The game must have two players and follow the rules of the connect four game. Books consist of the following information:

Rules:


1. Choose who plays first.
2. Each player in his turn drops one of his checkers down ANY of the columns in the top of the grid which are not full. (note that we will represent checkers on the screen with characters, see below)
3. The play alternates until one of the players gets FOUR checkers of his type in a row.  The four in a row can be horizontal, vertical, or diagonal.(See examples).
4. The first player to get four in a row wins.

Examples of the three general situations where the user can win:
 

·  horizontal example:
 

·  verticle example:
 

·  diagonal example:

Each player (2) enters their name and chooses their own checker  type to represent them in the game. For  example, one player could choose the character @ and the other could choose $.

MAIN MENU

One of the goals of this assignment is for you to implement the user interface exactly as specified. To do this, your program must match the prompts in the same order as shown. Do not add any prompts other than those shown. The one exception is error messages, which aren't shown below, but are required to be added. See the Testing section for more information on errors.

The main menu displays the operations that are available for users. When the program is started it begins by displaying the main menu. The main menu has the following options in this order:

Show the main menu here

This menu is redisplayed after the game has been finished or the user selects to quit the game early and return to the main menu. The following links take you to the detailed description of the main operations.

Add Book | Find Book | Process Book | Show All Books | Load From File | Save To File | Quit

Add Player prompts the user for information about a book and adds it to the database. Your program prompts for the following book information in this order (user's input is bold):

 
Book's Title: The Lord of the Rings
Book's Author: J.R.R. Tolkien
Book's Copyright Year: 1954

Once all the information has been entered, redisplay the information in the following format (user's input is bold):

Title: The Lord of the Rings
Author: J.R.R. Tolkien
Year: 1954
Do you want to add this book (Yes or No)? y

and request that the user confirm adding the information to the current database. If answered with any input that begins with a 'y' or 'Y', the book is added to the database, but do not write this information to a file at this time. For any other input or after the add is done, return to the main menu.

If the same book already exists in the database, do not add it to the database. Instead, combine the lists of reviews (you do not have to worry about duplicate reviews). Books are considered the same if they have the same title (ignoring case), author (ignoring case), and year. If only the book's title matches, then add the book to the database.

The database begins with capacity for 8 books. If the database is filled to capacity, you must double the size of the current database before adding a new book. For example, if the user tries to add a 9th book, your program must double the current database's capacity to 16 books. This doubling happens whenever a new book would overfill the current database (16, 32, 64, etc.). None of the current database information should be lost. There is no maximum number of books that the database can hold. Once a book has been added to the database, it cannot be removed.

Back to Database Design

Find Book displays a sub-menu with the following options in this order:

***** FIND A BOOK *****

1.     Find by Title
2.     Find by Year
3.     Find by Average Rating
4.     Return to Main Menu
Enter your selection:

This sub-menu is redisplayed after the selected lookup operation has been completed. Option 4 returns to the main menu of the program. Lookup options 1 - 3 do the following (user's input is bold):

  1. Find by Title prompts the user for the book's title:


Please enter a title: The Lord of the Rings

  1. Find by Year prompts the user for the year the copyright year of the book:


Please enter a year: 1954

  1. Find by Average Rating prompts the user for a book rating (a double):


Please enter an average rating between 0.0 and 5.0
(all ratings within +/- 0.5 will be displayed): 3.5

If a book's overall rating is within a 0.5 point range above and below the user's input it is considered a match.Then the entire book database is searched, each match is displayed in a numbered list with its average rating and the user is prompted for the book of interest:

1     The Lord of the Rings     4.0
2     The Book of Ruth     4.5
Enter a book to process (0 to return to Find Menu): 1

If 0 is entered, the Find sub-menu is redisplayed. If a book's number is entered then the Process Book sub-menu is displayed.

Process Book

The Process Book menu is displayed when working with a specific book. The Add Review option is used to add a review for the current book. View Book Details displays a numbered list of the reviews. The rating will be displayed as a number of stars (represented by the '*' character) followed by the comment. If there are no reviews for the current book, a message stating that the book has not been reviewed is displayed. The Process Book menu is redisplayed after completing choice 1 or choice 2. Choice 3 returns the user to the find menu. Examples are given below (user's input is bold):

***** PROCESS A BOOK *****

1.     Add Review
2.     View Book Details
3.     Return to Find Menu
Please enter a selection: 2
 

Title:          The Lord of the Rings
Author:         J.R.R. Tolkien
Copyright:      1954
Average Rating: 0.0

The Lord of the Rings has not yet been reviewed

***** PROCESS A BOOK *****

1.     Add Review
2.     View Book Details
3.     Return to Find Menu
Please enter a selection: 1

Entering a review for The Lord of the Rings:
Number of stars (1-5): 4
Comment (40 characters max): Great book!

The review is added to the book and then the Process Book sub-menu is redisplayed.

***** PROCESS A BOOK *****

1.     Add Review
2.     View Book Details
3.     Return to Find Menu
Please enter a selection: 2

Title:          The Lord of the Rings
Author:         J.R.R. Tolkien
Copyright:      1954
Average Rating: 4.0

REVIEWS for The Lord of the Rings:
1.) **** Great book!

The reviews are displayed in a numbered list and the Process Book sub-menu is redisplayed. The list of reviews does not need to reflect the order in which the reviews were entered. In other words, the review list need not be sorted.

Back to Database Design


Show All Books prints a listing of all the books currently in the database. The information for each book must be printed in the following format. The following information is displayed: title, author, year, and average rating:

Book #1
Title:          The Lord of the Rings
Author:         J.R.R. Tolkien
Copyright:      1954
Average Rating: 4.0

Book #2
Title:          The Book of Ruth
Author:         Jane Hamilton
Copyright:      1990
Average Rating: 4.5

After all the books are shown, the main menu is redisplayed.

Back to Database Design

Load From File prompts the user for the full path name of a file containing a book database (user's input is bold):

Enter PATH for database file: U:\private\cs302\myBooks.txt

Using the static method verify(String fullFileName) from the FileFormatVerifier class, the program first checks if this file's format is valid. If it is, then the program loads each book's information from this file into memory using the instantiable classes that you've created. If "Load From File" is done when a database is already opened, combine the databases by adding the new books into the  database currently in memory. Remember to merge the reviews for books that are the same as those currently in the database as described in Add Book. If the file is not in a valid format, your program must display this error message below. After this error, the main menu is redisplayed.

LOAD ERROR! Database file is incorrectly formatted.

Back to Database Design


Save To File prompts the user for the full path name of a file in which to store the database that is currently in memory (user's input is bold):

Enter PATH for database file: U:\private\cs302\myBooks.txt

If that file already exists, confirm with the user before overwriting the existing file (user's input is bold):

File exists. OK to overwrite [y/n]? y

If answered with any input that begins with a 'y' or 'Y', the file is overwritten. For any other input or after the save is done, return to the main menu. The file is used to store the book information and should contain the information in this format: title|author|year|and each review - rating followed by comment. Note each item is followed by a pipe (i.e. |), while each review has a delimiting colon (i.e. :) between the rating and the comment.

Breakfast of Champions|Kurt Vonnegut Jr.|1973|5:Great Book!|3:I've read better

Add a toString method in each instantiable class that you create for this assignment. Use it to generate the lines of files saved by your program.

Back to Database Design


Quit ends the program. If changes have been made since the last save of the database, it prompts the user to save the current database:

Changes were made to the database. Do you want to save [y/n]? y

If answered with any input that begins with a 'y' or 'Y', save the database as shown in Save To File. Otherwise end the program without saving.

Back to Database Design

Coding

Use the stationery file Assignment3 from cs302. Remember to save this as Assignment3 in your U:\private\cs302\ folder. Refer to Lesson 2 Step 2: How to create a new project if you need help creating a project.

To use an incremental coding approach when creating your instantiable classes, you can begin by coding and testing each method one at a time, starting with a constructor. Use your main method in the BookMain class to send messages to test these methods as they are coded. When a main method is used in this manner it is called a driver program. Once the instantiable class is completed, replace the test messages in main with the desired main program.

As you are coding, don't forget to follow the commenting and style requirements.

Back to Requirements

Testing

Once the program is coded you are not done. You still need to determine that your program works correctly and robustly. A correct program is one where each operation adheres exactly to the specifications laid out in the assignment description. A robust program is one that doesn't crash when unexpected or erroneous situations occur such as when the user enters invalid input. Error detection and resolution is an important aspect of this assignment. There are many places where the user's input can cause an error and your program must give clear error messages and must not crash or lose information from the database. Unless otherwise specified, after an error message is displayed, the prompt that appeared before the invalid input was entered is redisplayed.

For numeric input, make sure that numbers are entered (i.e. catch NumberFormatExceptions), and that they are reasonable (e.g. you cannot have a negative number for copyright year). If there is an invalid input, display the error message below before redisplaying the prompt for input.

Invalid Input.  Try again.

For character input, ensure that no titles, authors, comments, etc. contain '|' (i.e. pipe) characters. They may contain other characters, including ':' (i.e. colon) characters. If they contain any pipes, remove the pipes from the input value before adding them to the database. An empty string is considered invalid input.Display an error message and re-prompt the user to enter. It is an error if the user enters more characters than a specified limit (e.g. for a review's comment).

Several other common error situations that your program needs to handle include:

·  an empty database

·  an invalid menu choice

·  no matches being found

This list is not exhaustive. You need to ensure that your program behaves well for both expected and unexpected situations.

To receive full credit,  your code must compile and run correctly. It should not cause any exceptions that are not caught. Your program must display the menus with the options in the order specified and it must not ask the user for any additional information. You also must follow these commenting and style requirements.

Also, be sure to test your program using the second target in the stationery called RunTest. Click here for instructions and sample files for using the testing program.

Back to Requirements


At Home

What to do to work at home.

  • If this is your first time working at home, see the working at home page.
  • Download the Assignment3.zip file to your CS302 folder.
  • Unzip this file in your CS302 folder. You should see a folder named Assignment3. If you are using an older version of WinZip, you must install version 7 from DoIt's Electronic shelf.
  • Start CodeWarrior. Choose File|Open. Navigate to your CS302/Assignment3 folder and open the BookMain project file.
  • You're ready to work at home.

Warning: If you are having difficulty with the installation, then you should do your work in the CS computer labs. Problems with installation are not an acceptable excuse for not completing your work by the due date.

Back to Top


Hints:

Some tips to get you started.

·  START EARLY!

·  Read Chapter 8 for information about processing Strings and characters.

·  Read Chapter 9 for information about using arrays.

·  Read the Java IO web page for information about Input/Output (I/O).

·  See ConsoleIO.java for an example of console input and output.

·  See FileIO.java for an example of file input and output.

·  One by one, do basic database operations without user input to get your instantiable classes working. Use the main method as a driver program. After console input is covered, add the main menu. Add file operations after Java file I/O is covered. Finally add exception handling.

·  Test for error situations on each operation before starting the next operation.

·  You will need to create new classes.  See Step 5:  How to add a source file to an existing project of the Lesson 2 tutorial if you need help adding new source files.

Back to Top


Announcements:

Includes: Additions, Revisions, and FAQs (Frequently Asked Questions).
Please check here frequently and reload the page.

  • 5/3/2002 A discrepancy between test8.txt and log_test8.txt has been fixed. You should download new copies of these files to test your program.
  • 5/1/2002 The problem with the sample database and sequence files has been fixed. You should download new copies of these files to test your program.
  • 4/30/2002 There is a feedback.txt file in the stationery, but it was not added to the project. You don't need to add it to the project, but make sure to complete this file and submit it with your assignment.
  • 4/26/2002 Please see the update to the Testing section. There are now instructions on using the testing program included in the project stationery.
  • 4/16/2002 Please note the update to the Save To File section. Specifically, the use of colons to delimit ratings and comments for a review.



Back to Top


Hand-in Requirements:

What you must hand in for this assignment.

Use the Handin program to hand in the files listed below.  See Step 7: How to hand-in your  work of the Lesson 2 tutorial for instructions on how to use the Handin program.

  • BookMain.java (see commenting and style requirements)
  • *.java other java source files you create
  • feedback.txt

These files must be handed in anytime prior to the due date. Note: You may hand in your files before the deadline as many times as you wish. We suggest that you use your hand-in directory to keep your most recent working copy as you develop your solution.

Back to Top


Solution

No solution will be provided for this assignment.

Back to Top


© 2002
arman@cs.wisc.edu
blbowers@cs.wisc.edu
seabold@cs.wisc.edu
thien@cs.wisc.edu
votruba@cs.wisc.edu

modified from an assignment originally written by Jim Skrentny © 2001
skrentny@cs.wisc.edu