In my view something unwanted shows up - android

I am building a snake game app.
So fur it works, except for the what it shows.
For some reason it shows two snakes: the original snake that moves and can be controlled, and another begginging of a snake that doesn't do anything.
Before that I drew at every cycle in the loop a background color, so it would cover the last canvas, and there was no problem.
Then I decided to divide the snake from the background, so I have made the snake canvas's background transparent and that it would clear the canvas each time it wants to draw a new canvas (each loop-to move the snake).
Here is the code:
The run of the thread:
public void run() {
long stepPerSecond=1000/FPS;
long startTime;
long sleepTime;
while(isRunning){
Canvas c=null;
startTime=System.currentTimeMillis();
try{
c=this.getHolder().lockCanvas();
synchronized (this.getHolder()) {
this.onDraw(c);
}
}
catch(Exception e){
}
finally{
if(c!=null){
this.getHolder().unlockCanvasAndPost(c);
}
}
sleepTime= stepPerSecond-(System.currentTimeMillis()-startTime);
if(sleepTime>0)
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The snake's ondraw (it uses the snake's class on draw):
public void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
canvas.drawColor(color.transparent, Mode.CLEAR);
snake.onDraw(canvas);
}
The snake's class onDraw:
public void onDraw(Canvas canvas){
switch(dirTransfare(dir)){
case 1://RIGHT
xLoc=xLoc+PART_SIZE;
break;
case 2://UP
yLoc=yLoc-PART_SIZE;
break;
case -1://LEFT
xLoc=xLoc-PART_SIZE;
break;
case -2://DOWN
yLoc=yLoc+PART_SIZE;
break;
}//swich
int x=xLoc;
int y=yLoc;
for(Brick bp:SnakeBody){
bp.setR(0+x, 0+y, PART_SIZE+x, PART_SIZE+y);
canvas.drawRect(bp.getR(),bp.getP());
int xtemp=bp.getX();
int ytemp=bp.getY();
bp.setX(x);
bp.setY(y);
x=xtemp;
y=ytemp;
}//for each
}//onDraw
Here is the mainActivity, which summons the snakeVew and the backgorundView (snake is the game view and the background is the arena)
public class MainActivity extends Activity {
GameView gv;
ImageView left;
ImageView right;
ImageView up;
ImageView down;
Arena a;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*requestWindowFeature(Window.FEATURE_NO_TITLE);
v= new GameView1(this);
setContentView(v);
*/
gv= new GameView(this);
a=new Arena(this);
setContentView(R.layout.game_view);
LinearLayout surface = new LinearLayout(this);
LinearLayout backGround = new LinearLayout(this);
surface = (LinearLayout)findViewById(R.id.surface);
backGround = (LinearLayout)findViewById(R.id.background);
surface.addView(gv);
backGround.addView(a);
left=(ImageView) findViewById(R.id.left);
right=(ImageView) findViewById(R.id.right);
up=(ImageView) findViewById(R.id.up);
down=(ImageView) findViewById(R.id.down);
left.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(gv.snake.getDir()!="LEFT"&&gv.snake.getDir()!="RIGHT"){
gv.snake.Left();
}
}
});
right.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(gv.snake.getDir()!="RIGHT"&&gv.snake.getDir()!="LEFT"){
gv.snake.Right();
}
}
});
up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(gv.snake.getDir()!="UP"&&gv.snake.getDir()!="DOWN"){
gv.snake.Up();
}
}
});
down.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(gv.snake.getDir()!="DOWN"&&gv.snake.getDir()!="UP"){
gv.snake.Down();
}
}
});
}
The problem is not in the background (the arena class); I have alredy took it down and confirmed that (it worked the same away, with the bug, even without using the arena class).
Here is how it looks with the bug:
http://i.tinyuploads.com/q7oztz.jpg
(you can see two snakes - the long one is the real one)
The blue background is from class arena.
Any ideas? Tnx for help :D

Related

Android: Start animation after fragment is completely loaded

