Welcome, Guest. Please login or register. Did you miss your activation email?

Show Posts

This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.


Messages - cx3

Pages: [1]
1
Java / JSFML Text with texture as a background
« on: April 08, 2015, 10:20:51 am »
Hello World :)

I am trying to fill text with rendered gradient or with loaded texture. It does not want to work any manner I combine since several hours. With/without BlendMode, with/without rendering to RenderTexture, manipulating with pixels gives me all black texture (and other chochlics)... I tried at last a code with shaders with little changes... It does not like me ;] What is the best (fastest) method of binding texture to a text object?  :-X

2
Java / Re: Rectangle collision problem
« on: March 17, 2015, 10:23:38 am »
I did not get that null-pointer is returned by FloatRect.intersection(FloatRect) if no collision detected, therefore i tried to solve collisions by myself. Ehhh, inadvertant.

private Vector2f  calcColl(float x, float y, float r)
        {      
                for (FloatRect  rects : brickRects)
                {
                        FloatRect ins = rects.intersection(new FloatRect(x, y, r, r));
                       
                        if (ins!=null)
                                return new Vector2f
                                (
                                        ins.width -ins.left,
                                        ins.height-ins.top
                                );
                }
                return new Vector2f(0.f, 0.f);
        }
       
       
        public void nextMove(Time dt, KeybAction  action)
        {
                if (action == KeybAction.none) return;
               
                FloatRect pos = image.getSprite().getGlobalBounds(), tmp = null;
               
                Vector2f  v = new Vector2f(pos.left, pos.top), c = null;
               
                float f = dt.asMicroseconds()/1000, r = 50.f;
                       
                        switch(action)
                        {
                                case left:
                                   c = calcColl(v.x-f, v.y, r);
                                   v = new Vector2f(v.x+c.x-f, v.y);
                                   break;
                               
                                case right:
                                   c = calcColl(v.x+f, v.y, r);
                                   v = new Vector2f(v.x+c.x+f, v.y);
                                   break;
                                 
                                case up:
                                   c = calcColl(v.x, v.y-f, r);
                                   v = new Vector2f(v.x, v.y+c.y-f);
                                   break;
                                 
                                case down:
                                   c = calcColl(v.x, v.y+f, r);
                                   v = new Vector2f(v.x, v.y+c.y+f);
                                   break;
                        }
                       
                //if (c!=null) System.out.println(c.toString());
               
                Vector2i vi = new Vector2i(v);
                image.setXY(vi.x, vi.y);
               
                System.out.println(image.getSprite().getPosition().toString());
        }

Part of Player.class. Intersections works sweet, some corrects and show must go on. Sorry again ;x

3
Java / Re: Rectangle collision problem
« on: March 16, 2015, 11:04:24 pm »
You`re right... sorry :)

This is class that should detect collisions:

class SafeZone
{
        private static
                boolean isColliding //arglist
                (
                        Vector2f Ax1y1,
                        Vector2f Ax2y2,
                        Vector2f Bx1y1,
                        Vector2f Bx2y2
                )
                {//method`s body start:
                        float
                                widthA  = Math.abs(Ax1y1.x - Ax2y2.x),
                                widthB  = Math.abs(Bx1y1.x - Bx2y2.x),
                               
                                heightA = Math.abs(Ax1y1.y - Ax2y2.y),
                                heightB = Math.abs(Bx1y1.y - Bx2y2.y);
                               
                        if (
                                 (Math.abs(Ax1y1.x - Bx2y2.x) <= widthA + widthB)
                                                                        &&
                                  Math.abs(Ax1y1.y - Bx2y2.y) <= heightA + heightB
                                )      
                                return true;
                               
                        return false;
                }


public static
        boolean isColliding(Sprite A, Sprite B)
        {
                Vector2f
                        vA1 = A.getPosition(), vA2 = A.getOrigin(),
                        vB1 = B.getPosition(), vB2 = B.getOrigin();
                       
                float
                        vAdtx = Math.abs(vA2.x - vA1.x),
                    vAdty = Math.abs(vA2.y - vA1.y),
                   
                    vBdtx = Math.abs(vB2.x - vB1.x),
                    vBdty = Math.abs(vB2.y - vB1.y);
                   
               
                        vA2 = new Vector2f(vA1.x, vA1.x + 2*vAdtx);
                        vB2 = new Vector2f(vB1.x, vB1.x + 2*vBdtx);
               
                return isColliding(vA1, vA2, vB1, vB2);
        }
       
       
public static
        boolean isColliding(Sprite A, Sprite[] sprites)
        {
                for (Sprite sprite : sprites)
                        if (isColliding( sprite, A) == true ) return true;
                return false;
        }
}

And it does not work. I`ll repair it (this is a must), but anybody`s help make it faster.

I`m still learning JSFML, by now I feel that my knowledge about this library increased since last two weeks, so after several months of falling in love with I`m sure I`ll be able to create some video tut on YT ;>

Don't be angry with me, I'm really amazed ;)

4
Java / Rectangle collision problem
« on: March 16, 2015, 08:59:54 pm »
Hello :) I`ve been coding for about 20 hours ( xD ) and my brain does not work. I tried various combinations in detecting collisions... and none works. Below all code:

/**
 * @(#)GameFromScratch.java
 *
 * GameFromScratch application
 *
 * @author #cx3#
 * @version 1.00 2015/3/7
 */

 
import org.jsfml.graphics.RenderWindow;
import org.jsfml.graphics.Text;
import org.jsfml.graphics.*;
import org.jsfml.system.Clock;
import org.jsfml.system.Time;
import org.jsfml.window.VideoMode;
import org.jsfml.window.WindowStyle;
import org.jsfml.window.event.Event;
import org.jsfml.graphics.Color;
 
import org.jsfml.graphics.Font;
import org.jsfml.graphics.Texture;
import org.jsfml.graphics.Sprite;
import org.jsfml.system.*;

