formel0api.Game.java Source code

Java tutorial

Introduction

Here is the source code for formel0api.Game.java

Source

/**
 * <copyright>
 *
 * Copyright (c) 2013 http://www.big.tuwien.ac.at All rights reserved. This
 * program and the accompanying materials are made available under the terms of
 * the Eclipse Public License v1.0 which accompanies this distribution, and is
 * available at http://www.eclipse.org/legal/epl-v10.html
 *
 * </copyright>
 */
package formel0api;

import at.ac.tuwien.big.we.highscore.Failure;
import at.ac.tuwien.big.we.highscore.PublishHighScoreEndpoint;
import at.ac.tuwien.big.we.highscore.PublishHighScoreService;
import at.ac.tuwien.big.we.highscore.data.HighScoreRequestType;
import at.ac.tuwien.dbai.education.ssd.ss13.uebung.tournament.GameType.Players;
import at.ac.tuwien.dbai.education.ssd.ss13.uebung.tournament.ObjectFactory;
import at.ac.tuwien.dbai.education.ssd.ss13.uebung.tournament.TournamentType;
import java.io.File;
import java.io.InputStream;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.namespace.QName;
import javax.xml.transform.stream.StreamSource;
import javax.xml.ws.Service;
import tuwien.big.formel0.twitter.ITwitterClient;
import tuwien.big.formel0.twitter.TwitterStatusMessage;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;

/**
 * Class representing a Formel 0 game
 */
public class Game {

    private static final int LAST_FIELD = 6;
    /**
     * Player playing the game
     */
    private Player player;
    /**
     * Computer opponent
     */
    private Player computer;
    /**
     * Dice that is used in this game
     */
    private Dice dice = new Dice();
    /**
     * Specifies if the game is over (
     * <code>true</code>) or not (
     * <code>false</code)
     */
    private boolean gameOver = false;
    /**
     * Starting time of the game
     */
    private long gamestarttime = System.currentTimeMillis();
    /**
     * Time already spent in this game
     */
    private long spenttime;
    private final tuwien.big.formel0.entities.Player playerData;

    private String message = "";

    public String getError() {
        return message;
    }

    /**
     * Constructs a new {@link Game}
     */
    public Game(Player player, Player computer, tuwien.big.formel0.entities.Player playerData) {
        this.player = player;
        this.computer = computer;
        this.playerData = playerData;
    }

    /**
     * Specifies whether this game is over or not
     *
     * @return <code>true</code> if this game is over, <code>false</code>
     * otherwise
     */
    public boolean isGameOver() {
        return this.gameOver;
    }

    /**
     * Returns the time already spent on this game
     *
     * @return the time already spent on this game
     */
    public long getSpentTime() {
        if (!gameOver) {
            spenttime = System.currentTimeMillis() - this.gamestarttime;
        }
        return spenttime;
    }

    /**
     * Rolls the dice for the player and updates the position of the player's
     * car according to the score
     *
     * @param player Player who rolls the dice
     * @return score
     */
    public int rollthedice(Player player) {
        if (gameOver) {
            throw new IllegalArgumentException("Game is over. Rolling the dice is not allowed.");
        }

        int score = dice.roll();

        int position = player.getPosition();

        /**
         * Move on field
         */
        int newposition = Math.min(position + score, LAST_FIELD);
        player.setPosition(newposition);

        /**
         * Test if deadly field was reached
         */
        if (newposition == 2 || newposition == 5) {
            newposition = 0;
            player.setPosition(newposition);
        }

        /**
         * Test if the figure of the player reached the end and the game is over
         */
        if (newposition == LAST_FIELD) { // player reached end
            gameOver = true;
            sendHighScoreToServer();
        }

        return score;
    }

