📌  相关文章
📜  如何在 Android 中构建一个简单的滑动游戏?

📅  最后修改于: 2022-05-13 01:54:19.531000             🧑  作者: Mango

如何在 Android 中构建一个简单的滑动游戏?

在本文中,我们将使用 android studio 中的 RecyclerView 创建一个简单的滑动游戏。 RecyclerView 是包含与您的数据对应的视图的 ViewGroup。它本身就是一个视图,因此您可以像添加任何其他 UI 元素一样将 RecyclerView 添加到您的布局中。我们将使用ItemTouchHelper来实现滑动功能。此类旨在与任何 LayoutManager 一起使用,但在某些情况下,可以通过扩展 ItemTouchHelper.Callback 类中的方法或在 LayoutManager 中实现 ItemTouchHelper.ViewDropHandler 接口来针对您的自定义 LayoutManager 进行优化。

我们将在本文中构建什么?

在这个游戏中,玩家必须将不同颜色的条滑动到相应的侧面。如果是“红色”色条,则玩家必须将其滑动到左侧,如果是“黄色”色条,则玩家必须将其滑动到右侧。如果玩家正确滑动,他/她可以继续游戏。如果酒吧被刷到错误的一侧,游戏将结束,玩家必须重新开始游戏。下面给出了一个示例视频,以了解我们将在本文中做什么。请注意,我们将使用Java语言来实现这个项目。

该项目的输出

分步实施

以下是我们必须遵循的步骤来创建游戏:

  1. 创建一个基本的 RecyclerView
  2. 创建栏并将其添加到 RecyclerView
  3. 使用 ItemTouchHelper 将滑动功能添加到 RecyclerView
  4. 在警报对话框中添加游戏。

重要方法:

  • attachToRecyclerView() - 将 ItemTouchHelper 附加到提供的 RecyclerView。
  • SimpleCallback() – 默认回调的简单包装,您可以使用拖动和滑动方向构建该回调,此类将处理标志回调。您仍应根据您的用例覆盖 onMove 或 onSwiped。
  • onSwiped() - 用于实现 RecyclerView 的摆动函数

重要常数:

  • LEFT - 左方向,用于滑动和拖动控制
  • RIGHT - 右方向,用于滑动和拖动控制

让我们使用 RecyclerView 构建简单的滑动游戏。我们将使用Java编程语言来实现这个项目。

步骤 1:创建一个新项目

首先,我们要创建一个新项目。要在 Android Studio 中创建新项目,请参阅如何在 Android Studio 中创建/启动新项目。

第二步:创建类文件

为了实现基本的 RecyclerView,我们必须创建两个新的类文件。

  1. 适配器类
  2. 模型类

导航:应用程序> Java

适配器类

模型类

第 3 步:创建 XML 文件

我们必须创建两个 XML 文件:

  1. 在布局中——bars.xml
  2. 在drawable – shapeofthebar.xml

1.bars.xml

导航:应用 > 资源 > 布局

酒吧.xml

2.shapeofthebar.xml

导航:app > res > drawable

shapeofthebar.xml

第 4 步:使用 activity_main.xml 文件

导航到app > res > layout > activity_main.xml并将以下代码添加到该文件。下面是activity_main.xml文件的代码。

XML


  
    


XML




XML


    
    


Java
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
  
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Toast;
  
import org.jetbrains.annotations.NotNull;
  
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
  
  
public class MainActivity extends AppCompatActivity {
  
    // Creating RecyclerView
    private RecyclerView recyclerView;
    // Creating a ArrayList of type Modelclass
    private List barsColor;
  
    // Alert dialog
    AlertDialog.Builder alertDialog;
    private Adapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // Adding elements to the barsColor
        barsColor=new ArrayList<>();
        Random random = new Random();
        // Add 15 bars to the RecyclerView
        for(int i=0;i<15;i++)
        {
            // Generate a random number
            int n= random.nextInt(2);
            // Giving the color for the 
            // bar based on the random number
            if(n==0)
            {
                barsColor.add(new Modelclass("Yellow"));
            }
            else
            {
                barsColor.add(new Modelclass("Red"));
            }
        }
  
        // Finding the RecyclerView by it's ID
        recyclerView = findViewById(R.id.recyclerview);
  
        // Creating an Adapter Object
        adapter=new Adapter(this,barsColor);
  
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
  