import org.jsfml.system.Time;
import org.jsfml.system.Vector2f;
import org.jsfml.window.Keyboard;
import org.jsfml.window.event.Event;

import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;

import java.io.*;
import java.io.FileInputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import java.nio.file.Paths;
import java.nio.file.*;

import java.lang.Number;
import java.lang.Math;

import java.io.FileNotFoundException;
import java.util.Scanner;

import java.util.Arrays;

import java.lang.System;

/*
 * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
 */


enum KeybAction { left,right,up,down,none,esc };

enum SpriteType { PLAYER, ENEMY, FRUIT, BRICK, BACK };


class INFO
{
        public static String            MEDIA_DIR;
        public static Bricks            BRICKS;
        public static RenderWindow  GAMEWINDOW;
}


//################################################
//################################################


interface IGetSprites{  public Sprite[] getSprites();  }

interface IDrawRenderWindow{  public void draw(RenderWindow rw);  }

//################################################

 
class ImageLoader
{
        Texture texture = new Texture();
        Sprite  sprite  = new Sprite();
        Image   image   = new Image();
       
        SpriteType      spriteType;
       
        int x,y;
       
       
public
        ImageLoader(String spritePath, SpriteType  spriteType)
        {
                x=0; y=0;
               
                this.spriteType = spriteType;
               
                try
                {
                        texture.loadFromFile(Paths.get(spritePath));   
                        texture.setRepeated(true);
                       
                        sprite = new Sprite(texture);          
                        image  = texture.copyToImage();
                }
                catch  (Exception e)
                {
                        e.printStackTrace();
                }
        }
       
public
        ImageLoader(String spritePath, SpriteType  spriteType, int x, int y)
        {
                this(spritePath, spriteType);
               
                this.spriteType = spriteType;
                this.x = x;
                this.y = y;    
        }
       
       
        public Sprite  copySprite()
        {
                Texture tx = new Texture(texture);
                tx.setRepeated(true);
                return new Sprite(sprite.getTexture());
        }
       
       
        public Sprite  copySprite(int x, int y)
        {
                Sprite s = copySprite();
                s.setPosition(x,y);
                return s;
        }
       

        public void setX(int x){ this.x = x; }
        public void setY(int y){ this.y = y; }
       
        public void setXY(int x, int y){ setX(x); setY(y); }
       

        public Sprite  getSprite()
        {
                sprite.setPosition(x,y);
                return sprite;
        }
       
       
        public Sprite  getSprite(int x, int y)
        {
                sprite.setPosition(x,y);
                return sprite;
        }
       
               
        public Image       getImage(){   return image;   }
               
        public Texture     getTexture(){ return texture; }
       
        public SpriteType  getSpriteType(){ return spriteType; }
}


//################################################
//################################################


class SafeZone
{
        private static
                boolean isColliding //arglist
                (
                        Vector2f Ax1y1,
                        Vector2f Ax2y2,
                        Vector2f Bx1y1,
                        Vector2f Bx2y2
                )
                {//method`s body start:
                        float
                                widthA  = Math.abs(Ax1y1.x - Ax2y2.x),
                                widthB  = Math.abs(Bx1y1.x - Bx2y2.x),
                               
                                heightA = Math.abs(Ax1y1.y - Ax2y2.y),
                                heightB = Math.abs(Bx1y1.y - Bx2y2.y);
                               
                        if (
                                 (Math.abs(Ax1y1.x - Bx2y2.x) <= widthA + widthB)
                                                                        &&
                                  Math.abs(Ax1y1.y - Bx2y2.y) <= heightA + heightB
                                )      
                                return true;
                               
                        return false;
                }


public static
        boolean isColliding(Sprite A, Sprite B)
        {
                Vector2f
                        vA1 = A.getPosition(), vA2 = A.getOrigin(),
                        vB1 = B.getPosition(), vB2 = B.getOrigin();
                       
                float
                        vAdtx = vA2.x - vA1.x,
                    vAdty = vA2.y - vA1.y,
                   
                    vBdtx = vB2.x - vB1.x,
                    vBdty = vB2.y - vB1.y;
                   
               
                        vA2 = new Vector2f(vA1.x, vA1.x + 2*vAdtx);
                        vB2 = new Vector2f(vB1.x, vB1.x + 2*vBdtx);
               
                return isColliding(vA1, vA2, vB1, vB2);
        }
       
       
public static
        boolean isColliding(Sprite A, Sprite[] sprites)
        {
                for (Sprite sprite : sprites)
                        if (isColliding( sprite, A) == true ) return true;
                return false;
        }
}


//################################################
//################################################
 
class Bricks  implements  IGetSprites, IDrawRenderWindow
{
        ArrayList<Sprite>     bricks;
        //ArrayList<FloatRect>  rectangles;
       
        ImageLoader           image;
        Texture               texture;
       
public
        Bricks(ImageLoader  image, String mapFile)
        {
                this.image  = image;
                bricks          = new ArrayList<Sprite>();
                       
                loadMapFile(mapFile);
        }
       
       
        private void loadMapFile(String map)
        {
                Vector2i v = image.getTexture().getSize();
               
                try
                {
                        Scanner scanner = new Scanner( new File(map) );
                       
                        for (int x=0; x<7; ++x)
                        {
                                String line = scanner.nextLine();
                               
                                for (int y=0; y<7; ++y)
                                        if (line.charAt(y)!='.')
                                                bricks.add( image.copySprite( (1+x)*v.x,(1+y)*v.y) );
                                               
                        }
                        //rectangles = new ArrayList<FloatRect>();
                                               
                }
                catch(Exception e)
                {
                        e.printStackTrace();
                }
        }
       
       
       
