mercredi 14 août 2019

Replace %s by a random varriable of a List

Hello I'm currently programming a little drinking game. Here questions from a JSOn file via Gson are converted into an object and the questions are indicated. Some questions are meant to be specific to a player who was saved to the game at the beginning of the game. If there are several% s stringholders in a question, different players are supposed to play. The parameter "Player Dance" in Json, indicates the amount of requested players.

So far, the questions are outlined as they are without the% s Stingholders being replaced by player names. Unfortunately not at all how you could implement something like that.

Example from Json file:

  {
    "Id": 135,
    "Frage": "%s spielt mit seinem linken und rechten Nachbarn Stein, Schere, Papier! Die verlierer trinken 3 Schlücke",
    "Spieleranz": 1,
    "Level": 2,
    "Mode": 2
  },
  {
    "Id": 136,
    "Frage": "%s nenne von jedem Mitspieler eine Schwäche oder eine negative Eigenschaft. Trinke nach jedem Feedback einen Schluck",
    "Spieleranz": 0,
    "Level": 2,
    "Mode": 2
  },
  {
    "Id": 137,
    "Frage": "%s du wählst: Wurdest du lieber alleine eine Nacht mit %s oder %s verbringen? Der gewählt verteilt 4 Schlücke",
    "Spieleranz": 3,
    "Level": 2,
    "Mode": 2
  },
  {
    "Id": 138,
    "Frage": "%s du wählst: Wer verträgt deiner Meinung nach am meisten alkohol? %s oder %s? Der NICHT gewählte trinkt 4 Schlücke",
    "Spieleranz": 3,
    "Level": 2,
    "Mode": 2
  }....

Main Game class:

        int modi = 1;
        if (getIntent().hasExtra(getString(R.string.spielmodi))) {
            modi = getIntent().getIntExtra(getString(R.string.spielmodi), 1);
            System.out.println("modi = " + modi);
        }
        int grad = 1;
        if (getIntent().hasExtra(getString(R.string.betrunkenheitsgrad))) {
            grad = getIntent().getIntExtra(getString(R.string.betrunkenheitsgrad), 1);
            System.out.println("grad = " + grad);
        }


        Log.d("DF", "test");


        AssetManager assetManager = this.getAssets();
        List<Frage> data = null;
        InputStream json;
        try {
            json = assetManager.open("DichteFichte.json");
            BufferedReader br = new BufferedReader(new InputStreamReader(json, StandardCharsets.ISO_8859_1));
            String str = "";
            StringBuilder sb = new StringBuilder();
            while ((str = br.readLine()) != null) {
                sb.append(str);
            }
            br.close();
            Type list = new TypeToken<List<Frage>>() {
            }.getType();
            data = new Gson().fromJson(sb.toString(), list);
            System.out.println("data = " + data.toString());

        } catch (IOException e) {
            e.printStackTrace();
        }


        TextView Outout = findViewById(R.id.Output);
        Button Weiter = findViewById(R.id.weiter);
        Outout.setText("Keine Fragen mit diesen Parametern du Spast");

        //data.stream().unordered().limit(sternchenAnzahl);

        Random random = new Random();
        int finalModi = modi;
        System.out.println("finalModi = " + finalModi);
        int finalGrad = grad;
        System.out.println("finalGrad = " + finalGrad);
        if (data == null || data.isEmpty())
            return;

        List<Frage> finalData = data.stream()
                .filter(frage -> frage.getLevel() == finalGrad)
                .filter(frage -> frage.getMode() == finalModi)
                .collect(Collectors.toList());

        if (finalData.isEmpty())
            return;


        Weiter.setOnClickListener(v -> {
            Outout.setText(finalData.get(random.nextInt(finalData.size())).getFrage());
            clickcount=clickcount+1;
            if(clickcount%15==0){
                ShowPopupBetrunkenheitsgrad(v);
                betrunkenheitsgradup.show();
            }

        });
        Weiter.callOnClick();


    }

NameList Adapter class:

public class NamensListeAdapter extends RecyclerView.Adapter<NamensListeAdapter.NameViewHolder> {
    private List<Spieler> spielerList;
    private LayoutInflater inflater;



    public NamensListeAdapter(Context context, List<Spieler> namensList) {
        this.spielerList = namensList;
        this.inflater = LayoutInflater.from(context);
    }

    @Override
    public NameViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new NameViewHolder(inflater.inflate(R.layout.name_recyclerview, parent, false));

    }



    @Override
    public void onBindViewHolder(NameViewHolder holder, int position) {

        Spieler spieler = spielerList.get(position);

        String text = spieler.getName() + " (" + spieler.getGeschlecht().getCaption() + ")";

        holder.textView_name.setText(text);
    }


    @Override
    public int getItemCount() {
        return spielerList.size();

    }

    public void removeItem(int itemIndex) {
        spielerList.remove(itemIndex);
        notifyItemRemoved(itemIndex);
    }


    public class NameViewHolder extends RecyclerView.ViewHolder {
        TextView textView_name;

        public NameViewHolder(View itemView) {
            super(itemView);
            textView_name = itemView.findViewById(R.id.nameview_text);

        }


    }

}


```java
public class Spielereingabe extends Activity {
    private final List<Spieler> spielerList = new ArrayList<>();
    private Button button;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spielereingabe);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setActionBar(toolbar);
        final List<Spieler> spielerList = new ArrayList<>();


        //Button
        button = (Button) findViewById(R.id.zukategorieButton);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openKategorien_n();

            }
        });


        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDialog();
            }
        });

        RecyclerView recyclerView = findViewById(R.id.recycler_namensListe);

        final NamensListeAdapter namensListeAdapter = new NamensListeAdapter(this, spielerList);

        recyclerView.setLayoutManager(new LinearLayoutManager(Spielereingabe.this));

        recyclerView.setAdapter(namensListeAdapter);

        ItemTouchHelper.SimpleCallback itemTouchHelperCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                namensListeAdapter.removeItem(viewHolder.getAdapterPosition());

            }

            @Override
            public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
                // view the background view
            }
        };

        // attaching the touch helper to recycler view
        new ItemTouchHelper(itemTouchHelperCallback).attachToRecyclerView(recyclerView);
    }


    //mathode für button
    public void openKategorien_n() {
        Intent intent = new Intent(this, Kategorien_n.class);
        startActivity(intent);

    }


    //pop-up Dialog
    private void showDialog() {
        View ppview = LayoutInflater.from(getApplicationContext()).inflate(R.layout.popup_enter_name, null);
        final EditText editText = ppview.findViewById(R.id.name_edit);
        final RadioGroup radioGroup = ppview.findViewById(R.id.name_radiogroup);



        final AlertDialog.Builder builder = new AlertDialog.Builder(Spielereingabe.this);
        builder.setView(ppview)
                .setTitle("Namen Eingeben")

                .setPositiveButton("Speicher", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (!editText.getText().toString().isEmpty())
                            spielerList.add(new Spieler()
                                    .setName(editText.getText().toString())
                                    .setGeschlecht(radioGroup.getCheckedRadioButtonId() == R.id.radio_male ? Gender.MALE : Gender.FEMALE));

                        Toast.makeText(Spielereingabe.this, editText.getText().toString() + " wurde hinzugefügt", Toast.LENGTH_SHORT).show();
                    }
                })
                .setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.cancel();
                    }
                })
                .show();


    }


}

Sorry for so much code but I do not know where to start and I would prefer more than too little angegen. Would be great if someone ne solution




Aucun commentaire:

Enregistrer un commentaire