0

Within my android application I am creating a game base on the Stroop effect.

In order for the user to select an answer for the game they click one of two buttons:

  1. Will have the string of the TextView as its text
  2. Will have the color of the String in the TextView as it's text

For example:

enter image description here

In order for the user to be correct they must choose the button with the color NOT the string.

I do not want these two buttons to always be in the same positions on the screen as it would become very predictable to the user. I.e. I want them to alter so that sometimes one is on the right, then left etc after each answer is given.

How can I do so?

Current code of Activity:

public class Stroop extends ActionBarActivity implements View.OnClickListener {

    HashMap<String, Integer> colors = new HashMap<>();
    // putting the strings and color vals of the hashmap to an array
    Object stringOnScreen[];
    Object colorsOnScreen[];

    // declare vars
    TextView color;
    Button btn1;
    Button btn2;
    TextView result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.stroop);

        setUpGame();

        btn2.setOnClickListener(this);
        btn1.setOnClickListener(this);

        stringOnScreen = colors.keySet().toArray();
        colorsOnScreen = colors.values().toArray();

        setUpQuestion();

        Log.d("Length", "Length string: " + stringOnScreen.length);

        Log.d("Length", "Length color: " + colorsOnScreen.length);

    }// oncreate end

    public void setUpQuestion() {

        int randString = new Random().nextInt(stringOnScreen.length);
        int randColor = new Random().nextInt(colorsOnScreen.length);

        Log.d("ranString", "randString: " + randString);
        Log.d("rancolor", "randcolor: " + randColor);

        // set the text of the string in textview for user to see
        color.setText("" + stringOnScreen[randString]);
        color.setTextColor((int) colorsOnScreen[randColor]);

        btn1.setText("" + stringOnScreen[randString]); //Set btn1 to the string val

        //Note: uncomment below if the solution under doesnt work
        //btn2.setText("" + colorsOnScreen[randColor].toString()); // set btn2 to the color of the String

        setBtn2Text();

//      //logic to see if answer is correct, currently commented out to try answer from SO
//      
//      if(btn2.getText().equals(convertColorIntToString(color.getCurrentTextColor()))){
//          
//          result.setText("Correct");
//      }
//      
//      //trace code
//      Log.d("colortrace", " " + convertColorIntToString(color.getCurrentTextColor()));

        //trace to check SO method of logic is working
        Log.d("bool", " " + checkForMatchBtn2(btn2));


    }

    public void setUpGame() {

        // setting up the hashmap
        colors.put("Green", Color.GREEN);
        colors.put("Blue", Color.BLUE);
        colors.put("Red", Color.RED);
        colors.put("Yellow", Color.YELLOW);
        colors.put("Black", Color.BLACK);

        // setting up vars
        color = (TextView) findViewById(R.id.tvStroopColor);
        btn1 = (Button) findViewById(R.id.btnStroop1);
        btn2 = (Button) findViewById(R.id.btnStroop2);
        result = (TextView) findViewById(R.id.tvStroopResults);

    }

    public void setBtn2Text(){
        switch(color.getCurrentTextColor()){
            case Color.GREEN:
                btn2.setText("Green");
                break;
            case Color.RED:
                btn2.setText("Red");
                break;
            case Color.BLUE:
                btn2.setText("Blue");
                break;
            case Color.YELLOW:
                btn2.setText("Yellow");
                break;
            case Color.BLACK:
                btn2.setText("Black");
                break;

        }
    }

    public void onClick(View v){

        if(v.getId() == R.id.btnStroop2){
            if(checkForMatchBtn2(btn2))
                result.setText("Correct!");
            else
                result.setText("Wrong!");
        }

        if(v.getId() == R.id.btnStroop1){
            if(checkForMatchBtn1(btn1))
                result.setText("Correct!");
            else
                result.setText("Wrong!");
        }
    }

    public boolean checkForMatchBtn2(Button btn2){
        if(color.getCurrentTextColor() == Color.GREEN && btn2.getText().equals("Green"))
            return true;
        else if(color.getCurrentTextColor() == Color.RED && btn2.getText().equals("Red"))
            return true;
        else if(color.getCurrentTextColor() == Color.BLACK && btn2.getText().equals("Black"))
            return true;
        else if(color.getCurrentTextColor() == Color.YELLOW && btn2.getText().equals("Yellow"))
            return true;
        else if(color.getCurrentTextColor() == Color.BLUE && btn2.getText().equals("Blue"))
            return true;
        else 
            return false;
    }

    public boolean checkForMatchBtn1(Button btn1){
        if(color.getCurrentTextColor() == Color.GREEN && btn1.getText().equals("Green"))
            return true;
        else if(color.getCurrentTextColor() == Color.RED && btn1.getText().equals("Red"))
            return true;
        else if(color.getCurrentTextColor() == Color.BLACK && btn1.getText().equals("Black"))
            return true;
        else if(color.getCurrentTextColor() == Color.YELLOW && btn1.getText().equals("Yellow"))
            return true;
        else if(color.getCurrentTextColor() == Color.BLUE && btn1.getText().equals("Blue"))
            return true;
        else 
            return false;
    }

}

