文章目录
- 前言
- 一、效果展示
- 二、代码实现
- 1.UI布局
- 2.SlotAdapter
- 2.SlotsActivity
- 总结
前言
slots游戏:
Slots游戏是一种极具流行度的赌博和娱乐形式,通常被称为老虎机或水果机。它们在赌场、线上游戏平台和手机应用中广泛存在。一般这类游戏都使用Unity和Cocos2d-x两个常见的游戏引擎去开发的,下面介绍下 Android 原生代码实现Slots 旋转动画。
一、效果展示
二、代码实现
1.UI布局
先考虑如何让控件达到滑动旋转的效果,Android 中有许多具备滑动效果的控件,其中一些常见的包括:
RecyclerView
、ListView
、GridView
、ViewPager
、ScrollView
等都具备滑动效果。
Slots游戏滑动的效果我选择使用RecyclerView
来实现这个滑动动画效果。
创建SlotsActivity的xml布局activity_slots
,最外层LinearLayout
里面上半部分是五个RecyclerView
组成,下半部分是两个按钮Button
,一个点击执行单次滑动,另一个则是连续滑动的按钮。
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:ignore="MissingDefaultResource">
<data>
</data>
<LinearLayout
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_weight="1"
android:layout_height="0dp">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_1"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_2"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_3"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_4"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_5"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent" />
</LinearLayout>
<CheckBox
android:id="@+id/is_check"
android:text="是否向上滑动"
android:layout_marginTop="10dp"
android:layout_marginStart="10dp"
android:textSize="20sp"
android:visibility="gone"
android:layout_width="wrap_content"
android:layout_height="50dp" />
<LinearLayout
android:orientation="horizontal"
android:gravity="center"
android:layout_marginTop="20dp"
android:layout_marginBottom="30dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/startButton_down"
android:layout_marginStart="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textAllCaps="false"
android:text="@string/single_slide" />
<Button
android:id="@+id/startButton_up"
android:layout_marginStart="50dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textAllCaps="false"
android:text="@string/continuous_slide" />
</LinearLayout>
</LinearLayout>
</layout>
创建一个名为layout_recycler_item
的xml文件,用作RecyclerView
的xml布局。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_marginTop="20dp"
android:orientation="vertical"
android:gravity="center"
android:layout_height="80dp">
<ImageView
android:id="@+id/image"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:src="@mipmap/icon_orange"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
2.SlotAdapter
先创建文件RecyclerView
的适配器SlotAdapter
,list
列表存放的是五个icon素材。这里适配器是继承了BaseRecyclerViewAdapterHelper(高效的使用RecyclerView应对项目中的常见需求的Adapter),在onBindViewHolder
方法中获取到ImageView
控件的id
后直接利用随机数获取list
素材进行设置。同时getItemCount
方法我们需要设置无限大Int.MAX_VALUE
,确保列表中的数据能够一直滑动。
class SlotAdapter : BaseQuickAdapter<SlotBean, ViewHolder>(){
private var list = arrayListOf(
R.mipmap.icon_peach,
R.mipmap.icon_cherrie,
R.mipmap.icon_seven,
R.mipmap.icon_lemon,
R.mipmap.icon_orange
)
override fun onBindViewHolder(holder: ViewHolder, position: Int, item: SlotBean?) {
val image = holder.itemView.findViewById<ImageView>(R.id.image)
val randomNumber = Random.nextInt(5) // 生成0到5之间的随机整数
item?.type = randomNumber
val id = list[randomNumber]
image.setImageResource(id)
}
override fun getItemCount(items: List<SlotBean>): Int {
return Int.MAX_VALUE
}
override fun onCreateViewHolder(
context: Context,
parent: ViewGroup,
viewType: Int
): ViewHolder {
return QuickViewHolder(R.layout.layout_recycler_item, parent)
}
}
2.SlotsActivity
在SlotsActivity
中初始化RecyclerView
以及点击事件监听,
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_slots)
init()
}
private fun init() {
mDataBinding.startButtonDown.setOnClickListener {
startSlide(0)
}
mDataBinding.startButtonUp.setOnClickListener {
if (mDataBinding.startButtonUp.text.equals(resources.getString(R.string.continuous_slide))){
continuous = true
mDataBinding.startButtonUp.text = resources.getString(R.string.continuous_slide_stop)
startSlide(0)
}else{
mDataBinding.startButtonUp.text = resources.getString(R.string.continuous_slide)
continuous = false
}
}
initRecycler()
}
在初始化initRecycler()
方法中创建适配器进行关联,并且设置RecyclerView
禁止用户手动触摸滑动事件,同时将RecyclerView
的初始位置都设置在中间位置。isScrolling
变量则用来控制当前是否处于滑动状态,代码可以看见关于滑动监听我只监听了最后一个RecyclerView
的事件,其他四个RecyclerView
都没有进行监听设置,因为滑动的顺序案例内我是从左边第一个开始滑动到右边第五个结束。如果是随机滑动顺序的话,则需要监听最后一个开始滑动的RecyclerView
的滚动事件来进行下一次的滑动。
private fun initRecycler() {
val slotAdapter = SlotAdapter()
mDataBinding.recycler1.layoutManager = LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false)
mDataBinding.recycler1.adapter = slotAdapter
mDataBinding.recycler1.setOnTouchListener { p0, p1 -> true }//禁止用户手动触摸滑动
mDataBinding.recycler1.scrollToPosition(Int.MAX_VALUE / 2) // 初始位置
val slotAdapter2 = SlotAdapter()
mDataBinding.recycler2.layoutManager = LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false)
mDataBinding.recycler2.adapter = slotAdapter2
mDataBinding.recycler2.setOnTouchListener { p0, p1 -> true }
mDataBinding.recycler2.scrollToPosition(Int.MAX_VALUE / 2)
val slotAdapter3 = SlotAdapter()
mDataBinding.recycler3.layoutManager = LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false)
mDataBinding.recycler3.adapter = slotAdapter3
mDataBinding.recycler3.setOnTouchListener { p0, p1 -> true }
mDataBinding.recycler3.scrollToPosition(Int.MAX_VALUE / 2)
val slotAdapter4 = SlotAdapter()
mDataBinding.recycler4.layoutManager = LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false)
mDataBinding.recycler4.adapter = slotAdapter4
mDataBinding.recycler4.setOnTouchListener { p0, p1 -> true }
mDataBinding.recycler4.scrollToPosition(Int.MAX_VALUE / 2)
val slotAdapter5 = SlotAdapter()
mDataBinding.recycler5.layoutManager = LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false)
mDataBinding.recycler5.adapter = slotAdapter5
mDataBinding.recycler5.setOnTouchListener { p0, p1 -> true }
mDataBinding.recycler5.scrollToPosition(Int.MAX_VALUE / 2)
// 添加滚动监来控制按钮可点击状态
mDataBinding.recycler5.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
// 检查RecyclerView是否正在滚动
val isScrolling = newState != RecyclerView.SCROLL_STATE_IDLE
// startItemAnim(isScrolling,recyclerView)
if (continuous){
if(!isScrolling){//只有滑动停止的时候才进行下一次滑动
startSlide(1000)
}
}else{
// 单次滑动设置按钮的可点击状态
mDataBinding.startButtonDown.isEnabled = !isScrolling
}
}
})
}
调用startSlide()
方法开始滑动,关键的smoothScrollDownwards()
方法内,其中calculateSpeedPerPixel 函数用于计算每个像素的滚动速度,而 calculateTimeForScrolling 函数用于计算滚动所需的时间。accelerationFactor则是加速因子,影响着滑动的速度。最后启动平滑滚动。
fun startSlide(time:Long){
handler.postDelayed({
smoothScrollDownwards(mDataBinding.recycler1, 180f)
smoothScrollDownwards(mDataBinding.recycler2, 210f)
smoothScrollDownwards(mDataBinding.recycler3, 230f)
smoothScrollDownwards(mDataBinding.recycler4, 250f)
smoothScrollDownwards(mDataBinding.recycler5, 270f)
},time)
}
private fun smoothScrollDownwards(recyclerView: RecyclerView, speed: Float) {
val layoutManager = recyclerView.layoutManager as LinearLayoutManager?
layoutManager?.let {
val firstVisiblePosition = it.findFirstVisibleItemPosition()
val smoothScroller = object : LinearSmoothScroller(recyclerView.context) {
override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics?): Float {
return speed / displayMetrics?.densityDpi!!
}
override fun calculateTimeForScrolling(dx: Int): Int {
val initialTime = super.calculateTimeForScrolling(dx)
return (initialTime / accelerationFactor).toInt()
}
}
val checked = mDataBinding.isCheck.isChecked
smoothScroller.targetPosition = if (checked) firstVisiblePosition + number else firstVisiblePosition- number// 设置滚动的目标位置
layoutManager.startSmoothScroll(smoothScroller) // 启动平滑滚动
}
}
整个核心代码的实现到这里就已经完全ok了,下面附上SlotsActivity的完整代码参考:
package com.example.demo.activity
import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.DisplayMetrics
import android.util.Log
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSmoothScroller
import androidx.recyclerview.widget.RecyclerView
import com.example.demo.R
import com.example.demo.adapter.SlotAdapter
import com.example.demo.databinding.ActivitySlotsBinding
import com.example.demo.utils.AnimationUtil
/**
* @ClassName SlotsActivity
* @Description Slots Game
* @Author lmf
* @Date 2023/9/20 16:32
* @Version 1.0
*/
class SlotsActivity:AppCompatActivity() {
private final val TAG = "SlotsActivity"
private lateinit var mDataBinding:ActivitySlotsBinding
private val number = 20//列表每次滑动的数量
private val accelerationFactor = 2f //滑动加速因子
private var continuous = false //是否持续滚动
private val handler = Handler(Looper.getMainLooper())
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_slots)
init()
}
private fun init() {
mDataBinding.startButtonDown.setOnClickListener {
startSlide(0)
}
mDataBinding.startButtonUp.setOnClickListener {
if (mDataBinding.startButtonUp.text.equals(resources.getString(R.string.continuous_slide))){
continuous = true
mDataBinding.startButtonUp.text = resources.getString(R.string.continuous_slide_stop)
startSlide(0)
}else{
mDataBinding.startButtonUp.text = resources.getString(R.string.continuous_slide)
continuous = false
}
}
initRecycler()
}
/**
*
* @param recyclerView
* @param speed 滚动速度(每像素毫秒)
*/
private fun smoothScrollDownwards(recyclerView: RecyclerView, speed: Float) {
val layoutManager = recyclerView.layoutManager as LinearLayoutManager?
layoutManager?.let {
val firstVisiblePosition = it.findFirstVisibleItemPosition()
val smoothScroller = object : LinearSmoothScroller(recyclerView.context) {
override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics?): Float {
return speed / displayMetrics?.densityDpi!!
}
override fun calculateTimeForScrolling(dx: Int): Int {
val initialTime = super.calculateTimeForScrolling(dx)
return (initialTime / accelerationFactor).toInt()
}
}
val checked = mDataBinding.isCheck.isChecked
smoothScroller.targetPosition = if (checked) firstVisiblePosition + number else firstVisiblePosition- number// 设置滚动的目标位置
layoutManager.startSmoothScroll(smoothScroller) // 启动平滑滚动
}
}
//初始化列表
@SuppressLint("ClickableViewAccessibility")
private fun initRecycler() {
val slotAdapter = SlotAdapter()
mDataBinding.recycler1.layoutManager = LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false)
mDataBinding.recycler1.adapter = slotAdapter
mDataBinding.recycler1.setOnTouchListener { p0, p1 -> true }//禁止用户手动触摸滑动
mDataBinding.recycler1.scrollToPosition(Int.MAX_VALUE / 2) // 初始位置
val slotAdapter2 = SlotAdapter()
mDataBinding.recycler2.layoutManager = LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false)
mDataBinding.recycler2.adapter = slotAdapter2
mDataBinding.recycler2.setOnTouchListener { p0, p1 -> true }
mDataBinding.recycler2.scrollToPosition(Int.MAX_VALUE / 2)
val slotAdapter3 = SlotAdapter()
mDataBinding.recycler3.layoutManager = LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false)
mDataBinding.recycler3.adapter = slotAdapter3
mDataBinding.recycler3.setOnTouchListener { p0, p1 -> true }
mDataBinding.recycler3.scrollToPosition(Int.MAX_VALUE / 2)
val slotAdapter4 = SlotAdapter()
mDataBinding.recycler4.layoutManager = LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false)
mDataBinding.recycler4.adapter = slotAdapter4
mDataBinding.recycler4.setOnTouchListener { p0, p1 -> true }
mDataBinding.recycler4.scrollToPosition(Int.MAX_VALUE / 2)
val slotAdapter5 = SlotAdapter()
mDataBinding.recycler5.layoutManager = LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false)
mDataBinding.recycler5.adapter = slotAdapter5
mDataBinding.recycler5.setOnTouchListener { p0, p1 -> true }
mDataBinding.recycler5.scrollToPosition(Int.MAX_VALUE / 2)
// 添加滚动监来控制按钮可点击状态
mDataBinding.recycler5.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
// 检查RecyclerView是否正在滚动
val isScrolling = newState != RecyclerView.SCROLL_STATE_IDLE
// startItemAnim(isScrolling,recyclerView)
if (continuous){
if(!isScrolling){//只有滑动停止的时候才进行下一次滑动
startSlide(1000)
}
}else{
// 单次滑动设置按钮的可点击状态
mDataBinding.startButtonDown.isEnabled = !isScrolling
}
}
})
}
//调用开始滑动动画
fun startSlide(time:Long){
handler.postDelayed({
smoothScrollDownwards(mDataBinding.recycler1, 180f)
smoothScrollDownwards(mDataBinding.recycler2, 210f)
smoothScrollDownwards(mDataBinding.recycler3, 230f)
smoothScrollDownwards(mDataBinding.recycler4, 250f)
smoothScrollDownwards(mDataBinding.recycler5, 270f)
},time)
}
}
总结
以上就是Android 实现 Slots 的游戏旋转效果的全部内容了,本文仅仅简单介绍了仿Slots游戏的旋转效果,真正的Slots 游戏涉及到每次滑动的得分情况处理以及更加复杂的动画特效展示。