IT115: Introduction to Java Programming 1. IT115: Introduction to Java Programming. Tic Tac Toe Application. Trina VanderLouw

Similar documents
Question 1 [20 points]

Tic Tac Toe Game! Day 8

Due Date: Two Program Demonstrations (Testing and Debugging): End of Lab

Today in CS161. Lecture #12 Arrays. Learning about arrays. Examples. Graphical. Being able to store more than one item using a variable

RANDOM NUMBER GAME PROJECT

Lesson 10: Quiz #1 and Getting User Input (W03D2)

CS201 - Assignment 3, Part 2 Due: Wednesday March 5, at the beginning of class

CS1 Studio Project: Connect Four

Mid Term Exam 1. Programming I (CPCS 202) Instructor: M. G. Abbas Malik Date: Sunday November 3, 2013 Total Marks: 50 Obtained Marks:

while (/* array size less than 1*/){ System.out.print("Number of students is invalid. Enter" + "number of students: "); /* read array size again */

Introduction to Computer Science Unit 3. Programs

AP Computer Science Lists The Array type

Senet. Language Reference Manual. 26 th October Lilia Nikolova Maxim Sigalov Dhruvkumar Motwani Srihari Sridhar Richard Muñoz

Introduction to Computer Programming

D - Tic Tac Toe. Let's use our 9 sparkles to build a tic tac toe game! 2017 courses.techcamp.org.uk/ Page 1 of 9

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: if Single-Selection Statement CSC 209 JAVA I. week 3- Control Statements: Part I

More on Classes. The job of this method is to return a String representation of the object. Here is the tostring method from the Time class:

Programming with Java

Lab 1: Silver Dollar Game 1 CSCI 2101B Fall 2018

Global Gomoku Lab 4 in D0010E

Lab 4 Due April 18 th

Declaring and ini,alizing 2D arrays

BOREDGAMES Language for Board Games

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

Com S 227 Spring 2018 Assignment points Due Date: Thursday, September 27, 11:59 pm (midnight) "Late" deadline: Friday, September 28, 11:59 pm

Assignment 2.4: Loops

ECE15: Lab #4. Problem 1. University of California San Diego

CMPSCI 187 / Spring 2015 Hangman

General Certificate of Education Advanced Subsidiary Examination June 2010

CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING

Assignment Checklist. Prelab Activities. Lab Exercises. Labs Provided by Instructor. Postlab Activities. Section:

Question: Total Points: Score:

Object Oriented Programming. Java-Lecture 1

Learning objec-ves. Declaring and ini-alizing 2D arrays. Prin-ng 2D arrays. Using 2D arrays Decomposi-on of a solu-on into objects and methods

Midterm Examination (MTA)

CS 211: Existing Classes in the Java Library

COMP 110 Programming Exercise: Simulation of the Game of Craps

The Irving K. Barber School of Arts and Sciences COSC 111 Final Exam Winter Term II Instructor: Dr. Bowen Hui. Tuesday, April 19, 2016

CS100M November 30, 2000

CS159 Midterm #1 Review

Initial Coding Guidelines

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014

Exam 2. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 40 Obtained Marks:

CAT.woa/wa/assignments/eclipse

Chapter 6 Lab Classes and Objects

ios Tic Tac Toe Game John Robinson at Rowan University

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

Basic Problem solving Techniques Top Down stepwise refinement If & if else.. While.. Counter controlled and sentinel controlled repetition Usage of

Chapter 6 Lab Classes and Objects

Handout 4 Conditionals. Boolean Expressions.

Program #7: Let s Play Craps!

Controls Structure for Repetition

SFWR ENG/COMP SCI 2S03 Principles of Programming SOLUTIONS

Web-CAT submission URL: CAT.woa/wa/assignments/eclipse

Lecture 10: for, do, and switch

CPSC 217 Assignment 3

There are several files including the start of a unit test and the method stubs in MindNumber.java. Here is a preview of what you will do:

CSE 1223: Exam II Autumn 2016

LAB 5: SELECTION STATEMENTS

Introduction to Computer Science Unit 4B. Programs: Classes and Objects

CSC 108. Prof. Yue-Ling Wong. Lab 6: Tic-tac-toe Game

2.8. Decision Making: Equality and Relational Operators

Project 1 - Battleship Game

Haskell Refresher Informatics 2D

Example Program. public class ComputeArea {

Control Statements: Part 1

Lab 2: Booleans, Strings, Random Numbers, Recursion, Variables, Input function

Functionally Modular. Self-Review Questions

Tic-Tac-Toe. By the time you are done with this activity, you and your team should be able to:

Programming assignment A

Arrays. Eng. Mohammed Abdualal

Session 8.2. Finding Winners Using Arrays

Last Class. While loops Infinite loops Loop counters Iterations

Question: Total Points: Score:

Lab 2: Booleans, Strings, Random Numbers, Recursion, Variables, Input function

Loops. CSE 114, Computer Science 1 Stony Brook University

Lab Exercise 1. Objectives: Part 1. Introduction

Introduction to Java Applications

4. Java Project Design, Input Methods

CSIS-120 Final Exam Fall 2015 Name:

CS 142 Style Guide Grading and Details

CSE120 Wi18 Final Review

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

static String usersname; public static int numberofplayers; private static double velocity, time;

Exam 1. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 45 Obtained Marks:

New York University Introduction to Computer Science Exam Sample Problems 2013 Andrew I. Case. Instructions:

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous

Programming Project 1

Object Oriented Programming. Java-Lecture 6 - Arrays

Critters. Critter #2 Attack.ROAR Attack.POUNCE Attack.SCRATCH. Critter #1

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Chapter 6. Repetition Statements. Animated Version The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

STUDENT LESSON A12 Iterations

Practice Midterm 1. Problem Points Score TOTAL 50

Welcome1.java // Fig. 2.1: Welcome1.java // Text-printing program.

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Data & Variables It s elementary, my dear Riker. Sir.

HW4: Let s Play Poker

McGill University School of Computer Science COMP-202A Introduction to Computing 1

//If target was found, then //found == true and a[index] == target.

Transcription:

IT115: Introduction to Java Programming 1 IT115: Introduction to Java Programming Tic Tac Toe Application Trina VanderLouw Professor Derek Peterson Colorado Technical University Online October 28, 2011 Highlights: Java, Building Applications, Creating Javadocs, Importing Libraries Programs Used: NetBeans IDE, CTU Virtual Campus Instructor Feedback: Thanks for letting me show-off your code during the chat. You did a superb job on the code. It is nicely formatted, you do that well which makes it easy to follow. Instructor Recommendation: I had the pleasure of having Trina in my introduction to java programming course. She was an exemplary student and took control of her learning. I have taught this course for CTU Online for more than 3 years and she stands with a very short list of people who truly were successful. As a part-time adjunct professor who works full-time as an IT Director/Vice President managing and hiring programmers, given the opportunity to recommend and/or hire Trina for an IT position; I would not hesitate. She displayed in the 11 weeks I worked with her the aptitude and capability to be successful. Final Grade: A

IT115: Introduction to Java Programming 2 Tic Tac Toe Game Code and Libraries in NetBeans IDE -------------------- UML Diagrams --------------------

IT115: Introduction to Java Programming 3 ---------------------------- ACTIVITY DIAGRAMS ---------------------------- Players move inside of the play method activity repeats until win = true then the play is over

IT115: Introduction to Java Programming 4 Main Class File

IT115: Introduction to Java Programming 5 Java File for the Public Classes

IT115: Introduction to Java Programming 6 Java File for Tic Tac Toe Board

IT115: Introduction to Java Programming 7 /* * Trina VanderLouw * October 20, 2011 * IT115: Java Programming * Professor Derek Peterson import java.util.scanner; * This reusable class is for a Tic Tac Toe Game - It constructs a game board * with three columns and three rows and sets up a Player X and a Player O - * Each player takes turns and when one person wins it will display a message - * The counts for the winners are tallied and stats are displayed at the end * of the game - If there is a tie the program will allow one more game to be * played for a tiebreaker. * @author TrinaV public class TicTacToeGame // Creates new game board with 9 set values placed in the array private boardpiece[][] board = new boardpiece(), new boardpiece(), new boardpiece(), new boardpiece(), new boardpiece(), new boardpiece(), new boardpiece(), new boardpiece(), new boardpiece(); private int count = 0; // Counts the amount of turns - determines a draw private boolean win = false; // Sets win to false so a move can be made private char turn = 'X'; // Initializes turn to X so player X goes first private int xwon = 0; // Tallies how many games are won by Player X private int owon = 0; // Tallies how many games are won by Player O private int xlost = 0; // Tallies how many games are lost by Player X private int olost = 0; // Tallies how many games are lost by Player O * This public boolean allows the value to be passed to the test method * and determines whether or not the game will be restarted in the do_while * loop in the main method. public boolean again; // Returns true or false in the main method Scanner input = new Scanner(System.in); * This constructor is empty and allows for a new instance to be created public TicTacToeGame()

IT115: Introduction to Java Programming 8 * This method welcomes the players to the game public void displaywelcome() System.out.println("Welcome to Tic Tac Toe!"); System.out.print("Good Luck!!\n"); * This method checks to see if the game has been won and if not calls the * move method which initiates the next player's turn. public void play() // If the game has not been won, the next move will be initiated while (!win) // Calls the move method to start the next turn move(); // Ends play method * This method displays the current game board - Each place on the board * will have either an _X_, _O_, or. public void displayboard() // Runs a loop to display all the rows for (int i = 0; i < 3; i++) // Runs a loop to display all the columns for (int j = 0; j < 3; j++) // Prints out each space with the current value stored there System.out.print(board[i][j].piece); System.out.println(); // Ends displayboard method * This method tells the players whose turn it is and asks for their move - * the move entered will be checked using the checkmove method and if valid * will be entered onto the board - The board gets displayed and the program * checks for a winning move - If the game is not over the turn will switch * to the next player.

IT115: Introduction to Java Programming 9 public void move() int move = 0; // Stores the game board square the player selects String valid = " "; // Set to blank so the choice can be validated // Displays whose turn and prompts for selection System.out.print("\nPlayer " + turn + ", it's your turn!\n" + "Select a move (1-9): "); // Starts a loop for the selection and vaildation do // Stores the move so it can be passed to the checkmove method move = input.nextint(); // Sets valid to the return value in checkmove valid = checkmove(move); // If the player enters a number that is not between 1 and 9 they // will get an error prompting them to enter another number if (valid.equals("error:1")) System.out.print("Please enter a space between 1-9: "); // If the player chooses a space that is already taken they will // receive an error message prompting them to select a different one if (valid.equals("error:2")) System.out.print("Sorry, that space is not available.\n" + "Please enter another space: "); // Continues the validation loop until it returns OK while (!valid.equals("ok")); // Increments number of turns taken so game will stop after 9 turns count++; // Enters the turn into the proper place and marks the space as used board[(move - 1) / 3][(move - 1) % 3].piece = "_" + turn + "_ "; board[(move - 1) / 3][(move - 1) % 3].player = turn; board[(move - 1) / 3][(move - 1) % 3].used = true; // Calls the displayboard method to show the users the current board displayboard(); // Checks to be sure game is not over and then checks for a winning

IT115: Introduction to Java Programming 10 // move by calling the checkwin method if (count <= 9) // Checks to see if there are three in a row, column, or diagonal // and ends the game if there is a winning move checkwin(move); // Switches the players' turns so they alternate if (turn == 'X') turn = 'O'; else turn = 'X'; // Ends move method * This method will validate the entry by the player - If the number entered * is not between 1 and 9 it will return an Error 1 and if the space is * already taken it will return an Error 2, otherwise the number will be * validated so the move can be marked on the board. * @param move * @return public String checkmove(int move) // Sets validator to integers 1 through 9 or else returns Error 1 if (move < 1 move > 9) return "Error:1"; // Sets validator to check for empty spot or else returns Error 2 if (board[(move - 1) / 3][(move - 1) % 3].used) return "Error:2"; // Returns OK if value entered is validated return "OK"; // Ends checkmove * This method checks for a winning move - if there are three across, three * down, or three diagonal of the same character the current game will end * and a congratulations message will be displayed to the players - At the

IT115: Introduction to Java Programming 11 * end of the game the stats will be updated by players whether they won * or lost - If the game ends in a draw no stats will be incremented. * @param move public void checkwin(int move) // Starts loop to check for winning combination of moves in rows for (int i = 0; i < 3; i++) // Checks to see if each column in the row is used and if so if // each one has the same value stored if ((board[i][0].used && board[i][1].used && board[i][2].used) && (board[i][0].player == board[i][1].player) && (board[i][1].player == board[i][2].player)) System.out.printf("\nYou WIN!!\nCongrats, Player " +turn+ "!"); // Increments the winning and losing scores if (turn == 'X') xwon++; olost++; else owon++; xlost++; // Sets win to true so the game ends win = true; return; // Starts loop to check for winning combination of moves in columns for (int j = 0; j < 3; j++) // Checks to see if each row in the column is used and if so if // each one has the same value stored if ((board[0][j].used && board[1][j].used && board[2][j].used) && (board[0][j].player == board[1][j].player) && (board[1][j].player == board[2][j].player)) System.out.printf("\nYou WIN!!\nCongrats, Player " +turn+ "!"); // Increments the winning and losing scores if (turn == 'X') xwon++; olost++;

IT115: Introduction to Java Programming 12 else owon++; xlost++; // Sets win to true to the game ends win = true; return; // Checks for winning combination of moves in diagonal [0][0] to [2][2] if ((board[0][0].used && board[1][1].used && board[2][2].used) && (board[0][0].player == board[1][1].player) && (board[1][1].player == board[2][2].player)) System.out.printf("\nYou WIN!!\nCongrats, Player " + turn + "!"); // Increments the winning and losing scores if (turn == 'X') xwon++; olost++; if (turn == 'O') owon++; xlost++; // Sets win to true so the game ends win = true; return; // Checks for winning combination of moves in diagonal [2][0] to [0][2] if ((board[2][0].used && board[1][1].used && board[0][2].used) && (board[2][0].player == board[1][1].player) && (board[1][1].player == board[0][2].player)) System.out.printf("\nYou WIN!!\nCongrats, Player " + turn + "!"); // Increments winning and losing scores if (turn == 'X') xwon++; olost++;

IT115: Introduction to Java Programming 13 if (turn == 'O') owon++; xlost++; // Sets win to true so the game ends win = true; return; // Checks to see if the count is at the maximum number of moves and // then displays message that the game was a draw with no winner if (count == 9) System.out.print("\nDRAW\nSorry, there is no winner this time!"); // Sets win to true so the game ends win = true; return; * This method initializes all the attributes so the game can continue with * a new game board - The turn is not initialized to X as it is in the first * game so that the player who lost will get the chance to start first on * the new board. public void init() // Starts a loop to initialize each piece on the game board as empty // Without resetting these a new game would think the spaces were used for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) board[i][j] = new boardpiece(); // Sets win to false so game can start over by staring another move win = false; // Resets counter to 0 so the moves can increment again to 9 // Without resetting this the game would think it is a draw

IT115: Introduction to Java Programming 14 count = 0; * This method allows the players to decide if they would like to play a * new game board - It returns the attribute 'again' to the main method so * the loop can continue or end depending on the value stored. * @return public boolean again() // Prompts user to enter 1 for yes and 2 for no to restart new game System.out.print("\n\nWould you like to play again?\n" + "Enter 1 = yes, 2 = no: "); // Stores value of number entered int newgame = input.nextint(); // If user wants to play again the board will be initialized and the // value will return true to the main method if (newgame == 1) again = true; init(); return again; // If the player did not enter 1 the value will be set false and the // loop in the main method will end again = false; return again; * This method displays the results of the games played - It shows a total * for the number of games won and lost by each player - If there is a tie * it will give the players a chance to play one more game for a tiebreaker. public void stats() // Prints out the results of the players' stats System.out.printf("\nPLAYER X Won: %d Lost: %d", xwon, xlost); System.out.printf("\nPLAYER 0 Won: %d Lost: %d\n", owon, olost); // If X won a congratulations message will be printed if (xwon > owon) System.out.println("\nCongratulations, Player X!");

IT115: Introduction to Java Programming 15 // If O won a congratulations message will be printed if (xwon < owon) System.out.println("\nCongratulations, Player O!"); // If the games won were tied it will prompt for a tiebreaker if (xwon == owon) System.out.println("\nX and O Tied!\n" + "Would you like to play a tiebreaker?\n" + "Enter 1 = yes, 2 = no: "); int tiebreaker = input.nextint(); // If the players want one more game the board will be initialized // and the play method will start once to determine the winner if (tiebreaker == 1) init(); play(); // Ends stats method * This method displays a good-bye message to the user. public void displaygoodbye() // Calls the stats method to display stats of all games won and lost stats(); System.out.print("\n\nThanks for playing.\ngood-bye!\n"); // Ends displaygoodbye method

IT115: Introduction to Java Programming 16