        @Override
        public
                Sprite[]  getSprites()
                {
                        int s = bricks.size();
                        Sprite[] ret = new Sprite[s];
                       
                        for (int i=0; i<s; ++i) ret[i] = bricks.get(i);

                        return ret;    
                }
               
        @Override
        public
                void draw(RenderWindow  rw)
                {
                        for (Sprite sprite : bricks)  rw.draw(sprite);
                }
}
 
//################################################
//################################################

class FramedAnimation implements IGetSprites, IDrawRenderWindow
{
        ArrayList<ImageLoader>  frames;
       
        Clock                   clock;
       
        int                                     x, y, current, timePerFrame;
       
       
public
        FramedAnimation(String []imgFiles, SpriteType spriteType)
        {
                frames  = new ArrayList<ImageLoader>();
                current = 0;
               
                for (int i=0; i<imgFiles.length; ++i)
                        frames.add(new ImageLoader(imgFiles[i],spriteType) );
                       
                setTimePerFrame(1000);
        }
       
       
public
        FramedAnimation(String []imgFiles, SpriteType spriteType, int x, int y)
        {
                this(imgFiles, spriteType);
                this.setXY(x,y);
        }
       
public
        FramedAnimation(ArrayList<ImageLoader>  frames)
        {
                this.frames = frames;
                current = 0;
                setTimePerFrame(1000);
        }
       
               
        public void setTimePerFrame(int  msTimePerFrame)
        {
                if (clock == null) clock = new Clock();
                timePerFrame = msTimePerFrame;
                clock.restart();
        }
               
       
        public void setXY(int x, int y)
        {
                for (ImageLoader  image  :  frames)  image.setXY(x,y);
        }
       
       
        private void setFrame()
        {
                if (clock.getElapsedTime().asMilliseconds() >= timePerFrame)
                {
                        current++;
                        clock.restart();
                }
                if ( current >= frames.size() ) current = 0;
        }
       
       
        @Override    //IGetSprites
        public
                Sprite[]  getSprites()
                {
                        setFrame();
                       
                        Sprite sprite = frames.get(current).getSprite();
                        sprite.setPosition(x,y);
               
                        return new Sprite[]{ sprite };
                }
               
               
        @Override //IDrawRenderWindow
        public
                void draw(RenderWindow rw)
                {
                        for (Sprite sprite : getSprites()) rw.draw(sprite);
                }
}

//################################################
//################################################

class Background implements IGetSprites, IDrawRenderWindow
{
        FramedAnimation             frames;
        Vector2i                            vsize;
        Time                                    lastUpdate;
       
       
public
        Background(FramedAnimation  animation, int  msPerFrame)
        {
                frames = animation;
                frames.setTimePerFrame(msPerFrame);
        }
       
       
        @Override    //IGetSprites
        public
                Sprite[]  getSprites()
                {
                        Sprite []sprites = frames.getSprites();
                       
                        vsize = sprites[0].getTexture().getSize();
                       
                        ArrayList<Sprite>  background  =  new ArrayList<Sprite>();
                       
                        int index=0;
                       
                        for (int x=0;  x<800+vsize.x;  x+=vsize.x)
                                for (int y=0;  y<600+vsize.y;  y+=vsize.y)
                                {
                                        if (index == sprites.length-1) index=0; else index+=1;
                                       
                                        Sprite sp = new Sprite( sprites[index].getTexture() );
                                        sp.setPosition(x,y);
                                       
                                        background.add( sp );
                                }
                        return background.toArray( new Sprite[ background.size() ] );
                }
                       
                       
        @Override //IDrawRenderWindow
        public
                void draw(RenderWindow rw)
                {
                        for ( Sprite sprite : this.getSprites() )  rw.draw(sprite);
                }
}

//################################################
//################################################

class Player     implements IGetSprites
{
        ImageLoader  image;
        Vector2i     last, vleft, vright, vup, vdown;
       
        Sprite[]     bricks;
       
        int          speed;

public
        Player(ImageLoader  loader, int startx, int starty, int speed)
        {
                image = loader;
                image.setXY(100,100);
               
                last = new Vector2i(100,100);
               
                this.speed = speed;
        }
       
       
        public void setBricksMap(Sprite[]  safeZone)
        {
                this.bricks = /*new ArrayList<Sprite>( */ safeZone; /* );*/
        }
       
       
        /*
         * this code should checks collisions!
         */

        public void tryMoveTo(Vector2f  newPosition)
        {

                FloatRect  pos   = image.getSprite().getLocalBounds();
                Vector2i   vi    = new Vector2i(newPosition);
               
                if (vi.x> 800 || vi.x<0 || vi.y>600-pos.top || vi.y<pos.height) return;
               
                if (SafeZone.isColliding(image.getSprite(), bricks) == true)
                {
                        System.out.println("KOLIZJA");
                        return;
                }
               
                image.setXY(vi.x, vi.y);
               
                last = vi;
        }
       
       
        public void nextMove(Time dt, KeybAction  action)
        {
                if (action == KeybAction.none) return;
               
                float fmove = (dt.asMicroseconds() * speed)/5000;
               
                switch (action)
                {
                        case left  : tryMoveTo(new Vector2f(last.x -fmove, last.y)); break;
                        case right : tryMoveTo(new Vector2f(last.x +fmove, last.y)); break;
                        case up    : tryMoveTo(new Vector2f(last.x, last.y -fmove)); break;
                        case down  : tryMoveTo(new Vector2f(last.x, last.y +fmove)); break;
                }
        }
       
       
        @Override // IGetSprites
        public
                Sprite[] getSprites()
                {
                        return new Sprite[]{ image.getSprite() };
                }

}


                 
            /** ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                 
                                                GAME`S MAIN LOOP
                 
                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ **/



class GameLoop
{

        //internal helper class
        class World
        {
                ArrayList<Sprite>  list;// list of sprites to be drawn
                RenderWindow       window;
               
