Search in sources :

Example 1 with PlayerScore

use of com.nolanlawson.keepscore.db.PlayerScore in project KeepScore by nolanlawson.

the class GameActivity method createNewGame.

private void createNewGame() {
    String[] playerNames = getIntent().getStringArrayExtra(EXTRA_PLAYER_NAMES);
    String[] playerColors = getIntent().getStringArrayExtra(EXTRA_PLAYER_COLORS);
    game = new Game();
    playerScores = new ArrayList<PlayerScore>();
    game.setDateStarted(System.currentTimeMillis());
    game.setPlayerScores(playerScores);
    for (int i = 0; i < playerNames.length; i++) {
        PlayerScore playerScore = new PlayerScore();
        playerScore.setName(playerNames[i]);
        playerScore.setPlayerColor(PlayerColor.deserialize(playerColors[i]));
        playerScore.setPlayerNumber(i);
        playerScore.setHistory(new ArrayList<Delta>());
        playerScore.setScore(PreferenceHelper.getIntPreference(R.string.CONSTANT_pref_initial_score, R.string.CONSTANT_pref_initial_score_default, GameActivity.this));
        playerScores.add(playerScore);
    }
    log.d("created new game: %s", game);
    log.d("created new playerScores: %s", playerScores);
}
Also used : Game(com.nolanlawson.keepscore.db.Game) Delta(com.nolanlawson.keepscore.db.Delta) PlayerScore(com.nolanlawson.keepscore.db.PlayerScore)

Example 2 with PlayerScore

use of com.nolanlawson.keepscore.db.PlayerScore in project KeepScore by nolanlawson.

the class GameActivity method updateHighlightedPlayer.

private void updateHighlightedPlayer() {
    // highlight the most recently changed player.  This helps with round-based games
    // (where it's important to know that each player's round has been tallied)
    // or games where the scoring has to happen in a particular order (e.g. Cribbage)
    long maxLastUpdate = 0;
    int maxLastUpdateIdx = -1;
    for (int i = 0; i < playerScores.size(); i++) {
        PlayerScore playerScore = playerScores.get(i);
        log.d("playerScore lastUpdate is %s", playerScore.getLastUpdate());
        if (playerScore.getLastUpdate() > maxLastUpdate) {
            maxLastUpdate = playerScore.getLastUpdate();
            maxLastUpdateIdx = i;
        }
    }
    log.d("updating highlighted player score to idx %s", maxLastUpdateIdx);
    // if none of the player scores are above 0, then this is a game from an older version
    // of KeepScore where we didn't track the lastUpdate, so we don't highlight anything
    boolean disableTagIcon = PreferenceHelper.getBooleanPreference(R.string.CONSTANT_pref_disable_highlight_tag, R.string.CONSTANT_pref_disable_highlight_tag_default, this);
    for (int i = 0; i < playerViews.size(); i++) {
        PlayerView playerView = playerViews.get(i);
        boolean highlighted = (!disableTagIcon && (i == maxLastUpdateIdx));
        // highlight or un-highlight by showing or hiding the bullet
        ImageView tagImageView = playerView.getTagImageView();
        tagImageView.setVisibility(highlighted ? View.VISIBLE : View.INVISIBLE);
    }
}
Also used : PlayerView(com.nolanlawson.keepscore.widget.PlayerView) ImageView(android.widget.ImageView) PlayerScore(com.nolanlawson.keepscore.db.PlayerScore)

Example 3 with PlayerScore

use of com.nolanlawson.keepscore.db.PlayerScore in project KeepScore by nolanlawson.

the class HistoryRoundChartFragment method createByChartLayout.

private void createByChartLayout(Activity activity) {
    List<LineChartLine> data = new ArrayList<LineChartLine>();
    for (PlayerScore playerScore : game.getPlayerScores()) {
        List<Integer> dataPoints = new ArrayList<Integer>();
        // have to include the starting score as well
        long runningTally = playerScore.getScore() - CollectionUtil.sum(CollectionUtil.transform(playerScore.getHistory(), Delta.GET_VALUE));
        dataPoints.add((int) runningTally);
        for (Delta delta : playerScore.getHistory()) {
            runningTally += delta.getValue();
            dataPoints.add((int) runningTally);
        }
        LineChartLine line = new LineChartLine();
        line.setDataPoints(dataPoints);
        line.setLabel(playerScore.toDisplayName(activity).toString());
        data.add(line);
    }
    byRoundLineChartView.setLineColors(createLineColors(game, activity));
    byRoundLineChartView.loadData(data);
}
Also used : Delta(com.nolanlawson.keepscore.db.Delta) ArrayList(java.util.ArrayList) LineChartLine(com.nolanlawson.keepscore.widget.chart.LineChartLine) PlayerScore(com.nolanlawson.keepscore.db.PlayerScore)