        // Add ItemTouchHelper to the recyclerView
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleCallback);
        itemTouchHelper.attachToRecyclerView(recyclerView);
  
        adapter.notifyDataSetChanged();
  
    }
  
    ItemTouchHelper.SimpleCallback simpleCallback= new ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.LEFT|ItemTouchHelper.RIGHT) {
        @Override
        public boolean onMove(@NonNull @NotNull RecyclerView recyclerView, @NonNull @NotNull RecyclerView.ViewHolder viewHolder, @NonNull @NotNull RecyclerView.ViewHolder target) {
            return false;
        }
  
        @Override
        public void onSwiped(@NonNull @NotNull RecyclerView.ViewHolder viewHolder, int direction) {
            // get the position of the swiped bar
            int position = viewHolder.getPosition();
            switch (direction) {
                // Right side is for Yellow
                case ItemTouchHelper.LEFT: {
                    if ((barsColor.get(position).getColor()).equals("Red")) {
                        barsColor.remove(position);
                        adapter.notifyDataSetChanged();
                    } else {
                        endthegame();
                        adapter.notifyDataSetChanged();
                        alertDialog.show();
                    }
                    break;
                }
                // Left side is for Red
                case ItemTouchHelper.RIGHT: {
                    if ((barsColor.get(position).getColor()).equals("Yellow")) {
                        barsColor.remove(position);
                        adapter.notifyDataSetChanged();
                    } else {
                        endthegame();
                        adapter.notifyDataSetChanged();
                        alertDialog.show();
                    }
                    break;
                }
            }
        }
    };
  
    // Shows game ended dialog
    private void endthegame()
    {
        alertDialog=new AlertDialog.Builder(this);
        alertDialog.setMessage("Oopa! Wrong side! Try Again! ").setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "Try again", Toast.LENGTH_SHORT).show();
            }
        }).setNegativeButton("Later", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "Later!", Toast.LENGTH_SHORT).show();
            }
        });
        alertDialog.create();
    }
}


Java
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.ColorSpace;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
  
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;
  
import org.jetbrains.annotations.NotNull;
  
import java.util.List;
  
public class Adapter extends RecyclerView.Adapter {
  
    List bars;
    Context context;
  
    Adapter(Context c, List list )
    {
        bars=list;
        context = c;
    }
  
    @NonNull
    @NotNull
    @Override
    @SuppressLint("ResourceType")
    public ViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.bars,parent,false);
        return new ViewHolder(view);
    }
  
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onBindViewHolder(@NonNull @NotNull Adapter.ViewHolder holder, int position) {
  
        // Getting the color for every position
        String color = bars.get(position).getColor();
  
        // Set the color to the bar
        if (color.equals("Yellow"))
        {
            holder.linearLayout.setBackgroundTintList(context.getResources().getColorStateList(R.color.yellow));
        }
        else
        {
            holder.linearLayout.setBackgroundTintList(context.getResources().getColorStateList(R.color.Red));
        }
    }
  
    @Override
    public int getItemCount() {
        return bars.size();
    }
  
    public class ViewHolder extends RecyclerView.ViewHolder {
        LinearLayout linearLayout;
        public ViewHolder(@NonNull @org.jetbrains.annotations.NotNull View itemView) {
            super(itemView);
            linearLayout=itemView.findViewById(R.id.barlayout);
        }
    }
}


Java
public class Modelclass {
    
    String color;
  
    Modelclass(String color)
    {
        this.color=color;
    }
  
    public String getColor() {
        return color;
    }
  
}


第 5 步:使用 bar.xml 文件

导航到app > res > layout并将以下代码添加到该文件。下面是bars.xml文件的代码。

XML




第 6 步:使用 shapeofthebar.xml 文件

导航到app > res > drawable并将以下代码添加到该文件。下面是shapeofthebar.xml文件的代码。

XML



    
    

第 7 步:使用 MainActivity。Java

转到MainActivity。 Java文件并参考以下代码。下面是MainActivity 的代码。 Java文件。代码中添加了注释以更详细地理解代码。

Java

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
  
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Toast;
  
import org.jetbrains.annotations.NotNull;
  
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
  
  
public class MainActivity extends AppCompatActivity {
  
    // Creating RecyclerView
    private RecyclerView recyclerView;
    // Creating a ArrayList of type Modelclass
    private List barsColor;
  
