这篇文章主要为大家介绍了Java如何使用定时器编写一个简单的抢红包小游戏,文中的示例代码讲解详细,感兴趣的小伙伴可以尝试一下
1.新建项目
2. 添加 计时器,按钮组件
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:height="match_parent"
ohos:width="match_parent"
ohos:alignment="center"
ohos:orientation="vertical">
<TickTimer
ohos:id="$+id:tick_1"
ohos:height="match_content"
ohos:width="match_content"
ohos:text_color="red"
ohos:text_size="50vp"
ohos:text_alignment="center"
ohos:layout_alignment="center"
/>
<Button
ohos:id="$+id:bt_1"
ohos:height="match_content"
ohos:width="match_content"
ohos:margin="30vp"
ohos:clickable="false"
ohos:text="准备!"
ohos:text_color="red"
ohos:text_size="50vp"
ohos:text_alignment="center"
ohos:layout_alignment="center"/>
</DirectionalLayout>
3.抢红包业务逻辑
package com.sgg.hongbao.slice;
import com.sgg.hongbao.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.TickTimer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.logging.SimpleFormatter;
public class MainAbilitySlice extends AbilitySlice {
Long money = 0L;
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
// 获取定时器组件
TickTimer tickTimer = (TickTimer) findComponentById(ResourceTable.Id_tick_1);
//获取按钮组件
Button bt = (Button) findComponentById(ResourceTable.Id_bt_1);
tickTimer.setCountDown(false);
tickTimer.start();
// 10S 准备时间
int countDwonTime = 3;
tickTimer.setTickListener(tickTimer1 -> {
Long aLong = string2Long(tickTimer1.getText());
Long time = countDwonTime - aLong;
if (aLong >= 10) {
bt.setText(" 恭喜你 抢到 " + money + " 元 ");
bt.setMultipleLine(true);
//关闭定时器
tickTimer.setText(" 00 : 00 ");
tickTimer.stop();
return;
}
if (time <= 0) {
bt.setText("点我疯狂抢红包");
} else {
if (aLong == 0) {
} else {
bt.setText(" 倒计时 " + time + " 秒");
}
}
});
bt.setClickedListener(component -> {
money+=1000;
});
}
private Long string2Long(String str) {
long time = 0;
try {
time = new SimpleDateFormat("mm:ss").parse(str).getSeconds();
} catch (ParseException e) {
e.printStackTrace();
}
return time;
}
@Override
public void onActive() {
super.onActive();
}
@Override
public void onForeground(Intent intent) {
super.onForeground(intent);
}
}
4.效果演示
到此这篇关于Java使用定时器编写一个简单的抢红包小游戏的文章就介绍到这了,更多相关Java抢红包游戏内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!
沃梦达教程
本文标题为:Java使用定时器编写一个简单的抢红包小游戏
![](/xwassets/images/pre.png)
![](/xwassets/images/next.png)
猜你喜欢
- JSP 制作验证码的实例详解 2023-07-30
- Java中的日期时间处理及格式化处理 2023-04-18
- Java实现顺序表的操作详解 2023-05-19
- 基于Java Agent的premain方式实现方法耗时监控问题 2023-06-17
- SpringBoot使用thymeleaf实现一个前端表格方法详解 2023-06-06
- ExecutorService Callable Future多线程返回结果原理解析 2023-06-01
- 深入了解Spring的事务传播机制 2023-06-02
- JSP页面间传值问题实例简析 2023-08-03
- Springboot整合minio实现文件服务的教程详解 2022-12-03
- Spring Security权限想要细化到按钮实现示例 2023-03-07