Skip to content

Instantly share code, notes, and snippets.

@shannah
Created August 26, 2015 21:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shannah/cae28bbfcb1e7e8bbdfd to your computer and use it in GitHub Desktop.
Save shannah/cae28bbfcb1e7e8bbdfd to your computer and use it in GitHub Desktop.
ClassicFlickrConcentration Step 6: Game Logic
package com.codename1.demos.flickrconcentration;
import com.codename1.components.SpanLabel;
import com.codename1.io.ConnectionRequest;
import com.codename1.io.JSONParser;
import com.codename1.io.NetworkManager;
import com.codename1.ui.Button;
import com.codename1.ui.Container;
import com.codename1.ui.Display;
import com.codename1.ui.EncodedImage;
import com.codename1.ui.Form;
import com.codename1.ui.TextField;
import com.codename1.ui.URLImage;
import com.codename1.ui.animations.FlipTransition;
import com.codename1.ui.layouts.BorderLayout;
import com.codename1.ui.layouts.BoxLayout;
import com.codename1.ui.layouts.GridLayout;
import com.codename1.ui.plaf.UIManager;
import com.codename1.ui.util.Resources;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class ClassicFlickrConcentration {
// Cache map so we don't run into race conditions while loading
// the same image url.
private Map<String,URLImage> loadedUrls = new HashMap<String, URLImage>();
private int rows = 4;
private int cols = 4;
EncodedImage cardBack;
private Resources theme;
// Create a Card component. This will be a container
// that keeps a reference to two buttons: front and back
public class Card extends Container {
private Button front, back;
private String url;
/**
*
* @param url The url for the image we will use for the front of the card.
*/
public Card(String url) {
this.url = url;
URLImage img = null;
if (loadedUrls.containsKey(this.url)) {
img = loadedUrls.get(this.url);
} else {
img = URLImage.createToStorage(cardBack, url+"-"+cardBack.getWidth(), url, URLImage.RESIZE_SCALE_TO_FILL);
loadedUrls.put(url, img);
img.fetch();
}
setLayout(new BorderLayout());
back = new Button(cardBack);
back.setUIID("Label");
front = new Button(img);
front.setUIID("Label");
back.addActionListener((evt) -> {
flip();
});
front.addActionListener((evt) -> {
flip();
});
addComponent(BorderLayout.CENTER, back);
}
/**
* Flips the card. If it is currently showing front, we'll
* change it to show back. If showing back, we'll flip it to show front.
*/
public void flip() {
// TODO: Lock so that only one card can be flipped at a time
// to prevent race conditions
if (this.getComponentAt(0) == front) {
// Flip to back
this.replaceAndWait(front, back, new FlipTransition());
} else {
// Flip to front
this.replaceAndWait(back, front, new FlipTransition());
}
// TODO : If we are flipping to front, and another card is already
// flipped to the front, then check to see if they match. If they
// do then mark them as matches and don't allow them to be flipped anymore.
// If there is another card flipped to the front and they don't match,
// then flip them both back over to the back.
// If there is no card flipped up yet, then don't need to do anything.
}
/**
* Checks to see if the provided card is a match for this card.
* @param card The card to check
* @return True if the cards match (have the same image url)
*/
public boolean isMatchFor(Card card) {
// TODO implement this method
throw new RuntimeException("Not implemented");
}
/**
* If this card has already been matched by the user, then return
* the match. Otherwise return null.
* @return
*/
public Card getMatch() {
// TODO implement this method
return null;
}
}
public void init(Object context) {
try {
theme = Resources.openLayered("/theme");
UIManager.getInstance().setThemeProps(theme.getTheme(theme.getThemeResourceNames()[0]));
} catch(IOException e){
e.printStackTrace();
}
cardBack = (EncodedImage)theme.getImage("card-back-1024x1024.png")
.scaled(
Display.getInstance().getDisplayWidth()/cols,
Display.getInstance().getDisplayHeight()/rows
);
}
public void start() {
newGameForm();
}
/**
* The entry form for the app. Allows user to enter a search for flickr images.
*/
public void newGameForm() {
Form f = new Form("Classic Flickr Concentration");
f.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
f.addComponent(new SpanLabel("Welcome to Classic Flickr Concentration. "
+ "A card matching game that uses flickr images."));
f.addComponent(new SpanLabel("Begin by entering a keyword to search for matching images."));
TextField searchField = new TextField();
f.addComponent(searchField);
Button searchButton = new Button("Start Game");
searchButton.addActionListener((evt) -> {
showBoard(searchField.getText());
});
f.addComponent(searchButton);
f.show();
}
public void showBoard(String search) {
Form f = new Form("Game Board");
f.setLayout(new BorderLayout());
Container grid = new Container();
grid.setLayout(new GridLayout(rows, cols));
for (Card card : createCards(search, rows * cols/2)) {
grid.addComponent(card);
}
f.addComponent(BorderLayout.CENTER, grid);
Button newGameButton = new Button("New Game");
newGameButton.addActionListener((evt) -> {
newGameForm();
});
f.addComponent(BorderLayout.SOUTH, newGameButton);
f.show();
}
public void stop() {
}
public void destroy() {
}
private Card[] createCards(String keyword, int num) {
ArrayList<Card> out = new ArrayList<Card>();
java.util.List flickrEntries = getEntriesFromFlickrService(keyword);
for (int i=0; i<num; i++) {
String url = (String)((Map)((Map)flickrEntries.get(i)).get("media")).get("m");
out.add(new Card(url));
out.add(new Card(url));
}
Collections.shuffle(out);
return out.toArray(new Card[out.size()]);
}
// Utility method to get images from flickr.
public static java.util.List getEntriesFromFlickrService(String tag) {
try {
ConnectionRequest req = new ConnectionRequest();
req.setUrl("http://api.flickr.com/services/feeds/photos_public.gne");
req.setPost(false);
req.addArgument("tagmode", "any");
req.addArgument("tags", tag);
req.addArgument("format", "json");
NetworkManager.getInstance().addToQueueAndWait(req);
byte[] data = req.getResponseData();
if (data == null) {
throw new IOException("Network Err");
}
JSONParser parser = new JSONParser();
Map response = parser.parseJSON(new InputStreamReader(new ByteArrayInputStream(data), "UTF-8"));
System.out.println("res" + response);
java.util.List items = (java.util.List)response.get("items");
return items;
} catch (Exception e) {
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment