基于BaseAdapter 的翻牌游戏

原创 2018年04月16日 18:46:31

运行效果:



java:

MainActivity:



import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.GridView;
import android.widget.TextView;

import com.example.shinelon.mycardgame.model.Game;
import com.example.shinelon.mycardgame.model.GameAdapter;

public class MainActivity extends AppCompatActivity {

    GameAdapter gameAdapter;
    public Game game;
    public TextView textView_score;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        GridView gridView = findViewById(R.id.grid_view);
        textView_score = findViewById(R.id.score);
        game = new Game(40);
        gameAdapter = new GameAdapter(this,game.getCards());
        gridView.setAdapter(gameAdapter);


    }

    public void updateUI() {
        gameAdapter.notifyDataSetChanged();
        textView_score.setText(Integer.toString(game.getScore()));
    }
}


GameAdapter:


import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.BaseAdapter;
import android.widget.Button;

import com.example.shinelon.mycardgame.MainActivity;
import com.example.shinelon.mycardgame.R;

import java.util.ArrayList;
import java.util.Arrays;


public class GameAdapter extends BaseAdapter {

    MainActivity context;
    ArrayList<Card> cards;


    public GameAdapter(MainActivity context, ArrayList<Card> cards) {
        this.context = context;
        this.cards = cards;
    }

    @Override
    public int getCount() {
        return cards.size();
    }

    @Override
    public Object getItem(int position) {
        return cards.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        final Button cardButton;
        final Card card = this.cards.get(position);

        if (convertView == null) {
            View v = LayoutInflater.from(this.context).inflate(R.layout.card, null);
            cardButton = v.findViewById(R.id.card_btn);
        } else {
            cardButton = (Button) convertView;
        }



//        if(card.isChosen())
//        {
//            cardButton.setBackgroundResource(R.drawable.blankcard);
//            cardButton.setText(card.getCountents());
//        }
//        else
//        {
//            cardButton.setBackgroundResource(R.drawable.stanfordtree);
//            cardButton.setText("");
//        }
//


        // 动画效果
        if (card.isChosen())
        {
            if (!card.isChanged()) {
                ObjectAnimator animator1 = ObjectAnimator.ofFloat(cardButton, "rotationY", 0, 90).setDuration(500);
                animator1.setInterpolator(new AccelerateInterpolator());
                ObjectAnimator animator2 = ObjectAnimator.ofFloat(cardButton, "rotationY", 270, 360).setDuration(500);
                animator2.setInterpolator(new DecelerateInterpolator());

                animator1.addListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        super.onAnimationEnd(animation);
                        cardButton.setText(card.getCountents());
                        cardButton.setBackgroundResource(R.drawable.blankcard);
                        card.setChanged(true);
                    }
                });

                AnimatorSet set = new AnimatorSet();
                set.play(animator1).before(animator2);
                set.start();
            } else {

                cardButton.setText(card.getCountents());
                cardButton.setBackgroundResource(R.drawable.blankcard);
            }
        } else {
            if (card.isChanged()) {
                ObjectAnimator animator1 = ObjectAnimator.ofFloat(cardButton, "rotationY", 0, 90).setDuration(500);
                animator1.setInterpolator(new AccelerateInterpolator());
                ObjectAnimator animator2 = ObjectAnimator.ofFloat(cardButton, "rotationY", 270, 360).setDuration(500);
                animator2.setInterpolator(new DecelerateInterpolator());

                animator1.addListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        super.onAnimationEnd(animation);
                        cardButton.setText("");
                        cardButton.setBackgroundResource(R.drawable.stanfordtree);
                        card.setChanged(false);
                    }
                });

                AnimatorSet set = new AnimatorSet();
                set.play(animator1).before(animator2);
                set.start();
                card.setChanged(true);
            } else {
                cardButton.setText("");
                cardButton.setBackgroundResource(R.drawable.stanfordtree);
            }
        }


        if(card.isMatched() && cardButton.getAlpha() == 1)
        {
            ObjectAnimator animator_alpha = ObjectAnimator.ofFloat(cardButton, "alpha", 1, 0.3f).setDuration(1000);
            animator_alpha.setInterpolator(new AccelerateInterpolator());
            AnimatorSet set = new AnimatorSet();
            set.play(animator_alpha);
            set.start();
        }
        //cardButton.setAlpha(card.isMatched() ? 0.3f : 1);

        cardButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                context.textView_score.setText( Integer.toString(context.game.getScore()));
                context.game.chooseCardAtIndex(position);
                context.updateUI();
            }
        });
        return cardButton;
    }



}
Game:
package com.example.shinelon.mycardgame.model;