                public
                        World(RenderWindow renderWindow)
                        {
                                list = new ArrayList<Sprite>();
                               
                                this.window = renderWindow;
                        }
                       
                       
                public
                        void add(IGetSprites  toBeDrawn) //adds by interface
                        {
                                if (toBeDrawn==null) return;
                               
                                Sprite []sprites = toBeDrawn.getSprites();
                               
                                if (sprites==null || sprites.length == 0) return;
                               
                                this.add(sprites);
                        }
               
                       
                public
                        void add(Sprite[]  sprites) //adds by array
                        {
                                for (Sprite s : sprites) list.add(s);
                        }
               
                       
                public
                        void clear()
                        {
                                list.clear();
                        }
               
                       
                public
                        void render(RenderWindow rw)
                        {
                                rw.clear();
                               
                                for (Sprite s : list) rw.draw(s);
                                       
                                rw.display();
                                this.clear();
                        }
                       
                public
                        void render()
                        {
                                render(window);
                        }
                       
                public
                        void close()
                        {
                                this.clear();
                                //window.clear();
                                window.close();
                        }              
        }

                                                                        /* - - - -
                                        GameLoop`s interface
                          - - - - */

 
        FloatRect     bounds;
        World             world;
       
        Background    background;
        Bricks        bricks;
        Player        player;
       
        Time              timePerFrame;
       
        RenderWindow  window;
       
        String            mediaDirPath;
        boolean       isRun;
       
       
                                                /*  ~  ~  ~
                                                        IMPLEMENTATION
                                                                           ~  ~  ~  */

       
public
        GameLoop(String mediaDirPath)
        {
                this.mediaDirPath = mediaDirPath;
               
                timePerFrame = Time.getSeconds(1.0f / 60.0f);
               
                bounds     = new FloatRect(new IntRect(0, 0, 800, 600));
                window     = new RenderWindow(new VideoMode(800,600), "GameFromScratch");
               
                background = new Background
                                   (    new FramedAnimation
                                                (       new ArrayList<ImageLoader>
                                                        (    Arrays.asList
                                                                 (      new ImageLoader[]
                                                                        {
                                                                                new ImageLoader("C:\\PROJ\\Media\\Maps\\map1.png",SpriteType.BACK),
                                                                                new ImageLoader("C:\\PROJ\\Media\\Maps\\map2.png",SpriteType.BACK),
                                                                                new ImageLoader("C:\\PROJ\\Media\\Maps\\map3.png",SpriteType.BACK),
                                                                                new ImageLoader("C:\\PROJ\\Media\\Maps\\map4.png",SpriteType.BACK),
                                                                        }
                                                                 )
                                                        )      
                                                ),
                                                250 //ms per frame
                                   );
               
                bricks     = new Bricks
                                   (
                                                new ImageLoader
                                                        (
                                                                "c:\\PROJ\\MEDIA\\Maps\\map1.png",
                                                                SpriteType.BRICK
                                                        ),
                                                "C:\\PROJ\\Media\\Maps\\map1.txt"
                                   );
                                   
                player     = new Player
                                   (
                                                new ImageLoader
                                                (
                                                        mediaDirPath+"\\Textures\\player2.png",
                                                        SpriteType.PLAYER
                                                ),
                                                100, //startX
                                                100, //startY
                                                5    //speed
                                   );
                player.setBricksMap(bricks.getSprites());
        }
       
       
        private KeybAction  getKey()
        {
                for (Event event : window.pollEvents())
        {
            if (Keyboard.isKeyPressed(Keyboard.Key.LEFT))  return KeybAction.left;
            if (Keyboard.isKeyPressed(Keyboard.Key.RIGHT)) return KeybAction.right;
            if (Keyboard.isKeyPressed(Keyboard.Key.UP))    return KeybAction.up;
            if (Keyboard.isKeyPressed(Keyboard.Key.DOWN))  return KeybAction.down;
           
            if (event.type == Event.Type.CLOSED) return KeybAction.esc;
           
            if (Keyboard.isKeyPressed(Keyboard.Key.ESCAPE)) return KeybAction.esc;

        }
        return KeybAction.none;
        }
       
       
        public void playGame()
        {
                Clock clock      = new Clock();
        Time  lastUpdate = Time.ZERO;
                       
                window  = new RenderWindow(new VideoMode(800,600),"JSFML RenderTest");
                world   = new World(window);
               
                isRun   = true;
               
                window.setFramerateLimit(60);
                window.setKeyRepeatEnabled(true);

                KeybAction key = KeybAction.none;
               
                while( window.isOpen() )
                {
                        Time dt    = clock.restart();
            lastUpdate = Time.add(lastUpdate, dt);
                     
            while (lastUpdate.asMicroseconds() > timePerFrame.asMicroseconds())
            {
                lastUpdate = Time.sub(lastUpdate, timePerFrame);

                                key = getKey();

                player.nextMove(lastUpdate, key);
               
                if (key==KeybAction.esc) window.close();
            }
     
                world.add(background);
            world.add(player);
            world.add(bricks);
           
            world.render();
                }
                world.close();
        }
}
 


/**
 * Run
 */

public class GameFromScratch
{
    public static void main(String[] args)
    {
        INFO.MEDIA_DIR = "C:\\PROJ\\Media";
       
        System.out.println("tak");
       
        GameLoop game = new GameLoop(INFO.MEDIA_DIR);
        game.playGame();
    }
}
 

Can anybody help? In attachments media for game.

I know that code should be separatet etc, I`ll tidy it in near future. I'm planning to create tutorial about JSFML, it's f.. amazing lib!

5
Java / Re: [Solved] Why walls (bricks) are not displayed?
« on: March 13, 2015, 06:34:47 pm »
I would spend a lot of time unless Your help. Very big Thanx !!!

6
Java / [Solved] Why walls (bricks) are not displayed?
« on: March 13, 2015, 04:39:46 pm »
Local variable`s declaration hided field which should have stored brick-spirte

