Skip to content

Commit

Permalink
refactor(DataBase.kt): Rewrote DataBase.kt
Browse files Browse the repository at this point in the history
Decomposed some functions to improve readability. Note that some
functions are in an early stage and may change at any time
  • Loading branch information
Dream-Rainy committed Jul 20, 2023
1 parent 6479663 commit 3b7a250
Show file tree
Hide file tree
Showing 23 changed files with 613 additions and 539 deletions.
37 changes: 25 additions & 12 deletions README.MD
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,29 @@
core {
# 指定显示语言
language="en_us"
# 玩家补货时的税率
"tax_rate"=0.01
# 数据库地址,数据库目前仅支持Postgresql
"database_url"="jdbc:postgresql://localhost:12346/imyvmvillagershop"
# 数据库用户名
"database_username"=root
# 数据库密码
"database_password"="1145141919810"
tax {
# 玩家补货时的税率
restock=0.01
}
# 数据库相关设置
database {
# 数据库类型,支持 "POSTGRESQL" , "MYSQL" , "ORACLE" 以及 "SQLSERVER"
# 只有 POSTGRESQL 确认可用,其余理论可行
database=POSTGRESQL
# 数据库地址,默认为 POSTGRESQL
# mysql相关地址 : jdbc:mysql://localhost:3306/imyvmvillagershop
# 或 Oracle : jdbc:oracle:thin:@//localhost:1521/imyvmvillagershop
# 或 SQL Server : jdbc:sqlserver://localhost:32768;databaseName=imyvmvillagershop
# 如果均不可用,插件会在world文件夹下自动生成Sqlite数据库文件
url="jdbc:pgsql://localhost:5432/imyvmvillagershop"
# 数据库用户名
username=root
# 数据库密码
password="1145141919810"
# 仅在MySQL数据库生效,用来调整Hikari池的大小
maximumPoolSize=10
}
}
```

管理员可以使用`/villagershop config reload`来重载配置,使用`/villagershop taxrate set <taxrate>`来设置税率。
Expand Down Expand Up @@ -71,13 +85,13 @@ f(x) = p \times c \times t
### 2.商店设置
玩家可以使用`/villagershop manager info set <shopname> {shopnamenew,x y z}`来修改商店的名称或者位置。当你不想要该商店时,可以使用`/villagershop delete {shopname,shopnumber}`[^1]来删除该商店,管理员可以使用`shopnumber`删除任意不符合规定的商店,无需提前通知拥有者。删除商店会返还所有的库存,但是并不会返还创建时消耗的货币。同时,被管理员删除的商店并不会返还库存
玩家可以使用`/villagershop manager info set {shopname,id} {shopnamenew,x y z}`来修改商店的名称或者位置。当你不想要该商店时,可以使用`/villagershop delete {shopname,shopnumber}`[^1]来删除该商店,管理员可以使用`shopnumber`删除任意不符合规定的商店,无需提前通知拥有者。删除商店会返还所有的库存,但是并不会返还创建时消耗的货币。同时,被管理员删除的商店并不会返还库存
同时,管理员可以使用`/villagershop manager search {shopname:shopname, location:location, owner:owner, range:range}`,owner参数可以使用玩家**创建商店时**的ID。可以使用`/villagershop manager inquire <shopnumber>`获取特定商店的详细信息。
管理员在征得玩家以及管理组同意的情况下,可以使用`/villagershop setAdmin <shopnumber>`[^1]来将该商店转化为系统商店。**注意,该操作也不会返还库存。**
## 四、收购相关
服务器在特定时间(如每半小时)就系统商店中已在出售的一种物品发起一次收购,拥有物品的玩家可以使用`/villagershop sell [count]`出售指定数量的收购物品,达到收购数量后服务器停止收购
目前收购改为实体商店收购,仍在实现中
收购价格为系统商店在售价格的**80%**
## 五、其他
Expand All @@ -88,8 +102,7 @@ f(x) = p \times c \times t
- [ ] 补货时可以从玩家身上的潜影盒中获取所需物品
- [ ] 系统商店限制单个玩家购买数量
- [x] 支持范围搜索商店,以及通过玩家名称搜索商店,不输出重复结果。
- [x] 完成收购指令
- [x] 完成商店的实体创建
- [ ] 完成商店的实体创建
- [ ] 完成GUI呈现以及操作监听
[^1]: 对于该指令,你需要使用`/villagershop confirm`来确定执行。同时,你可以使用`/villagershop cancel`来取消操作,所有操作在60s后都会自动取消。并且,在执行下一个需要确认的操作前,你需要先确认已有的操作。
17 changes: 11 additions & 6 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,10 @@ repositories {
url = uri("https://share.dreamrain.top")
}

maven {
name = "JP Mods"
url = uri("https://maven.jpcode.dev")
}
// maven {
// name = "JP Mods"
// url = uri("https://maven.jpcode.dev")
// }

// Fabric Permissions Api
maven {
Expand Down Expand Up @@ -69,9 +69,14 @@ dependencies {
implementation("org.jetbrains.exposed:exposed-core:${project["exposed_version"]}")
implementation("org.jetbrains.exposed:exposed-dao:${project["exposed_version"]}")
implementation("org.jetbrains.exposed:exposed-jdbc:${project["exposed_version"]}")
implementation("org.postgresql:postgresql:${project["postgresql_version"]}")
implementation("com.mysql:mysql-connector-j:${project["mysql-connector_version"]}")
implementation("com.zaxxer:HikariCP:${project["HikariCP_version"]}")
implementation("com.impossibl.pgjdbc-ng", "pgjdbc-ng", project["postgresql_version"])
implementation("org.xerial:sqlite-jdbc:${project["sqlite-jdbc_version"]}")
implementation("com.microsoft.sqlserver:mssql-jdbc:${project["mssql-jdbc_version"]}")
implementation("com.oracle.database.jdbc:ojdbc11:${project["ojdbc11_version"]}")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:${project["kotlinx-serialization-json_version"]}")
implementation("com.typesafe:config:1.4.2")
implementation("com.typesafe:config:${project["typesafe_version"]}")
// Uncomment the following line to enable the deprecated Fabric API modules.
// These are included in the Fabric API production distribution and allow you to update your mod to the latest modules at a later more convenient time.

Expand Down
36 changes: 24 additions & 12 deletions gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,38 @@ org.gradle.jvmargs=-Xmx2G
kotlin.code.style=official

# Gradle Plugins
kotlin_version=1.8.21
loom_version=1.2-SNAPSHOT
kotlin_version=1.9.0
loom_version=1.3-SNAPSHOT

# Fabric Properties
# check these on https://fabricmc.net/develop
minecraft_version=1.19
yarn_mappings=1.19+build.4
loader_version=0.14.19
minecraft_version=1.20.1
yarn_mappings=1.20.1+build.9
loader_version=0.14.21

# Mod Properties
mod_version = 1.0.0
maven_group = com.imyvm

# Dependencies
fabric_version = 0.58.0+1.19
fabric_kotlin_version=1.9.3+kotlin.1.8.20
fabric_version= 0.86.0+1.20.1
fabric_kotlin_version=1.10.8+kotlin.1.9.0
brigadier_version = 1.0.18
fabric_permissions_api_version = 0.2-SNAPSHOT
imyvm_hoki_version = 1.1.3
imyvm_economy_version = 1.2.3
exposed_version = 0.40.1
postgresql_version = 42.2.2
kotlinx-serialization-json_version = 1.5.0
imyvm_hoki_version = 1.1.4
imyvm_economy_version = 1.2.4
exposed_version = 0.41.1
postgresql_version = 0.8.9
mysql-connector_version = 8.0.33
HikariCP_version = 5.0.1
sqlite-jdbc_version = 3.42.0.0
mssql-jdbc_version = 12.3.0.jre17-preview
ojdbc11_version = 23.2.0.0
typesafe_version= 1.4.2
kotlinx-serialization-json_version = 1.5.1

loom_libraries_base=https://bmclapi2.bangbang93.com/maven/
loom_resources_base=https://bmclapi2.bangbang93.com/assets/
loom_version_manifests=https://bmclapi2.bangbang93.com/mc/game/version_manifest.json
loom_experimental_versions=https://maven.fabricmc.net/net/minecraft/experimental_versions.json
loom_fabric_repository=https://repository.hanbings.io/proxy/
2 changes: 1 addition & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip
networkTimeout=10000
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
3 changes: 2 additions & 1 deletion settings.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@ pluginManagement {

repositories {
gradlePluginPortal()
mavenCentral()
maven {
name = "Fabric"
url = uri("https://maven.fabricmc.net/")
}
maven {
url = uri("https://libraries.minecraft.net")
}
mavenCentral()

}

plugins {
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public abstract class VillagerMovementMixin {

@Redirect(method = "tickMovement", at = @At(value = "INVOKE",target = "Lnet/minecraft/entity/LivingEntity;setVelocity(DDD)V"))
private void modifySetVelocity(LivingEntity entity, double x, double y, double z) {
if (entity instanceof VillagerEntity && entity.getScoreboardTags().contains("VillagerShop")) {
if (entity instanceof VillagerEntity && entity.getCommandTags().contains("VillagerShop")) {
entity.setVelocity(0.0, y, 0.0);
} else {
entity.setVelocity(x, y, z);
Expand All @@ -21,7 +21,7 @@ private void modifySetVelocity(LivingEntity entity, double x, double y, double z

@Redirect(method = "tickMovement", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/LivingEntity;travel(Lnet/minecraft/util/math/Vec3d;)V"))
private void modifyTravel(LivingEntity entity, Vec3d movement) {
if (entity instanceof VillagerEntity && entity.getScoreboardTags().contains("VillagerShop")) {
if (entity instanceof VillagerEntity && entity.getCommandTags().contains("VillagerShop")) {
entity.travel(new Vec3d(0.0, movement.y, 0.0));
} else {
entity.travel(movement);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public VillagerPreventWitchMixin(EntityType<? extends PassiveEntity> entityType,
@Inject(method = "onStruckByLightning", at = @At("HEAD"), cancellable = true)
private void preventWitchTransformation(CallbackInfo ci) {
VillagerEntity villager = (VillagerEntity) (Object) this;
if (villager.getScoreboardTags().contains("VillagerShop")) {
if (villager.getCommandTags().contains("VillagerShop")) {
ci.cancel();
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.imyvm.villagerShop.mixin;

import net.minecraft.item.ItemStack;
import net.minecraft.village.TradeOffer;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;

import java.util.Objects;

@Mixin(TradeOffer.class)
public abstract class VillagerTradeItemsMatchMixin {
@Shadow public abstract ItemStack getAdjustedFirstBuyItem();

@Shadow @Final private ItemStack firstBuyItem;

@Inject(method = "depleteBuyItems", at = @At("HEAD"), cancellable = true)
private void depleteBuyItems(ItemStack first, ItemStack second, CallbackInfoReturnable<Boolean> cir) {
if (Objects.requireNonNull(this.getAdjustedFirstBuyItem().getNbt()).contains("imyvmCurrency")) {
cir.setReturnValue(true);
}
}
}
17 changes: 17 additions & 0 deletions src/main/kotlin/com/imyvm/villagerShop/TradeType.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.imyvm.villagerShop

import com.imyvm.economy.api.TradeTypeEnum.TradeTypeExtension

enum class TradeType : TradeTypeExtension{
STOCK;

private var tax: Double = 0.0

override fun getTax(): Double {
return this.tax
}

override fun setTax(tax: Double) {
this.tax = tax
}
}
68 changes: 21 additions & 47 deletions src/main/kotlin/com/imyvm/villagerShop/VillagerShopMain.kt
Original file line number Diff line number Diff line change
@@ -1,87 +1,54 @@
package com.imyvm.villagerShop

import com.imyvm.economy.EconomyMod
import com.imyvm.villagerShop.apis.DataBase
import com.imyvm.villagerShop.apis.Items
import com.imyvm.villagerShop.apis.ModConfig
import com.imyvm.villagerShop.apis.ModConfig.Companion.ADMIN_NAME
import com.imyvm.villagerShop.apis.SearchOperation
import com.imyvm.villagerShop.apis.Translator.tr
import com.imyvm.villagerShop.commands.itemPurchaseMain
import com.imyvm.villagerShop.apis.ModConfig.Companion.TAX_RESTOCK
import com.imyvm.villagerShop.commands.register
import com.imyvm.villagerShop.shops.spawnInvulnerableVillager
import kotlinx.serialization.json.Json
import net.fabricmc.api.ModInitializer
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerChunkEvents
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents
import net.minecraft.entity.Entity
import net.minecraft.entity.EntityType
import net.minecraft.server.network.ServerPlayerEntity
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.Box
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.io.BufferedWriter
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit

import java.io.File
import java.io.FileWriter

class VillagerShopMain : ModInitializer {
override fun onInitialize() {
CONFIG.loadAndSave()
CommandRegistrationCallback.EVENT.register { dispatcher, commandRegistryAccess, _ ->
register(dispatcher, commandRegistryAccess)
}
itemList.addAll(purchaseItemLoad())
TradeType.STOCK.tax = TAX_RESTOCK.value
ServerLifecycleEvents.SERVER_STARTED.register { server ->
itemPurchaseMain(server)
ServerChunkEvents.CHUNK_LOAD.register { serverWorld,chunk ->
val scheduledExecutorService = Executors.newScheduledThreadPool(1)
scheduledExecutorService.schedule({
server.execute {
val boundingBox = Box(chunk.pos.startPos, chunk.pos.startPos.add(16, 256, 16))
val entitiesInChunk = serverWorld.getEntitiesByType(EntityType.VILLAGER,boundingBox) {entity -> entity.scoreboardTags.contains("VillagerShop")}
val entitiesInChunk = serverWorld.getEntitiesByType(EntityType.VILLAGER, boundingBox) {entity -> entity.commandTags.contains("VillagerShop")}
entitiesInChunk.forEach { it.remove(Entity.RemovalReason.KILLED) }
val worldUUID: String = serverWorld.registryKey.value.toString()
val shopInfo = DataBase().dataBaseInquire(
targetValueString = chunk.pos.centerX.toString() + ",0," + chunk.pos.centerZ,
rangeX = 8, rangeY = 32767, rangeZ = 8, operation = SearchOperation.LOCATION, world = worldUUID
val shopInfo = DataBase().dataBaseInquireByLocation(
chunk.pos.centerX.toString() + ",0," + chunk.pos.centerZ,
8, 32767, 8 , worldUUID
)
for (i in shopInfo) {
val (type,value) = i.split(":")
if (type == "pos") {
spawnInvulnerableVillager(DataBase().stringToBlockPos(value), serverWorld)
}
val sellItemList = mutableListOf<Items>(Json.decodeFromString(i.items))
val shopName = i.shopname
spawnInvulnerableVillager(BlockPos(i.posX, i.posY, i.posZ), serverWorld, sellItemList, shopName)
}
}
}, 500, TimeUnit.MILLISECONDS)
}
ServerPlayConnectionEvents.JOIN.register { handler, _, _ ->
if (handler.player.name.toString() == ADMIN_NAME.value) {
LOGGER.info(handler.player.entityName)
ADMIN = handler.player
val file = File("../world/tax.txt")
val amount = file.readText().toLong()
val scheduledExecutorService = Executors.newScheduledThreadPool(1)
scheduledExecutorService.schedule({
server.execute {
ADMIN?.let { admin ->
val fileWriter = FileWriter("../world/tax.txt", false)
val bufferedWriter = BufferedWriter(fileWriter)
val adminData = EconomyMod.data.getOrCreate(admin)
adminData.addMoney(amount)
admin.sendMessage(tr("admin.tax.offline",amount))
bufferedWriter.write("0")
}
}
},2,TimeUnit.SECONDS)
}
}
ServerPlayConnectionEvents.DISCONNECT.register { handler,_ ->
if (handler.player.name.toString() == ADMIN_NAME.value) {
ADMIN = null
}
}
}
LOGGER.info("Imyvm Villager Shop initialized")
}
Expand All @@ -90,6 +57,13 @@ class VillagerShopMain : ModInitializer {
val LOGGER: Logger = LoggerFactory.getLogger("Imyvm-VillagerShop")
const val MOD_ID = "imyvm_villagershop"
val CONFIG: ModConfig = ModConfig()
var ADMIN: ServerPlayerEntity? =null
val itemList: MutableList<Items> = mutableListOf()
}
private fun purchaseItemLoad(): MutableList<Items> {
val itemList: MutableList<Items> = mutableListOf()
for (i in DataBase().dataBaseInquireByType()) {
itemList.addAll(DataBase().stringToJson(i.items))
}
return itemList
}
}
Loading

0 comments on commit 3b7a250

Please sign in to comment.