Example 4 with PlayerScore

use of com.nolanlawson.keepscore.db.PlayerScore in project KeepScore by nolanlawson.

the class HistoryTimelineFragment method smoothData.

private SparseArray<SparseArray<Long>> smoothData(Game game) {
    long roundedStartTimeInMs = Math.round(Math.floor(game.getDateStarted() * 1.0 / TIMELINE_ROUNDING_IN_MS)) * TIMELINE_ROUNDING_IN_MS;
    // first, plot all players' deltas with their timestamps on the same timeline (x axis), rounded to
    // the nearest ten seconds
    SparseArray<SparseArray<Long>> timeline = new SparseArray<SparseArray<Long>>();
    for (int i = 0; i < game.getPlayerScores().size(); i++) {
        PlayerScore playerScore = game.getPlayerScores().get(i);
        // have to include the starting score as well
        long startingScore = playerScore.getScore() - CollectionUtil.sum(CollectionUtil.transform(playerScore.getHistory(), Delta.GET_VALUE));
        timeline.put(0, SparseArrays.create(i, startingScore));
        long runningTally = startingScore;
        for (Delta delta : playerScore.getHistory()) {
            runningTally += delta.getValue();
            long timeSinceStartInMs = delta.getTimestamp() - roundedStartTimeInMs;
            int roundedTimeSinceStartInSecs = (int) TimeUnit.MILLISECONDS.toSeconds(Math.round(Math.floor(timeSinceStartInMs * 1.0 / TIMELINE_ROUNDING_IN_MS)) * TIMELINE_ROUNDING_IN_MS);
            if (roundedTimeSinceStartInSecs == 0) {
                // just in case someone was actually fast enough to log the first score in <5 seconds, bump
                // it up to the first mark instead
                roundedTimeSinceStartInSecs = (int) TimeUnit.MILLISECONDS.toSeconds(TIMELINE_ROUNDING_IN_MS);
            }
            log.d("roundedStartTimeInMs: %s, timeSinceStartInMs: %s, roundedTimeSinceStartInSecs: %s", roundedStartTimeInMs, timeSinceStartInMs, roundedTimeSinceStartInSecs);
            SparseArray<Long> existingScoresAtThisTime = timeline.get(roundedTimeSinceStartInSecs);
            if (existingScoresAtThisTime == null) {
                timeline.put(roundedTimeSinceStartInSecs, SparseArrays.create(i, runningTally));
            } else {
                // If the same player updated his score twice within the same rounded span,
                // then just add the two values together
                existingScoresAtThisTime.put(i, runningTally);
            }
        }
    }
    return timeline;
}
Also used : SparseArray(android.util.SparseArray) Delta(com.nolanlawson.keepscore.db.Delta) PlayerScore(com.nolanlawson.keepscore.db.PlayerScore)

Example 5 with PlayerScore

use of com.nolanlawson.keepscore.db.PlayerScore in project KeepScore by nolanlawson.

the class SdcardHelper method saveSpreadsheet.

/**
 * Write  CSV file with games on the X axis and players (and basic game data) on the Y axis.
 *
 * @param filename
 * @param games
 * @return
 */