Hello :)

I am writing little game from scratch. Everything went ok till i met big problem:

/**
 * @(#)GameFromScratch.java
 *
 * GameFromScratch application
 *
 * @author #cx3#
 * @version 1.00 2015/3/7
 */

 
import org.jsfml.graphics.RenderWindow;
import org.jsfml.graphics.Text;
import org.jsfml.graphics.*;
import org.jsfml.system.Clock;
import org.jsfml.system.Time;
import org.jsfml.window.VideoMode;
import org.jsfml.window.WindowStyle;
import org.jsfml.window.event.Event;
import org.jsfml.graphics.Color;
 
import org.jsfml.graphics.Font;
import org.jsfml.graphics.Texture;
import org.jsfml.graphics.Sprite;
import org.jsfml.system.*;

import org.jsfml.system.Time;
import org.jsfml.system.Vector2f;
import org.jsfml.window.Keyboard;
import org.jsfml.window.event.Event;

import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;

import java.io.IOException;
import java.util.HashMap;

import java.nio.file.Paths;
import java.io.FileInputStream;
import java.io.File;

import java.nio.file.*;
import java.util.ArrayList;


import java.io.IOException;
import java.io.*;



import java.nio.file.Paths;
import java.io.FileInputStream;

import java.lang.Number;

/**
 * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
 * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
 * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
 */


enum KAction { left,right,up,down,none };


class INFO
{
        public static String MEDIA_DIR;
        public static Bricks BRICKS;
        public static RenderWindow GAMEWINDOW;
}


/**
 * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
 */


interface IFramePart
{
        public Sprite[] getSprites();
}

 
class ImageLoader
{
        Texture texture = new Texture();
        Sprite  sprite = new Sprite();
        Image   image = new Image();
        String  name;
       
        int x,y;
       
       
        private ImageLoader()
        {
        }
       
       
        public ImageLoader(String spritePath, String name)
        {
                this.name =  name;
               
                try
                {
                        texture.loadFromFile(Paths.get(spritePath));   
                        texture.setRepeated(true);
                        sprite  = new Sprite(texture);         
                        image = texture.copyToImage();
                }
                catch  (Exception e)
                {
                        e.printStackTrace();
                }
        }
       
       
        /*
        public ImageLoader  copy()
        {
                ImageLoader ret = new ImageLoader();
                ret.texture = new Texture(this.texture);
                //ret.texture = this.texture;
                ret.sprite  = new Sprite();
                ret.sprite  = this.sprite;
                ret.image   = new Image();
                ret.image   = this.image;
                ret.x       = this.x;
                ret.y       = this.y;
               
                return ret;
        }*/

       
       
        public Sprite  copySprite()
        {
                Texture tx = new Texture(texture);
                tx.setRepeated(true);
                return new Sprite(sprite.getTexture());
        }
       
       
        public void setX(int x){ this.x = x;}
        public void setY(int y){ this.y = y;}
       
        public void setXY(int x, int y)
        {
                setX(x); setY(y);
        }
       

        public Sprite  getSprite()
                {
                        sprite.setPosition(x,y);
                        return sprite;
                }
               
        public Image  getImage()
                {
                        return image;
                }
               
        public Texture getTexture()
                {
                        return texture;
                }
}

/**
 * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
 * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
 * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
 */

 
 
class Bricks implements IFramePart
{
        ArrayList<Sprite>  bricks;// = new ArrayList<Vector2i>();
       
        ImageLoader image;
        Texture     texture;
       
       
        /**
         * IMO here problem is
         */

        public
                Bricks(String imgPath, String mapFile)
                {
                        image = new ImageLoader("c:\\PROJ\\MEDIA\\Textures\\player.png","bricks");     
                       
                        image.setXY(300,300);
                       
                        Sprite s = new Sprite(image.getTexture());
                        s.setPosition(300,300);
                       
                        bricks = new ArrayList<Sprite>();
                       
                        bricks.add(s);
                       
                        //loadMapFile(mapFile);
                }
       
private
        void loadMapFile(String map)
        {
               
        }      
       
       

        @Override
        public
                Sprite[]  getSprites()
                {
                        int s = bricks.size();
                        Sprite[] ret = new Sprite[s];
                       
                        for (int i=0; i<s; ++i)
                        {
                                ret[i] = bricks.get(i);
                                //ret[i].setPosition(points.get(i).x, points.get(i).y);
                                //ret[i].setOrigin(points.get(i).x+20, points.get(i).y+20);
                                //ret[i].setScale(1,1);
                        }
                        return ret;    
                }
               
       
}
 
 
 /**
 * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
 * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
 * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
 */



class Player implements IFramePart
{
        ImageLoader  il;
        Vector2i     last, vleft, vright, vup, vdown;
       
       
        /*
         * Load player`s setting at beginning
         */

        public Player(ImageLoader  loader)
        {
                il = loader;
                il.setXY(100,100);
               
                last = new Vector2i(100,100);
               
                vleft  = new Vector2i(-1,0); //unused yet
                vright = new Vector2i(1,0);
                vup    = new Vector2i(0,1);
                vdown  = new Vector2i(0,-1);
        }
       
       
       
        /*
         * this code should checks collisions!
         */

        public void tryMoveTo(Vector2i  newPosition)
        {
                //in near futture check collisions here
               
                il.setXY(newPosition.x, newPosition.y);
               
                last = newPosition;
                //return true;
        }
       
       
        public void nextMove(Time dt, KAction  action)
        {
                if (action == KAction.none) return;
               
                switch (action)
                {
                        case left  : tryMoveTo(new Vector2i(last.x -1, last.y) ); break;
                        case right : tryMoveTo(new Vector2i(last.x +1, last.y) ); break;
                        case up    : tryMoveTo(new Vector2i(last.x, last.y -1) ); break;
                        case down  : tryMoveTo(new Vector2i(last.x, last.y +1) ); break;
                }
        }
       