import android.util.Log;
import android.widget.Toast;

import com.example.shinelon.mycardgame.MainActivity;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;

public class Game {
    private int play_cards_max_num;
    private int cards_num;
    private String suits[];
    private String ranks[];
    private ArrayList<Card> cards = new ArrayList<>();
    private int score = 0;


    public Game(int play_cards_max_num) {
        this.play_cards_max_num = play_cards_max_num > 52 ? 52 : play_cards_max_num;
        this.cards_num = 52;
        this.suits = new String[]{"♥", "♣", "◆", "♠"};
        this.ranks = new String[]{"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
        this.setCards();
    }

    private void addCard(Card card)
    {
        cards.add(card);
    }


    //in a range generate not repetition number
    private int[] rangeRandom(int rand_num)
    {
        int[] intRet = new int[rand_num];
        int intRd = 0; //存放随机数
        int count = 0; //记录生成的随机数个数
        int flag = 0; //是否已经生成过标志
        while (count < rand_num) {
            Random rdm = new Random(System.currentTimeMillis());
            intRd = Math.abs(rdm.nextInt()) % this.cards_num;
            for (int i = 0; i < count; i++) {
                if (intRet[i] == intRd) {
                    flag = 1;
                    break;
                } else {
                    flag = 0;
                }
            }
            if (flag == 0) {
                intRet[count] = intRd;
                count++;
            }
        }
        return intRet;
    }

    public void setCards() {

        int range_random[];
        range_random = this.rangeRandom(this.play_cards_max_num);
        ArrayList<Card> all_cards = new ArrayList<>();
        for(String suit:this.suits){
            for(String rank:this.ranks){
                Card card = new Card();
                card.setSuit(suit);
                card.setRank(rank);
                all_cards.add(card);
            }
        }
        for(int i:range_random)
        {
            cards.add(all_cards.get(i));
        }
    }

    public ArrayList<Card> getCards()
    {
        return cards;
    }

    public Card cardAtIndex(int index) {
        return (index < cards.size()) ? cards.get(index) : null;
    }

    public int getScore() {
        return score;
    }

    public void chooseCardAtIndex(int index) {
        Card card = cardAtIndex(index);
        if (!card.isMatched()) {
            if (card.isChosen()) {
                card.setChosen(false);
            } else {
                for (Card otherCard : cards) {
                    if (otherCard.isChosen() && !otherCard.isMatched()) {
                        int matchScore = card.match(new Card[]{otherCard});
                        if (matchScore > 0) {
                            this.score += matchScore;
                            otherCard.setMatched(true);
                            card.setMatched(true);
                        } else {
                            this.score -= 1;
                            otherCard.setChosen(false);
                        }
                        break;
                    }
                }
                card.setChosen(true);
            }
        }
    }
}
Card:

package com.example.shinelon.mycardgame.model;

public class Card {
    private boolean chosen = false;
    private boolean matched = false;
    private String suit;
    private String rank;
    private boolean changed = false;

    //if chosen
    public boolean isChosen(){
        return chosen;
    }

    public void setChosen(boolean chosen) {
        this.chosen = chosen;
    }

    //if matched
    public boolean isMatched()
    {
        return matched;
    }

    public void setMatched(boolean matched)
    {
        this.matched = matched;
    }

    public boolean isChanged() {
        return changed;
    }

    public void setChanged(boolean changed) {
        this.changed = changed;
    }

    public void setSuit(String suit) {
        this.suit = suit;
    }

    public void setRank(String rank) {
        this.rank = rank;
    }

    public String getCountents(){
        return this.suit + this.rank;
    }

    public int match(Card card){
        if(card.getCountents().equals(this.getCountents()))
        {
            return 1;
        }
        else
        {
            return 0;
        }
    }

    public int match(Card[] otherCards) {
        int score = 0;
        for (Card card : otherCards) {
            if (card.rank.equals(this.rank)) {
                score = 2;
                if(card.suit.equals(this.suit))
                {
                    score += 3;
                }
            }
            else if(card.suit.equals(this.suit))
            {
                score = 1;
            }
        }
        return score;
    }
}


收藏助手
不良信息举报
您举报文章:基于BaseAdapter 的翻牌游戏
举报原因:
原因补充:

(最多只允许输入30个字)