Image Guess Game

... by Bittle in Java Telegram Bot April 12, 2019

Let's create our first game already! First of all, we need to respect Telegram's servers, so we will not send files. We will tell Telegram where the pictures are located (url) and the API will take care of sending them. This is lightweight on both the server and our storage. To send photos we create a sendPhoto instance and set the chat id and url. Then we call execute and pass the sendPhoto instance:

public void sendPhoto(String chatId, String url) {
    SendPhoto sendPhoto = new SendPhoto();
    sendPhoto.setChatId(chatId);
    sendPhoto.setPhoto(url);
    try {
        execute(sendPhoto);
    } catch (TelegramApiException e) {
        e.printStackTrace();
    }
}

We also need a function to send text messages, which is very similar to the above sendPhoto function:

public void sendMessage(String chatId, String message) {
    SendMessage sendMessageRequest = new SendMessage();
    sendMessageRequest.setChatId(chatId);
    sendMessageRequest.setText(message);
    try {
        execute(sendMessageRequest);
    } catch (TelegramApiException e) {
        e.printStackTrace();
    }
}

Now we are going to create ImageGuess.java in our src directory. ImageGuess will have a url and an answer variable. It will also contain a list of ImageGuess objects and a function to retrieve a random one:

ImageGuess.java
import java.util.ArrayList;
import java.util.Random;

class ImageGuess {
    private String url;
    private String answer;

    public ImageGuess(String url, String answer) {
        this.url = url;
        this.answer = answer;
    }

    public String getUrl() {
        return url;
    }

    public String getAnswer() {
        return answer;
    }

    private static ArrayList<ImageGuess> l = new ArrayList<>();

    private static void initList() {

        l.add(new ImageGuess("https://bit.ly/2R9FiRU", "zebra"));
        l.add(new ImageGuess("https://bit.ly/2RCc3Gu", "horse"));
        l.add(new ImageGuess("https://bit.ly/2RxAcOD", "shark"));
        // and so forth...
    }

    // get a random image
    static ImageGuess random() {
        if (l.isEmpty())
            initList();
        return l.get(new Random().nextInt(l.size()));
    }
}

We then modify ImageGuess check function to create a new ImageGuess instance if /guess is sent. We also need to check if there is already a game in progress, and if an incoming message is the answer:

public static void check(KodeCentralBot kodeCentralBot, Update update) {
    // create a new game if this group doesn't have one already, otherwise grab from HashMap
    Game game = new Game();
    long chatId = update.getMessage().getChatId();
    if (games.containsKey(chatId))
        game = games.get(chatId);
    else {
        games.put(chatId, game);
    }

    // variables
    Message message = update.getMessage();
    String message_text = message.getText();
    String message_text_lower = message_text.toLowerCase();
    String username = message.getFrom().getUserName();

    // check if starting a new guess game
    if (message_text_lower.equals("/guess") || message_text_lower.equals("???? guess")) {
        // only create a new guess game if there isn't one
        if (game.guessGame == null) {
            game.guessGame = ImageGuess.random();
        }
        kodeCentralBot.sendPhoto(Long.toString(chatId), game.guessGame.getUrl());
    } 
    // check if guess game answered correctly
    else if (game.guessGame != null && message_text_lower.contains(game.guessGame.getAnswer())) {
        // reset the guess game!
        game.guessGame = null;
        kodeCentralBot.sendMessage(Long.toString(chatId), username + " has won!");
    }
}


Files

KodeCentralBot.java
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.methods.send.SendPhoto;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class KodeCentralBot extends TelegramLongPollingBot {
    @Override
    public void onUpdateReceived(Update update) {

        // We check if the update has a message and the message has text
        if (update.hasMessage() && update.getMessage().hasText()) {
            // NEW:
            GameHandler.check(this, update);
        }
    }

    private void log(String username, String chatId, String textReceived, String botResponse) {
        System.out.println("----------------------------\n");
        // print out in PM/AM time
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd h:mm a");
        Date date = new Date();
        System.out.println(dateFormat.format(date));
        System.out.println("Message from " + username + ". (id = " + chatId + ") \n Text - " + textReceived);
        System.out.println("Bot answer: \n Text - " + botResponse);
    }

    public void sendPhoto(String chatId, String url) {
        SendPhoto sendPhoto = new SendPhoto();
        sendPhoto.setChatId(chatId);
        sendPhoto.setPhoto(url);

        try {
            execute(sendPhoto);
        } catch (TelegramApiException e) {
            e.printStackTrace();
        }
    }

    public void sendMessage(String chatId, String message) {
        SendMessage sendMessageRequest = new SendMessage();
        sendMessageRequest.setChatId(chatId);
        sendMessageRequest.setText(message);
        try {
            execute(sendMessageRequest);
        } catch (TelegramApiException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getBotUsername() {
        // Return bot username
        // If bot username is @KodeCentralBot, it must return 'KodeCentralBot'
        return "KodeCentralBot";
    }

    @Override
    public String getBotToken() {
        // Return bot token from BotFather
        return "token";
    }
}


GameHandler.java
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.Update;

import java.util.HashMap;

public class GameHandler {

    private static class Game {

        // for upcoming tutorial
        private ImageGuess guessGame = null;
    }

    // to play separate games on separate groups
    private static HashMap<Long, Game> games = new HashMap<>();

    public static void check(KodeCentralBot kodeCentralBot, Update update) {
        // create a new game if this group doesn't have one already, otherwise grab from HashMap
        Game game = new Game();
        long chatId = update.getMessage().getChatId();
        if (games.containsKey(chatId))
            game = games.get(chatId);
        else {
            games.put(chatId, game);
        }

        // variables
        Message message = update.getMessage();
        String message_text = message.getText();
        String message_text_lower = message_text.toLowerCase();
        String username = message.getFrom().getUserName();

        // check if starting a new guess game
        if (message_text_lower.equals("/guess") || message_text_lower.equals("???? guess")) {
            // only create a new guess game if there isn't one
            if (game.guessGame == null) {
                game.guessGame = ImageGuess.random();
            }
            kodeCentralBot.sendPhoto(Long.toString(chatId), game.guessGame.getUrl());
        }
        // check if guess game answered correctly
        else if (game.guessGame != null && message_text_lower.contains(game.guessGame.getAnswer())) {

            // reset the guess game!
            game.guessGame = null;
            kodeCentralBot.sendMessage(username + " has won!", chatId);
        }
    }
}


ImageGuess.java
import java.util.ArrayList;
import java.util.Random;

class ImageGuess {
    private String url;
    private String answer;

    public ImageGuess(String url, String answer) {
        this.url = url;
        this.answer = answer;
    }

    public String getUrl() {
        return url;
    }

    public String getAnswer() {
        return answer;
    }

    private static ArrayList<ImageGuess> l = new ArrayList<>();

    private static void initList() {

        l.add(new ImageGuess("https://bit.ly/2R9FiRU", "zebra"));
        l.add(new ImageGuess("https://bit.ly/2RCc3Gu", "horse"));
        l.add(new ImageGuess("https://bit.ly/2RxAcOD", "shark"));
        // and so forth...
    }

    // get a random image
    static ImageGuess random() {
        if (l.isEmpty())
            initList();
        return l.get(new Random().nextInt(l.size()));
    }
}


Example output

And there you have it! Next we will learn how to save player scores to a local database!

Comments (0)

Search Here