        @Override
        public Sprite[] getSprites()
        {
                return new Sprite[]{il.getSprite()};
        }
       
}


/**
 * Class responsible for a game loop
 */


class GameLoop
{

        /*
         * Internal helper class
         */


        private class Animation
        {
                ArrayList<Sprite>  list;// list of sprites to be drawn
               
               
                public
                        Animation()
                        {
                                list   =  new ArrayList<Sprite>();
                        }
                       
                       
                public
                        void add(IFramePart  toBeDrawn) //adds by interface
                        {
                                if (toBeDrawn==null) return;
                                Sprite []sprites = toBeDrawn.getSprites();
                               
                                if (sprites==null || sprites.length == 0) return;
                                for (Sprite s: sprites) list.add(s);
                        }
               
                       
                public
                        void add(Sprite[]   sprites)
                        {
                                for (Sprite s : sprites) list.add(s);
                        }
               
                       
                public
                        void clear()
                        {
                                list.clear();
                        }
               
                       
                public
                        void render(RenderWindow rw)
                        {
                                //RenderWindow r = INFO.GAMEWINDOW;
                                rw.clear();
                               
                                for (Sprite s : list) rw.draw(s);
                                       
                                rw.display();
                                list.clear();
                        }      
               
        }


/*
 * Body of a GameLoop class
 */

 
       
        Animation         anim;
        FloatRect     bounds;
       
        Player        player;
       
        Time timePerFrame;// = Time.getSeconds(1.0f / 60.0f);
       
        RenderWindow window;
        Bricks       bricks;
       
        String mediaDirPath;
       
       
        /* IMPLEMENTATION*/
       
       
        public GameLoop(String mediaDirPath)
        {
                this.mediaDirPath = mediaDirPath;
               
                timePerFrame = Time.getSeconds(1.0f / 60.0f);
               
                bounds = new FloatRect(new IntRect(0, 0, 800, 600));
                window = new RenderWindow(new VideoMode(800,600), "GameFromScratch");
               
                player = new Player(new ImageLoader(mediaDirPath+"\\Textures\\player2.png","player"));
               
                Bricks bricks = new Bricks("C:\\PROJ\\Media\\Textures\\player.png",mediaDirPath+"\\Maps\\map1.txt");
        }
       
       
        private KAction  getKey()
        {
                for (Event event : window.pollEvents())
        {
            if (event.type == Event.Type.CLOSED)     window.close();
           
            if (Keyboard.isKeyPressed(Keyboard.Key.LEFT))  return KAction.left;
            if (Keyboard.isKeyPressed(Keyboard.Key.RIGHT)) return KAction.right;
            if (Keyboard.isKeyPressed(Keyboard.Key.UP))    return KAction.up;
            if (Keyboard.isKeyPressed(Keyboard.Key.DOWN))  return KAction.down;
        }
        return KAction.none;
        }
       
       
        public void play()
        {
                Clock clock = new Clock();
        Time lastUpdate = Time.ZERO;
                       
                window = new RenderWindow(new VideoMode(800,600),"SFML");
                anim   = new Animation();
               
                while(window.isOpen())
                {
                        Time dt = clock.restart();
            lastUpdate = Time.add(lastUpdate, dt);
           
            //window.clear();
           
            while (lastUpdate.asMicroseconds() > timePerFrame.asMicroseconds())
            {
                lastUpdate = Time.sub(lastUpdate, timePerFrame);

                player.nextMove(lastUpdate, getKey());
            }
       
            anim.add(player);
            anim.add(bricks);
           
            anim.render(window);
                }
        }
}
 


/**
 * Run
 */

public class GameFromScratch
{
    public static void main(String[] args)
    {
        INFO.MEDIA_DIR = "C:\\PROJ\\Media";
       
        GameLoop  game = new GameLoop(INFO.MEDIA_DIR);
        game.play();
    }
}

 

Can anybody explain me what i did wrong? Player is displayed and can be moved. I want to make some wall, bricks (name does not matter), but it does not want to be drawn. Why?

7
Java / Re: SFML book source code port
« on: March 06, 2015, 11:39:43 pm »
Please join my posts :)

Basing on Chapter 5 of Kalimatas code, I am trying to add walls that does not to allow to cross them.

/**
/**
 * @(#)GameMap.java
 *
 *
 * @author cx3
 * @version 1.00 2015/3/6
 */



package com.github.kalimatas.c05_States;

import org.jsfml.graphics.Texture;
import org.jsfml.graphics.RenderWindow;
import org.jsfml.system.Vector2f;
import org.jsfml.graphics.Sprite;
import org.jsfml.system.Vector2i;
import org.jsfml.graphics.ConstTexture;
import org.jsfml.graphics.RenderTarget;
import org.jsfml.graphics.RenderStates;
import org.jsfml.graphics.Transform;
import org.jsfml.system.Time;

import java.nio.file.*;
import java.util.ArrayList;

import java.io.IOException;
import java.io.*;
//import java.util.HashMap;

import java.nio.file.Paths;
import java.io.FileInputStream;

import java.lang.Number;


class Block
{
        public char     type;
        public Vector2i vec;
       
        public Block(){type='.'; vec = new Vector2i(0,0); }
       
        public Block(char btype, Vector2i vector){ type=btype; vec=vector;}
       
        public char     getLeft() { return type;  }
        public Vector2i getRight(){ return vec; }
}



public class GameMap //extends SceneNode//implements org.jsfml.graphics.Drawable
{
        Texture                      wallBlock;
        ArrayList<Block>     gameMap = new ArrayList<Block>();;
        RenderWindow             window;


