Ranking Players and Declaring a Winner

I’ve written about comparators once before but only just realized that the usefulness of that post hinges on the availability of the site it links to. Not wanting to rely on a third party site and the owner’s ability to pay hosting fees, here’s my quick blurb on how comparators work in Java.

But first, why do I need a comparator in the first place? Simply put, to declare a winner at the end of a round of Board Rogue. When a player reaches the board’s exit, the game is over. Scores are tallied, players are ranked, and the player with the highest score wins.

So you know how to sort numbers. You probably know how to sort alphabetically. There are functions for that sort of stuff built into most every programming language. But how do you take something like a PLAYER and sort them? You use a custom comparator, and the Collections class.

So you’ve got a player.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Player {
 
	private int score;
	private String name;
 
	public Player(String name) {
		this.name = name;
	}
 
	public int getScore() {
		return score;
	}
 
	public void setScore(int score) {
		this.score = score;
	}
}

And the game itself has a list of Players.

List<Player> playerList = new ArrayList<Player>();

And through the course of the game, each player accumulates a varied amount of treasure and items. Each piece of loot has a value associated with it, and the player with the highest loot value wins.

You could just loop through all of the players, look for the highest score, and declare a winner. But what’s the fun in that? You can’t easily tell who’s in second, third, or last place. But you can if you sort them! So create a comparator class that we’ll use to compare scores.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class PlayerScoreComparator implements Comparator<Player> {
 
	public int compare(Player p1, Player p2) {
 
		int p1score = p1.getScore();
		int p2score = p2.getScore();
 
		if (p1score > p2score)
			return -1;
		else if (p1score < p2score)
			return 1;
		else
			return 0;
	}
 
}

And now, to sort the playerList, simply apply the comparator to the Collection.sort function.

Collections.sort(playerList, new PlayerScoreComparator());

Finally, putting it all together you get the following.

Code.

1
2
3
4
5
6
7
8
9
for (Player player : playerList) {
	System.out.println ("Unsorted " + player.getName() + " has " + player.getScore() + " points");
}
 
Collections.sort(playerList, new PlayerScoreComparator());
 
for (Player player : playerList) {
	System.out.println ("Sorted " + player.getName() + " has " + player.getScore() + " points");
}

Output.

Unsorted Player One has 116 points
Unsorted Player Two has 616 points
Unsorted Player Three has 129 points
Sorted Player Two has 616 points
Sorted Player Three has 129 points
Sorted Player One has 116 points

New Game: Board Rogue

I’ve started on my next game. At the moment it’s called Board Rogue, though that’s subject to change. I said the same thing about Squishy Bugs. Squishy Bugs was supposed to be the code-name for the project, like Helicopter Ninja and Space Fight before it. But Squishy Bugs stuck, and who knows if Board Rogue is going to get another name by the time it ships. The name is really growing on me.

So I’m feeling a little inspired by this article on open board game design. It basically boils down to don’t be afraid to openly share your game’s development because other people are too busy working on their own killer game and ideas area cheap. At least that’s what I got out of it. So without further ado, here’s a little glimpse into what Board Rogue is going to be about.

First, a couple definitions.

Board game
 A board game is a game that involves counters
 or pieces moved or placed on a pre-marked
 surface or "board", according to a set of rules.
Roguelike
 The roguelike is a sub-genre of role-playing
 video games, characterized by level
 randomization and permanent death.

So what is Board Rogue?

A board game, played on a single Android tablet, played by and passed between 1 to 6 players. Players take turns rolling dice to traverse the randomly generated dungeon in search of the big treasure at the end of the board.

There are currently only 4 types of “squares” that make up the board. Each square is a type of room. Either empty, monster, trap, or treasure.

Empty rooms are just that. Generally safe rooms that don’t help or hinder player progress.

Monster rooms are occupied by monsters. Landing in a monster room prompts you to fight with the monster. Killing the monster rewards the player with loot which may alter the player’s skills when used. It’s not in place yet but there will probably be an option to flee the fight if the battle is going poorly for you. Player death sends the player back to the board’s entrance. And they drop all of their loot on the floor of the monster’s room. The good news, the monster remains hurt so anyone else who comes across that monster square later will have an easier fight… unless the monster has regenerative abilities. Trolls typically regenerate when not in battle, so be aware!

Trap rooms mostly do bad things to players. They might cause the player to lose a turn, go back 2 squares, or take damage. If a trap kills you then you drop your loot and go back to the beginning of the board. Noticing a theme here?

Death is permanent. Your hero dies and you go back to the beginning of the board as a brand new hero with no special loot or skills.

Last, the treasure room. The game is points based, where the player with the highest score at the end of the game wins. Treasure counts toward your total points. A bar of gold might be worth 750 points. A small gem might be worth 100. But treasure rooms aren’t limited to jewellery and gems. Players might get lucky and find special armor or a weapon. Or an unset trap…

Unset traps are the game’s way of allowing a player to hinder other players. When a player is in an empty room, and they have an unset trap in their inventory, the player can trap that room. That room will remain a safe room for that player, for the duration of their hero’s life. The trap springs only for a hero that didn’t set the trap. In most cases this means all of the other players, but what if the trap’s hero dies? Then the trap is now hostile toward that player’s new hero as well.

So that’s the general outline of the game. Take your turn, pass the tablet to the next player, and so on. Collect as many points as you can before someone reaches the exit. Highest score wins the game.

Stay tuned for more Board Rogue tidbits as development continues. As usual you can follow along with the game’s development at the task tracker or discuss it at the WaggSoft Forums.

Find me as @kdnewton on Twitter and the WaggSoft Facebook page.

PHP, curl and SSL23_GET_SERVER_HELLO

Using the following curl block I was getting an unexpected response from the server.

1
2
3
4
5
6
7
$ch = curl_init($post_url);
curl_setopt( $ch, CURLOPT_POST, 1 );
curl_setopt( $ch, CURLOPT_POSTFIELDS, "orderXML=".$xmlRequest );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_TIMEOUT, 3000 );
curl_setopt( $ch, CURLOPT_VERBOSE, 1 );
$xmlResponse = curl_exec( $ch );

Pretty simple call. It’s attempting to communicate with an url over https which is where the problem lies. Here is the response I was receiving.

1
2
Curl error number: 35
Curl error: error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure

Simple call. Confusing problem. Simple solution. Add the following line before the curl_exec.

1
curl_setopt($ch, CURLOPT_SSLVERSION, 1);

Checking the documentation, it says this: CURLOPT_SSLVERSION – The SSL version (2 or 3) to use. By default PHP will try to determine this itself, although in some cases this must be set manually.

I tried setting the value to 2 but it didn’t work.

1
2
Curl error number: 4
Curl error: OpenSSL was built without SSLv2 support

And setting it to 3 didn’t either.

1
2
Curl error number: 35
Curl error: error:1408F10B:SSL routines:SSL3_GET_RECORD:wrong version number

I wish I could tell you why setting it to 1 worked for me, but I don’t understand it. It just works for me where the documented values do not.

Fit Width of Background Image But Keep Aspect Ratio in Android

So you have an image that you want to use as a background on one of your activities.

android_01

 

You probably have something that looks like this.

android_scale_01

But the desired effect is to scale the original image into the blue outline below.

android_02

The actual effect (depending on your current layout)  is the graphic anchored to the top left (android:scaleType=”fitStart”) or center (android:scaleType=”fitCenter”) of the device’s screen with no scaling performed. Through all of your research on Google (directing you mostly to Stack Overflow threads) you’re stuck with a non-scaling graphic that’s positioned incorrectly on the screen. Or maybe you’ve got a distorted graphic that has stretched both in length and width and looks terrible. The short answer?

You can not scale the width of an ImageView to the screen’s resolution while maintaining aspect ratio in an Android layout using only XML.

That’s the information I got from one of the random Stack Overflows I found. And I ignored it for quite a while before giving in and trying to scale the image manually through code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
 
        <ImageView
            android:id="@+id/iv_background"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:scaleType="fitCenter"
            android:src="@drawable/the_background" />
    </LinearLayout>
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
 
        <Button
            android:id="@+id/b_login"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="50dp"
            android:text="@string/login_button" />
    </LinearLayout>
 
</RelativeLayout>

And the necessary code placed at the bottom of the activity’s onCreate method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int width = metrics.widthPixels;
 
BitmapDrawable bmap = (BitmapDrawable) this.getResources().getDrawable(R.drawable.the_background);
float bmapWidth = bmap.getBitmap().getWidth();
float bmapHeight = bmap.getBitmap().getHeight();
 
float wRatio = width / bmapWidth;
float hRatio = height / bmapHeight;
 
float ratioMultiplier = wRatio;
// Untested conditional though I expect this might work for landscape mode
if (hRatio < wRatio) {
	ratioMultiplier = hRatio;
}
 
int newBmapWidth = (int) (bmapWidth*ratioMultiplier);
int newBmapHeight = (int) (bmapHeight*ratioMultiplier);
 
ImageView iView = (ImageView) findViewById(R.id.iv_background);
iView.setLayoutParams(new LinearLayout.LayoutParams(newBmapWidth, newBmapHeight));

android_scale_02

This results in an ImageView that’s stretched to fit the width of the screen while maintaining the aspect ratio of the image.

Startup Weekend Postmortem: A Developers Perspective

A couple weekends ago I took part in Startup Weekend Okanagan at the Kelowna Innovation Center. It’s a full, catered, weekend of building a product from scratch, intending to build a business around that product, and pitching it to a panel of judges. I was lucky enough to be one of 6 attendees from Vernon who were fully sponsored by way of entrance fee (thank you Vernon UPS Store & Bold Media) as well as 2 nights in a hotel (thank you City of Vernon). While it’s all still relatively fresh in my mind, I thought I’d share my thoughts on what went right, what went wrong, and what I’d do differently next time.

What Went Right

