Currently, I'm playing around with JavaFX as I'm writing a Snake game for my Java Fundamentals class final project. I'm not that new to creating simple games with animations as I've made a bit of them using PyGame module and SDL in C. Anyway, now I'm quite struggling with understanding the correlations of some objects in JavaFX, especially when combined with SceneBuilder's FXMLs.
I just can't understand how to create an equivalent of gameloop I used to implement in PyGame or SDL. What I want to do with the code below is to enter the gameloop as soon as a new Game object is created and draw the state of the game continuously on the gameCanvas created in the SceneBuilder. I think I can easily manage all the stuff later, but I just can't sort it out how to create a legit bond between the FXML canvas and the gameloop I want to run.
GameController.java
public class GameController implements Initializable, ControlledScreen {
#FXML
private Canvas gameCanvas;
#Override
public void setScreenParent(ScreensController screenPage) {
// THIS IS FOR SCENE MANAGEMENT CONCEPT
}
Game.java
public class Game implements Runnable {
public static final int EASY = 1,
MEDIUM = 2,
HARD = 3;
int difficultyLevel, score = 0;
Snake snake;
Food food;
boolean isRunning = true;
public void setLevelEasy() {
difficultyLevel = EASY;
}
public void setLevelMedium() {
difficultyLevel = MEDIUM;
}
public void setLevelHard() {
difficultyLevel = HARD;
}
#Override
public void run() {
while (isRunning) {
}
}
}
#Override
public void initialize(URL location, ResourceBundle resources) {
// TODO Auto-generated method stub
}
}
You cant use FXML file to create new scene. Use this instead
public class Screen extends Application implements Runnable
{
#Override
public void start ( Stage primaryStage )
{
Pane pane = new Pane ();
Scene scene = new Scene(pane,500,300);
primaryStage.setScene ( scene );
primaryStage.show ();
}
#Override
public void run ()
{
launch ();
}
}
anything you want to add goes to pane element your canvas etc.
and by the way make dificulty enum not int like
enum {easy,medium,hard}
that way nobody can set dificulty level to something does not exist.
Related
At this moment I have 2 screens: MainScreen (it's the main menu of the game) and GameScreen. I have a "button" (it's an image) that when the user clicks on it, the MainScreen switchs to the GameScreen.
The problem is that all the images of the MainScreen don't disappear when the second screen appears (the button and the main title). I have been working on this for days and I don't know what more to do.
Main class of the game:
public class MyGame extends Game {
#Override
public void create () {
Sounds.load();
Texts.load();
Buttons.load();
setScreen(new MainScreen(this));
}
#Override
public void dispose () {
super.dispose();
Sounds.dispose();
Texts.dispose();
Buttons.dispose();
}
}
MainScreen:
public class MainScreen implements Screen {
private MyGame game;
private Stage stage;
private OrthographicCamera camera;
private Viewport viewport;
public static Image tituloPrincipal, botonPlay;
public MainScreen(final MyGame game) {
this.game = game;
//stage
camera = new OrthographicCamera(Settings.SCREEN_WIDTH, Settings.SCREEN_HEIGHT);
viewport = new StretchViewport(Settings.SCREEN_WIDTH, Settings.SCREEN_HEIGHT, camera);
stage = new Stage(viewport);
//background
stage.addActor(new Image(Sprites.mainBackground));
//Title of the game
tituloPrincipal = new Image();
tituloPrincipal.setPosition(Settings.SCREEN_WIDTH * 1 / 6, Settings.SCREEN_HEIGHT * 4 / 12);
tituloPrincipal.setDrawable(new TextureRegionDrawable(new TextureRegion(Texts.tituloPrincipal)));
tituloPrincipal.setSize(Texts.tituloPrincipal.getWidth()/3,
Texts.tituloPrincipal.getHeight()/3);
stage.addActor(tituloPrincipal);
//Play Button
botonPlay = new Image();
botonPlay.setPosition(Settings.SCREEN_WIDTH * 4 / 10, Settings.SCREEN_HEIGHT / 16);
botonPlay.setDrawable(new TextureRegionDrawable(new TextureRegion(Buttons.playbutton)));
botonPlay.setSize(Buttons.playbutton.getWidth()/16,
Buttons.playbutton.getHeight()/18);
stage.addActor(botonPlay);
//Song
Sounds.musicMainScreen.play();
}
#Override
public void show() {
Gdx.input.setInputProcessor(stage);
}
#Override
public void render(float delta) {
botonPlay.addListener(new ClickListener(){
#Override
public void clicked(InputEvent event, float x, float y) {
game.setScreen(new GameScreen(game));
dispose();
}
});
stage.draw();
stage.act(delta);
}
#Override
public void resize ( int width, int height){
}
#Override
public void pause () {
}
#Override
public void resume () {
}
#Override
public void hide () {
}
#Override
public void dispose () {
}
}
GameScreen:
public class GameScreen implements Screen {
private Game game;
private Stage stage;
public GameScreen(Game game) {
this.game = game;
stage = new Stage();
Gdx.input.setInputProcessor(stage);
deleteMainScreenSources();
//song
Sounds.musicGameScreen.play();
}
public void deleteMainScreenSources() {
Sounds.musicMainScreen.stop();
}
#Override
public void show() {
}
#Override
public void render(float delta) {
}
#Override
public void resize ( int width, int height){
}
#Override
public void pause () {
}
#Override
public void resume () {
}
#Override
public void hide () {
}
#Override
public void dispose () {
}
}
Button class:
public class Buttons {
public static Texture playbutton;
public static void load() {
playbutton = new Texture(Gdx.files.internal("playbutton.png"));
playbutton.setFilter(Texture.TextureFilter.Nearest, Texture.TextureFilter.Nearest);
}
public static void dispose() {
playbutton.dispose();
}
}
The class of the title it's like the class of the button.
Your render method is what draws your screen. If you are not aware, it is kind of a game loop , which gets executed non stop ( around 60/sec by default I believe). So all your drawing and redrawing goes here.Usually , you would be clearing your screen at first and then draw other images on the screen. Libgdx provide interfacing to opengl to clear the screen. In my case, I always clear screen at the very first line of render method and draw additional things on it so that it makes sure my stale content of the screens are gone.In your GameScreen , your render method is empty , so your previous screen is not yet wiped out. I believe adding clear and drawing your new stage in GameScreen will resolve your issue.
Make your code in GameScreen render something like this and try ,
#Override
public void render(float delta) {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act();
stage.draw();
}
Also, I would try to avoid creation of any new object in 'render` method for the same reason. Your addListener method in your menu screen can go in it's constructor. So that you don't create anonymous listener in every game loop execution. This may not impact by that much in your current scenario, but if you create some heavy object or some Sprites in this way in game loop, that can drag your game perfomance a lot.
Here is my OOP setup:
Class MainGame extends Game:
...
public void create () {
assets = new Assets(); // my custom Assets object (constructor creates manager and AssetDescriptors
assets.load(); // loads Asset Descriptors into manager
assets.getManager().finishLoading();
batch = new SpriteBatch();
setScreen(new PlayScreen(this, assets));
}
...
public void dispose () {
assets.dispose(); // disposes asset manager
super.dispose();
batch.dispose();
}
Class PlayScreen implements Screen:
public PlayScreen(MainGame game, Assets assets) {
this.assets = assets;
this.game = game;
background = assets.getManager().get(assets.getBackground());
hero = new HeroSprite(290, 1100, this, assets);
// Create Game camera and Hub also
}
public void render(float delta) {
// Clear screen
// Use game batch to draw to screen
}
public void dispose() {
assets.dispose();
}
Class HeroSprite:
public HeroSprite(int x, int y, PlayScreen screen, Assets assets){
this.assets = assets;
this.screen = screen;
// Animation Textures
heroWalking = assets.getManager().get(assets.getWalking()); // This is an Asset Descriptor
walkAnime = new Animation(heroWalking) // my own custom animation class which takes the spritesheet and returns the appropriate frames
...
}
// This does not contain a dispose method
Sorr if there's a lot of code there I tried to minimize as much as possible. My main question is if I am disposing correctly?
It seems ok, my game runs fine. But when I quit the game and re-enter a black screen shows. This happens both on Desktop and Android.
A solution that works is to clear the memory on Android using Super Cleaner App. Since it's a memory issue I figures it has something to do with me disposing incorrectly.
EDIT : Revealing my Assets Class
public class Assets {
private AssetManager manager;
private AssetDescriptor<Texture> background;
private AssetDescriptor<Texture> wood;
public AssetManager getManager() {
return manager;
}
public AssetDescriptor<Texture> getBackground() {
return background;
}
public AssetDescriptor<Texture> getWood() {
return hero;
}
public Assets(){
manager = new AssetManager();
background = new AssetDescriptor<Texture>("textures/static/bg.png", Texture.class);
hero = new AssetDescriptor<Texture>("textures/static/hero.png", Texture.class);
...
}
public void load(){
manager.load(background);
manager.load(hero);
...
}
public void dispose(){
manager.dispose();
}
}
Screen.dispose() does not get called automatically, you should manually call dispose when you exit a screen and not needing the assets anymore. But obviously when you need them again you need to load them again and you need a new AssetManager for that. So if your assets won't take up that much you should just keep it in memory.
On exit however you need to dispose. Game.dispose() does get called automatically. Here you should call getScreen().dispose() and have everything needing disposing in the dispose() method of the effective Screen.
Since currently it does not look like you are disposing between screens it might be because you have a static AssetManager, you should show your Assets() class.
In my game I have currently two screens. The MenuScreen and the GameScreen. Through the Play option in the menu the player can switch to the GameScreen and start the Gameplay and with Escape he can get back to the MenuScreen. I dispose the used Assets when I switch to the other Screen in the hide() method and load the needed Assets for the new Screen in the constructor of the Screen I switch to. The problem is that the Textures and Sound Effects aren't rendered/played when I switch back.
For example when I start the game in the MenuScreen, then switch to the GameScreen everything is fine. But when I switch back to the MenuScreen the MenuScreen is just a black window. When I then switch to the GameScreen again it's black too except for the BitmapFont.
Maybe there is a fundemental flaw in the way I handle this. I tried to leave out as much unnecessary things as I can from the code I post here, but I fear that it's still too much.
RessourceLoader Class:
public class RessourceLoader {
public static AssetManager manager;
public static void create() {
manager = new AssetManager();
}
public static void loadMenuScreen() {
manager.load("gfx/menuBackground.png", Texture.class);
}
public static void getMenuScreen() {
menuBackground = manager.get("gfx/menuBackground.png", Texture.class);
}
public static void disposeMenuScreen() {
menuBackground.dispose();
}
public static void loadGameScreen() {
// load GameScreen Assets through AssetManager
}
public static void getGameScreen() {
// get GameScreen Assets through AssetManager
}
public static void disposeGameScreen() {
// dispose all GameScreen Assets
}
public static void dispose() {
manager.dispose();
}
}
MenuScreen Class:
public class MenuScreen implements Screen {
// Game starts in the MenuScreen
// Instance of game
private PHGame game;
// Orthographic camera
private OrthographicCamera cam;
public MenuScreen(PHGame phGame) {
game = phGame;
RessourceLoader.loadMenuScreen();
RessourceLoader.manager.finishLoading();
RessourceLoader.getMenuScreen();
cam = new OrthographicCamera();
cam.setToOrtho(true, 640, 480);
game.batcher.setProjectionMatrix(cam.combined);
}
#Override
public void render(float delta) {
// Fills background with black to avoid flickering
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// Begin Drawing
game.batcher.begin();
// Draw Menu
// Stop drawing
game.batcher.end();
// Pressing Space confirms currently selected menu item
if (GameKeys.isPressed(GameKeys.SPACE)) {
game.setScreen(new GameScreen(game));
}
// Update Key Presses
GameKeys.update();
}
#Override
public void hide() {
dispose();
}
#Override
public void dispose() {
RessourceLoader.disposeMenuScreen();
}
}
GameScreen Class:
public class GameScreen implements Screen {
// Instance of game
private PHGame game;
private GameWorld world;
private GameRenderer renderer;
private float runTime;
public GameScreen(PHGame phGame) {
game = phGame;
RessourceLoader.loadGameScreen();
RessourceLoader.manager.finishLoading();
RessourceLoader.getGameScreen();
world = new GameWorld(game, this);
renderer = new GameRenderer(world, game);
}
#Override
public void render(float delta) {
// runTime is the amount of time the game is running
runTime += delta;
// Updates the Game World
world.update(delta);
// Renders everything
renderer.render(runTime);
// Update Key Presses
GameKeys.update();
}
#Override
public void hide() {
dispose();
}
#Override
public void dispose() {
RessourceLoader.disposeGameScreen();
}
}
GameRenderer Class:
public class GameRenderer {
// Instance of PHGame
PHGame game;
// Instance of Game World
private GameWorld world;
// Orthographic Camera
private OrthographicCamera cam;
// If true hitbox's will be shown
private boolean showHitbox;
// Game Objects
private Player player;
public GameRenderer(GameWorld world, PHGame game) {
this.game = game;
this.world = world;
player = world.getPlayer();
cam = new OrthographicCamera();
cam.setToOrtho(true, 640, 480);
showHitbox = false;
game.batcher.setProjectionMatrix(cam.combined);
}
public void render(float runTime) {
// draw objects and hud
}
}
If there are any questions regarding my problem I'll try to answer then as good as I can.
Refer to the github article 'managing your assets'. AssetManagers should not be static. 'This typically would cause black/missing textures or incorrect assets.'
After you dispose your asset manager it can no londer be used. Instead use manager.unload to unload assets. manager.unload("gfx/menuBackground.png");
EDIT:
I also didn't see any overriden show() methods. If you want your assets back you will need to load your assets in the screen's show method every time.
ok i have two classes similar like this(the graphics are set up the same way) and another class that is displayed on the bottom. as you can see i have two graphics2ds that i would like to display at the same time with the items class being transparent and on top (the items class has almost nothing in it, and the game class is fully covered with pictures and such)
is there any way to do this?
currently the items class take priority ever the game class because it was called last and totally blocks the game class.
public class game extends Canvas implements Runnable
{
public game()
{
//stuff here
setBackground(Color.white);
setVisible(true);
new Thread(this).start();
addKeyListener(this);
}
public void update(Graphics window)
{
paint(window);
}
public void paint(Graphics window)
{
Graphics2D twoDGraph = (Graphics2D)window;
if(back==null)
back = (BufferedImage)(createImage(getWidth(),getHeight()));
Graphics graphToBack = back.createGraphics();
//draw stuff here
twoDGraph.drawImage(back, null, 0, 0);
}
public void run()
{
try
{
while(true)
{
Thread.currentThread();
Thread.sleep(8);
repaint();
}
}catch(Exception e)
{
}
}
}
class two
public class secondary extends JFrame
{
private static final int WIDTH = 800;
private static final int HEIGHT = 600;
public secondary()
{
super("Test RPG");
setSize(WIDTH,HEIGHT);
game game = new game();
items items = new items();
((Component)game).setFocusable(true);
((Component)items).setFocusable(true);
getContentPane().add(game);
getContentPane().add(items);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main( String args[] )
{
secondary run = new secondary();
}
}
Here are my suggestions:
Extend JComponent rather than Canvas (you probably want a lightweight Swing component rather than a heavyweight AWT one)
Then don't bother with the manual back-buffering for your drawing - Swing does back-buffering for you automatically (and will probably use hardware acceleration while doing so)
Have one component draw both items and the rest of the game background. There is no good reason to do it separately (even if you only change the items layer, the background will need to be redrawn because of the transparency effects)
Capitalise Your ClassNames, it makes my head hurt to see lowercase class names :-)
EDIT
Typically the approach would be to have a class that represents the visible area of the game e.g. GameScreen, with a paintCompoent method as follows:
public class GameScreen extends JComponent {
....
public void paintComponent(Graphics g) {
drawBackground(g);
drawItems(g);
drawOtherStuff(g); // e.g. animated explosions etc. on top of everything else
}
}
I started using jMonekyEngine and it's easy way of interacting with Swing GUI.
Following their tutorial here http://jmonkeyengine.org/wiki/doku.php/jme3:advanced:swing_canvas
It all works and I get everything loaded,however I'm having trouble modifying things.
According to their tutorial, the constant update and happens here:
public void simpleUpdate(float tpf) {
geom.rotate(0, 2 * tpf, 0);
}
(this is an example from the tutorial on rotating objects).
what i'm trying to do is just increasing and decreasing the speed of rotation (by changing the 2 or tpf with a variable which gets update inside an ActionListener in the Swing gui.
However, since in their tutorial they stated that the swing gui is to be created inside the main method, I have to create a variable which is static in order to change it.
static float rotate = 0.0f;
it gets modified inside the main method, but when trying to use it like so:
public void simpleUpdate(float tpf) {
geom.rotate(0, rotate * tpf, 0);
}
it remains constant to the initial value.
I tried creating a GUI class to build the gui (extends JPanel) and using getters and setters, but still not go..
Any help would be appreciated!
Thanks!
EDIT:
Here's how I change the rotate value:
JButton faster = new JButton("Faster");
faster.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
rotate +=0.1f;
}
});
inside the main method. rotate is a static field.
This is working for me
http://test.jmonkeyengine.org/wiki/doku.php/jme3:beginner:hello_main_event_loop
http://test.jmonkeyengine.org/wiki/doku.php/jme3:beginner:hello_input_system?s[]=input
Is your action listener really triggering the event on click? maybe you have a problem there and not in the rotate variable. Note that I'm not using swing on this example..
import com.jme3.app.SimpleApplication;
import com.jme3.input.KeyInput;
import com.jme3.input.controls.ActionListener;
import com.jme3.input.controls.KeyTrigger;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import com.jme3.scene.Geometry;
import com.jme3.scene.shape.Box;
/** Sample 4 - how to trigger repeating actions from the main update loop.
* In this example, we make the player character rotate. */
public class HelloLoop extends SimpleApplication {
public static void main(String[] args){
HelloLoop app = new HelloLoop();
app.start();
}
protected Geometry player;
#Override
public void simpleInitApp() {
Box b = new Box(Vector3f.ZERO, 1, 1, 1);
player = new Geometry("blue cube", b);
Material mat = new Material(assetManager,
"Common/MatDefs/Misc/Unshaded.j3md");
mat.setColor("Color", ColorRGBA.Blue);
player.setMaterial(mat);
rootNode.attachChild(player);
initKeys();
}
/* This is the update loop */
#Override
public void simpleUpdate(float tpf) {
// make the player rotate
player.rotate(0, val*tpf, 0);
}
float val = 2f;
private void initKeys() {
// Adds the "u" key to the command "coordsUp"
inputManager.addMapping("sum", new KeyTrigger(KeyInput.KEY_ADD));
inputManager.addMapping("rest", new KeyTrigger(KeyInput.KEY_SUBTRACT));
inputManager.addListener(al, new String[]{"sum", "rest"});
}
private ActionListener al = new ActionListener() {
public void onAction(String name, boolean keyPressed, float tpf) {
if (name.equals("sum") ) {
val++;
}else if (name.equals("rest")){
val--;
}
}
};
}