Hangman Console Game in Java and Microsoft .net

This game is a console game application based on hangman, a popular game worldwide.
There is a text file with a list of movies in it, one per line. When the game begins, the user is shown a movie title with the letters obscured by asterisks or stars.

The user is asked to guess a letter, not any non-alphabetic character. If the letter does not occur in the movie title, the player will be alerted that the guess is wrong. Also, the player will lose a chance out of a maximum of 5 chances. If all chances are gone and the movie title is still not guessed, the game is lost.

If all letters are guessed within 5 chances, the game is won. The player is then asked if he wants to continue playing the game. If yes, the game goes to another round. If not, the game exits.

The roles and functions are divided into 2 classes:

  1. GetMovie: This will fetch a random movie for playing one round of the game.
  2. GamePlay: Handles the playing of the game.

The code listings for these classes are given below. The game has two versions: Java and C#

Java Version

Get Movie Class

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.Hangman;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

/**
 *
 * 
 */
public class GetMovie {
    
    static ArrayList movies = new ArrayList();
    
    static String movie;
    
    static String path;
    
    GetMovie(String pathToFile)
    {
        path = pathToFile;
    }
    
    public static String getRandMovie()
    {
        String randWord = "";
        try{
        
            InputStream istream = new FileInputStream(path); 

            InputStreamReader isr = new InputStreamReader(istream);

            BufferedReader br = new BufferedReader(isr);
            
            String movie;
            
            while((movie = br.readLine()) != null)
            {
                movies.add(movie);
            }
            
            int size = movies.size();
            
            int idx = (new java.util.Random()).nextInt(size);
            
            randWord = movies.get(idx);
        
        }
        catch(FileNotFoundException f)
        {
            System.out.println(f.getMessage());
            
            System.exit(0);
        }
        catch(IOException io)
        {
            System.out.println(io.getMessage());
            
            System.exit(0);
        }
        
        return randWord;
    }
    
}

 

GamePlay Class

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.Hangman;

import java.util.Scanner;

/**
 *
 * 
 */
public class GamePlay {
    
    static char[] movieChars;
    static char[] guessChars;
    static int chances = 5;
    
    static void renderMovie(String movie)
    {
        movieChars = movie.toCharArray();
        
        guessChars = new char[movieChars.length];
        
        for(int i = 0; i< movieChars.length; i++)
        {
            if(Character.isLetter(movieChars[i]))
            {
                System.out.print("* ");
            }
            else
            {
                System.out.print(movieChars[i] + " ");
                
                guessChars[i] = movieChars[i];
                
            }
        }
        
        System.out.println();
    }
    
    private static boolean playChar(char ch)
    {
        int matchCount = 0;
        
        for(int i = 0; i < movieChars.length; i++)
        {
            if(Character.toLowerCase(movieChars[i]) == Character.toLowerCase(ch))
            {
                matchCount++;
                
                guessChars[i] = movieChars[i];
            }
        }
        
        if(matchCount == 0)
        {
            chances--;
                
            System.out.println("WRONG Guess! You have "+chances+" chances left!");
        }
        
        /**/
        
        for(int i = 0; i< guessChars.length; i++)
        {
            if(guessChars[i] == '\0')
            {
                System.out.print("* ");
            }
            else
            {
                System.out.print(guessChars[i]+ " ");
            }
        }
        
        System.out.println();
        
        
        String movie = new String(movieChars);
        
        String guessed = new String(guessChars);
        
        return movie.equals(guessed);
        
    }
    
    public static void main(String[] args)
    {
        GetMovie gm = new GetMovie("movies.txt");
        
        char choice = '\0';
        
        System.out.println("/***************WELCOME TO JAVA HANGMAN**************/");
        
        do{
        
            chances = 5;
            
            String movie = GetMovie.getRandMovie();

            renderMovie(movie);

            System.out.print("Enter a letter: ");

            Scanner sc = new Scanner(System.in);

            char gchar = sc.next().charAt(0);

            while(!playChar(gchar))
            {
                if(chances == 0)
                {
                    break;
                }

                System.out.print("Enter a letter: ");

                sc = new Scanner(System.in);

                gchar = sc.next().charAt(0);
            }

            if(chances == 0)
            {
                System.out.println("You LOSE! The movie was: \n"+movie);
            }
            else
            {
                System.out.println("You WIN!");
            }
            
            System.out.print("\nPlay again (y/n)?: ");

            sc = new Scanner(System.in);

            choice = sc.next().charAt(0);
        
        }
        while(choice == 'y' || choice == 'Y');
        
        System.out.println("EXITING...");
        System.exit(0);
    }
    
}

 

Copy, compile, run and ENJOY!

