How to add settings to snake game(Processing)? - processing

Im trying to add settings to a snake game made in processing. I want to have something like easy, normal and hard or something along the lines of that and change the speed and maybe size of the grid. If anyone coudl explain how to id greatly appreciate it!
ArrayList<Integer> x = new ArrayList<Integer>(), y = new ArrayList<Integer>();
int w = 30, h = 30, bs = 20, dir = 2, applex = 12, appley = 10;
int[] dx = {0,0,1,-1}, dy = {1,-1,0,0};
boolean gameover = false;
void setup() {
size(600,600);
x.add(5);
y.add(5);
}
void draw() {
background(255);
for(int i = 0 ; i < w; i++) line(i*bs, 0, i*bs, height); //Vertical line for grid
for(int i = 0 ; i < h; i++) line(0, i*bs, width, i*bs); //Horizontal line for grid
for(int i = 0 ; i < x.size(); i++) {
fill (0,255,0);
rect(x.get(i)*bs, y.get(i)*bs, bs, bs);
}
if(!gameover) {
fill(255,0,0);
rect(applex*bs, appley*bs, bs, bs);
if(frameCount%5==0) {
x.add(0,x.get(0) + dx[dir]);
y.add(0,y.get(0) + dy[dir]);
if(x.get(0) < 0 || y.get(0) < 0 || x.get(0) >= w || y.get(0) >= h) gameover = true;
for(int i = 1; i < x.size(); i++) if(x.get(0) == x.get(i) && y.get(0) == y.get(i)) gameover = true;
if(x.get(0)==applex && y.get(0)==appley) {
applex = (int)random(0,w);
appley = (int)random(0,h);
}else {
x.remove(x.size()-1);
y.remove(y.size()-1);
}
}
} else {
fill(0);
textSize(30);
text("GAME OVER. Press Space to Play Again", 20, height/2);
if(keyPressed && key == ' ') {
x.clear(); //Clear array list
y.clear(); //Clear array list
x.add(5);
y.add(5);
gameover = false;
}
}
if (keyPressed == true) {
int newdir = key=='s' ? 0 : (key=='w' ? 1 : (key=='d' ? 2 : (key=='a' ? 3 : -1)));
if(newdir != -1 && (x.size() <= 1 || !(x.get(1) ==x.get(0) + dx[newdir] && y.get (1) == y.get(0) + dy[newdir]))) dir = newdir;
}
}

You need to break your problem down into smaller steps:
Step one: Can you store the difficulty in a variable? This might be an int that keeps track of a level, or a boolean that switches between easy and hard. Just hardcode the value of that variable for now.
Step two: Can you write your code so it changes behavior based on the difficulty level? Use the variable you created in step one. You might use an if statement to check the difficulty level, or maybe the speed increases over time. It's completely up to you. Start out with a hard-coded value. Change the value to see different behaviors.
Step three: Can you programatically change that value? Maybe this requires a settings screen where the user chooses the difficulty, or maybe it gets more difficult over time. But you have to do the first two steps before you can start this step.
If you get stuck on a specific step, then post an MCVE and we'll go from there.

Related

How to code a servomotor with two buttons in arduino?