    private void sendHighScoreToServer() {
        try {
            String now = this.javaDate2XmlDate(new Date()).toString();

            StringBuffer xmlStr = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"
                    + "<highScoreRequestType \n" + "   xmlns=\"http://big.tuwien.ac.at/we/highscore/data\" \n"
                    + "   xmlns:ssd=\"http://www.dbai.tuwien.ac.at/education/ssd/SS13/uebung/Tournament\">\n" + "\n"
                    + "   <UserKey>34EphAp2C4ebaswu</UserKey>\n" + "   <ssd:tournament start-date=\"" + now
                    + "\" end-date=\"" + now + "\" registration-deadline=\"" + now + "\">\n"
                    + "      <ssd:players>\n" + "         <ssd:player username=\"" + this.getLeaderData().getName()
                    + "\">\n" + "            <ssd:date-of-birth>"
                    + this.getFormattedDate(this.getLeaderData().getBirthday()) + "</ssd:date-of-birth>\n"
                    + "            <ssd:gender>" + this.getLeaderData().getSex() + "</ssd:gender>\n"
                    + "         </ssd:player>\n" + "      </ssd:players>\n" + "      <ssd:rounds>\n"
                    + "         <ssd:round number=\"0\">\n" + "            <ssd:game date=\"" + now
                    + "\" status=\"finished\" duration=\"" + this.getSpentTime() + "\" winner=\""
                    + this.getLeaderData().getName() + "\">\n" + "               <ssd:players>\n"
                    + "                  <ssd:player ref=\"" + this.getLeaderData().getName() + "\"/>\n"
                    + "               </ssd:players>\n" + "            </ssd:game>\n" + "         </ssd:round>\n"
                    + "      </ssd:rounds>\n" + "   </ssd:tournament>\n" + "</highScoreRequestType>");

            JAXBContext jaxbContext = JAXBContext.newInstance(HighScoreRequestType.class);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            HighScoreRequestType request = (HighScoreRequestType) jaxbUnmarshaller
                    .unmarshal(new StreamSource(new StringReader(xmlStr.toString())));

            PublishHighScoreService service = new PublishHighScoreService();
            PublishHighScoreEndpoint endpoint = service.getPublishHighScorePort();
            String uuid = endpoint.publishHighScore(request);

            Logger.getLogger(Game.class.getName()).log(Level.INFO, uuid);

            TwitterStatusMessage tmsg = new TwitterStatusMessage(this.getLeader().getName(), uuid, new Date());

            (new ITwitterClient() {
                @Override
                public void publishUuid(TwitterStatusMessage message) throws Exception {
                    ConfigurationBuilder cb = new ConfigurationBuilder();
                    cb.setDebugEnabled(true).setOAuthConsumerKey("GZ6tiy1XyB9W0P4xEJudQ")
                            .setOAuthConsumerSecret("gaJDlW0vf7en46JwHAOkZsTHvtAiZ3QUd2mD1x26J9w")
                            .setOAuthAccessToken("1366513208-MutXEbBMAVOwrbFmZtj1r4Ih2vcoHGHE2207002")
                            .setOAuthAccessTokenSecret("RMPWOePlus3xtURWRVnv1TgrjTyK7Zk33evp4KKyA");
                    TwitterFactory tf = new TwitterFactory(cb.build());
                    Twitter twitter = tf.getInstance();
                    twitter.updateStatus(message.toString());
                }
            }).publishUuid(tmsg);

            message = "UUID " + uuid + " wurde auf Twitter verffentlicht";

        } catch (JAXBException e) {
            Logger.getLogger(Game.class.getName()).log(Level.SEVERE, null, e);
        } catch (Failure e) {
            Logger.getLogger(Game.class.getName()).log(Level.SEVERE, e.getFaultInfo().getDetail());
        } catch (Exception ex) {
            Logger.getLogger(Game.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private XMLGregorianCalendar javaDate2XmlDate(Date d) {
        try {
            GregorianCalendar c = new GregorianCalendar();
            c.setTime(d);
            return DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
        } catch (DatatypeConfigurationException ex) {
            Logger.getLogger(Game.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    /**
     * Returns the currently leading player
     *
     * @return the currently leading player
     */
    public Player getLeader() {
        if (player.getPosition() > computer.getPosition()) {
            return player;
        } else if (computer.getPosition() > player.getPosition()) {
            return computer;
        } else {
            return null;
        }
    }

    public tuwien.big.formel0.entities.Player getLeaderData() {
        if (player.getPosition() > computer.getPosition()) {
            return playerData;
        } else if (computer.getPosition() > player.getPosition()) {
            tuwien.big.formel0.entities.Player temp = new tuwien.big.formel0.entities.Player();
            DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
            temp.setBirthday(dateFormat.format(new Date()));
            temp.setName("Computer");
            temp.setSex("FEMALE");
            return temp;
        } else {
            return null;
        }
    }

    public String getFormattedDate(String date) {
        DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
        DateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        String result = "1985-01-01";
        try {
            result = dateFormat1.format(dateFormat.parse(date));
        } catch (Exception ex) {

        }
        return result;
    }

    /**
     * Returns the player
     *
     * @return player
     */
    public Player getPlayer() {
        return player;
    }

    /**
     * Returns the computer
     *
     * @return computer
     */
    public Player getComputer() {
        return computer;
    }
}