public static void saveSpreadsheet(String filename, List<Game> games, final Context context) {
    // get all the unique player names so we can put them on the X axis
    SortedSet<String> playerNames = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
    // special value for players whose names weren't specified
    for (Game game : games) {
        for (PlayerScore playerScore : game.getPlayerScores()) {
            playerNames.add(playerScore.toDisplayName(context).toString());
        }
    }
    // sort by start date descending
    List<Game> sortedGames = new ArrayList<Game>(games);
    Collections.sort(sortedGames, new Comparator<Game>() {

        @Override
        public int compare(Game lhs, Game rhs) {
            return Long.valueOf(rhs.getDateStarted()).compareTo(lhs.getDateStarted());
        }
    });
    File file = new File(getDirectory(Location.Spreadsheets), filename);
    BufferedWriter writer = null;
    try {
        writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
        // write the column names
        List<String> columnNames = new ArrayList<String>(Arrays.asList(context.getResources().getStringArray(R.array.share_spreadsheet_column_names)));
        columnNames.addAll(playerNames);
        writer.write(CSVUtil.convertToLine(columnNames));
        // write each game as a line in the CSV
        for (Game game : sortedGames) {
            List<String> entries = new ArrayList<String>();
            // date started
            entries.add(CSV_DATE_FORMAT.format(new Date(game.getDateStarted())));
            // date saved
            entries.add(CSV_DATE_FORMAT.format(new Date(game.getDateSaved())));
            // play time, using duration format HH:MM:SS
            long duration = (game.getDateSaved() - game.getDateStarted()) / 1000;
            entries.add(String.format("%02d:%02d:%02d", duration / 3600, (duration % 3600) / 60, duration % 60));
            // num players
            entries.add(Integer.toString(game.getPlayerScores().size()));
            // num rounds
            entries.add(Integer.toString(CollectionUtil.max(game.getPlayerScores(), Functions.PLAYER_SCORE_TO_HISTORY_SIZE)));
            // game name
            entries.add(game.getName());
            Function<PlayerScore, String> playerScoreToName = new Function<PlayerScore, String>() {

                @Override
                public String apply(PlayerScore obj) {
                    return obj.toDisplayName(context).toString();
                }
            };
            // player(s) with max
            entries.add(TextUtils.join(", ", CollectionUtil.transform(CollectionUtil.maxWithTies(game.getPlayerScores(), Functions.PLAYER_SCORE_TO_SCORE), playerScoreToName)));
            // player(s) with min
            entries.add(TextUtils.join(", ", CollectionUtil.transform(CollectionUtil.minWithTies(game.getPlayerScores(), Functions.PLAYER_SCORE_TO_SCORE), playerScoreToName)));
            // rest of columns are just all the player names, so add blank for irrelevant players
            // or the score for the actual players
            Map<String, Long> playerScoreLookup = new HashMap<String, Long>();
            for (PlayerScore playerScore : game.getPlayerScores()) {
                playerScoreLookup.put(playerScore.toDisplayName(context).toString(), playerScore.getScore());
            }
            for (String playerName : playerNames) {
                Long score = playerScoreLookup.get(playerName);
                entries.add(score != null ? Long.toString(score) : null);
            }
            writer.write(CSVUtil.convertToLine(entries));
        }
    } catch (IOException e) {
        log.e(e, "unexpected error");
        throw new RuntimeException(e);
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                log.e(e, "unexpected error");
                throw new RuntimeException(e);
            }
        }
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Date(java.util.Date) BufferedWriter(java.io.BufferedWriter) Function(com.nolanlawson.keepscore.util.CollectionUtil.Function) Game(com.nolanlawson.keepscore.db.Game) TreeSet(java.util.TreeSet) FileOutputStream(java.io.FileOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) File(java.io.File) PlayerScore(com.nolanlawson.keepscore.db.PlayerScore)

Aggregations

PlayerScore (com.nolanlawson.keepscore.db.PlayerScore)19 Delta (com.nolanlawson.keepscore.db.Delta)5 Game (com.nolanlawson.keepscore.db.Game)5 ArrayList (java.util.ArrayList)5 View (android.view.View)3 TextView (android.widget.TextView)3 HistoryItem (com.nolanlawson.keepscore.data.HistoryItem)3 IOException (java.io.IOException)3 SparseArray (android.util.SparseArray)2 ImageView (android.widget.ImageView)2 TableRow (android.widget.TableRow)2 PlayerView (com.nolanlawson.keepscore.widget.PlayerView)2 LineChartLine (com.nolanlawson.keepscore.widget.chart.LineChartLine)2 XmlPullParserException (org.xmlpull.v1.XmlPullParserException)2 Intent (android.content.Intent)1 LayoutInflater (android.view.LayoutInflater)1 OnClickListener (android.view.View.OnClickListener)1 ImageButton (android.widget.ImageButton)1 EditablePlayerAdapter (com.nolanlawson.keepscore.data.EditablePlayerAdapter)1 RecordedChange (com.nolanlawson.keepscore.data.RecordedChange)1