C# Version

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleHangman
{
    class GetMovie
    {
        private static List lines = new List();

        static string movie;

        static string path;

        public GetMovie(string pathToFile)
        {
            path = pathToFile;
        }

        internal static string getRandMovie()
        {
            System.IO.StreamReader file =
            new System.IO.StreamReader(@path);

            string line;

            while ((line = file.ReadLine()) != null)
            {
                lines.Add(line);
            }

            int count = lines.Count;

            Random r = new Random();

            int index = r.Next(count);

            string line1 = lines[index];

            file.Close();

            return line1; //working
        }
    }

    class GamePlay
    {
        static char[] movieChars;
        static char[] guessChars;
        static int chances = 5;

        static void renderMovie(String movie)
        {
            movieChars = movie.ToCharArray();

            guessChars = new char[movieChars.Length];

            for (int i = 0; i < movieChars.Length; i++)
            {
                if (Char.IsLetter(movieChars[i]))
                {
                    Console.Write("* ");
                }
                else
                {
                    Console.Write(movieChars[i] + " ");

                    guessChars[i] = movieChars[i];

                }
            }

            Console.WriteLine();
        }

        private static bool playChar(char ch)
        {
            int matchCount = 0;

            for (int i = 0; i < movieChars.Length; i++)
            {
                if (Char.ToLower(movieChars[i]) == Char.ToLower(ch))
                {
                    matchCount++;

                    guessChars[i] = movieChars[i];
                }
            }

            if (matchCount == 0)
            {
                chances--;

                Console.WriteLine("WRONG Guess! You have " + chances + " chances left!");
            }

            /**/

            for (int i = 0; i < guessChars.Length; i++)
            {
                if (guessChars[i] == '\0')
                {
                    Console.Write("* ");
                }
                else
                {
                    Console.Write(guessChars[i] + " ");
                }
            }

            Console.WriteLine();


            string movie = new string(movieChars);

            string guessed = new string(guessChars);

            return (movie == guessed);

        }

        public static void Main(string[] args)
        {
            GetMovie gm = new GetMovie("..\\..\\movies.txt");

            char choice = '\0';

            Console.WriteLine("/***************WELCOME TO C# HANGMAN**************/");

            do
            {

                chances = 5;

                String movie = GetMovie.getRandMovie();

                renderMovie(movie);

                Console.Write("Enter a letter: ");

                char gchar = Convert.ToChar(Console.ReadLine());

                while (!playChar(gchar))
                {
                    if (chances == 0)
                    {
                        break;
                    }

                    Console.Write("Enter a letter: ");

                    gchar = Convert.ToChar(Console.ReadLine());
                }

                if (chances == 0)
                {
                    Console.WriteLine("You LOSE! The movie was: \n" + movie);
                }
                else
                {
                    Console.WriteLine("You WIN!");
                }

                Console.Write("\nPlay again (y/n)?: ");

                choice = Convert.ToChar(Console.ReadLine());

            }
            while (choice == 'y' || choice == 'Y');

            Console.WriteLine("Press a key to exit...");
            Console.ReadKey();
        }
    }
}

 

See the video below. COPY, COMPILE, RUN and ENJOY!

PHP Web Services: What they are, what they do and how to make one.

A “Web Service” is a bunch of code that resides on a server in an intranet or the internet. It performs some function and returns some data required by the client application that calls it. e.g. A foreign exchange web service might return the rates at which euros are converted to US dollars. A weather web service will return local temperature during any day. These web services can then be used in client applications like an e-commerce site that shows product prices in euros or dollars depending on the country the buyer is in, etc.

One common use of web services is in smartphone apps as a backend. A smartphone does not typically query a site’s database directly since it is not good to store database credentials locally on it. So the app calls a web service residing on a server. This web service fetches data from a web application and returns the data found to the smartphone app. e.g. An mobile e-commerce store allows users to search products by keywords. This app will call a web service which acts like a function that will accept the search keyword as a parameter. The web service returns a list of products to the calling app either as JSON or XML. The calling app will parse the results and display a list of products with names and images to the buyer.

But how is this achieved from the coding standpoint ? How does one create a PHP web service? There are many ways but I shall discuss about SOAP-based web services and illustrate with an example containing both the web service and the calling code in PHP. I will be using the NUSOAP library in my example. This will be an parameterized hello world web service. The client will call the web service and pass a name as a parameter to it. The result will be a
“Hello” greeting to the name given.

We need to do two things, (1) Setup the server side and (2) Setup the client side, from which we will call our web service.

DISCLAIMER: It is assumed that the reader knows basics of PHP development and can work on web servers or locally setup development servers.