I have a fragment that has an animation of textView fadein. The animation must start after some time delay say 2 seconds after fragment is loaded. I wrote a code for this. but the animation part is done and then the view is rendered. How can I load the fragment and after some time delay start my animation
My code is as below: Note: the class extends Fragment
Animation animFadein;
MenuClickHelper mClickHelper;
TextView tv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_main_menu,
container, false);
mClickHelper = new MenuClickHelper(rootView, getFragmentManager());
tv = (TextView) rootView.findViewById(R.id.tvPresentation);
animFadein = AnimationUtils.loadAnimation(getActivity()
.getApplicationContext(), R.anim.fade_in);
animFadein.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationEnd(Animation animation) {
if (animation == animFadein) {
Toast.makeText(getActivity().getApplicationContext(),
"Animation Stopped", Toast.LENGTH_SHORT).show();
}
}
});
try {
Thread.sleep(2000);
tv.startAnimation(animFadein);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rootView;
}
Thread.sleep(2000); dont block your main using the sleep method instead you can use the Handler class and use postdelay to delay the animation:
sample:
change this:
try {
Thread.sleep(2000);
tv.startAnimation(animFadein);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
to
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
tv.startAnimation(animFadein);
}
}, 2000); //will start animation in 2 seconds
You can achieve the same result with
android:startOffset="2000"
in your XML animation set file.

Reacting to a button click right away

