Here’s an example of a simple Android game program using Java and the Android Studio development environment. This program creates a basic “Guess the Number” game where the player tries to guess a randomly generated number.
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
private int randomNumber;
private EditText guessInput;
private Button guessButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
guessInput = findViewById(R.id.guess_input);
guessButton = findViewById(R.id.guess_button);
generateRandomNumber();
guessButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkGuess();
}
});
}
private void generateRandomNumber() {
Random random = new Random();
randomNumber = random.nextInt(100) + 1;
}
private void checkGuess() {
String guessText = guessInput.getText().toString();
if (guessText.isEmpty()) {
Toast.makeText(this, "Please enter a number", Toast.LENGTH_SHORT).show();
return;
}
int guess = Integer.parseInt(guessText);
if (guess < randomNumber) {
Toast.makeText(this, "Higher!", Toast.LENGTH_SHORT).show();
} else if (guess > randomNumber) {
Toast.makeText(this, "Lower!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Congratulations! You guessed the number!", Toast.LENGTH_SHORT).show();
generateRandomNumber();
}
guessInput.setText("");
}
}
In this example, we define an MainActivity class that extends AppCompatActivity. Inside the onCreate method, we initialize the EditText and Button views from the layout file using their respective IDs. We also generate a random number using the generateRandomNumber method. We set an OnClickListener on the guess button to trigger the check Guess method when the button is clicked. Inside checkGuess, we retrieve the user’s guess from the input field and compare it to the randomly generated number. Based on the comparison, we display a toast message indicating whether the guess should be higher or lower. If the guess is correct, we display a congratulatory message and generate a new random number for the next round. Remember to create the corresponding layout XML file (e.g., activity_main.xml) in the res/layout directory to define the user interface for this game. The layout should include an Edit Text for the user’s guess input, a Button for submitting the guess, and any additional views you may want to include. This is a basic example to get you started with Android game development. You can enhance and expand upon this code to add more features, levels, and Android game mechanics as you progress.
Pingback: Future developments that will influence the fantasy gaming sector in 2023 - sameerjadeja.in