Setting Up The Server Side

  1. Check SOAP is enabled on the server: Your server phpinfo() should look like this.If your phpinfo() does not look like the screenshot above, you need to locate your php.ini file and uncomment the semi-colon in the lines containing the soap DLL file (php_soap.dll in Windows). Save the modified php.ini and restart Apache Server. Then check your phpinfo() again.
  2. Create a new project folder on server.
  3. Install the PHP NUSOAP library: Download it from here.
  4. Extract the archive and keep the lib folder in your project folder.
  5. Call lib/nusoap.php in your PHP file where you will be working.
    <?php require('lib/nusoap.php'); //make sure that the nusoap.php file is found at this path relative to your php source file ?>
  6. Create a SOAP server object.
    <?php $soapServer = new soap_server(); //create the soap server object ?>
  7. Configure WSDL
    <?php $soapServer-&gt;configureWSDL("HelloWorldWSDL", "http://www.helloworldsite.com"); //configure the WSDL ?>
  8. Register a method with your SOAP server.
    <?php $soapServer-&gt;register('helloWorldWebSvc', array('name'=&gt;'xsd:string'),array('return'=&gt;"xsd:string"), "http://www.helloworldsite.com", "http://www.helloworldsite.com#helloWorldWebSvc", 'rpc', 'encoded', 'Hello World App!'); //register the method with the server ?>
  9. Make sure you call the service method of the SOAP server.
    <?php /*$soapServer-&gt;service($HTTP_RAW_POST_DATA); //Fault:SOAP-ENV:Client error in msg parsing: xml was empty, didn't parse! */ @$soapServer-&gt;service(file_get_contents("php://input")); //FIXED ?>
  10. Putting It All Together
    <?php 
    
    require("lib/nusoap.php"); 
    
    $soapServer = new soap_server(); //create the soap server object 
    
    $soapServer->configureWSDL("HelloWorldWSDL", "http://www.helloworldsite.com"); //configure the WSDL 
    
    $soapServer->register('helloWorldWebSvc', array('name'=&amp;gt;'xsd:string'),array('return'=&amp;gt;"xsd:string"), "http://www.helloworldsite.com", "http://www.helloworldsite.com#helloWorldWebSvc", 'rpc', 'encoded', 'Hello World App!'); //register the method with the server 
    
    function helloWorldWebSvc($name) //our function with business logic. Also called the server-side method. 
    { return "Hello $name!"; } 
    
    $HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA)?$HTTP_RAW_POST_DATA:''; 
    /*$soapServer->service($HTTP_RAW_POST_DATA); //Fault:SOAP-ENV:Client error in msg parsing: xml was empty, didn't parse! */
    
    @$soapServer->service(file_get_contents("php://input")); //FIXED 
    
    exit; ?>

     

Important Note

It is important to note that there are outdated code snippets out there using $soapServer->service($HTTP_RAW_POST_DATA);

This wont work with NUSOAP in PHP 7. It will give the error:

Fault:SOAP-ENV:Client error in msg parsing: xml was empty, didn’t parse!

Fix it by using the following:

@$soapServer->service(file_get_contents(“php://input”));

Setting Up the Client Side

  1. Check SOAP is enabled on the server: This step is identical to its counterpart in the server-side above.
  2. Create a new project folder on server: This step is identical to its counterpart in the server-side above.
  3. Install the PHP NUSOAP library: This step is identical to its counterpart in the server-side above.
  4. Call lib/nusoap.php in your PHP file where you will be working: This step is identical to its counterpart in the server-side above.
  5. Create a SOAP client object.
    <?php $client = new nusoap_client("http://localhost/HelloSvc/hello_world_web_svc.php?wsdl"); ?>
  6. Call the server-side method.
    <?php $response = $client-&gt;call("helloWorldWebSvc", array("Some User")); //calling the registered method of the web service from client. ?>
  7. Putting It All Together
    <?php 
    
    require("lib/nusoap.php"); 
    
    $client = new nusoap_client("http://localhost/HelloSvc/hello_world_web_svc.php?wsdl"); 
    
    $response = $client->call("helloWorldWebSvc", array("Some User")); //calling the registered method of the web service from client 
    
    if($client->fault) { 
      
      echo "Fault:".$client->faultcode." ".$client->faultstring; 
      
    } else { 
    
      print_r($response); 
    
    } 
      
    exit; 
      
    ?>

 

 

Note: In Android and iOS apps, no PHP client is used generally. Instead coding is done in Java or Objective-C, etc that uses the HTTP Client API of the respective programming languages.

 

The End Result

If all goes well you will see a screen like the one below when you invoke the PHP Web Service client in your browser.

Note: This example is compliant with PHP 7.