    // Alert dialog
    AlertDialog.Builder alertDialog;
    private Adapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // Adding elements to the barsColor
        barsColor=new ArrayList<>();
        Random random = new Random();
        // Add 15 bars to the RecyclerView
        for(int i=0;i<15;i++)
        {
            // Generate a random number
            int n= random.nextInt(2);
            // Giving the color for the 
            // bar based on the random number
            if(n==0)
            {
                barsColor.add(new Modelclass("Yellow"));
            }
            else
            {
                barsColor.add(new Modelclass("Red"));
            }
        }
  
        // Finding the RecyclerView by it's ID
        recyclerView = findViewById(R.id.recyclerview);
  
        // Creating an Adapter Object
        adapter=new Adapter(this,barsColor);
  
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
  
        // Add ItemTouchHelper to the recyclerView
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleCallback);
        itemTouchHelper.attachToRecyclerView(recyclerView);
  
        adapter.notifyDataSetChanged();
  
    }
  
    ItemTouchHelper.SimpleCallback simpleCallback= new ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.LEFT|ItemTouchHelper.RIGHT) {
        @Override
        public boolean onMove(@NonNull @NotNull RecyclerView recyclerView, @NonNull @NotNull RecyclerView.ViewHolder viewHolder, @NonNull @NotNull RecyclerView.ViewHolder target) {
            return false;
        }
  
        @Override
        public void onSwiped(@NonNull @NotNull RecyclerView.ViewHolder viewHolder, int direction) {
            // get the position of the swiped bar
            int position = viewHolder.getPosition();
            switch (direction) {
                // Right side is for Yellow
                case ItemTouchHelper.LEFT: {
                    if ((barsColor.get(position).getColor()).equals("Red")) {
                        barsColor.remove(position);
                        adapter.notifyDataSetChanged();
                    } else {
                        endthegame();
                        adapter.notifyDataSetChanged();
                        alertDialog.show();
                    }
                    break;
                }
                // Left side is for Red
                case ItemTouchHelper.RIGHT: {
                    if ((barsColor.get(position).getColor()).equals("Yellow")) {
                        barsColor.remove(position);
                        adapter.notifyDataSetChanged();
                    } else {
                        endthegame();
                        adapter.notifyDataSetChanged();
                        alertDialog.show();
                    }
                    break;
                }
            }
        }
    };
  
    // Shows game ended dialog
    private void endthegame()
    {
        alertDialog=new AlertDialog.Builder(this);
        alertDialog.setMessage("Oopa! Wrong side! Try Again! ").setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "Try again", Toast.LENGTH_SHORT).show();
            }
        }).setNegativeButton("Later", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "Later!", Toast.LENGTH_SHORT).show();
            }
        });
        alertDialog.create();
    }
}

第 8 步:使用适配器。Java

下面是适配器的代码。 Java文件。

Java

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.ColorSpace;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
  
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;
  
import org.jetbrains.annotations.NotNull;
  
import java.util.List;
  
public class Adapter extends RecyclerView.Adapter {
  
    List bars;
    Context context;
  
    Adapter(Context c, List list )
    {
        bars=list;
        context = c;
    }
  
    @NonNull
    @NotNull
    @Override
    @SuppressLint("ResourceType")
    public ViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.bars,parent,false);
        return new ViewHolder(view);
    }
  
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onBindViewHolder(@NonNull @NotNull Adapter.ViewHolder holder, int position) {
  
        // Getting the color for every position
        String color = bars.get(position).getColor();
  
        // Set the color to the bar
        if (color.equals("Yellow"))
        {
            holder.linearLayout.setBackgroundTintList(context.getResources().getColorStateList(R.color.yellow));
        }
        else
        {
            holder.linearLayout.setBackgroundTintList(context.getResources().getColorStateList(R.color.Red));
        }
    }
  
    @Override
    public int getItemCount() {
        return bars.size();
    }
  
    public class ViewHolder extends RecyclerView.ViewHolder {
        LinearLayout linearLayout;
        public ViewHolder(@NonNull @org.jetbrains.annotations.NotNull View itemView) {
            super(itemView);
            linearLayout=itemView.findViewById(R.id.barlayout);
        }
    }
}

第 9 步:使用模型类。Java

下面是模型类的代码。 Java文件。

Java

public class Modelclass {
    
    String color;
  
    Modelclass(String color)
    {
        this.color=color;
    }
  
    public String getColor() {
        return color;
    }
  
}

输出:

这是我们项目的输出。

该项目的输出