I am building a snake game, and it works, but with a little bug that really irritates me.
when I click on one of the buttons that in the xml, the snake changes it's direction according to the button.
the problem is that if you have clicked on a button after it's has already re-entered the loop inside the run() of the thread and entered the loop inside the the onDraw() (you can see in the code) it will first finish the loop of the run() and then re-enter and do the turn. and by that a delay is created from the click time to when it turns.
the turn works like this- there is a String variable that gets "LEFT","RIGHT", "UP" or "DOWN", according to what it gets it moves the snake. when you click on a button it changes the variable accoring to what button u have clicked on.
heres the code of how it moves the snake accoring to the direction:
public void onDraw(Canvas canvas){
switch(direction){
case "RIGHT"
xLoc=xLoc+PART_SIZE;
break;
case "UP"
yLoc=yLoc-PART_SIZE;
break;
case "LEFT"
xLoc=xLoc-PART_SIZE;
break;
case "DOWN"
yLoc=yLoc+PART_SIZE;
break;
}//swich
int x=xLoc;
int y=yLoc;
for(BodyPart bp:WholeBody){
Rect r=new Rect();
r.set(0+x, 0+y, PART_SIZE+x, PART_SIZE+y);
bp.setR(r);
canvas.drawRect(bp.getR(),bp.getP());
int xtemp=bp.getX();
int ytemp=bp.getY();
bp.setX(x);
bp.setY(y);
x=xtemp;
y=ytemp;
}//for each
}//onDraw
the xLoc and the yLoc is the location of where the head of the snake will go to, and the its moves each body part(each rect of the snake-each bodypart is an equall rect) the the location of where the bodypart before it was.
here are the onClick()s:
left.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(gv.snake.getDir()!="LEFT"&&gv.snake.getDir()!="RIGHT"){
gv.snake.Left();
}
}
});
right.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(gv.snake.getDir()!="RIGHT"&&gv.snake.getDir()!="LEFT"){
gv.snake.Right();
}
}
});
up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(gv.snake.getDir()!="UP"&&gv.snake.getDir()!="DOWN"){
gv.snake.Up();
}
}
});
down.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(gv.snake.getDir()!="DOWN"&&gv.snake.getDir()!="UP"){
gv.snake.Down();
}
}
});
gv is an variable from class gameView which in it has a variable from the class snake
here are the setDirection:
public void Left(){
direction="LEFT";
}
public void Up(){
direction="UP";
}
public void Right(){
direction="RIGHT";
}
public void Down(){
direction="DOWN";
}
and here is the run of the thread:
public void run() {
long stepPerSecond=1000/FPS;
long startTime;
long sleepTime;
while(isRunning){
Canvas c= null;
startTime=System.currentTimeMillis();
try{
c=this.getHolder().lockCanvas();
synchronized (this.getHolder()) {
this.onDraw(c);
}
}
catch(Exception e){
}
finally{
if(c!=null){
this.getHolder().unlockCanvasAndPost(c);
}
}
sleepTime= stepPerSecond-(System.currentTimeMillis()-startTime);
if(sleepTime>0)
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
else
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
is there someway that there will not be that delay?
maby when you click on a button it will stop the run() and redo it after it had updated the direction variable acording to the click.

surfaceview gives darker shade

I am new to graphics and surfaceviews etc. I have heard that it is better to draw on a seperate thread than on the main thread. i have 2 activities one which is drawn using ondraw of the view, the other uses surface view. both have the same code for drawing. however the latter gives a much darker backgroung color-even at max alpha setting(255). If I comment out the drawargb line I get a black background. I tried many things like setting background color of surfaceview object and setting pixelformat to rgb888 or transparent but none of these work.Following is the code:
SurfaceHolder ourHolder;Boolean isRunning=true;
Thread ourThread;ArrayList<Float> amtint=new ArrayList();float max;
String names[];String company;
public GraphSview(Context c) {
super(c);
ourHolder=getHolder();
ourThread=new Thread(this);
ourThread.start();}
public void pause(){
isRunning=false;
while(true){try {
ourThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}break;}ourThread=null;
}
public void Resume()
{
isRunning=true;
ourThread=new Thread(this);
ourThread.start();}
#Override
public void run() {
// TODO Auto-generated method stub
while(isRunning){
if(!ourHolder.getSurface().isValid())continue;
Canvas canvas=ourHolder.lockCanvas();
canvas.drawARGB(255, 33, 181, 238);
.... ourHolder.unlockCanvasAndPost(canvas);
code for the main activity is
public class GraphS extends Activity{
GraphSview ourSview;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
ourSview=new GraphSview(this);
ourSview.getHolder().setFormat(PixelFormat.TRANSPARENT);
setContentView(ourSview);
//ourSview.setBackgroundColor(0Xffffffff);
}
#Override
protected void onPause() {
ourSview.pause();
super.onPause();
}
#Override
protected void onResume() {
ourSview.Resume(); // TODO Auto-generated method stub
super.onResume();
}
}
is there something wrong with the code?
is there any alternate way of creating and displaying graphs other than surface view?

Reloading Animated sprite while on the game scene Andengine

While on the game play scene, when player fires, the enemy will automatically animate and have to move out from the scene. i tried alot but didn't find the solution.
here is my code.
it = bulletList.iterator();
while (it.hasNext()) {
final Bullet b = (Bullet) it.next();
if (b.sprite.collidesWith(enemy)) {
engine.runOnUpdateThread(new Runnable() {
public void run() {
enemy.animate(new long[]{100,100,100,100,100},10,14,1
, new IAnimationListener() {
#Override
public void onAnimationStarted(AnimatedSprite pAnimatedSprite,int
pInitialLoopCount) {
}
#Override
public void onAnimationLoopFinished(AnimatedSprite pAnimatedSprite,
int pRemainingLoopCount, int
pInitialLoopCount) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationFrameChanged(AnimatedSprite pAnimatedSprite,
int pOldFrameIndex, int pNewFrameIndex) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationFinished(AnimatedSprite pAnimatedSprite) {
// TODO Auto-generated method stub
detachChild(sprite);
}
});
enemy.setIgnoreUpdate(true);
it.remove();
break;
}
}
}
what is it that's actually happening?
i did not understand...
But i understood your code a bit.And i recommend you to remove the runonupdatethread.
And put your animation code outside the runonupdatetheard and try it.
I animate the sprite directly...

SurfaceView implements Runnable - Thread does not start

Have been looking on some tutorials for drawing canvas using SurfaceView, but the only thing that shows up is a black background.
public class FighterActivity extends Activity implements OnTouchListener {
/** Called when the activity is first created. */
SurfaceController surface;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
surface = new SurfaceController(this);
surface.setOnTouchListener(this);
setContentView(surface);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
surface.pause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
surface.resume();
}
public class SurfaceController extends SurfaceView implements Runnable{
Thread thread = null;
SurfaceHolder holder;
public SurfaceController(Context context) {
super(context);
// TODO Auto-generated constructor stub
holder = getHolder();
System.out.println("HERE");
}
public void run() {
// TODO Auto-generated method stub
System.out.println("Hello World2");
while(true){
if(!holder.getSurface().isValid()){
System.out.println("NOT VALID");
continue;
}
System.out.println("VALID!");
Canvas can = holder.lockCanvas();
can.drawARGB(255, 150, 150, 0);
holder.unlockCanvasAndPost(can);
}
}
public void pause(){
}
public void resume(){
}
}
public boolean onTouch(View view, MotionEvent me) {
// TODO Auto-generated method stub
return false;
}
}
It gets to the System.out.println("HERE"); and prints out HERE, but nothing more happends, In other words the thread does not get started since "Hello World2" is not printed, what is the problem?
Thanks for any help
I'm assuming you're building off of this: http://android-coding.blogspot.ca/2011/05/drawing-on-surfaceview.html
You'll notice there the onResumeMySurfaceView and onPauseMySurfaceView (resume and pause in your SurfaceController, respectively) start the actual thread. You'll need to do that in your code, too, e.g. in SurfaceController:
protected boolean running = false;
public void resume() {
running = true;
thread = new Thread(this);
thread.start();
}

Categories

Resources