loading player from json file

This commit is contained in:
minjaesong
2021-08-28 16:31:06 +09:00
parent 29cccea19b
commit b84a0a770b
31 changed files with 308 additions and 145 deletions

View File

@@ -32,7 +32,6 @@ import net.torvald.terrarum.gameworld.WorldSimulator
import net.torvald.terrarum.modulebasegame.gameworld.GameEconomy
import net.torvald.terrarum.modulebasegame.ui.*
import net.torvald.terrarum.weather.WeatherMixer
import net.torvald.terrarum.modulebasegame.worldgenerator.RoguelikeRandomiser
import net.torvald.terrarum.modulebasegame.worldgenerator.Worldgen
import net.torvald.terrarum.modulebasegame.worldgenerator.WorldgenParams
import net.torvald.terrarum.ui.UICanvas
@@ -40,7 +39,6 @@ import net.torvald.terrarum.worlddrawer.BlocksDrawer
import net.torvald.terrarum.worlddrawer.FeaturesDrawer
import net.torvald.terrarum.worlddrawer.WorldCamera
import net.torvald.util.CircularArray
import net.torvald.util.SortedArrayList
import java.util.*
import java.util.concurrent.locks.ReentrantLock
import kotlin.math.roundToInt
@@ -313,8 +311,8 @@ open class TerrarumIngame(batch: SpriteBatch) : IngameInstance(batch) {
/** Load rest of the game with GL context */
fun postInit() {
//setTheRealGamerFirstTime(PlayerBuilderSigrid())
// setTheRealGamerFirstTime(PlayerBuilderTestSubject1())
setTheRealGamerFirstTime(PlayerBuilderWerebeastTest())
setTheRealGamerFirstTime(PlayerBuilderTestSubject1())
// setTheRealGamerFirstTime(PlayerBuilderWerebeastTest())
@@ -850,9 +848,9 @@ open class TerrarumIngame(batch: SpriteBatch) : IngameInstance(batch) {
if (it is Pocketed) {
it.inventory.forEach { inventoryEntry ->
ItemCodex[inventoryEntry.item]!!.effectWhileInPocket(delta)
if (it.equipped(inventoryEntry.item)) {
ItemCodex[inventoryEntry.item]!!.effectWhenEquipped(delta)
ItemCodex[inventoryEntry.itm]!!.effectWhileInPocket(delta)
if (it.equipped(inventoryEntry.itm)) {
ItemCodex[inventoryEntry.itm]!!.effectWhenEquipped(delta)
}
}
}
@@ -920,17 +918,25 @@ open class TerrarumIngame(batch: SpriteBatch) : IngameInstance(batch) {
if (actor.referenceID == theRealGamer.referenceID || actor.referenceID == 0x51621D) // do not delete this magic
throw RuntimeException("Attempted to remove player.")
val indexToDelete = actorContainerActive.searchForIndex(actor.referenceID) { it.referenceID }
if (indexToDelete != null) {
printdbg(this, "Removing actor $actor")
printStackTrace(this)
actorContainerActive.removeAt(indexToDelete)
forceRemoveActor(actor)
}
// indexToDelete >= 0 means that the actor certainly exists in the game
// which means we don't need to check if i >= 0 again
if (actor is ActorWithBody) {
actorToRenderQueue(actor).remove(actor)
override fun forceRemoveActor(actor: Actor) {
arrayOf(actorContainerActive, actorContainerInactive).forEach { actorContainer ->
val indexToDelete = actorContainer.searchForIndex(actor.referenceID) { it.referenceID }
if (indexToDelete != null) {
printdbg(this, "Removing actor $actor")
printStackTrace(this)
actor.dispose()
actorContainer.removeAt(indexToDelete)
// indexToDelete >= 0 means that the actor certainly exists in the game
// which means we don't need to check if i >= 0 again
if (actor is ActorWithBody) {
actorToRenderQueue(actor).remove(actor)
}
}
}
}
@@ -973,10 +979,7 @@ open class TerrarumIngame(batch: SpriteBatch) : IngameInstance(batch) {
}
actorContainerActive.add(actor)
if (actor is ActorWithBody) {
actorToRenderQueue(actor).add(actor)
}
if (actor is ActorWithBody) actorToRenderQueue(actor).add(actor)
}
}

View File

@@ -6,6 +6,7 @@ import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
import net.torvald.terrarum.modulebasegame.TerrarumIngame
import net.torvald.terrarum.modulebasegame.gameactors.IngamePlayer
import net.torvald.terrarum.serialise.WriteActor
import net.torvald.terrarum.serialise.WriteMeta
import net.torvald.terrarum.serialise.WriteWorld
@@ -40,10 +41,10 @@ object ExportWorld : ConsoleCommand {
if (args.size == 2) {
try {
val str = WriteWorld(Terrarum.ingame!! as TerrarumIngame).invoke()
val writer = java.io.FileWriter(AppLoader.defaultDir + "/Exports/${args[1]}", false)
val writer = java.io.FileWriter(AppLoader.defaultDir + "/Exports/${args[1]}.json", false)
writer.write(str)
writer.close()
Echo("Exportworld: exported to ${args[1]}")
Echo("Exportworld: exported to ${args[1]}.json")
}
catch (e: IOException) {
Echo("Exportworld: IOException raised.")
@@ -56,7 +57,7 @@ object ExportWorld : ConsoleCommand {
}
override fun printUsage() {
Echo("Usage: Exportworld filename.json")
Echo("Usage: Exportworld filename-without-extension")
}
}
@@ -67,7 +68,7 @@ object ExportActor : ConsoleCommand {
val player = (Terrarum.ingame!! as TerrarumIngame).actorNowPlaying
if (player == null) return
val str = WriteActor(player)
val str = WriteActor(player as IngamePlayer)
val writer = java.io.FileWriter(AppLoader.defaultDir + "/Exports/${args[1]}.json", false)
writer.write(str)
writer.close()

View File

@@ -5,6 +5,7 @@ import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
import net.torvald.terrarum.modulebasegame.TerrarumIngame
import net.torvald.terrarum.serialise.ReadActor
import net.torvald.terrarum.serialise.ReadWorld
import net.torvald.terrarum.serialise.WriteMeta
import java.io.IOException
@@ -16,9 +17,9 @@ object ImportWorld : ConsoleCommand {
override fun execute(args: Array<String>) {
if (args.size == 2) {
try {
val reader = java.io.FileReader(AppLoader.defaultDir + "/Exports/${args[1]}")
val reader = java.io.FileReader(AppLoader.defaultDir + "/Exports/${args[1]}.json")
ReadWorld(Terrarum.ingame!! as TerrarumIngame).invoke(reader)
Echo("Importworld: imported a world from ${args[1]}")
Echo("Importworld: imported a world from ${args[1]}.json")
}
catch (e: IOException) {
Echo("Importworld: IOException raised.")
@@ -31,6 +32,29 @@ object ImportWorld : ConsoleCommand {
}
override fun printUsage() {
Echo("Usage: Importworld filename.json")
Echo("Usage: Importworld filename-without-extension")
}
}
object ImportActor : ConsoleCommand {
override fun execute(args: Array<String>) {
if (args.size == 2) {
try {
val reader = java.io.FileReader(AppLoader.defaultDir + "/Exports/${args[1]}.json")
ReadActor(Terrarum.ingame!! as TerrarumIngame).invoke(reader)
Echo("Importactor: imported an actor from ${args[1]}.json")
}
catch (e: IOException) {
Echo("Importactor: IOException raised.")
e.printStackTrace()
}
}
else {
printUsage()
}
}
override fun printUsage() {
Echo("Usage: Importactor filename-without-extension")
}
}

View File

@@ -9,11 +9,9 @@ import net.torvald.terrarum.AppLoader.printdbg
import net.torvald.terrarum.gameactors.*
import net.torvald.terrarum.gameactors.faction.Faction
import net.torvald.terrarum.gameitem.GameItem
import net.torvald.terrarum.gameworld.GameWorld
import net.torvald.terrarum.itemproperties.ItemCodex
import net.torvald.terrarum.itemproperties.Material
import net.torvald.terrarum.realestate.LandUtil
import net.torvald.terrarum.worlddrawer.LightmapRenderer
import org.dyn4j.geometry.Vector2
import java.util.*
@@ -28,12 +26,13 @@ import java.util.*
*
* Created by minjaesong on 2016-10-24.
*/
open class ActorHumanoid(
birth: Long,
death: Long? = null,
physProp: PhysProperties = PhysProperties.HUMANOID_DEFAULT
) : ActorWithBody(RenderOrder.MIDDLE, physProp = physProp), Controllable, Pocketed, Factionable, Luminous, LandHolder, HistoricalFigure {
open class ActorHumanoid() : ActorWithBody(), Controllable, Pocketed, Factionable, Luminous, LandHolder, HistoricalFigure {
constructor(birth: Long, death: Long? = null, physProp: PhysProperties = PhysProperties.HUMANOID_DEFAULT) : this() {
actorValue[AVKey.__HISTORICAL_BORNTIME] = birth
death?.let { actorValue[AVKey.__HISTORICAL_DEADTIME] = death }
this.physProp = physProp
}
var vehicleRiding: Controllable? = null // usually player only
@@ -176,11 +175,6 @@ open class ActorHumanoid(
override val material = Material()
}
init {
actorValue[AVKey.__HISTORICAL_BORNTIME] = birth
death?.let { actorValue[AVKey.__HISTORICAL_DEADTIME] = death }
}
override fun update(delta: Float) {
super.update(delta)
@@ -217,11 +211,11 @@ open class ActorHumanoid(
// update inventory items
inventory.forEach {
if (!inventory.itemEquipped.contains(it.item)) { // unequipped
ItemCodex[it.item]!!.effectWhileInPocket(delta)
if (!inventory.itemEquipped.contains(it.itm)) { // unequipped
ItemCodex[it.itm]!!.effectWhileInPocket(delta)
}
else { // equipped
ItemCodex[it.item]!!.effectWhenEquipped(delta)
ItemCodex[it.itm]!!.effectWhenEquipped(delta)
}
}
}
@@ -640,7 +634,7 @@ open class ActorHumanoid(
// make quickslot work
if (key == AVKey.__PLAYER_QUICKSLOTSEL && value != null) {
// ONLY FOR HAND_GRIPs!!
val quickBarItem = ItemCodex[inventory.getQuickslot(actorValue.getAsInt(key)!!)?.item]
val quickBarItem = ItemCodex[inventory.getQuickslot(actorValue.getAsInt(key)!!)?.itm]
if (quickBarItem != null && quickBarItem.equipPosition == GameItem.EquipPosition.HAND_GRIP) {
equipItem(quickBarItem)

View File

@@ -1,29 +1,30 @@
package net.torvald.terrarum.modulebasegame.gameactors
import net.torvald.terrarum.AppLoader
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.blockproperties.BlockCodex
import net.torvald.terrarum.gameactors.AVKey
import net.torvald.terrarum.gameactors.Actor
import net.torvald.terrarum.gameitem.GameItem
import net.torvald.terrarum.itemproperties.ItemCodex
import net.torvald.terrarum.gameitem.ItemID
import net.torvald.terrarum.lock
import net.torvald.terrarum.modulebasegame.TerrarumIngame
import net.torvald.terrarum.modulebasegame.ui.UIQuickslotBar
import java.math.BigInteger
import java.util.*
import java.util.concurrent.locks.ReentrantLock
/**
* Created by minjaesong on 2016-03-15.
*/
class ActorInventory(@Transient val actor: Pocketed, maxCapacity: Int, capacityMode: Int):
FixtureInventory(maxCapacity, capacityMode) {
class ActorInventory() : FixtureInventory() {
// FIXME unless absolutely necessary, don't store full item object; only store its dynamicID
@Transient lateinit var actor: Pocketed
internal set
constructor(actor: Pocketed, maxCapacity: Int, capacityMode: Int) : this() {
this.actor = actor
this.maxCapacity = maxCapacity
this.capacityMode = capacityMode
}
/**
* List of all equipped items (tools, armours, rings, necklaces, etc.)
*/
@@ -38,7 +39,7 @@ class ActorInventory(@Transient val actor: Pocketed, maxCapacity: Int, capacityM
override fun remove(item: GameItem, count: Int) {
super.remove(item, count) { existingItem ->
// unequip, if applicable
actor.unequipItem(existingItem.item)
actor.unequipItem(existingItem.itm)
// also unequip on the quickslot
actor.actorValue.getAsInt(AVKey.__PLAYER_QUICKSLOTSEL)?.let {
setQuickBar(it, null)

View File

@@ -13,8 +13,16 @@ import java.util.concurrent.locks.ReentrantLock
* Created by minjaesong on 2021-03-16.
*/
open class FixtureInventory(var maxCapacity: Int, var capacityMode: Int) {
open class FixtureInventory() {
var maxCapacity = 100
var capacityMode = CAPACITY_MODE_COUNT
constructor(maxCapacity: Int, capacityMode: Int) : this() {
this.maxCapacity = maxCapacity
this.capacityMode = capacityMode
}
companion object {
val CAPACITY_MODE_NO_ENCUMBER = 0
val CAPACITY_MODE_COUNT = 1
@@ -60,7 +68,7 @@ open class FixtureInventory(var maxCapacity: Int, var capacityMode: Int) {
// if the item already exists
if (existingItem != null) {
// increment count
existingItem.amount += count
existingItem.qty += count
}
// new item
else {
@@ -90,14 +98,14 @@ open class FixtureInventory(var maxCapacity: Int, var capacityMode: Int) {
val existingItem = invSearchByDynamicID(item.dynamicID)
if (existingItem != null) { // if the item already exists
val newCount = existingItem.amount - count
val newCount = existingItem.qty - count
if (newCount < 0) {
throw Error("Tried to remove $count of $item, but the inventory only contains ${existingItem.amount} of them.")
throw Error("Tried to remove $count of $item, but the inventory only contains ${existingItem.qty} of them.")
}
else if (newCount > 0) {
// decrement count
existingItem.amount = newCount
existingItem.qty = newCount
}
else {
// depleted item; remove entry from inventory
@@ -128,12 +136,12 @@ open class FixtureInventory(var maxCapacity: Int, var capacityMode: Int) {
else
getTotalCount().toDouble()
fun getTotalWeight(): Double = itemList.map { ItemCodex[it.item]!!.mass * it.amount }.sum()
fun getTotalWeight(): Double = itemList.map { ItemCodex[it.itm]!!.mass * it.qty }.sum()
/**
* Real amount
*/
fun getTotalCount(): Int = itemList.map { it.amount }.sum()
fun getTotalCount(): Int = itemList.map { it.qty }.sum()
/**
* Unique amount, multiple items are calculated as one
@@ -182,7 +190,7 @@ open class FixtureInventory(var maxCapacity: Int, var capacityMode: Int) {
ReentrantLock().lock {
var j = arr.lastIndex - 1
val x = arr.last()
while (j >= 0 && arr[j].item > x.item) {
while (j >= 0 && arr[j].itm > x.itm) {
arr[j + 1] = arr[j]
j -= 1
}
@@ -200,9 +208,9 @@ open class FixtureInventory(var maxCapacity: Int, var capacityMode: Int) {
val mid = (low + high).ushr(1) // safe from overflows
val midVal = if (searchMode == STATIC_ID)
ItemCodex[this[mid].item]!!.originalID
ItemCodex[this[mid].itm]!!.originalID
else
ItemCodex[this[mid].item]!!.dynamicID
ItemCodex[this[mid].itm]!!.dynamicID
if (ID > midVal)
low = mid + 1
@@ -215,4 +223,19 @@ open class FixtureInventory(var maxCapacity: Int, var capacityMode: Int) {
}
}
data class InventoryPair(val item: ItemID, var amount: Int)
class InventoryPair {
var itm: ItemID = ""; private set
var qty: Int = 0
private constructor()
constructor(item: ItemID, quantity: Int) : this() {
itm = item
qty = quantity
}
operator fun component1() = itm
operator fun component2() = qty
}

View File

@@ -2,6 +2,7 @@ package net.torvald.terrarum.modulebasegame.gameactors
import net.torvald.spriteanimation.HasAssembledSprite
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.gameactors.AVKey
/**
@@ -10,11 +11,17 @@ import net.torvald.terrarum.Terrarum
* Created by minjaesong on 2015-12-31.
*/
class IngamePlayer(
override var animDescPath: String,
override var animDescPathGlow: String? = null,
born: Long
) : ActorHumanoid(born), HasAssembledSprite {
class IngamePlayer() : ActorHumanoid(), HasAssembledSprite {
override var animDescPath = "invalid"
override var animDescPathGlow: String? = null
constructor(animDescPath: String, animDescPathGlow: String?, born: Long) : this() {
this.animDescPath = animDescPath
this.animDescPathGlow = animDescPathGlow
actorValue[AVKey.__HISTORICAL_BORNTIME] = born
}
/**
* Creates new Player instance with empty elements (sprites, actorvalue, etc.).

View File

@@ -16,9 +16,9 @@ class ThreadActorUpdate(val startIndex: Int, val endIndex: Int) : Callable<Unit>
if (it is Pocketed) {
it.inventory.forEach { inventoryEntry ->
ItemCodex[inventoryEntry.item]?.effectWhileInPocket(AppLoader.UPDATE_RATE)
if (it.equipped(inventoryEntry.item)) {
ItemCodex[inventoryEntry.item]?.effectWhenEquipped(AppLoader.UPDATE_RATE)
ItemCodex[inventoryEntry.itm]?.effectWhileInPocket(AppLoader.UPDATE_RATE)
if (it.equipped(inventoryEntry.itm)) {
ItemCodex[inventoryEntry.itm]?.effectWhenEquipped(AppLoader.UPDATE_RATE)
}
}
}

View File

@@ -19,7 +19,7 @@ object AmmoMeterProxy {
else {
meter.vitalGetterVal = {
if (currentItem.stackable && currentItem.maxDurability == GameItem.DURABILITY_NA) {
actor.inventory.invSearchByDynamicID(currentItem.dynamicID)!!.amount.toFloat()
actor.inventory.invSearchByDynamicID(currentItem.dynamicID)!!.qty.toFloat()
}
else
currentItem.durability

View File

@@ -139,7 +139,7 @@ class UIItemInventoryEquippedView(
val itemRecord = inventory.invSearchByDynamicID(item)!!
itemGrid[k].item = ItemCodex[item]
itemGrid[k].amount = itemRecord.amount
itemGrid[k].amount = itemRecord.qty
itemGrid[k].itemImage = ItemCodex.getItemImage(item)
itemGrid[k].quickslot = null // don't need to be displayed
itemGrid[k].equippedSlot = null // don't need to be displayed

View File

@@ -120,7 +120,7 @@ class UIItemInventoryItemGrid(
inventory.setQuickBar(
slot,
if (currentSlotItem?.item != item.dynamicID)
if (currentSlotItem?.itm != item.dynamicID)
item.dynamicID // register
else
null // drop registration
@@ -129,7 +129,7 @@ class UIItemInventoryItemGrid(
// search for duplicates in the quickbar, except mine
// if there is, unregister the other
(0..9).minus(slot).forEach {
if (inventory.getQuickslot(it)?.item == item.dynamicID) {
if (inventory.getQuickslot(it)?.itm == item.dynamicID) {
inventory.setQuickBar(it, null)
}
}
@@ -412,27 +412,27 @@ class UIItemInventoryItemGrid(
// filter items
inventory.forEach {
if ((filter.contains(ItemCodex[it.item]!!.inventoryCategory) || filter[0] == CAT_ALL))
if ((filter.contains(ItemCodex[it.itm]!!.inventoryCategory) || filter[0] == CAT_ALL))
inventorySortList.add(it)
}
// sort if needed
// test sort by name
inventorySortList.sortBy { ItemCodex[it.item]!!.name }
inventorySortList.sortBy { ItemCodex[it.itm]!!.name }
// map sortList to item list
for (k in items.indices) {
// we have an item
try {
val sortListItem = inventorySortList[k + itemPage * items.size]
items[k].item = ItemCodex[sortListItem.item]
items[k].amount = sortListItem.amount
items[k].itemImage = ItemCodex.getItemImage(sortListItem.item)
items[k].item = ItemCodex[sortListItem.itm]
items[k].amount = sortListItem.qty
items[k].itemImage = ItemCodex.getItemImage(sortListItem.itm)
// set quickslot number
if (inventory is ActorInventory) {
for (qs in 1..UIQuickslotBar.SLOT_COUNT) {
if (sortListItem.item == inventory.getQuickslot(qs - 1)?.item) {
if (sortListItem.itm == inventory.getQuickslot(qs - 1)?.itm) {
items[k].quickslot = qs % 10 // 10 -> 0, 1..9 -> 1..9
break
}

View File

@@ -48,7 +48,7 @@ class UIQuickslotBar : UICanvas() {
override fun renderUI(batch: SpriteBatch, camera: Camera) {
for (i in 0..SLOT_COUNT - 1) {
val item = ItemCodex[(Terrarum.ingame!! as TerrarumIngame).actorNowPlaying?.inventory?.getQuickslot(i)?.item]
val item = ItemCodex[(Terrarum.ingame!! as TerrarumIngame).actorNowPlaying?.inventory?.getQuickslot(i)?.itm]
val image = if (i == selection)
ItemSlotImageFactory.produceLarge(false, (i + 1) % SLOT_COUNT, item)

View File

@@ -64,7 +64,7 @@ class UIQuickslotPie : UICanvas() {
override fun renderUI(batch: SpriteBatch, camera: Camera) {
// draw radial thingies
for (i in 0..slotCount - 1) {
val item = ItemCodex[(Terrarum.ingame!! as TerrarumIngame).actorNowPlaying?.inventory?.getQuickslot(i)?.item]
val item = ItemCodex[(Terrarum.ingame!! as TerrarumIngame).actorNowPlaying?.inventory?.getQuickslot(i)?.itm]
// set position
val angle = Math.PI * 2.0 * (i.toDouble() / slotCount) + Math.PI // 180 deg monitor-wise