        public
                GameMap(){}


public
        GameMap(String  mapPath, String  blockImagePath)
    {
        try
            {
                wallBlock = new Texture();
                wallBlock.loadFromStream(new FileInputStream(new File(blockImagePath)));
           
                File file = new File(mapPath);
               
                    FileInputStream fis         = null;
                    BufferedInputStream bis = null;
                    DataInputStream dis         = null;
       
           
                        fis = new FileInputStream(file);
                       
                        // Here BufferedInputStream is added for fast reading.
                        bis = new BufferedInputStream(fis);
                        dis = new DataInputStream(bis);
                       
                        String
                                xs   = dis.readLine()
                                ys   = dis.readLine();
                                       
                        int
                                x = Integer.parseInt(xs),
                                y = Integer.parseInt(ys);
                       
                        for (int i=0; i<x; ++i)
                        {
                                String s = dis.readLine();
                               
                            for (int j=0; j<s.length(); ++j)
                                gameMap.add
                                ( new Block
                                          (
                                               s.charAt(j),
                                                   new Vector2i(0+i*128, 0+j*72)
                                          )
                                 );
                              }
                       
                              // dispose all the resources after using them.
                              fis.close();
                              bis.close();
                              dis.close();
       
            } catch (Exception e){
           
              e.printStackTrace();
            }
    String s2 = "LOADED: "+gameMap.size()+" blocks";
    try{throw new RuntimeException(s2);}catch(Exception e){e.printStackTrace();}
    }
   
    /*
    public void setWindow(RenderWindow rewi)
    {
        window = rewi;
    }*/

   
   
    /*@Override
    public final void draw(RenderTarget target, RenderStates states)
    {
        // Apply transform of current node
        RenderStates rs = new RenderStates(states, Transform.combine(states.transform, getTransform()));

        // Draw node and children with changed transform
        drawCurrent(target, rs);
        drawChildren(target, rs);
    }*/

 
 
  /*
    //@Override
    public void draw(RenderTarget target, RenderStates states)
    {
        for (Block block : gameMap)
        {
                if (block.getLeft()!='.')
                {
                        Sprite s = new Sprite(wallBlock);
                        Vector2i v = block.getRight();
                        s.setOrigin(new Vector2f(v.x, v.y));
                        s.setPosition(new Vector2f(v.x, v.y));
                       
                        target.draw(s);
                        /*RenderStates rs = new RenderStates
                                (
                                        states,
                                        Transform.combine
                                                (
                                                        states.transform, getTransform()
                                                )
                                );*/

                }
        }
    }*/
   
    public void draw2(RenderWindow r)
    {
        for (Block block : gameMap)
        {
                if (block.getLeft()!='.')
                {
                        Sprite s = new Sprite(wallBlock);
                        Vector2i v = block.getRight();
                        s.setOrigin(v.x, v.y);
                        s.setPosition(v.x, v.y);
                       
                        r.draw(s);
                        /*RenderStates rs = new RenderStates
                                (
                                        states,
                                        Transform.combine
                                                (
                                                        states.transform, getTransform()
                                                )
                                );*/

                }
        }
    }
   
}
   
 

This is one of various tests i made, none of them works. Even if i had working class that displays map well, where in game loop while(window.isOpen()) should I write code to be run correctly with all scenes? I feel myself like i saw programming first time, lol. Please help :)

edit:
After some editing of code, at World`s class (World.java) in method adaptPlayerVelocity(..)

i wrote as a last line: 
Code: [Select]
Application.GAME_MAP.draw2(this.window);
Application`s has field GAME_MAP which is public static GameMap.

Result: draws only one block in left up corner of scrollable world, instead of correct position that are stored in text file:

Code: [Select]
7
5
...x...
...x...
...x...
...x...
...x...

7 - seven sprites in row, only x is to be drawn
5 - five rows

--------

I want achieve an effect that world is scrolled but loaded map is constant - background is animated and does not influence for player or enemies - I will implement enemies in next years without a sleep ;p

8
Java / Re: SFML book source code port
« on: February 27, 2015, 08:16:08 am »
Your code... OMG! Something i always needed. Really nice, elegant and clear. Very easy to extend! Artwork

9
Java / From JTextField to JSFML RenderWindow
« on: February 19, 2015, 09:45:04 pm »
Hello :)

I'm trying to write an application that is based on JFrame (JTextArea, JTextField, JButton) as a console components. JButton has event as private class implementing ActionListener`s method actionPerformed, an instance of RenderWindow is kept in JFrame`s extended class as a private field.

For instance client of an application writes "circle 30 150 200" clicks enter or presses JButton, and it should draw a circle in RenderWindow (it should not create new instance for any command). I tried various combinations without visible effects. Please help :)

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

import java.util.*;
import java.lang.Object;

import java.nio.file.*;


import org.jsfml.graphics.*;
import org.jsfml.graphics.Color;
import org.jsfml.graphics.RenderWindow;
import org.jsfml.window.VideoMode;
import org.jsfml.window.event.Event;
import org.jsfml.graphics.Texture;
import org.jsfml.graphics.Shader.Type;
import org.jsfml.system.Clock;
import org.jsfml.system.Vector2f;
import org.jsfml.window.*;
import org.jsfml.window.event.MouseWheelEvent;


class JSFML_Frame extends JFrame //implements Runnable
{

        private JTextField     text;
       
        private JPanel         panel;
        private JTextArea      area;
        private JScrollPane    scroll;
       
        org.jsfml.graphics.Shape shape;

        RenderWindow               rw;
       
        /*internal helper class for JButton in JSFML c-tor*/
        class  ButtonOnClick   implements ActionListener
        {              
                //RenderWindow rw;
               
                public ButtonOnClick(/*RenderWindow  rw_arg*/)
                {
                //rw = rw_arg;
                }
               
