Reputation: 1
I have created my first game Snake, it works pretty well, but I want to make snake movements smoothy, so..
I have created timer with 250ms delay:
timer = new Timer(250, this);
timer.start();
Imported two images 10x10 pixels:
ImageIcon iid = new ImageIcon("dot.png");
dot = iid.getImage();
ImageIcon iih = new ImageIcon("head.png");
head = iih.getImage();
Initialize snake body and head coordinates:
dots = 3;
for (int z = 0; z < dots; z++) {
x[z] = 50 - z * DOT_SIZE;
y[z] = 50;
}
Where x[] and y[] are arrays with snake coordinates (head is x[0] and [0]), dots - snake length (including body and head) and DOT_SIZE is const with value == 10, because head and body images are 10x10 pixels.
Then I paint snake at frame:
for (int z = 0; z < dots; z++) {
if (z == 0) {
g.drawImage(head, x[z], y[z], this);
} else {
g.drawImage(dot, x[z], y[z], this);
}
}
And then every 250ms I recalculate snake coordinates:
for (int z = dots; z > 0; z--) {
x[z] = x[(z - 1)];
y[z] = y[(z - 1)];
}
if (leftDirection) {
x[0] -= DOT_SIZE;
}
if (rightDirection) {
x[0] += DOT_SIZE;
}
if (upDirection) {
y[0] -= DOT_SIZE;
}
if (downDirection) {
y[0] += DOT_SIZE;
}
Left, right, up and down directions - are variables what change after I press the key and allows me to control the snake. After I just repaint frame with the code shown above (paint snake at frame).
So my snake moves with the step of 10 pixels every 250ms. The main my idea is to make snake movement smoothy with the step of 1 pixel every 25ms, but other things shouldn't change. I mean, for example, I'm able to turn my snake into another direction every 10 pixels (it should be because image resolution is 10x10 pixels). I have created counter what repaints frame 10 times and then call the other methods (key pressing, setting apples at frame etc) and insert DOT_SIZE=1 to move snake smoothy. But the problem appeared because images resolutions are 10x10 pixels, so my images started overlapping each other (the step of 1 pixel with image resolution of 10x10 pixels) in this fragment of code:
for (int z = dots; z > 0; z--) {
x[z] = x[(z - 1)];
y[z] = y[(z - 1)];
}
So the question is:
How to make snake movements smoothy with the step of 1 pixel and be able to turn snake into another direction every 10 pixels with images resolutions of 10x10 pixels?
And how to make the corners after I turn my snake into another direction smoothy too?
Upvotes: 0
Views: 862
Reputation: 1132
Create tile(s) for turning segments[use one and rotate it, or 4 for the different turns] . keep a queue of turns. draw from the head to the first turn. from first turn to next turn until you run out of snake to draw. when the end of the snake is in turn tile remove that turn tile from the queue.
Upvotes: 1