Corresponding XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/tvStroopColor"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:paddingBottom="3dp"
            android:text="meditation "
            android:textSize="25dp" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/btnStroop1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/text_to_set"
            android:text=" " />

        <Button
            android:id="@+id/btnStroop2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/text_to_set"
            android:text=" " />
    </LinearLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/tvStroopResults"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:paddingBottom="3dp"
            android:text=" results... "
            android:textSize="25dp" />
    </RelativeLayout>

</LinearLayout>
bigcoder995
  • 97
  • 1
  • 1
  • 7
  • You can add the buttons dynamically at runtime and perform some logic to randomise the order you add them in. Here is an example of adding them dynamically - http://stackoverflow.com/a/1851833/1134429 – Willie Nel Jul 28 '14 at 05:06
  • Thank you, how would I then randomise the oder they are in? – bigcoder995 Jul 28 '14 at 10:15
  • Here is a very basic example of how to shuffle a list of strings. The idea would be to get the button names (From a resource or wherever), shuffle them and then add them to your layout - http://pastebin.com/MhDGzAhp – Willie Nel Jul 28 '14 at 10:50
  • Thanks for your help. I am trying to cannot seem to implement the functionality for my app. Should this be such a difficult process? – bigcoder995 Jul 28 '14 at 11:44

1 Answers1

0

I've decided to add a short example, please note that this is not a final solution but just a hint to get you going in the right direction.

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.colorquiz"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity android:name="com.example.colorquiz.activities.MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <color name="red">#FF0000</color>
    <color name="green">#00FF00</color>
    <color name="blue">#0000FF</color>

</resources>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:padding="16dp" >

    <View
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <TextView
        android:id="@+id/colorName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:textStyle="bold" />

    <View
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <LinearLayout
        android:id="@+id/buttonContainer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:orientation="horizontal" />

    <View
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <Button
        android:id="@+id/btnRefresh"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Refresh" />

    <View
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

</LinearLayout>

MainActivity.java

package com.example.colorquiz.activities;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.colorquiz.R;

public class MainActivity extends Activity {

    private TextView mColorName;
    private LinearLayout mButtonContainer;
    private Button mRefresh;

    private QuizColor mRandomColor;
    private final List<QuizColor> mColors = Arrays.asList(new QuizColor("Red", R.color.red), new QuizColor("Green", R.color.green), new QuizColor("Blue", R.color.blue));

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mButtonContainer = (LinearLayout) findViewById(R.id.buttonContainer);
        mRefresh = (Button) findViewById(R.id.btnRefresh);
        mColorName = (TextView) findViewById(R.id.colorName);

        mRefresh.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                refreshButtons();
            }
        });

        refreshButtons();
    }

    private void refreshButtons() {

        // Shuffle the colors to make sure they are random each time

        Collections.shuffle(mColors);

        // Select a random color to be the "Correct" color

        int randomColorIndex = new Random().nextInt(mColors.size());

        mRandomColor = mColors.get(randomColorIndex);

        mColorName.setText(mRandomColor.getName());
        mColorName.setTextColor(getResources().getColor(mRandomColor.getColorResourceId()));

        // Create the layout parameters for the buttons we are about to add

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

        // Remove previously added buttons if they exist

        if (mButtonContainer.getChildCount() > 0) {
            mButtonContainer.removeAllViews();
        }

        // Loop through all the colors and add a button for each of them

        for (final QuizColor color : mColors) {

            Button colorButton = new Button(this);
            colorButton.setText(color.getName());
            colorButton.setLayoutParams(params);

            colorButton.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    validateColor(color);
                }
            });

            mButtonContainer.addView(colorButton);
        }
    }

    // Check if the clicked color is equal to the current "Correct" color

    private void validateColor(QuizColor selectedColor) {
        if (mRandomColor.equals(selectedColor)) {
            Toast.makeText(this, "Correct color selected.", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "Incorrect color selected.", Toast.LENGTH_SHORT).show();
        }
    }

    public class QuizColor {

        private String name;
        private int colorResourceId;

        public QuizColor(String name, int colorResourceId) {
            super();
            this.name = name;
            this.colorResourceId = colorResourceId;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getColorResourceId() {
            return colorResourceId;
        }

        public void setColorResourceId(int colorResourceId) {
            this.colorResourceId = colorResourceId;
        }
    }
}

Hope this helps

Willie Nel
  • 363
  • 2
  • 9