I wanted to make a servomotor oscilate between 0-90 degrees when i push a button, but when i push another one, it stops oscillating and then remains in its latest position.
i started with this:
#include <Servo.h>
Servo myservo;
int pos = 0;
const int button1 = 5;
const int button2 = 6;
int lastpos = pos;
void setup() {
myservo.attach(3);
pinMode(button1, INPUT);
pinMode(button2, INPUT);
}
void loop() {
if(digitalRead(button1) == HIGH)
{for(pos = 0; pos <= 90; pos += 1)
{myservo.write(pos);
for(pos = 90; pos >= 0; pos -= 1)
{myservo.write(pos);
delay(36);
} } if(digitalRead(button2) == HIGH){ myservo.write(lastpos);}}}
To start, take a look at how to format code inside a question. It makes it a lot easier to read and help you out. See below for how I formatted for the site, but also readability.
Servo myservo;
int pos = 0;
const int button1 = 5;
const int button2 = 6;
int lastpos = pos;
void setup() {
myservo.attach(3);
pinMode(button1, INPUT);
pinMode(button2, INPUT);
}
void loop() {
if(digitalRead(button1) == HIGH) {
for(pos = 0; pos <= 90; pos += 1) {
myservo.write(pos);
for(pos = 90; pos >= 0; pos -= 1) {
myservo.write(pos);
delay(36);
}
}
if(digitalRead(button2) == HIGH) {
myservo.write(lastpos);
}
}
}
There are several issues with your code based on your description of what you are trying to achieve. First, let's start with the button presses. You are ready the button state, but your code will only detect the button if it is pressed at the exact moment you are doing the digital read. Here's a good resource for reading up on how to properly implement buttons on Arduino: https://www.logiqbit.com/perfect-arduino-button-presses
The second objective is to have the servo sweep back and forth, but stop when you press a button. Your for loops won't let that happen. As currently written, you will always do a sweep to one end and back and then check the next button.
You should update the position of the servo once each time through the loop so you can check on the status of the buttons. In pseudo-code, what I suggest you do is:
void loop() {
//Check button statuses
if(button1), start sweep
if(button2), stop sweep
//Update sweep position
if(ascending && pos < 90) {
//You should be increasing in angle and you haven't reached 90 yet
ascending = TRUE;
pos += 1
myservo.write(pos);
delay(36); //Or whatever delay you need for the servo
} else if(pos > 0) {
//You already reached 90 and are coming back down to 0
ascending = FALSE;
pos -= 1;
delay(36);
}

GLSL math conditional AND

Maybe I'm not understanding the language or maybe the compiler is doing some kind of black magic but this code is not identical if I uncomment the comment which surprises me because to accept the conditional that should be the value of the variable :
`
while (distance < tMax) {
coords = uvec3(-1, -1, -1);
int active_voxel = volume_data_box_get_coords_from_point(
mi.block, first_prim_offset, mi.min.xyz, mi.max.xyz,
mi.slices_by_dimension, mi.memory_size, mi.voxel_size, hit, coords);
if ((active_voxel == 1) && (coords.x == 0) && (coords.y == 0) &&
(coords.z == 0)) {
// coords.x = 0;
// coords.y = 0;
// coords.z = 0;
bool are_extents = volume_data_box_get_extents_from_coords(
mi.block, first_prim_offset, mi.min.xyz, mi.slices_by_dimension, mi.memory_size,
mi.voxel_size, coords, voxel_extents);
if (are_extents) {
s = intersectRayOBB(ray.origin, ray.direction, mi.transform,
voxel_extents.min, voxel_extents.max);
tHit = s.t;
voxel_uv = s.uv;
hitKind = 1;
break;
}
}
// Update hit point from previous point plus direction multiplied by
// voxel size
hit += ray.direction * mi.voxel_size;
// Calculate distance between new hit point and ray origin
distance = length(hit - ray.origin);
}
`
I hope someone can clarify what is going on. Thanks!
The evaluated value is different from the expected one.

How to set up if statements so that loop goes forward and then in reverse? Processing

int x = 31;
int y = 31;
int x_dir = 4;
int y_dir = 0;
void setup ()
{
size (800, 800);
}
void draw ()
{
background (150);
ellipse (x,y,60, 60);
if (x+30>=width)
{
x_dir =-4;
y_dir = 4;
}
if (y+30>=height)
{
x_dir=4;
y_dir = 0;
}
if (x+30>=width)
{
x_dir = -4;
}
x+=x_dir;
y+=y_dir;
println(x,y);
}
Hi,
I have to create this program in processing which produces an animation of a ball going in a Z pattern (top left to top right, diagonal top right to bottom left, and then straight from bottom left to bottom right) which then goes backwards along the same path it came.
While I have the code written out for the forward direction, I don't know what 2 if or else statements I need to write for the program so that based on one condition it goes forwards, and based on another condition it will go backwards, and it will continue doing so until it terminates.
If I am able to figure out which two if statements I need to write, all I need to do is copy and reverse the x_dir and y_dir signs on the forward loop.
There are a ton of different ways you can do this.
One approach is to keep track of which "mode" you're in. You could do this using an int variable that's 0 when you're on the first part of the path, 1 when you're on the second part of the path, etc. Then just use an if statement to decide what to do, how to move the ball, etc.
Here's an example:
int x = 31;
int y = 31;
int mode = 0;
void setup ()
{
size (800, 800);
}
void draw ()
{
background (150);
ellipse (x, y, 60, 60);
if (mode == 0) {
x = x + 4;
if (x+30>=width) {
mode = 1;
}
} else if (mode == 1) {
x = x - 4;
y = y + 4;
if (y+30>=height) {
mode = 2;
}
} else if (mode == 2) {
x = x + 4;
if (x+30>=width) {
mode = 3;
}
} else if (mode == 3) {
x = x - 4;
y = y - 4;
if (y-30 < 0) {
mode = 2;
}
}
}
Like I said, this is only one way to approach the problem, and there are some obvious improvements you could make. For example, you could store the movement speeds and the conditions that change the mode in an array (or better yet, in objects) and get rid of all of the if statements.

Generate several random numbers, one of which must be the correct answer to a sum?

I have created a Space Invaders game in which the player must shoot an asteroid which displays a random number. A sum will also be randomly generated at the start of the scene. Once the player shoots an asteroid the scene reloads, with points awarded for correct answers.
The problem I am having is that I need at least one asteroid to display the correct answer. I am currently achieving this by reloading the scene until an asteroids number matches the answer to the sum. This can take quite a few reloads and looks really bad. Is there a better way to achive this which will look better and be more efficient. I have included my effort below. I appreciate any comments. Thanks!
Script for checking the correct answer and reloading the scene.
#pragma strict
function Start ()
{
}
{
if (
Asteroid1_Script.asteroid1Value != (Sum_Script.sumA - Sum_Script.sumB) &&
Asteroid2_Script.asteroid2Value != (Sum_Script.sumA - Sum_Script.sumB) &&
Asteroid3_Script.asteroid3Value != (Sum_Script.sumA - Sum_Script.sumB) &&
Asteroid4_Script.asteroid4Value != (Sum_Script.sumA - Sum_Script.sumB) &&
Asteroid5_Script.asteroid5Value != (Sum_Script.sumA - Sum_Script.sumB)
)
{
Application.LoadLevel("L1");
}
}
Script for randomly generating the sum.
#pragma strict
static var sumA :int = 0;
static var sumB :int = 0;
function Start ()
{
var newSumA = Random.Range(6,10);
sumA = newSumA;
var newSumB = Random.Range(1,6);
sumB = newSumB;
}
function Update () {
//Question Output.
guiText.text = sumA.ToString() + " - " + sumB.ToString()+ " =";
}
Script for generating an asteroids random number.
#pragma strict
var mainCam: Camera;
static var asteroid1Value : int = 0;
var asteroid1 : Transform;
var Asteroid1Style : GUIStyle;
function Start ()
{
var newAsteroid1Value = Random.Range(0,10);
asteroid1Value = newAsteroid1Value;
asteroid1.position.x = mainCam.ScreenToWorldPoint (new Vector3 (160f, 0f, 0f)).x;
asteroid1.position.y = mainCam.ScreenToWorldPoint (new Vector3 (0f, 450f, 0f)).y;
}
function OnGUI()
{
var point = Camera.main.WorldToScreenPoint(transform.position);
GUI.Label(new Rect(point.x, Screen.currentResolution.height - point.y - 530, 110, 100), asteroid1Value.ToString(), Asteroid1Style);
}
function OnCollisionEnter(col : Collision)
{
if(asteroid1Value == (Sum_Script.sumA - Sum_Script.sumB))
{
Destroy(gameObject);
Score_Script.score ++;
}
if(asteroid1Value != (Sum_Script.sumA - Sum_Script.sumB))
{
Score_Script.score --;
}
}
Do as you are doing, generate 5 random numbers for your asteroids.
Then generate a random number between 1 and 5, this is your random asteroid, and then set its value to the answer. (sumA - sumB)
You just need to abstract your logic.
The best argument I can make is, simply put, build your random numbers before you build your asteroids.
That way, you always have a correct one.
I would simply code:
function start(){
var x = 5 //X being whatever number of asteroids you wish.
var a = new Array();
for(var i=0; i<x; i++){
a[i] = Random.Range(0,10);
}
for( i in a){ buildAsteroid(a[i]) }
}
And... if the number matches, success.

Game AI algorithm, enemy following player

I'm using LigGdx to make a game, it looks like a RPG game. When enemy is in alert state, it have to follow the player, but it can move only forward, backward, left and right, and also have to divert objects when it collides, searching for the best way to reach the player, i'm newbie on game development, and my algorithm may be completely wrong, so, I really need help...
private void enemyInAlert(Enemy enemy, float delta) {
detectDirection(enemy);
enemyWalking(enemy, delta);
if (Math.round(getDistanceXofLastPosition(enemy)) == 0 && Math.round(getDistanceYofLastPosition(enemy)) == 0) {
enemy.setState(States.IDLE);
lastPosition = null;
}
}
private void detectDirection(Enemy enemy) {
float diff = getDistanceXofLastPosition(enemy) - getDistanceYofLastPosition(enemy);
if (diff < 0) {
getDirectionX(enemy);
} else if (diff > 0) {
getDirectionY(enemy);
}
}
private void getDirectionY(Enemy enemy) {
int enemyY = Math.round(enemy.getY());
int lastPositionY = Math.round(lastPosition.getY());
if (enemyY < lastPositionY && enemy.isDirectionBlocked(Direction.FORWARD) == false) { //Enemy needs to go forward
enemy.setDirection(Direction.FORWARD);
enemy.blockDirection(Direction.BACKWARD);
} else if (enemyY > lastPositionY && enemy.isDirectionBlocked(Direction.FORWARD) == false) { //Enemy needs to go backward
enemy.setDirection(Direction.BACKWARD);
enemy.blockDirection(Direction.FORWARD);
} else { //Enemy needs to change direction
if (enemy.isDirectionBlocked(Direction.LEFT) == false || enemy.isDirectionBlocked(Direction.LEFT) == false) {
enemy.blockDirection(Direction.BACKWARD);
enemy.blockDirection(Direction.FORWARD);
getDirectionX(enemy);
} else {
sortRandomDirection(enemy);
}
}
}
private void getDirectionX(Enemy enemy) {
int enemyX = Math.round(enemy.getX());
int lastPositionX = Math.round(lastPosition.getX());
if (enemyX < lastPositionX && enemy.isDirectionBlocked(Direction.RIGHT) == false) { //Enemy needs to go right
enemy.setDirection(Direction.RIGHT);
enemy.blockDirection(Direction.LEFT);
} else if (enemyX > lastPositionX && enemy.isDirectionBlocked(Direction.LEFT) == false) {
enemy.setDirection(Direction.LEFT);
enemy.blockDirection(Direction.RIGHT);
} else { //Enemy needs to change direction
if (enemy.isDirectionBlocked(Direction.FORWARD) == false && enemy.isDirectionBlocked(Direction.BACKWARD) == false) {
enemy.blockDirection(Direction.LEFT);
enemy.blockDirection(Direction.RIGHT);
getDirectionY(enemy);
} else {
sortRandomDirection(enemy);
}
}
}
I'm accepting suggestions, I can change all the code, no mercy... Sorry for the bad English :D
Thanks!!
Edit: now, I'm trying to use A*, or something like it. :D ... my code:
private void calculateRoute(Enemy enemy) {
int lowerPath = getDistanceXofLastPosition(enemy.getBounds()) + getDistanceYofLastPosition(enemy.getBounds());
path = new ArrayList<Rectangle>();
Rectangle finalRect = new Rectangle(enemy.getBounds());
List<Rectangle> openList = new ArrayList<Rectangle>();
while (getDistanceXofLastPosition(finalRect) > 0 || getDistanceYofLastPosition(finalRect) > 0) {
for (int i = -1; i < 2; i+= 1) {
outerloop:
for (int j = -1; j < 2; j+= 1) {
Rectangle temp = new Rectangle(finalRect);
temp.offSet(i, j);
if (openList.contains(temp)) {
continue;
}
if ((i == -1 && j == -1) || (i == 1 && j == -1) || (i == 0 && j == 0) || (i == 1 && j == -1) || (i == 1 && j == 1)) {
continue;
}
for (Collider collider : colliders) {
if (collider.isSolid() && Utils.detectCollision(temp, collider.getBounds())) {
continue outerloop;
}
}
openList.add(temp);
}
}
int lowerDistance = Integer.MAX_VALUE;
for (Rectangle rect : openList) {
int distance = getDistanceXofLastPosition(rect) + getDistanceYofLastPosition(rect);
distance = distance + lowerPath;
if (distance < lowerDistance) {
lowerDistance = distance;
finalRect = rect;
}
}
path.add(new Rectangle(finalRect));
}
}
but is very slow, what I can do to increase performance?
You may want to look into A* .
You can easily convert your map into a graph, using each tile as a vertex, and having said vertex connected with an edge to all the other vertices close to it. The cost associated with the edge may be variable, for instance, moving i tile on a river could cost more than moving one tile in a plane.
Then you can use a path search algorithm to find the best path from one point to another. Using this algorithm will have 2 downsides :
It has an high computational cost
It always finds the optimal solution, making your bot smarter than the average player :)
If computational and storage cost are indeed a problem, you can resort to one of A*'s cousins, such as
IDA* for cheaper memory requirements, iterate over the depth of the solutions
SMA* bounds the amount of memory the algorithm can use

Resources