Similar but not-so-popular groups merged into one · Initially there were 12 groups who gathered enough votes to move on to the recruitment round (before the planning/development round ~ rest of the weekend). I was one of the 12 (lucky) but only had one person interested in helping me. After joining my team, and wandering the floor, he actually found other groups with little enough individual interest but with similar enough ideas that we all merged into one group. 12 groups boiled down to 7, and our group ended up with 9 members with well rounded skills.

Building an MVP (Minimum Viable Product) · You only have a single weekend to piece together the group’s collective ideas to form an end product. We built our product around WordPress, customizing it with pre-built plugins where necessary. We used WordPress to express how the product would work rather than wasting time building a functional prototype from the ground up. When the weekend is over, and presentations begin, you only have 5 minutes to pitch your business and product. At least half of which is a presentation on the business plan of your product. There’s not much time left to show off the actual product. So we took our customized WordPress site and made it look pretty with a dummy profile page, pre-filled meals and static calendar feature. Enough to be able to quickly click through the main features to help express to the judges how the product would be used.

Picking a product name early · As soon as the name was decided, the rest of the team (marketing/business) could get to work on the social branding pages, including Twitter and Facebook. A logo was born, promotional video was shot. The team really felt like they had something to build around.

Ignoring everyone while they picked a name · From a developer perspective, work had to get done. We already knew we were building around WordPress but had no idea what the url of the site would be. So I set to work configuring my hosts file and apache vhosts with a dummy domain, installing WordPress, and starting on my piece of the project.

Focus on a limited feature set · We were 5 teams that merged together. 3 of our individual team ideas were very similar. We wanted to provide a service around sharing specific items. “Professional skills” was one idea, I wanted to do a co-operative advertisement service. The other idea was to share meals. Obviously cooking is a very specific “professional skill” which we could use to drive focus toward our product. We could have chosen lawn mowing. We could have chosen painting. We could have tried to tackle “all odd jobs” but we focused on this vertical slice, limiting the features and helping us make the most of the limited time we had.

What Went Wrong

I did not prepare my pitch · You get 60 seconds to pitch your idea. They are strict when it comes to those 60 seconds. I was just about to get to the good part when the buzzer rang and I was ushered off the floor. Without maximizing the use of my 60 seconds I failed to gain enough interest from my peers and barely gained enough votes to bring my idea it into the team building round.

Spending time creating features never shown · As previously stated, your time is limited. Part of my responsibilities early in the weekend were to work on the customer-facing interface. This had me researching how to customize the WordPress user profile page and installing and configuring the Adminimize plugin to limit what dashboard features the non-admin users would get to see. This was time wasted since during the final presentation we were never going to walk through the process of 1) signing up, 2) creating meals, and 3) “purchasing” other people’s meals.

Picking a product name early · You’ll notice this is in “what went right” as well. Most of the team was involved in this, while myself and the other programmer tried our best to start building something without first knowing the brand. It seemed like a whole hour (of our precious 50 or so) was dedicated to what we should call ourselves. It’s a necessary activity but most of the team was doing nothing else but this for the hour.

What I’d Do Differently

I’m guilty of this myself in that I did not do this, and had the project I’d pitched had support behind it I’d have wasted time, too: Already have a list of potential product names before the group meets for the first time. Having the brand figured out before-hand will help everyone hit the ground running. The community/social brand manager could then get to work right away creating the social profiles used to generate buzz. The project manager can get started securing a domain which in turn allows the developers to set up the site and their workspaces.

Next time I will not eat so much. There’s more food than anyone can eat in a weekend. Drinks included. I brought my own “snacks” (chocolate covered coffee beans and chocolate covered raisins) and I barely had an opportunity to eat them. I spent the weekend half focused on how uncomfortable I was from all of the food and drink in me. My own fault, a lesson learned.

While I didn’t see it as an issue, the other developer had said he wished everyone communicated a little better. I can see where he’s coming from but I was actually impressed with how well everyone worked together. Given that he thought that was an area for improvement, imagine how much we’d have accomplished if we did all communicate a little more. We didn’t really have an acting “project manager”. Rather, we had “the guy whose idea we were working on” and we all approached him when we had a specific question. If I’m responsible for that role next time, taking this lesson learned, I’ll make an effort to circle the room every so often to ensure 1) no one is working on duplicate tasks unless required and 2) there are no unasked questions from those who may not like to ask questions. All in all, we as a team didn’t suffer from 1) or 2) but a little more communication may have led to a better finished product.

Conclusion

Startup Weekend is a fantastic experience. Not only do you meet many people, making it a great networking event, but you’ll learn a thing or two as well. I know of an applications developer who learned MySQL for the first time. A Joomla developer who’s now eager to try his hand with WordPress. Myself, I was ready to build the MVP from scratch, account management system and all, before someone suggested we use WordPress instead. Brilliant.

Go for the comforts of food and drink and the company of like-minded individuals. Stay for the challenge. Take away a wealth of knowledge and industry contacts. And just maybe you’ll take first place.

*Note: We didn’t take first place. Our project, ChefShuffle.com, took the “biggest social impact” award. Coo Coo, a parking space service, took runner-up. Arkitektor took first place.

Staypressed theme by Themocracy