Blackjack Card Display Issue - android-studio

For my App Dev 2 project, we were told to make a basic Blackjack game on Android Studio. The problems revolve around the Stand button. Anytime I press it, the app closes. Another issue is that whenever the button does work, it will replace the dealer's first card with their second card, when I need the second facedown card to be replaced with the second faceup card. I will link everything pertaining to this issue, as the whole program is too large for stackoverflow.
public ImageView dealer_Card1, dealer_Card2, dealer_Card3, dealer_Card4, dealer_Card5;
public ImageView player_Card1, player_Card2, player_Card3, player_Card4, player_Card5;
public void btn_Stand_Click() {
do {
dealer_Call();
calculate_Dealer_Score();
if (dealer_Score > 21) {
for (int i = 0; i < 5; i++) {
if (dealer_Card_Array[i] == 'A' && dealer_Score_Count[i] == 11) {
dealer_Score_Count[i] = 1;
break;
}
}
calculate_Dealer_Score();
}
} while (dealer_Score < 17 && dealer_Score <= player_Score && dealer_Card_Number < 5);
results();
}
public void btn_Stand(View view) {
do {
dealer_Call();
calculate_Dealer_Score();
if (dealer_Score > 21) {
for (int i = 0; i < 5; i++) {
if (dealer_Card_Array[i] == 'A' && dealer_Score_Count[i] == 11) {
dealer_Score_Count[i] = 1;
break;
}
}
calculate_Dealer_Score();
}
} while (dealer_Score < 17 && dealer_Score <= player_Score && dealer_Card_Number < 5);
if (player_Score == 21) {
black_Jack();
} else if (dealer_Score == 21) {
dealer_black_Jack();
} else if (dealer_Score > 21) {
total = total + (bet * 2);
Toast toast = Toast.makeText(getApplicationContext(), "Dealer Bust! You won!", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
disable_Buttons();
alert_Box();
} else results();
}
private void card_Image_Switcher() {
dealer_Card1.setImageResource(R.drawable.cardback);
dealer_Card2.setImageResource(R.drawable.cardback);
dealer_Card3.setImageResource(R.drawable.cardback);
dealer_Card4.setImageResource(R.drawable.cardback);
dealer_Card5.setImageResource(R.drawable.cardback);
player_Card1.setImageResource(R.drawable.cardback);
player_Card2.setImageResource(R.drawable.cardback);
player_Card3.setImageResource(R.drawable.cardback);
player_Card4.setImageResource(R.drawable.cardback);
player_Card5.setImageResource(R.drawable.cardback);
}

Related

Solving LeetCode #13 Roman to Integer Question (Char comparison)

Here is the problem link: https://leetcode.com/problems/roman-to-integer/
I kept having problem on comparison s.charAt() and a char of Roman.
I am very new to JAVA. Isn't if(s.charAt(i) == 'I') supposed to work?
I saw other solutions of this problem, but the solutions tend to make a char and put the char of string in that char.
Could you please explain why my comparison is not working?
I really appreciate your answer in advance.
class Solution {
public int romanToInt(String s) {
int i = 0;
int sum = 0;
for(i=0;i<s.length();i++)
{
if(s.charAt(i) == 'I')
{
if(s.charAt(i+1) == 'X') //4
{
i++;
sum += 4;
}
else if(s.charAt(i+1) == 'V') //9
{
i++;
sum += 9;
}
else
{
sum += 1;
}
}
else if(s.charAt(i) == 'V')
{
sum += 10;
}
else if(s.charAt(i) == 'X')
{
if(s.charAt(i+1) == 'L') //40
{
i++;
sum += 40;
}
else if(s.charAt(i+1) == 'C') //90
{
i++;
sum += 90;
}
else
{
sum += 10;
}
}
else if(s.charAt(i) == 'L')
{
sum += 50;
}
else if(s.charAt(i) == 'C')
{
if(s.charAt(i+1) == 'D') //400
{
i++;
sum += 400;
}
else if(s.charAt(i+1) == 'M') //900
{
i++;
sum += 900;
}
else
{
sum+=100;
}
}
else if(s.charAt(i) == 'D')
{
sum += 500;
}
else if(s.charAt(i) == 'M')
{
sum += 1000;
}
}
return sum;
}
}
I used Java for this:
public int romanToInt(String s) {
HashMap<Character, Integer> dict = new HashMap<Character, Integer>();
{
dict.put('I', 1);
dict.put('V', 5);
dict.put('X', 10);
dict.put('L', 50);
dict.put('C', 100);
dict.put('D', 500);
dict.put('M', 1000);
}
int temp = 0;
for(int i=0; i<s.length(); i++){
char c= s.charAt(i);
temp += dict.get(c);
char d= '.';
if((i+1)<s.length() && d!=c){
d = s.charAt(i+1);
if((c=='I' && (d=='V' || d=='X')) ||
(c=='X' && (d=='L' || d=='C')) ||
(c=='C' && (d=='D' || d=='M')))
{
temp += dict.get(d)-2*dict.get(c);
i++;
}
}
}
return temp;
}

Sound won't play at a specific time in unity

I am trying to make a sound play with the timer goes to 3, 2, 1.
My timer starts at ten and has a three second delay. If I use the following code:
if (tl.myCoolTimer == 10)
{
print("Play Sound");
myAudioSource.Play();
}
It plays the Beep over and over again until the game starts and the counter goes below 10.
If I use the code:
if (tl.myCoolTimer == 3)
{
print("Play Sound");
myAudioSource.Play();
}
It doesn't play the sound at all. It doesn't even print the print statement.
I literally only changed the number. I am not sure why this isn't working.
I have also tried setting it to 3f to see if it is a float issue.
Timer Scripts
This is the starting Timer. it counts down to 3 (then the game starts)
public Text startGameTimerText;
public float startGameTimer = 3;
public void Start ()
{
startGameTimerText = GetComponent<Text> ();
}
public void Update ()
{
startGameTimer -= Time.deltaTime;
startGameTimerText.text = startGameTimer.ToString ("f1");
if (startGameTimer < 0) {
GameObject.Find ("GameStartTimer").SetActive (false);
}
}
This is the Game Timer It starts at 10 and counts down to 0.
public StartGameTimer gt; //this is the script the other timer is on
public Text timerText;
public float myCoolTimer = 10;
public void Start ()
{
timerText = GetComponent<Text> ();
}
public void Update ()
{
if (gt.startGameTimer > 0) {
myCoolTimer = 10;
} else {
myCoolTimer -= Time.deltaTime;
timerText.text = myCoolTimer.ToString ("f1");
}
}
Thanks Joe for the help. Here was my final answer. I know it is hacked, but I haven't figured out the Invoke thing yet. When I set the into it kept playing the entire time it was at "3", so i need to make it play only once.
private AudioSource myAudioSource;
public bool isSoundPlayed;
void Start()
{
myAudioSource = GetComponent<AudioSource>();
isSoundPlayed = false;
}
void Update()
{
if((int)tl.myCoolTimer == 3)
{
if (isSoundPlayed == false)
{
myAudioSource.Play();
isSoundPlayed = true;
}
return;
}
if ((int)tl.myCoolTimer == 2)
{
if (isSoundPlayed == true)
{
myAudioSource.Play();
isSoundPlayed = false;
}
return;
}
if ((int)tl.myCoolTimer == 1)
{
if (isSoundPlayed == false)
{
myAudioSource.Play();
isSoundPlayed = true;
}
return;
}
}

How can I make start again after gameover?? (Processing)

I want to make this game in Processing.
When in 'Switch' those are displayed case0,1,2 in same time.
I don't know how to edit it.
and after case2(gameover), press key '1' to start again.
but I think it goes to case1 when gameover situation...
How can I edit it??
PImage work[] = new PImage[3];
float workSize[] = new float[3];
float workX[] = new float[3];
float workY[] = new float[3];
float workS[] = new float[3];
PImage handA, handB;
PFont font;
int level;
boolean gameover = false;
boolean selected[] = new boolean [3];
int salary = 0;
void setup(){
size(1000,800);
background(255);
imageMode(CENTER);
for (int i=0; i<3; i++) {
workX[i] = random(0, width);
workY[i] = random(0, height);
selected[i] = false;
workSize[i] = 120;
}
handA = loadImage("handA.png");
handB = loadImage("handB.png");
work[0] = loadImage("work0.png");
work[1] = loadImage("work1.png");
work[2] = loadImage("work2.png");
font = createFont("Gulim", 48);
textFont(font);
textAlign(CENTER, CENTER);
}
void draw(){
background(255);
if (mousePressed) {
cursor(handB, 0, 0);
} else {
cursor(handA, 0, 0);
}
switch (level) {
default: // press'1' to start game
fill(0);
text("1을 눌러 일 얻기", width/2, height/2);
if (key == '1') {
level = 1;
}
break;
case 1:
game();
if (gameover == true) {
level = 2;
}
break;
case 2: // press '1' to start again
fill(0);
text("퇴직금 : "+ salary + " + (비정규직으로 퇴직금 없음)", width/2, height/2-100);
text("일을 못해서 정리해고", width/2, height/2);
text("1을 눌러 다시 일 얻기", width/2, height/2+100);
if (key == '1') {
level = 1;
}
break;
}
}
void game() {
for (int i=0; i<3; i++) {
float clickedDist = dist(workX[i], workY[i], mouseX, mouseY);
if (clickedDist<workSize[i]/2 && mousePressed) {
workSize[i] = workSize[i] - 2;
} else {
workSize[i] = workSize[i] + 0.7;
}
if (workSize[i]<100) {
workSize[i] = 0;
}
if (workSize[i]>400) {
gameover = true;
}
if (workSize[i] == 0 && selected[i] == false) {
salary = salary + 50;
selected[i] = true;
workX[i] = random(0, width);
workY[i] = random(0, height);
selected[i] = false;
workSize[i] = 120;
}
if (salary > 150) {
workS[i] = workSize[i] + 0.5;
workSize[i] = workS[i];
}
if (abs(mouseX-workX[i]) < workSize[i]/2 && abs(mouseY-workY[i]) < workSize[i]/2) {
workX[i] += random(-5,5);
workY[i] += random(-5,5);
}
image(work[i], workX[i], workY[i], workSize[i], workSize[i]);
pushMatrix();
fill(0);
textSize(48);
text("봉급 : "+ salary, textWidth("salary"), (textAscent()+textDescent()/2));
popMatrix();
}
}
All you have to do is reset any variables that store the state of your game, such as your level variable. Something like this:
void keyPressed(){
if(gameover && key == '1'){
gameover = false;
level = 1;
}
}

SDL multiple animations on same screen flicker

I am playing around with SDL, trying to make a simple fighting game like street fighter or such, but I don't understand how to make more than one animation at once on the screen without flickering. For some reason while both players are idle on the screen they don't flicker, but for other animations the second player flickers. The code looks something like this:
Class player1:
...
void setrects_idle(SDL_Rect* clip) //loads the frames from a bmp image
{
for(int i = 0; i < 10; i ++) {
clip[i].x = 0 + i*224;
clip[i].y = 0;
clip[i].w = 224;
clip[i].h = 226;
}
}
void setrects_walkf(SDL_Rect* clip)
{
for(int i = 0; i < 11; i ++) {
clip[i].x = 0 + i*224;
clip[i].y = 0;
clip[i].w = 224;
clip[i].h = 226;
}
}
void player::idle(SDL_Surface* screen)
{
if (!other_action)
{
SDL_BlitSurface(player1_idle, &frames_idle[static_cast<int>(frame_idle)], screen, &offset);
SDL_Flip(screen);
if(frame_idle > 8)
frame_idle = 0;
else
frame_idle ++;
}
}
void player::walkf(SDL_Surface* screen)
{
other_action = true;
SDL_BlitSurface(player1_walkf, &frames_walkf[static_cast<int>(frame_walkf)], screen, &offset);
SDL_Flip(screen);
if(frame_walkf > 9)
frame_walkf = 0;
else
frame_walkf ++;
}
********************
Class player2:
void player2::idle(SDL_Surface* screen)
{
if (!other_action)
{
SDL_BlitSurface(player2_idle, &frames_idle[static_cast<int>(frame_idle)], screen, &offset);
//SDL_Flip(screen); //with this commented, there is no flicker on both players idle
if(frame_idle > 8)
frame_idle = 0;
else
frame_idle ++;
}
}
void player2::walkf(SDL_Surface* screen)
{
other_action = true;
SDL_BlitSurface(player2_walkf, &frames_walkf[static_cast<int>(frame_walkf)], screen, &offset);
SDL_Flip(screen); //if I comment this there is no animation for player2 at all. with it on, it flickers.
if(frame_walkf > 9)
frame_walkf = 0;
else
frame_walkf ++;
}
*****************************
SDL_Surface *screen;
screen = SDL_SetVideoMode(800, 600, 32, SDL_HWSURFACE | SDL_DOUBLEBUF);
In the main loop:
player1.idle(screen);
player2.idle(screen);
...
case SDLK_d:
player1.b[1] = 1;
break;
case SDLK_j:
player2.b[1] = 1;
break;
...
if(player1.b[0])
player1.walkb(screen);
else
player1.return_to_idle();
if(player2.b[0])
player2.walkb(screen);
else
player2.return_to_idle();
You call several time SDL_Flip.
Into your main loop, call it juste once.
Erase background
Draw ALL objects.
Flip Once
Do not flip in your function walkf

JavaFX: Massive collision detection optimization (Quad Tree)

I was working on massive collision detection for my game(more than 1000 sprites is massive for my game), and i was searching to find a way to implement this, then i reached to quad tree:
http://en.wikipedia.org/wiki/Quadtree
Well it's approach to reduce the number of objects that should be check for collision by dividing them to the groups of objects which have more chance to collide.
I found a java version of quad tree here:
http://gamedev.tutsplus.com/tutorials/implementation/quick-tip-use-quadtrees-to-detect-likely-collisions-in-2d-space/
Then i change it and use it for my javafx game. but the performance wasn't really good for huge number of objects, so i made some optimisation on it.
Well i used AnimationTimer for each tree to check for collisions which has improved performance so much. i think Animation Timer use GPU to process because when i run my code CPU usage doesn't go hight(3% to 5% - 1640 sprites). but if i use Thread instead of AnimationTimer it use much more CPU(about 40% to 50% - 1640 sprites).
import java.util.ArrayList;
import java.util.List;
import javafx.animation.AnimationTimer;
import javafx.scene.layout.Region;
import javafx.scene.layout.RegionBuilder;
import javafx.scene.paint.Color;
import viwofx.sprit.Sprite;
import viwofx.ui.GameScene;
public class QuadTree
{
private int MAX_OBJECTS = 10;
private int MAX_LEVELS = 5;
private int level;
private ArrayList<Sprite> sprites;
private ArrayList<Sprite> unAllocatedSprites;
private Region bounds;
private QuadTree[] nodes;
private QuadTree parent;
private AnimationTimer detection;
private boolean detecting = false;
private QuadTree getqt()
{
return this;
}
public QuadTree(QuadTree p, int pLevel, Region pBounds)
{
this.parent = p;
level = pLevel;
sprites = new ArrayList<>(0);
unAllocatedSprites = new ArrayList<>(0);
bounds = pBounds;
nodes = new QuadTree[4];
detection = new AnimationTimer()
{
#Override
public void handle(long l)
{
// This for happens when this node has child nodes and there is some object which can not fit whitin the bounds of child nodes
// these object being checked till they can fit inside the bounds of child nodes then they will be added to correspinding child node,
// or object is out of bounds then it will be pushed to the parent node
for (int i = 0; i < unAllocatedSprites.size(); i++)
{
if (!isInside(unAllocatedSprites.get(i)))
{
pushToParent(unAllocatedSprites.get(i));
continue;
}
int index = getIndex(unAllocatedSprites.get(i));
if (index != -1)
{
nodes[index].add(unAllocatedSprites.remove(i));
}
}
for (int i = 0; i < sprites.size(); i++)
{
Sprite ts = sprites.get(i);
if (isInside(ts))
{
int ii = 0;
for (ii = 0; ii < sprites.size(); ii++)
{
Sprite ts2 = sprites.get(ii);
if (ts != ts2)
{
Your collision detection logic
}
}
if (parent != null)
{
for (ii = 0; ii < parent.getUnAllocatedSprites().size(); ii++)
{
Sprite ts2 = parent.getUnAllocatedSprites().get(ii);
if (ts != ts2 && isInside(ts2))
{
Your collision detection logic
}
}
}
}
else
{
pushToParent(ts);
}
}
}
};
}
public int getLevel()
{
return level;
}
public ArrayList<Sprite> getUnAllocatedSprites()
{
return unAllocatedSprites;
}
// Split the node into 4 subnodes
private void split()
{
double subWidth = (bounds.getPrefWidth() / 2);
double subHeight = (bounds.getPrefHeight() / 2);
double x = bounds.getLayoutX();
double y = bounds.getLayoutY();
nodes[0] = new QuadTree(this, level + 1, RegionBuilder.create().layoutX(x).layoutY(y).prefWidth(subWidth).prefHeight(subHeight).build());
nodes[1] = new QuadTree(this, level + 1, RegionBuilder.create().layoutX(x + subWidth).layoutY(y).prefWidth(subWidth).prefHeight(subHeight).build());
nodes[2] = new QuadTree(this, level + 1, RegionBuilder.create().layoutX(x).layoutY(y + subHeight).prefWidth(subWidth).prefHeight(subHeight).build());
nodes[3] = new QuadTree(this, level + 1, RegionBuilder.create().layoutX(x + subWidth).layoutY(y + subHeight).prefWidth(subWidth).prefHeight(subHeight).build());
}
private int getIndex(Sprite s)
{
int index = -1;
double verticalMidpoint = bounds.getLayoutX() + (bounds.getPrefWidth() / 2);
double horizontalMidpoint = bounds.getLayoutY() + (bounds.getPrefHeight() / 2);
double spriteMaxX = (s.getNode().getTranslateX() + s.getWidth());
double spriteMaxY = (s.getNode().getTranslateY() + s.getHeight());
// Object can completely fit within the top quadrants
boolean topQuadrant = (spriteMaxY < horizontalMidpoint);
// Object can completely fit within the bottom quadrants
boolean bottomQuadrant = (s.getNode().getTranslateY() >= horizontalMidpoint);
// Object can completely fit within the left quadrants
if (s.getNode().getTranslateX() >= bounds.getLayoutX() && spriteMaxX < verticalMidpoint)
{
if (topQuadrant)
{
index = 0;
}
else if (bottomQuadrant)
{
index = 2;
}
}
// Object can completely fit within the right quadrants
else if (s.getNode().getTranslateX() >= verticalMidpoint && (s.getNode().getTranslateX() + s.getWidth()) < (bounds.getLayoutX() + bounds.getPrefWidth()))
{
if (topQuadrant)
{
index = 1;
}
else if (bottomQuadrant)
{
index = 3;
}
}
return index;
}
public boolean isInside(Sprite s)
{
double maxX = bounds.getLayoutX() + bounds.getPrefWidth();
double maxY = bounds.getLayoutY() + bounds.getPrefHeight();
// Object can completely fit within the left quadrants
if (s.getNode().getTranslateX() >= bounds.getLayoutX() && (s.getNode().getTranslateX() + s.getWidth()) < maxX && s.getNode().getTranslateY() >= bounds.getLayoutY() && (s.getNode().getTranslateY() + s.getHeight()) < maxY)
{
return true;
}
if (parent != null && parent.getUnAllocatedSprites().contains(s))
{
return true;
}
return false;
}
public void pushToParent(Sprite s)
{
sprites.remove(s);
unAllocatedSprites.remove(s);
if (parent == null)
{
//System.out.println("parent");
if (!unAllocatedSprites.contains(s))
{
unAllocatedSprites.add(s);
}
return;
}
parent.add(s);
if (sprites.size() < 1 && unAllocatedSprites.size() < 1)
{
stopDetection();
}
}
public void add(viwofx.sprit.Sprite sprite)
{
// if sprite is not fit in the bounds of node, it will be pushed to the parent node.
// this is a optimization for when child node push a object to this node and object still is not fit in the bounds this node,
// so it will be pushed to the parent node till object can be fited whitin the node bounds
// this if prevent of out of bounds object to being added to unAllocatedSprites and then being pushed to parent
if (!isInside(sprite))
{
pushToParent(sprite);
return;
}
// if tree has been splited already add sprite to corrosponding child
if (nodes[0] != null)
{
int index = getIndex(sprite);
if (index != -1)
{
nodes[index].add(sprite);
return;
}
else
{
unAllocatedSprites.add(sprite);
return;
}
}
sprites.add(sprite);
if (!detecting)
{
startDetection();
}
if (sprites.size() > MAX_OBJECTS && level < MAX_LEVELS)
{
if (nodes[0] == null)
{
split();
}
int i = 0;
while (i < sprites.size())
{
int index = getIndex(sprites.get(i));
if (index != -1)
{
nodes[index].add(sprites.remove(i));
}
else
{
unAllocatedSprites.add(sprites.remove(i));
}
}
}
}
public List<Sprite> retrieve(List<Sprite> returnObjects, Sprite pRect)
{
int index = getIndex(pRect);
if (index != -1 && nodes[0] != null)
{
nodes[index].retrieve(returnObjects, pRect);
}
returnObjects.addAll(sprites);
return returnObjects;
}
public void startDetection()
{
detecting = true;
detection.start();
}
public void stopDetection()
{
//detecting = false;
//detection.stop();
}
}
I hope this will be helpful for you.

Resources