                @Override
                public void actionPerformed(ActionEvent  ae)
                {
                        String s = text.getText();
                       
                        area.append("JSFML>" s+"\n");
                        //rw.clear(Color.BLACK);
                       
                        if (s.equals("circle"))
                        {
                                CircleShape circle = new CircleShape(30,30);
                                circle.setOrigin(50,50);
                                circle.setRadius(30);
                                circle.setFillColor(Color.GREEN);
                               
                                //shape = circle;
                               
                                rw.clear();
                                rw.draw(circle);
                                rw.display();
                        }
                        //rw.display();
                       
                }
        }
                       
       
        public JSFML_Frame()   
        {      
                rw = new RenderWindow( new VideoMode(800,600), "JSFML" );
                //shapeToDraw = new CircleShape();
       
                setTitle("JSFML_Frame  command manager");
                setSize(375,175);
               
                Container ctr    = getContentPane();
                JButton   button = new JButton("Enter");
                       
                panel = new JPanel();
                text  = new JTextField(20);
               
                panel.add(text);
                panel.add(button);
                       
                button.addActionListener(       new ButtonOnClick()    );
               
                area    = new JTextArea(8, 40);
                scroll  = new JScrollPane(area);
               
                area.setEditable(false);
                area.setFont(new java.awt.Font("SansSerif" ,java.awt.Font.BOLD, 16));
                       
                ctr.add(panel, BorderLayout.SOUTH);
                ctr.add(area, BorderLayout.CENTER);
                       
                setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                setVisible(true);
                Sprite   sprite = new Sprite();;
                try
                {
                        Texture texture = new Texture();
                        texture.loadFromFile( Paths.get("code.jpg") );
                        sprite = new Sprite( /*(ConstTexture)*/ texture );
                }
                catch(Exception e){}
                rw.setFramerateLimit(30);
                //fWindow.setVerticalSyncEnabled(false);
                Clock frameClock = new Clock();
               
       
                while (rw.isOpen())
                {
                        rw.clear(Color.BLACK);
                        rw.draw(sprite);
                        //if (shape!=null)  rw.draw(shape);
                        rw.display();
                                       
                        for (Event event : rw.pollEvents())    
                                switch (event.type)
                                {
                                        case CLOSED:  { rw.close(); return; }
                                               
                                        case MOUSE_WHEEL_MOVED:
                                        {      
                                                Random r = new Random(9);
                                               
                                                float dt = frameClock.restart().asSeconds();   
                                               
                                                rw.clear(Color.BLACK);
                                                sprite.rotate(dt*45);
                                                rw.draw(sprite);
                                                rw.display();
                                        }
                                }
                                       
                }
        }
                               
}

//...
 

And second question. From time to time I do not use any IDE for Java. How to compile project using command line?

10
DotNet / SFML & Visual Studio 2013 Express FOR WEB - possible?
« on: July 08, 2014, 02:19:58 am »
Helo :) Forgive me if similar topic went somewhere in the forum and i did not see it.

Is it possible somehow to configure Web-based project to work with SFML? I am very new to .NET. I understand that web-based projects are "little bit" another than usual applications for Windows, but maybe [i believe] there is any possibility to create browser applications? Please tell me it is, please :)

11
Java / NetBeans + jSFML, linker error at first project
« on: January 19, 2014, 07:14:02 am »
Hello :) I am new here. From time to time i write a little app in C++ using SFML and this library is really great!

Because i started to learn Java recently, i decided that it would be great idea to create an applet which uses jSFML. I downloaded NetBeans, run it and configured as it is written in tutorial at https://github.com/pdinklag/JSFML/wiki .The first step, setup, brought me some troubles that i resolved with Google. I created a catalog "c:\java"  where i put all my projects in separated catalogs. With NetBeans i created new java project, and set up the classpath to jar file (c:\java\Game\lib\jsfml.jar). I tried all three enabled options with RadioButtons (relative path / copy libraries, absolute path), i found also various proposals of adding another params for "run" category - i've been trying to compile source code for about eight hours with one big fail :)

Windows XP, SP3

Game.java
package game;

import org.jsfml.graphics.RenderWindow;
import org.jsfml.graphics.*;
import org.jsfml.audio.Music;
import org.jsfml.window.VideoMode;
import org.jsfml.window.event.Event;

import java.io.IOException;
import java.nio.file.Paths;


public class Game {

    /**
     * @param args the command line arguments
     */

    public static void main(String[] args) {
       
        RenderWindow window = new RenderWindow();
        window.create(new VideoMode(640, 480), "Hello JSFML!");

        //Limit the framerate
        window.setFramerateLimit(30);

        //Main loop
        while(window.isOpen()) {
            //Fill the window with red
            window.clear(Color.RED);

            //Display what was drawn (... the red color!)
            window.display();

            //Handle events
            for(Event event : window.pollEvents()) {
                if(event.type == Event.Type.CLOSED) {
                    //The user pressed the close button
                window.close();
                }
            }
        }  
    }
   
}

 

and linker errors:

run:
Exception in thread "main" java.lang.UnsatisfiedLinkError: C:\Documents and Settings\cx3\.jsfml\windows_x86\sfml-system-2.dll: Can't find dependent libraries
        at java.lang.ClassLoader$NativeLibrary.load(Native Method)
        at java.lang.ClassLoader.loadLibrary1(ClassLoader.java:1965)
        at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1890)
        at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1851)
        at java.lang.Runtime.load0(Runtime.java:795)
        at java.lang.System.load(System.java:1062)
        at org.jsfml.internal.SFMLNative.loadNativeLibraries(Unknown Source)
        at org.jsfml.internal.SFMLNativeObject.<init>(Unknown Source)
        at org.jsfml.window.Window.<init>(Unknown Source)
        at org.jsfml.graphics.RenderWindow.<init>(Unknown Source)
        at game.Game.main(Game.java:26)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
 

I saw several similar topis to mine, but none of them gave any explanation what is going wrong.
I am beginner in Java so i please for forbearance :)

Greetz

Pages: [1]