path
stringlengths
4
297
contentHash
stringlengths
1
10
content
stringlengths
0
13M
StudentNotes/app/src/test/java/com/example/studentnotes/ExampleUnitTest.kt
762012797
package com.example.studentnotes import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
StudentNotes/app/src/main/java/com/example/studentnotes/MainActivity.kt
3475830078
package com.example.studentnotes import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button import android.widget.EditText import android.widget.ImageView import android.widget.TextView import android.widget.Toast class MainActivity : AppCompatActivity() { private lateinit var loginImg: ImageView private lateinit var googleLogo: ImageView private lateinit var welcomeText: TextView private lateinit var descriptionText: TextView private lateinit var alreadyText: TextView private lateinit var loginText: TextView private lateinit var registerText: TextView private lateinit var registerButton: Button private lateinit var nameText: EditText private lateinit var emailText: EditText private lateinit var passwordText: EditText private lateinit var conformpasswordText: EditText override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) loginImg = findViewById(R.id.loginImg) googleLogo = findViewById(R.id.googleLogo) welcomeText = findViewById(R.id.welcomeText) descriptionText = findViewById(R.id.descriptionText) alreadyText = findViewById(R.id.alreadyText) loginText = findViewById(R.id.loginText) registerText = findViewById(R.id.registerText) registerButton = findViewById(R.id.registerButton) nameText = findViewById(R.id.nameText) emailText = findViewById(R.id.emailText) passwordText = findViewById(R.id.passwordText) conformpasswordText = findViewById(R.id.conformpasswordText) } fun toRegister(view: View) { val nameText = nameText.text.toString() val emailText = emailText.text.toString() val passwordText = passwordText.text.toString() val conformpasswordText = conformpasswordText.text.toString() if (view.getId() == R.id.registerButton){ if (nameText.isEmpty()){ Toast.makeText(this, "Fill Name", Toast.LENGTH_SHORT).show() } else if (emailText.isEmpty()){ Toast.makeText(this, "Fill Email", Toast.LENGTH_SHORT).show() } else if (passwordText.isEmpty() || conformpasswordText.isEmpty() ){ Toast.makeText(this, "Fill Password", Toast.LENGTH_SHORT).show() } else if(passwordText != conformpasswordText){ Toast.makeText(this, "Password not Match", Toast.LENGTH_SHORT).show() } else{ val home = Intent(this, HomeActivity::class.java) startActivity(home) } } if (view.getId() == R.id.registerText){ Toast.makeText(this, "Opening Google", Toast.LENGTH_SHORT).show() } } fun toLogin(view: View) { if (view.getId() == R.id.loginText){ val login = Intent(this, LoginActivity::class.java) startActivity(login) } } }
StudentNotes/app/src/main/java/com/example/studentnotes/HomeActivity.kt
3934841756
package com.example.studentnotes import android.annotation.SuppressLint import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.ImageView import android.widget.TextView import android.widget.Toast import com.example.studentnotes.TaskBar.CreateActivity import com.example.studentnotes.TaskBar.ProfileActivity class HomeActivity : AppCompatActivity() { private lateinit var joinedImg: ImageView private lateinit var createImg: ImageView private lateinit var profileImg: ImageView private lateinit var joinedTxt: TextView private lateinit var createTxt: TextView private lateinit var profileTxt: TextView @SuppressLint("MissingInflatedId") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_home) joinedImg = findViewById(R.id.joinedImg) createImg = findViewById(R.id.createImg) profileImg = findViewById(R.id.profileImg) joinedTxt = findViewById(R.id.joinedTxt) createTxt = findViewById(R.id.createTxt) profileTxt = findViewById(R.id.profileTxt) } fun Join(view: View) { if (view.getId() == R.id.joinedImg || view.getId() == R.id.joinedTxt){ Toast.makeText(this,"See Joined Notes", Toast.LENGTH_SHORT).show() } } fun Create(view: View) { if (view.getId() == R.id.createImg || view.getId() == R.id.createTxt){ Toast.makeText(this,"Create Notes", Toast.LENGTH_SHORT).show() val create = Intent(this, CreateActivity::class.java) startActivity(create) } } fun Profile(view: View) { if (view.getId() == R.id.profileImg || view.getId() == R.id.profileTxt){ val profile = Intent(this, ProfileActivity::class.java) startActivity(profile) Toast.makeText(this,"Opening Profile", Toast.LENGTH_SHORT).show() } } }
StudentNotes/app/src/main/java/com/example/studentnotes/TaskBar/ProfileActivity.kt
3036019865
package com.example.studentnotes.TaskBar import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.ImageView import android.widget.TextView import com.example.studentnotes.HomeActivity import com.example.studentnotes.LoginActivity import com.example.studentnotes.MainActivity import com.example.studentnotes.R class ProfileActivity : AppCompatActivity() { private lateinit var cros: ImageView private lateinit var userprofileImg: ImageView private lateinit var lOut: ImageView private lateinit var switchAcc: ImageView private lateinit var infoTxt: TextView private lateinit var userprofileName: TextView private lateinit var showprofileName: TextView private lateinit var userprofileEmail: TextView private lateinit var showprofileEmail: TextView private lateinit var userprofileNumber: TextView private lateinit var showprofileNumber: TextView private lateinit var userprofileAge: TextView private lateinit var showprofileAge: TextView private lateinit var userprofileRegion: TextView private lateinit var showprofileRegion: TextView private lateinit var userprofileLanguage: TextView private lateinit var showprofileLanguage: TextView private lateinit var logOut: TextView private lateinit var switchAccount: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_profile) cros = findViewById(R.id.cros) userprofileImg = findViewById(R.id.userprofileImg) lOut = findViewById(R.id.lOut) switchAcc = findViewById(R.id.switchAcc) switchAcc = findViewById(R.id.switchAcc) infoTxt = findViewById(R.id.infoTxt) userprofileName = findViewById(R.id.userprofileName) showprofileName = findViewById(R.id.showprofileName) userprofileEmail = findViewById(R.id.userprofileEmail) showprofileEmail = findViewById(R.id.showprofileEmail) userprofileNumber = findViewById(R.id.userprofileNumber) showprofileNumber = findViewById(R.id.showprofileNumber) userprofileAge = findViewById(R.id.userprofileAge) showprofileAge = findViewById(R.id.showprofileAge) userprofileRegion = findViewById(R.id.userprofileRegion) showprofileRegion = findViewById(R.id.showprofileRegion) userprofileLanguage = findViewById(R.id.userprofileLanguage) showprofileLanguage = findViewById(R.id.showprofileLanguage) logOut = findViewById(R.id.logOut) switchAccount = findViewById(R.id.switchAccount) } fun Cros(view: View) { val cross = Intent(this, HomeActivity::class.java) startActivity(cross) } fun SwitchAccount(view: View) { val switch = Intent(this, MainActivity::class.java) startActivity(switch) } fun LogOut(view: View) { val log = Intent(this, LoginActivity::class.java) startActivity(log) } }
StudentNotes/app/src/main/java/com/example/studentnotes/TaskBar/CreateActivity.kt
851675538
package com.example.studentnotes.TaskBar import android.annotation.SuppressLint import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.TextView import com.example.studentnotes.HomeActivity import com.example.studentnotes.R class CreateActivity : AppCompatActivity() { private lateinit var addtitleTxt: TextView private lateinit var titleTxt: TextView private lateinit var contentTxt: TextView private lateinit var savenoteTxt: TextView @SuppressLint("MissingInflatedId") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_create) addtitleTxt = findViewById(R.id.addtitleTxt) titleTxt = findViewById(R.id.titleTxt) contentTxt = findViewById(R.id.contentTxt) savenoteTxt = findViewById(R.id.savenoteTxt) } fun SaveNote(view: View) { val save = Intent(this, HomeActivity::class.java) startActivity(save) } }
StudentNotes/app/src/main/java/com/example/studentnotes/LoginActivity.kt
1188261811
package com.example.studentnotes import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button import android.widget.EditText import android.widget.ImageView import android.widget.TextView import android.widget.Toast class LoginActivity : AppCompatActivity() { private lateinit var doorImg: ImageView private lateinit var orImg: ImageView private lateinit var emailTxt: EditText private lateinit var passTxt: EditText private lateinit var logBtn: Button private lateinit var sinBtn: Button private lateinit var createrTxt: TextView private lateinit var forgetTxt: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) doorImg = findViewById(R.id.doorImg) orImg = findViewById(R.id.orImg) emailTxt = findViewById(R.id.emailTxt) passTxt = findViewById(R.id.passTxt) logBtn = findViewById(R.id.logBtn) sinBtn = findViewById(R.id.sinBtn) createrTxt = findViewById(R.id.createTxt) forgetTxt = findViewById(R.id.forgetTxt) } fun LogIn(view: View) { val emailTxt = emailTxt.text.toString() val passTxt = passTxt.text.toString() if(view.getId() == R.id.logBtn){ if(emailTxt.isEmpty()){ Toast.makeText(this, "Fill Email", Toast.LENGTH_SHORT).show() } else if (passTxt.isEmpty()){ Toast.makeText(this, "Fill Password", Toast.LENGTH_SHORT).show() } else{ Toast.makeText(this, "Loging In", Toast.LENGTH_SHORT).show() val log = Intent(this, HomeActivity::class.java) startActivity(log) } } } fun SignIn(view: View) { Toast.makeText(this, "Signing In", Toast.LENGTH_SHORT).show() val sin = Intent(this, MainActivity::class.java) startActivity(sin) } fun Forget(view: View) { Toast.makeText(this, "Try To Remember", Toast.LENGTH_SHORT).show() } }
rock-paper-scissors-kotlin/app/src/androidTest/java/com/aminulrony/rockpaperscissors/ExampleInstrumentedTest.kt
2058466800
package com.aminulrony.rockpaperscissors import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.aminulrony.rockpaperscissors", appContext.packageName) } }
rock-paper-scissors-kotlin/app/src/test/java/com/aminulrony/rockpaperscissors/ExampleUnitTest.kt
572296573
package com.aminulrony.rockpaperscissors import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
rock-paper-scissors-kotlin/app/src/main/java/com/aminulrony/rockpaperscissors/RockPaperScissors.kt
2976849866
package com.aminulrony.rockpaperscissors fun main(){ var computerChoice = "" var playerChoice = "" println("Rock, Paper or Scissors ? Enter your choice :") playerChoice = readln() val randomNumber = (1..3).random() if(randomNumber == 1) computerChoice = "Rock" else if(randomNumber == 2) computerChoice = "Paper" else computerChoice = "Scissors" println(computerChoice) val winner = when{ playerChoice == computerChoice -> "Tie" playerChoice == "Rock" && computerChoice == "Scissors" -> "Player" playerChoice == "Scissors" && computerChoice == "Paper" -> "Player" else -> "Computer" } if(winner == "Tie") println("It's a tie") else println(winner + " won!"); }
Ejercicio3.ObjetoyMercader/app/src/androidTest/java/com/example/personajecreacion/ExampleInstrumentedTest.kt
3837218097
package com.example.personajecreacion import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.personajecreacion", appContext.packageName) } }
Ejercicio3.ObjetoyMercader/app/src/test/java/com/example/personajecreacion/ExampleUnitTest.kt
3882230298
package com.example.personajecreacion import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
Ejercicio3.ObjetoyMercader/app/src/main/java/com/example/personajecreacion/MainActivity.kt
4103850343
package com.example.personajecreacion import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.AdapterView import android.widget.Button import android.widget.EditText import android.widget.ImageView import android.widget.Spinner import java.util.logging.Logger class MainActivity : AppCompatActivity(), AdapterView.OnItemSelectedListener { // Creación de variables para saber si han sido seleccionadas o no en el spinner private var opcionSpinnerClase: String? = null private var opcionSpinnerRaza: String? = null private var opcionSpinnerEdad: String? = null private lateinit var opcionImagen: String private lateinit var nombreEditText: EditText override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Creacion de variables nombreEditText = findViewById(R.id.nombre) val boton: Button = findViewById(R.id.boton_siguiente) val spinnerRaza: Spinner = findViewById(R.id.spinner_raza) val spinnerClase: Spinner = findViewById(R.id.spinner_clase) val spinnerEdad: Spinner = findViewById(R.id.spinner_edad) // Se esta asociando a quien tiene que llamar el Spinner cuando ocurre el evento onItemSelected. spinnerRaza.onItemSelectedListener = this spinnerEdad.onItemSelectedListener = this spinnerClase.onItemSelectedListener = this nombreEditText = findViewById(R.id.nombre) boton.setOnClickListener { val intent = Intent(this@MainActivity, MostrarDatos::class.java) intent.putExtra("raza",opcionSpinnerRaza) intent.putExtra("clase",opcionSpinnerClase) intent.putExtra("edad",opcionSpinnerEdad) intent.putExtra("nombre",nombreEditText.text.toString()) startActivity(intent) } } override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { var imageView: ImageView = findViewById(R.id.imageView2) when (parent?.id) { R.id.spinner_clase -> { opcionSpinnerClase = parent.getItemAtPosition(position) as String } R.id.spinner_raza -> { opcionSpinnerRaza = parent.getItemAtPosition(position) as String } R.id.spinner_edad -> { opcionSpinnerEdad = parent.getItemAtPosition(position) as String } } if (opcionSpinnerClase != null && opcionSpinnerRaza != null && opcionSpinnerEdad != null) { when(opcionSpinnerRaza) { "Humano"->{ when(opcionSpinnerClase){ "Brujo"->{ when(opcionSpinnerEdad){ "Anciano"->{ imageView.setImageResource(R.drawable.humano_brujo_anciano) } "Adulto"->{ imageView.setImageResource(R.drawable.humano_brujo_adulto) } "Joven"->{ imageView.setImageResource(R.drawable.humano_brujo_joven) } } } "Mago"->{ when(opcionSpinnerEdad){ "Anciano"->{ imageView.setImageResource(R.drawable.humano_mago_anciano) } "Adulto"->{ imageView.setImageResource(R.drawable.humano_mago_adulto) } "Joven"->{ imageView.setImageResource(R.drawable.humano_mago_joven) } } } "Guerrero"->{ when(opcionSpinnerEdad){ "Anciano"->{ imageView.setImageResource(R.drawable.humano_guerrero_anciano) } "Adulto"->{ imageView.setImageResource(R.drawable.humano_guerrero_adulto) } "Joven"->{ imageView.setImageResource(R.drawable.humano_guerrero_joven) } } } } } "Elfo"->{ when(opcionSpinnerClase){ "Brujo"->{ when(opcionSpinnerEdad){ "Anciano"->{ opcionImagen = "elfo_brujo_anciano" imageView.setImageResource(R.drawable.elfo_brujo_anciano) } "Adulto"->{ opcionImagen = "elfo_brujo_adulto" imageView.setImageResource(R.drawable.elfo_brujo_adulto) } "Joven"->{ opcionImagen = "elfo_brujo_joven" imageView.setImageResource(R.drawable.elfo_brujo_joven) } } } "Mago"->{ when(opcionSpinnerEdad){ "Anciano"->{ imageView.setImageResource(R.drawable.elfo_mago_anciano) } "Adulto"->{ imageView.setImageResource(R.drawable.elfo_mago_adulto) } "Joven"->{ imageView.setImageResource(R.drawable.elfo_mago_joven) } } } "Guerrero"->{ when(opcionSpinnerEdad){ "Anciano"->{ imageView.setImageResource(R.drawable.elfo_guerrero_anciano) } "Adulto"->{ imageView.setImageResource(R.drawable.elfo_guerrero_adulto) } "Joven"->{ imageView.setImageResource(R.drawable.elfo_guerrero_joven) } } } } } "Enano"->{ when(opcionSpinnerClase){ "Brujo"->{ when(opcionSpinnerEdad){ "Anciano"->{ imageView.setImageResource(R.drawable.enano_brujo_anciano) } "Adulto"->{ imageView.setImageResource(R.drawable.enano_brujo_adulto) } "Joven"->{ imageView.setImageResource(R.drawable.enano_brujo_joven) } } } "Mago"->{ when(opcionSpinnerEdad){ "Anciano"->{ imageView.setImageResource(R.drawable.enano_mago_anciano) } "Adulto"->{ imageView.setImageResource(R.drawable.enano_mago_adulto) } "Joven"->{ imageView.setImageResource(R.drawable.enano_mago_joven) } } } "Guerrero"->{ when(opcionSpinnerEdad){ "Anciano"->{ imageView.setImageResource(R.drawable.enano_guerrero_anciano) } "Adulto"->{ imageView.setImageResource(R.drawable.enano_guerrero_adulto) } "Joven"->{ imageView.setImageResource(R.drawable.enano_guerrero_joven) } } } } } "Maldito"->{ when(opcionSpinnerClase){ "Brujo"->{ when(opcionSpinnerEdad){ "Anciano"->{ imageView.setImageResource(R.drawable.maldito_brujo_anciano) } "Adulto"->{ imageView.setImageResource(R.drawable.maldito_brujo_adulto) } "Joven"->{ imageView.setImageResource(R.drawable.maldito_brujo_adolescente) } } } "Mago"->{ when(opcionSpinnerEdad){ "Anciano"->{ imageView.setImageResource(R.drawable.maldito_mago_anciano) } "Adulto"->{ imageView.setImageResource(R.drawable.maldito_mago_adulto) } "Joven"->{ imageView.setImageResource(R.drawable.maldito_mago_adolescente) } } } "Guerrero"->{ when(opcionSpinnerEdad){ "Anciano"->{ imageView.setImageResource(R.drawable.maldito_guerrero_anciano) } "Adulto"->{ imageView.setImageResource(R.drawable.maldito_guerrero_adulto) } "Joven"->{ imageView.setImageResource(R.drawable.maldito_guerrero_adolescente) } } } } } } } } override fun onNothingSelected(parent: AdapterView<*>?) { TODO("Not yet implemented") } }
Ejercicio3.ObjetoyMercader/app/src/main/java/com/example/personajecreacion/Ciudad.kt
388663833
package com.example.personajecreacion import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button class Ciudad : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_ciudad) val entrar: Button = findViewById(R.id.entrar) val continuar : Button = findViewById(R.id.continuar) entrar.setOnClickListener { val intent = Intent(this,Blanco::class.java) startActivity(intent) } continuar.setOnClickListener { val intent = Intent(this,Aventura::class.java) startActivity(intent) } } }
Ejercicio3.ObjetoyMercader/app/src/main/java/com/example/personajecreacion/MostrarDatos.kt
139375512
package com.example.personajecreacion import android.content.Intent import android.os.Bundle import android.widget.Button import android.widget.TextView import androidx.appcompat.app.AppCompatActivity class MostrarDatos: AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.mostrar_datos) var personaje : Personaje val botonSiguiente: Button = findViewById(R.id.boton_siguiente2) val botonAtras: Button = findViewById(R.id.boton_atras1) val nombre_personaje : TextView = findViewById<TextView>(R.id.nombre_personaje) val raza_personaje : TextView =findViewById(R.id.raza_personaje) val clase_personaje : TextView = findViewById(R.id.clase_personaje) val edad_personaje : TextView = findViewById(R.id.edad_personaje) var raza = intent.getStringExtra("raza") var clase = intent.getStringExtra("clase") var edad = intent.getStringExtra("edad") var nombre = intent.getStringExtra("nombre") nombre_personaje.text = "El nombre del personaje es: $nombre" raza_personaje.text = "La raza del personaje es: $raza" clase_personaje.text = "La clase del personaje es: $clase" edad_personaje.text = "La edad del personaje es: $edad" personaje = Personaje("nombre","viejo","raza","clase") botonAtras.setOnClickListener { val intent = Intent(this, MainActivity::class.java) startActivity(intent) } botonSiguiente.setOnClickListener { val intent = Intent(this, Aventura::class.java) intent.putExtra("Personaje",personaje) startActivity(intent) } } }
Ejercicio3.ObjetoyMercader/app/src/main/java/com/example/personajecreacion/Aventura.kt
427328823
package com.example.personajecreacion import android.content.Intent import android.os.Bundle import android.widget.ImageButton import androidx.appcompat.app.AppCompatActivity class Aventura : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_aventura) val personaje : Personaje? = intent.getParcelableExtra("Personaje", Personaje::class.java) val dado : ImageButton = findViewById(R.id.dado) dado.setOnClickListener{ var num = (1..4).random() val intent:Intent when(num){ 1->{ intent = Intent(this,Objeto::class.java) startActivity(intent) } 2->{ intent = Intent(this,Ciudad::class.java) startActivity(intent) } 3->{ intent = Intent(this,Mercader::class.java) startActivity(intent) } 4->{ intent = Intent(this,Enemigo::class.java) startActivity(intent) } } } } }
Ejercicio3.ObjetoyMercader/app/src/main/java/com/example/personajecreacion/Blanco.kt
2095510273
package com.example.personajecreacion import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class Blanco : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_blanco) } }
Ejercicio3.ObjetoyMercader/app/src/main/java/com/example/personajecreacion/Personaje.kt
1992164710
package com.example.personajecreacion import android.os.Parcel import android.os.Parcelable import kotlin.random.Random data class Personaje( private var nombre: String, private var estadoVital: String, private var raza: String, private var clase: String, ): Parcelable { private var experiencia : Int private var nivel : Int private var salud : Int private var ataque : Int private var defensa : Int private val mochila = Mochila(10) constructor(parcel: Parcel) : this( parcel.readString().toString(), parcel.readString().toString(), parcel.readString().toString(), parcel.readString().toString() ) { } init { salud = 100 ataque = 10 experiencia = 0 nivel = 1 defensa = 4 } fun getNombre(): String { return nombre } fun setNombre(nombre: String) { this.nombre = nombre } fun getEstadoVital(): String { return estadoVital } fun setEstadoVital(estadoVital: String) { this.estadoVital = estadoVital } fun getRaza(): String { return raza } fun setRaza(raza: String) { this.raza = raza } fun getClase(): String { return clase } fun setClase(clase: String) { this.clase = clase } override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeString(nombre) parcel.writeString(estadoVital) parcel.writeString(raza) parcel.writeString(clase) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<Personaje> { override fun createFromParcel(parcel: Parcel): Personaje { return Personaje(parcel) } override fun newArray(size: Int): Array<Personaje?> { return arrayOfNulls(size) } } }
Ejercicio3.ObjetoyMercader/app/src/main/java/com/example/personajecreacion/Objeto.kt
2916663596
package com.example.personajecreacion import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button class Objeto : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_objeto) val recoger:Button = findViewById(R.id.recoger) val siguiente : Button = findViewById(R.id.continuarOb) recoger.setOnClickListener { val intent = Intent(this,Aventura::class.java) startActivity(intent) } siguiente.setOnClickListener { val intent = Intent(this,Aventura::class.java) startActivity(intent) } } }
Ejercicio3.ObjetoyMercader/app/src/main/java/com/example/personajecreacion/Enemigo.kt
975956169
package com.example.personajecreacion import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button class Enemigo : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_enemigo) val luchar: Button = findViewById(R.id.luchar) val huir : Button = findViewById(R.id.huir) luchar.setOnClickListener { val intent = Intent(this,Blanco::class.java) startActivity(intent) } huir.setOnClickListener { val intent = Intent(this,Aventura::class.java) startActivity(intent) } } }
Ejercicio3.ObjetoyMercader/app/src/main/java/com/example/personajecreacion/Mercader.kt
2198561116
package com.example.personajecreacion import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button class Mercader : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_mercader) val comerciar: Button = findViewById(R.id.comerciar) val continuar : Button = findViewById(R.id.continuarM) val comprar : Button = findViewById(R.id.comprar) val vender : Button = findViewById(R.id.vender) val cancelar : Button = findViewById(R.id.cancelar) comerciar.setOnClickListener { //val intent = Intent(this,Blanco::class.java) //startActivity(intent) comerciar.setVisibility(View.INVISIBLE) continuar.setVisibility(View.INVISIBLE) comprar.setVisibility(View.VISIBLE) vender.setVisibility(View.VISIBLE) cancelar.setVisibility(View.VISIBLE) } continuar.setOnClickListener { val intent = Intent(this,Aventura::class.java) startActivity(intent) } } }
Ejercicio3.ObjetoyMercader/app/src/main/java/com/example/personajecreacion/Mochila.kt
3212052551
package com.example.personajecreacion class Mochila(private var pesoMochila: Int){ private var contenido=ArrayList<Articulo>() fun getPesoMochila():Int{ return pesoMochila } fun addArticulo(articulo: Articulo) { if (articulo.getPeso() <= pesoMochila) { when (articulo.getTipoArticulo()) { Articulo.TipoArticulo.ARMA -> { when (articulo.getNombre()) { Articulo.Nombre.BASTON, Articulo.Nombre.ESPADA, Articulo.Nombre.DAGA, Articulo.Nombre.MARTILLO, Articulo.Nombre.GARRAS -> { contenido.add(articulo) this.pesoMochila -= articulo.getPeso() println("${articulo.getNombre()} ha sido añadido a la mochila.") } else -> println("Nombre del artículo no válido para el tipo ARMA.") } } Articulo.TipoArticulo.OBJETO -> { when (articulo.getNombre()) { Articulo.Nombre.POCION, Articulo.Nombre.IRA -> { contenido.add(articulo) this.pesoMochila -= articulo.getPeso() println("${articulo.getNombre()} ha sido añadido a la mochila.") } else -> println("Nombre del artículo no válido para el tipo OBJETO.") } } Articulo.TipoArticulo.PROTECCION -> { when (articulo.getNombre()) { Articulo.Nombre.ESCUDO, Articulo.Nombre.ARMADURA -> { contenido.add(articulo) this.pesoMochila -= articulo.getPeso() println("${articulo.getNombre()} ha sido añadido a la mochila.") } else -> println("Nombre del artículo no válido para el tipo PROTECCION.") } } } } else { println("El peso del artículo excede el límite de la mochila.") } } fun getContenido(): ArrayList<Articulo> { return contenido } fun findObjeto(nombre: Articulo.Nombre): Int { return contenido.indexOfFirst { it.getNombre() == nombre } } override fun toString(): String { return if (contenido.isEmpty()) { "Mochila vacía" } else { "Artículos en la mochila: ${contenido.joinToString("\n")}" } } }
Ejercicio3.ObjetoyMercader/app/src/main/java/com/example/personajecreacion/db/DataBaseHelper.kt
2776296751
package com.example.personajecreacion.db class DataBaseHelper { }
Ejercicio3.ObjetoyMercader/app/src/main/java/com/example/personajecreacion/Articulo.kt
2427879643
package com.example.personajecreacion class Articulo( private var tipoArticulo: TipoArticulo, private var nombre: Nombre, private var peso: Int ) { enum class TipoArticulo { ARMA, OBJETO, PROTECCION, ORO } enum class Nombre { BASTON, ESPADA, DAGA, MARTILLO, GARRAS, POCION, IRA, ESCUDO, ARMADURA, MONEDA } fun getPeso(): Int { return peso } fun getNombre(): Nombre { return nombre } fun getTipoArticulo(): TipoArticulo { return tipoArticulo } fun getAumentoAtaque(): Int { return when (nombre) { Nombre.BASTON -> 10 Nombre.ESPADA -> 20 Nombre.DAGA -> 15 Nombre.MARTILLO -> 25 Nombre.GARRAS -> 30 Nombre.IRA -> 80 else -> 0 // Para otros tipos de armas no especificados } } fun getAumentoDefensa(): Int { return when (nombre) { Nombre.ESCUDO -> 10 Nombre.ARMADURA -> 20 else -> 0 // Para otros tipos de protecciones no especificados } } fun getAumentoVida(): Int { return when (nombre) { Nombre.POCION -> 100 else -> 0 // Para otros tipos de objetos no especificados } } override fun toString(): String { return "[Tipo Artículo:$tipoArticulo, Nombre:$nombre, Peso:$peso]" } }
wotr-cli/src/test/kotlin/ch/chrigu/wotr/location/LocationNameTest.kt
2300602548
package ch.chrigu.wotr.location import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class LocationNameTest { @Test fun `should not have duplicate shortcuts`() { val duplicates = LocationName.entries.groupBy { it.shortcut } .filter { (_, names) -> names.size > 1 } assertThat(duplicates).isEmpty() } }
wotr-cli/src/test/kotlin/ch/chrigu/wotr/location/LocationFinderTest.kt
3658880758
package ch.chrigu.wotr.location import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.CsvSource class LocationFinderTest { @ParameterizedTest @CsvSource( "RIVENDELL, MORANNON, MORIA, 10", "RIVENDELL, RIVENDELL, , 0", "MORIA, HOLLIN, HOLLIN, 1" ) fun `should find paths`(from: LocationName, to: LocationName, through: LocationName?, length: Int) { val result = LocationFinder.getShortestPath(from, to) assertThat(result.map { it.getLength() }).containsOnly(length) if (through != null) { assertThat(result).allMatch { it.locations.contains(through) } } } }
wotr-cli/src/test/kotlin/ch/chrigu/wotr/figure/FigureTypeTest.kt
2329574359
package ch.chrigu.wotr.figure import org.assertj.core.api.Assertions import org.junit.jupiter.api.Test class FigureTypeTest { @Test fun `shortcuts should be unique`() { val duplicates = FigureType.entries.filter { it.isUniqueCharacter } .groupBy { it.shortcut } .filterValues { it.size > 1 } Assertions.assertThat(duplicates).isEmpty() } }
wotr-cli/src/test/kotlin/ch/chrigu/wotr/figure/FiguresTest.kt
2702892541
package ch.chrigu.wotr.figure import ch.chrigu.wotr.nation.NationName import ch.chrigu.wotr.player.Player import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class FiguresTest { @Test fun `should allow opposed character on field`() { val shadowArmy = Figures( listOf( Figure(FigureType.REGULAR, NationName.SAURON), Figure(FigureType.ELITE, NationName.SOUTHRONS_AND_EASTERLINGS), Figure(FigureType.LEADER_OR_NAZGUL, NationName.SAURON) ) ) val withAragorn = Figures(listOf(Figure(FigureType.ARAGORN, NationName.GONDOR))) + shadowArmy assertThat(withAragorn.armyPlayer).isEqualTo(Player.SHADOW) assertThat(withAragorn.getArmy().size).isEqualTo(3) assertThat(withAragorn.getArmyPerNation().keys).isEqualTo(setOf(NationName.SAURON, NationName.SOUTHRONS_AND_EASTERLINGS)) } }
wotr-cli/src/test/kotlin/ch/chrigu/wotr/dice/DiceAndRingsTest.kt
28310711
package ch.chrigu.wotr.dice import ch.chrigu.wotr.player.Player import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class DiceAndRingsTest { @Test fun `should use only one die`() { val testee = DiceAndRings(listOf(DieType.ARMY, DieType.ARMY, DieType.ARMY_MUSTER), 0, Player.SHADOW) val result = testee.use(DieUsage(DieType.ARMY, false, Player.SHADOW)) assertThat(result.rolled).containsExactly(DieType.ARMY, DieType.ARMY_MUSTER) } }
wotr-cli/src/test/kotlin/ch/chrigu/wotr/nation/NationNameTest.kt
1688976099
package ch.chrigu.wotr.nation import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class NationNameTest { @Test fun `shortcuts should be unique`() { assertThat(NationName.entries.groupBy { it.shortcut }.filterValues { it.size > 1 }).isEmpty() } }
wotr-cli/src/test/kotlin/ch/chrigu/wotr/WotrCliApplicationTests.kt
2405809127
package ch.chrigu.wotr import org.junit.jupiter.api.Test import org.springframework.boot.test.context.SpringBootTest @SpringBootTest class WotrCliApplicationTests { @Test fun contextLoads() { } }
wotr-cli/src/test/kotlin/ch/chrigu/wotr/bot/BotEvaluationServiceTest.kt
1486308169
package ch.chrigu.wotr.bot import ch.chrigu.wotr.action.* import ch.chrigu.wotr.card.EventType import ch.chrigu.wotr.dice.DieType import ch.chrigu.wotr.dice.DieUsage import ch.chrigu.wotr.figure.Figures import ch.chrigu.wotr.gamestate.GameState import ch.chrigu.wotr.gamestate.GameStateFactory import ch.chrigu.wotr.location.LocationName import ch.chrigu.wotr.nation.NationName import ch.chrigu.wotr.player.Player import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.extension.ExtensionContext import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.ArgumentsProvider import org.junit.jupiter.params.provider.ArgumentsSource import java.util.stream.Stream class BotEvaluationServiceTest { private val initial = GameStateFactory.newGame() .let { it.copy(dice = it.dice.fakeShadowRoll(DieType.MUSTER, DieType.ARMY, DieType.EVENT)) } private val initialScore = BotEvaluationService.count(initial) @ParameterizedTest(name = "{0}") @ArgumentsSource(Args::class) fun `should have higher score after action`(description: String, action: (GameState) -> GameAction) { val newState = action(initial).apply(initial) val newScore = BotEvaluationService.count(newState) assertThat(newScore).describedAs(description).isGreaterThan(initialScore) } class Args : ArgumentsProvider { override fun provideArguments(context: ExtensionContext?): Stream<Arguments> = Stream.of( action("MoveAction", DieType.ARMY) { MoveAction(LocationName.GORGOROTH, LocationName.MINAS_MORGUL, Figures.parse(arrayOf("1"), LocationName.GORGOROTH, it)) }, action("MusterAction", DieType.MUSTER) { MusterAction(Figures.parse(arrayOf("1"), it.reinforcements, NationName.SAURON), LocationName.DOL_GULDUR) }, action("DrawEventAction", DieType.EVENT) { DrawEventAction(EventType.CHARACTER) }, action("PoliticsMarkerAction", DieType.MUSTER) { PoliticsMarkerAction(NationName.SAURON) } ).flatMap { it.toArguments() } private fun action(description: String, dieType: DieType, action: (GameState) -> GameAction) = ActionArgument(description, dieType, action) class ActionArgument(private val description: String, private val dieType: DieType, private val action: (GameState) -> GameAction) { fun toArguments(): Stream<Arguments> = Stream.of( Arguments.of(description, action), Arguments.of("DieAction($description)", toDieAction()) ) private fun toDieAction(): (GameState) -> GameAction = { DieAction(DieUsage(dieType, false, Player.SHADOW), listOf(action(it))) } } } }
wotr-cli/src/test/kotlin/ch/chrigu/wotr/bot/MoveArmyStrategyTest.kt
2665054736
package ch.chrigu.wotr.bot import ch.chrigu.wotr.action.MoveAction import ch.chrigu.wotr.figure.Figure import ch.chrigu.wotr.figure.FigureType import ch.chrigu.wotr.figure.Figures import ch.chrigu.wotr.gamestate.GameState import ch.chrigu.wotr.location.Location import ch.chrigu.wotr.location.LocationName import ch.chrigu.wotr.nation.NationName import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock class MoveArmyStrategyTest { @Test fun `should create 2 times 3 move actions`() { val testee = MoveArmyStrategy(mock()) val army = Figures(listOf(Figure(FigureType.REGULAR, NationName.ISENGARD), Figure(FigureType.ELITE, NationName.ISENGARD), Figure(FigureType.SARUMAN, NationName.ISENGARD))) val orthanc = mock<Location> { on { nonBesiegedFigures } doReturn army on { adjacentLocations } doReturn listOf(LocationName.SOUTH_DUNLAND) on { name } doReturn LocationName.ORTHANC } val state = mock<GameState> { on { location } doReturn mapOf(LocationName.ORTHANC to orthanc) } val result = testee.getActions(state) assertThat(result.filterIsInstance<MoveAction>()).hasSize(2 * 3) } }
wotr-cli/src/test/kotlin/ch/chrigu/wotr/bot/BotActionFactoryTest.kt
273776203
package ch.chrigu.wotr.bot import ch.chrigu.wotr.gamestate.GameStateFactory import org.jline.terminal.Terminal import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.mockito.kotlin.* import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.boot.test.context.TestConfiguration import org.springframework.boot.test.mock.mockito.MockBean import org.springframework.context.annotation.ComponentScan import org.springframework.context.annotation.Import import java.io.PrintWriter @SpringBootTest(classes = [BotActionFactory::class]) @Import(BotActionFactoryTest.Config::class) class BotActionFactoryTest(@Autowired private val testee: BotActionFactory) { @MockBean private lateinit var terminal: Terminal @Test fun `should beat free people`() { var gameState = GameStateFactory.newGame() while (gameState.vpShadow() < 10) { val next = testee.getNext(gameState) gameState = next.simulate(gameState) println("$next ->\n$gameState") } } @BeforeEach fun initTerminal() { val writer = mock<PrintWriter> { on { this.println(any<String>()) } doAnswer { println(it.arguments[0] as String) } } whenever(terminal.writer()) doReturn writer } @TestConfiguration @ComponentScan(basePackageClasses = [HarmFellowshipStrategy::class]) class Config }
wotr-cli/src/test/kotlin/ch/chrigu/wotr/bot/CombinationsTest.kt
2924234998
package ch.chrigu.wotr.bot import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.MethodSource import java.util.stream.Stream class CombinationsTest { @ParameterizedTest @MethodSource("allCombinations") fun `should list all combinations`(input: List<String>, expected: Array<List<String>>) { val result = Combinations.allSizes(input) assertThat(result).containsExactlyInAnyOrder(*expected) } @ParameterizedTest @MethodSource("ofSize2") fun `should list combinations of size 2`(input: List<String>, expected: Array<List<String>>?) { val result = Combinations.ofSize(input, 2) if (expected == null) assertThat(result).isEmpty() else assertThat(result).containsExactlyInAnyOrder(*expected) } companion object { @JvmStatic fun ofSize2(): Stream<Arguments> = Stream.of( Arguments.of(listOf("a", "b", "c"), arrayOf(listOf("a", "b"), listOf("a", "c"), listOf("b", "c"))), Arguments.of(listOf("a", "b"), arrayOf(listOf("a", "b"))), Arguments.of(listOf("a"), null) ) @JvmStatic fun allCombinations(): Stream<Arguments> = Stream.of( Arguments.of( listOf("a", "b", "c"), arrayOf( emptyList(), listOf("a"), listOf("b"), listOf("c"), listOf("a", "b"), listOf("a", "c"), listOf("b", "c"), listOf("a", "b", "c") ) ), Arguments.of(listOf("a", "b"), arrayOf(emptyList(), listOf("a"), listOf("b"), listOf("a", "b"))), Arguments.of(listOf("a"), arrayOf(emptyList(), listOf("a"))) ) } }
wotr-cli/src/test/kotlin/ch/chrigu/wotr/gamestate/GameStateLoaderTest.kt
458459266
package ch.chrigu.wotr.gamestate import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import java.io.File class GameStateLoaderTest { @Test fun `should save and load initial state`() { val initialState = GameStateFactory.newGame() val file = File("build/test.json") GameStateLoader.saveFile(file, initialState) val loaded = GameStateLoader.loadFile(file) assertThat(loaded.toString()).isEqualTo(initialState.toString()) } }
wotr-cli/src/test/kotlin/ch/chrigu/wotr/gamestate/GameStateFactoryTest.kt
1787781419
package ch.chrigu.wotr.gamestate import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class GameStateFactoryTest { @Test fun `adjacent locations should have a pointer back`() { val all = GameStateFactory.newGame().location all.values.forEach { location -> location.adjacentLocations.forEach { neighbor -> assertThat(all[neighbor]!!.adjacentLocations).contains(location.name) } } } }
wotr-cli/src/test/kotlin/ch/chrigu/wotr/CommandShellTest.kt
2634458339
package ch.chrigu.wotr import ch.chrigu.wotr.bot.BotActionFactory import ch.chrigu.wotr.commands.WotrPromptProvider import ch.chrigu.wotr.figure.FiguresCompletionProvider import ch.chrigu.wotr.figure.ReinforcementsCompletionProvider import ch.chrigu.wotr.gamestate.GameStateHolder import ch.chrigu.wotr.location.LocationCompletionProvider import org.awaitility.Awaitility.await import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.TestConfiguration import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Import import org.springframework.shell.test.ShellAssertions.assertThat import org.springframework.shell.test.ShellScreenAssert import org.springframework.shell.test.ShellTestClient import org.springframework.shell.test.ShellTestClient.BaseShellSession import org.springframework.shell.test.ShellWriteSequence import org.springframework.shell.test.autoconfigure.ShellTest import java.util.concurrent.TimeUnit @ShellTest @Import(WotrPromptProvider::class, GameStateHolder::class, BotActionFactory::class) class CommandShellTest(@Autowired private val client: ShellTestClient) { private lateinit var session: BaseShellSession<*> @BeforeEach fun initSession() { session = client.interactive().run() } @AfterEach fun undo() { write { text("undo").carriageReturn() } } @Test fun `should move figures`() { write { text("move --from ri").ctrl('\t') } assertScreen { containsText("rivendell") } write { text(" -t tr -w ").ctrl('\t') } assertScreen { containsText("021") } write { text("011").carriageReturn() } assertScreen { containsText("Trollshaws: 011 (Elves)") } } @Test fun `should kill figure`() { write { text("k orthanc -w 100").carriageReturn() } assertScreen { containsText("Orthanc: 310") } } @Test fun `should muster figure`() { write { text("muster or 010").carriageReturn() } assertScreen { containsText("Orthanc: 420") } } private fun assertScreen(shellAssert: ShellScreenAssert.() -> ShellScreenAssert) { await().atMost(5, TimeUnit.SECONDS).untilAsserted { val screen = session.screen() assertThat(screen).shellAssert() } } private fun write(cmd: ShellWriteSequence.() -> ShellWriteSequence) { session.write(session.writeSequence().cmd().build()) } @TestConfiguration class Config { @Bean fun locationCompletionProvider() = LocationCompletionProvider() @Bean fun figuresCompletionProvider(gameStateHolder: GameStateHolder) = FiguresCompletionProvider(gameStateHolder) @Bean fun reinforcementsCompletionProvider(gameStateHolder: GameStateHolder) = ReinforcementsCompletionProvider(gameStateHolder) } }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/card/EventType.kt
3361648425
package ch.chrigu.wotr.card enum class EventType { CHARACTER, STRATEGY; override fun toString() = name.take(1) }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/card/Cards.kt
659505160
package ch.chrigu.wotr.card import kotlinx.serialization.Serializable /** * Yet we're interested in the number of shadow cards per type only. This is a simplification, but implementing all cards will * be a time intensive task. */ @Serializable data class Cards(private val shadow: Map<EventType, Int> = EventType.entries.associateWith { 0 }) { init { require(shadow.values.all { it >= 0 }) { "Cannot play cards that are not drawn yet" } require(numCards() <= 6) { "Should not hold more than 6 cards" } } fun play(type: EventType) = copy(shadow = shadow.mapValues { (t, num) -> if (type == t) num - 1 else num }) fun phase1() = if (numCards() <= 4) draw(EventType.CHARACTER).draw(EventType.STRATEGY) else if (numCards() == 5) draw(EventType.CHARACTER) else this fun draw(type: EventType) = copy(shadow = shadow.mapValues { (t, num) -> if (type == t) num + 1 else num }) fun numCards() = shadow.values.fold(0) { a, b -> a + b } override fun toString() = shadow.map { (t, num) -> "$num$t" }.joinToString("/") }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/combat/CombatType.kt
3712408959
package ch.chrigu.wotr.combat enum class CombatType { SIEGE, SORTIE, FIELD_BATTLE }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/combat/CombatSimulator.kt
4265390594
package ch.chrigu.wotr.combat import ch.chrigu.wotr.action.KillAction import ch.chrigu.wotr.action.MusterAction import ch.chrigu.wotr.figure.Figure import ch.chrigu.wotr.figure.FigureType import ch.chrigu.wotr.figure.Figures import ch.chrigu.wotr.figure.FiguresType import ch.chrigu.wotr.gamestate.GameState import ch.chrigu.wotr.location.LocationName import ch.chrigu.wotr.location.LocationType import kotlin.math.min import kotlin.math.round import kotlin.random.Random class CombatSimulator( private val attacker: Figures, private val defender: Figures, private val combatType: CombatType, private val locationType: LocationType, private val attackerLocation: LocationName, private val defenderLocation: LocationName ) { fun repeat(num: Int): List<Casualties> { val requires = if (combatType == CombatType.SIEGE) 6 else if (locationType == LocationType.CITY || locationType == LocationType.FORTIFICATION) 6 else 5 val attackerDice = CombatDice(attacker.combatRolls(), attacker.maxReRolls(), requires) val defenderDice = CombatDice(defender.combatRolls(), defender.maxReRolls(), 5) val hits = (0 until num).map { attackerDice.roll() to defenderDice.roll() } .fold(0.0 to 0.0) { (a1, d1), (a2, d2) -> a1 + a2 to d1 + d2 } .let { (a, d) -> round(a / num) to round(d / num) } return listOf(Casualties(defenderLocation, defender, hits.first.toInt()), Casualties(attackerLocation, attacker, hits.second.toInt())) } } data class Casualties(private val at: LocationName, private val from: Figures, private val hits: Int) { fun apply(state: GameState) = initActions(state.reinforcements).fold(state) { a, b -> b.apply(a) } private fun initActions(reinforcements: Figures) = takeCasualty(from.copy(type = FiguresType.REINFORCEMENTS), hits, reinforcements.all.filter { it.type == FigureType.REGULAR }) .fold(Casualty.zero()) { a, b -> a + b } .let { listOfNotNull( if (it.killed.isEmpty()) null else KillAction(at, it.killed), // TODO: GameState should not allow adding and removing figure, just moving from one zone to another if (it.spawn.isEmpty()) null else MusterAction(Figures(it.spawn), at) // TODO: Can also be from killed ) } private fun takeCasualty(left: Figures, remainingHits: Int, regularReinforcements: List<Figure>): List<Casualty> { // TODO: Prefer killed regulars, test val numUnits = left.numRegulars() + left.numRegulars() if (numUnits == 0) return listOf(Casualty(left, 0, emptyList())) if (remainingHits <= 0) return emptyList() val take = if (numUnits > 5 && left.numRegulars() > 0) Casualty.kill(left.all.first { it.type == FigureType.REGULAR }) else { val regular = regularReinforcements.firstOrNull { regular -> left.all.any { downgrade -> downgrade.type == FigureType.ELITE && regular.nation == downgrade.nation } } if (regular != null) Casualty.downgrade(left.all.first { it.type == FigureType.ELITE && it.nation == regular.nation }, regular) else if (left.numRegulars() > 0) Casualty.kill(left.all.first { it.type == FigureType.REGULAR }) else Casualty.kill(left.all.first { it.type.isUnit }) } return listOf(take) + takeCasualty(left - take.killed + Figures(take.spawn), remainingHits - take.hits, regularReinforcements - take.spawn.toSet()) } class Casualty(val killed: Figures, val hits: Int, val spawn: List<Figure>) { operator fun plus(other: Casualty) = Casualty(killed + other.killed, hits + other.hits, spawn + other.spawn) companion object { fun kill(figure: Figure) = Casualty(Figures(listOf(figure)), if (figure.type == FigureType.REGULAR) 1 else 2, emptyList()) fun downgrade(elite: Figure, regular: Figure) = Casualty(Figures(listOf(elite)), 1, listOf(regular)) fun zero() = Casualty(Figures(emptyList()), 0, emptyList()) } } } data class CombatDice(private val combatRolls: Int, private val maxReRolls: Int, val requires: Int) { init { require(combatRolls in 1..5) require(maxReRolls in 0..5) require(requires in 5..6) } fun roll(): Int { val dice = rollDice(combatRolls) val ok = dice.count { it >= requires } val nok = dice.count { it < requires } val reRoll = rollDice(min(nok, maxReRolls)).count { it >= requires } return ok + reRoll } private fun rollDice(num: Int) = (0 until num).map { Random.nextInt(6) + 1 } }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/location/Location.kt
2349014088
package ch.chrigu.wotr.location import ch.chrigu.wotr.figure.FigureType import ch.chrigu.wotr.figure.Figures import ch.chrigu.wotr.figure.FiguresType import ch.chrigu.wotr.gamestate.GameState import ch.chrigu.wotr.nation.NationName import ch.chrigu.wotr.player.Player import kotlinx.serialization.Serializable @Serializable data class Location( val name: LocationName, val nonBesiegedFigures: Figures, val besiegedFigures: Figures = Figures(emptyList()), val captured: Boolean = false ) { init { if (name.nation == null) { require(name.type == LocationType.NONE || name.type == LocationType.FORTIFICATION) { "This location must have a nation: $this" } } if (name.type != LocationType.STRONGHOLD) { require(besiegedFigures.isEmpty()) { "Only strongholds may have besieged figures: $this" } } else if (!besiegedFigures.isEmpty()) { require(!nonBesiegedFigures.isEmpty()) { "Besieged figures require besieging figures: $this" } } if (currentlyOccupiedBy() == Player.FREE_PEOPLE && name.type == LocationType.STRONGHOLD && besiegedFigures.isEmpty()) { require(nonBesiegedFigures.all.none { it.isCharacterOrNazgul() && it.nation.player == Player.SHADOW }) { "Nazgul and minions may not enter strongholds controlled by free people" } } require(nonBesiegedFigures.type == FiguresType.LOCATION) { "Figures must have location type: $this" } require(besiegedFigures.type == FiguresType.LOCATION) { "Figures must have location type: $this" } } val adjacentLocations: List<LocationName> get() = name.adjacent() val nation: NationName? get() = name.nation val type: LocationType get() = name.type val victoryPoints: Int get() = if (type == LocationType.STRONGHOLD) 2 else if (type == LocationType.CITY) 1 else 0 fun remove(figures: Figures) = if (besiegedFigures.containsAll(figures)) { val newBesiegedFigures = besiegedFigures - figures if (newBesiegedFigures.isEmpty()) copy(besiegedFigures = newBesiegedFigures, captured = newCapturedValueForArmy(nonBesiegedFigures.armyPlayer)) else copy(besiegedFigures = newBesiegedFigures) } else { copy(nonBesiegedFigures = nonBesiegedFigures - figures) } fun add(figures: Figures): Location { val armyPlayer = figures.armyPlayer return if (type == LocationType.STRONGHOLD && armyPlayer != null && nonBesiegedFigures.armyPlayer?.opponent == armyPlayer) { val army = Figures(nonBesiegedFigures.getArmy()) copy(nonBesiegedFigures = nonBesiegedFigures - army + figures, besiegedFigures = besiegedFigures + army) } else { copy(nonBesiegedFigures = nonBesiegedFigures + figures, captured = newCapturedValueForArmy(armyPlayer)) } } fun currentlyOccupiedBy() = if (captured) nation?.player?.opponent else nation?.player fun contains(type: FigureType) = allFigures().any { it.type == type } fun allFigures() = nonBesiegedFigures.all + besiegedFigures.all fun getShortestPath(from: LocationName, to: LocationName): List<LocationPath> { return LocationFinder.getShortestPath(from, to) } fun adjacentArmies(player: Player, gameState: GameState) = adjacentLocations .map { gameState.location[it]!!.nonBesiegedFigures } .filter { it.armyPlayer == player } .map { it.getArmy() } fun nearestLocationWith(state: GameState, condition: (Location) -> Boolean): Int { val candidates = state.location.values.filter(condition) return candidates.minOf { LocationFinder.getDistance(name, it.name) } } fun distanceTo(state: GameState, condition: (Location) -> Boolean): Map<Location, Int> { val candidates = state.location.values.filter(condition) return candidates.associateWith { LocationFinder.getDistance(name, it.name) } } override fun toString() = name.fullName + ": " + nonBesiegedFigures.toString() + printStronghold() private fun newCapturedValueForArmy(armyPlayer: Player?) = if (currentlyOccupiedBy() == armyPlayer || armyPlayer == null) captured else !captured private fun printStronghold() = if (type == LocationType.STRONGHOLD) "/$besiegedFigures" else "" }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/location/LocationName.kt
190899888
package ch.chrigu.wotr.location import ch.chrigu.wotr.nation.NationName enum class LocationName(val shortcut: String, val adjacent: () -> List<LocationName>, val nation: NationName? = null, val type: LocationType = LocationType.NONE) { ANDRAST("and", { listOf(DRUWAITH_IAUR, ANFALAS) }), ANFALAS("anf", { listOf(ANDRAST, ERECH, DOL_AMROTH) }, NationName.GONDOR), ANGMAR("ang", { listOf(ARNOR, ETTENMOORS, MOUNT_GRAM) }, NationName.SAURON, LocationType.CITY), ARNOR("arn", { listOf(EVENDIM, NORTH_DOWNS, ETTENMOORS, ANGMAR) }), ASH_MOUNTAINS("am", { listOf(SOUTHERN_DORWINION, NOMAN_LANDS, DAGORLAD, SOUTH_RHUN) }), BARAD_DUR("bd", { listOf(GORGOROTH) }, NationName.SAURON, LocationType.STRONGHOLD), BREE("br", { listOf(NORTH_DOWNS, BUCKLAND, SOUTH_DOWNS, WEATHER_HILLS) }, NationName.NORTHMEN, LocationType.VILLAGE), BUCKLAND("bu", { listOf(THE_SHIRE, OLD_FOREST, CARDOLAN, SOUTH_DOWNS, BREE, NORTH_DOWNS, EVENDIM) }, NationName.NORTHMEN), CARDOLAN("cn", { listOf(OLD_FOREST, SOUTH_ERED_LUIN, MINHIRIATH, THARBAD, NORTH_DUNLAND, SOUTH_DOWNS, BUCKLAND) }), CARROCK("ck", { listOf(EAGLES_EYRIE, OLD_FORD, RHOSGOBEL, OLD_FOREST_ROAD, WESTERN_MIRKWOOD, NORTHERN_MIRKWOOD) }, NationName.NORTHMEN, LocationType.VILLAGE), DAGORLAD("dad", { listOf(NOMAN_LANDS, EASTERN_EMYN_MUIL, NORTH_ITHILIEN, MORANNON, ASH_MOUNTAINS) }), DALE("da", { listOf(EREBOR, WITHERED_HEATH, WOODLAND_REALM, OLD_FOREST_ROAD, NORTHERN_RHOVANION, VALE_OF_THE_CARNEN, IRON_HILLS) }, NationName.NORTHMEN, LocationType.CITY), DEAD_MARSHES("dm", { listOf(EASTERN_EMYN_MUIL, WESTERN_EMYN_MUIL, DRUADAN_FOREST, OSGILIATH, NORTH_ITHILIEN) }), DIMRILL_DALE("dd", { listOf(GLADDEN_FIELDS, MORIA, LORIEN, PARTH_CELEBRANT, SOUTH_ANDUIN_VALE, NORTH_ANDUIN_VALE) }), DOL_AMROTH("dam", { listOf(ANFALAS, ERECH, LAMEDON) }, NationName.GONDOR, LocationType.STRONGHOLD), DOL_GULDUR( "dg", { listOf(NARROWS_OF_THE_FOREST, NORTH_ANDUIN_VALE, SOUTH_ANDUIN_VALE, WESTERN_BROWN_LANDS, EASTERN_BROWN_LANDS, SOUTHERN_MIRKWOOD, EASTERN_MIRKWOOD) }, NationName.SAURON, LocationType.STRONGHOLD ), DRUADAN_FOREST("df", { listOf(EASTEMNET, FOLDE, MINAS_TIRITH, OSGILIATH, DEAD_MARSHES, WESTERN_EMYN_MUIL) }, NationName.GONDOR), DRUWAITH_IAUR("di", { listOf(ENEDWAITH, ANDRAST, FORDS_OF_ISEN, GAP_OF_ROHAN) }), EAGLES_EYRIE("ee", { listOf(MOUNT_GUNDABAD, OLD_FORD, CARROCK) }), EASTEMNET("ea", { listOf(PARTH_CELEBRANT, FANGORN, WESTEMNET, FOLDE, DRUADAN_FOREST, WESTERN_EMYN_MUIL, WESTERN_BROWN_LANDS) }, NationName.ROHAN), EASTERN_BROWN_LANDS("ebl", { listOf(SOUTHERN_MIRKWOOD, DOL_GULDUR, WESTERN_BROWN_LANDS, WESTERN_EMYN_MUIL, EASTERN_EMYN_MUIL, NOMAN_LANDS, SOUTHERN_RHOVANION) }), EASTERN_EMYN_MUIL("eem", { listOf(EASTERN_BROWN_LANDS, WESTERN_EMYN_MUIL, DEAD_MARSHES, NORTH_ITHILIEN, DAGORLAD, NOMAN_LANDS) }), EASTERN_MIRKWOOD("em", { listOf(OLD_FOREST_ROAD, NARROWS_OF_THE_FOREST, DOL_GULDUR, SOUTHERN_MIRKWOOD, NORTHERN_RHOVANION) }), EAST_HARONDOR("eh", { listOf(SOUTH_ITHILIEN, WEST_HARONDOR, NEAR_HARAD) }), EAST_RHUN("erh", { listOf(IRON_HILLS, VALE_OF_THE_CARNEN, NORTH_RHUN, SOUTH_RHUN) }, NationName.SOUTHRONS_AND_EASTERLINGS), EDORAS("ed", { listOf(WESTEMNET, FOLDE) }, NationName.ROHAN, LocationType.CITY), ENEDWAITH("en", { listOf(THARBAD, MINHIRIATH, DRUWAITH_IAUR, GAP_OF_ROHAN, SOUTH_DUNLAND) }), EREBOR( "eb", { listOf(WITHERED_HEATH, DALE, IRON_HILLS) }, NationName.DWARVES, LocationType.STRONGHOLD ), ERECH( "ere", { listOf(ANFALAS, DOL_AMROTH, LAMEDON) }, NationName.GONDOR ), ERED_LUIN( "el", { listOf(FORLINDON, GREY_HAVENS, TOWER_HILLS, NORTH_ERED_LUIN, EVENDIM) }, NationName.DWARVES, LocationType.VILLAGE ), ETTENMOORS("et", { listOf(ANGMAR, ARNOR, NORTH_DOWNS, WEATHER_HILLS, TROLLSHAWS, MOUNT_GRAM) }), EVENDIM("ev", { listOf(NORTH_ERED_LUIN, ERED_LUIN, TOWER_HILLS, THE_SHIRE, BUCKLAND, NORTH_DOWNS, ARNOR) }), FANGORN("fa", { listOf(PARTH_CELEBRANT, FORDS_OF_ISEN, WESTEMNET, EASTEMNET) }), FAR_HARAD( "fh", { listOf(KHAND, NEAR_HARAD) }, NationName.SOUTHRONS_AND_EASTERLINGS, LocationType.CITY ), FOLDE( "fol", { listOf(EASTEMNET, WESTEMNET, EDORAS, DRUADAN_FOREST) }, NationName.ROHAN, LocationType.VILLAGE ), FORDS_OF_BRUINEN("fb", { listOf(RIVENDELL, TROLLSHAWS, HOLLIN, HIGH_PASS) }), FORDS_OF_ISEN( "fi", { listOf(ORTHANC, GAP_OF_ROHAN, DRUWAITH_IAUR, HELMS_DEEP, WESTEMNET, FANGORN) }, NationName.ROHAN, LocationType.FORTIFICATION ), FORLINDON("for", { listOf(NORTH_ERED_LUIN, ERED_LUIN, GREY_HAVENS) }), GAP_OF_ROHAN( "gr", { listOf(SOUTH_DUNLAND, ENEDWAITH, DRUWAITH_IAUR, FORDS_OF_ISEN, ORTHANC) }, NationName.ISENGARD ), GLADDEN_FIELDS("gf", { listOf(OLD_FORD, DIMRILL_DALE, RHOSGOBEL, NORTH_ANDUIN_VALE) }), GOBLINS_GATE("gg", { listOf(HIGH_PASS, OLD_FORD) }), GORGOROTH( "go", { listOf(BARAD_DUR, MORANNON, MINAS_MORGUL, NURN) }, NationName.SAURON ), GREY_HAVENS( "gh", { listOf(FORLINDON, HARLINDON, TOWER_HILLS, ERED_LUIN) }, NationName.ELVES, LocationType.STRONGHOLD ), HARLINDON("ha", { listOf(GREY_HAVENS, SOUTH_ERED_LUIN) }), HELMS_DEEP( "hd", { listOf(FORDS_OF_ISEN, WESTEMNET) }, NationName.ROHAN, LocationType.STRONGHOLD ), HIGH_PASS("hp", { listOf(FORDS_OF_BRUINEN, GOBLINS_GATE) }), HOLLIN("ho", { listOf(FORDS_OF_BRUINEN, TROLLSHAWS, SOUTH_DOWNS, NORTH_DUNLAND, MORIA) }), IRON_HILLS( "ih", { listOf(EREBOR, DALE, VALE_OF_THE_CARNEN, EAST_RHUN) }, NationName.DWARVES, LocationType.VILLAGE ), KHAND( "kh", { listOf(NEAR_HARAD, FAR_HARAD) }, NationName.SOUTHRONS_AND_EASTERLINGS ), LAMEDON( "la", { listOf(ERECH, DOL_AMROTH, PELARGIR) }, NationName.GONDOR, LocationType.VILLAGE ), LORIEN( "lor", { listOf(DIMRILL_DALE, PARTH_CELEBRANT) }, NationName.ELVES, LocationType.STRONGHOLD ), LOSSARNACH( "los", { listOf(MINAS_TIRITH, PELARGIR, OSGILIATH) }, NationName.GONDOR, LocationType.VILLAGE ), MINAS_MORGUL( "mm", { listOf(NORTH_ITHILIEN, SOUTH_ITHILIEN, GORGOROTH) }, NationName.SAURON, LocationType.STRONGHOLD ), MINAS_TIRITH( "mt", { listOf(DRUADAN_FOREST, LOSSARNACH, OSGILIATH) }, NationName.GONDOR, LocationType.STRONGHOLD ), MINHIRIATH("mi", { listOf(SOUTH_ERED_LUIN, ENEDWAITH, THARBAD, CARDOLAN) }), MORANNON( "mn", { listOf(DAGORLAD, GORGOROTH) }, NationName.SAURON, LocationType.STRONGHOLD ), MORIA( "mo", { listOf(HOLLIN, NORTH_DUNLAND, DIMRILL_DALE) }, NationName.SAURON, LocationType.STRONGHOLD ), MOUNT_GRAM( "mgr", { listOf(ANGMAR, ETTENMOORS, MOUNT_GUNDABAD) }, NationName.SAURON ), MOUNT_GUNDABAD( "mgu", { listOf(MOUNT_GRAM, EAGLES_EYRIE) }, NationName.SAURON, LocationType.STRONGHOLD ), NARROWS_OF_THE_FOREST("nf", { listOf(OLD_FOREST_ROAD, RHOSGOBEL, NORTH_ANDUIN_VALE, DOL_GULDUR, EASTERN_MIRKWOOD) }), NEAR_HARAD( "nh", { listOf(EAST_HARONDOR, WEST_HARONDOR, UMBAR, FAR_HARAD, KHAND) }, NationName.SOUTHRONS_AND_EASTERLINGS, LocationType.VILLAGE ), NOMAN_LANDS("nl", { listOf(SOUTHERN_RHOVANION, EASTERN_BROWN_LANDS, EASTERN_EMYN_MUIL, DAGORLAD, ASH_MOUNTAINS, SOUTHERN_DORWINION) }), NORTHERN_DORWINION("ndn", { listOf(VALE_OF_THE_CELDUIN, SOUTHERN_RHOVANION, SOUTHERN_DORWINION, NORTH_RHUN) }), NORTHERN_MIRKWOOD("nm", { listOf(CARROCK, WESTERN_MIRKWOOD, WOODLAND_REALM, WITHERED_HEATH) }), NORTHERN_RHOVANION("nrv", { listOf(DALE, OLD_FOREST_ROAD, EASTERN_MIRKWOOD, SOUTHERN_MIRKWOOD, SOUTHERN_RHOVANION, VALE_OF_THE_CELDUIN, VALE_OF_THE_CARNEN) }), NORTH_ANDUIN_VALE("nav", { listOf(RHOSGOBEL, GLADDEN_FIELDS, DIMRILL_DALE, SOUTH_ANDUIN_VALE, DOL_GULDUR, NARROWS_OF_THE_FOREST) }), NORTH_DOWNS( "nds", { listOf(ARNOR, EVENDIM, BUCKLAND, BREE, WEATHER_HILLS, ETTENMOORS) }, NationName.NORTHMEN ), NORTH_DUNLAND( "ndd", { listOf(MORIA, HOLLIN, SOUTH_DOWNS, CARDOLAN, THARBAD, SOUTH_DUNLAND) }, NationName.ISENGARD, LocationType.VILLAGE ), NORTH_ERED_LUIN( "nel", { listOf(FORLINDON, ERED_LUIN, EVENDIM) }, NationName.DWARVES ), NORTH_ITHILIEN("ni", { listOf(EASTERN_EMYN_MUIL, DEAD_MARSHES, OSGILIATH, SOUTH_ITHILIEN, MINAS_MORGUL, DAGORLAD) }), NORTH_RHUN( "nrh", { listOf( EAST_RHUN, VALE_OF_THE_CARNEN, VALE_OF_THE_CELDUIN, NORTHERN_DORWINION ) }, NationName.SOUTHRONS_AND_EASTERLINGS, LocationType.VILLAGE ), NURN( "nu", { listOf(GORGOROTH) }, NationName.SAURON, LocationType.VILLAGE ), OLD_FORD("ofd", { listOf(EAGLES_EYRIE, GOBLINS_GATE, GLADDEN_FIELDS, RHOSGOBEL, CARROCK) }), OLD_FOREST("oft", { listOf(BUCKLAND, THE_SHIRE, SOUTH_ERED_LUIN, CARDOLAN) }), OLD_FOREST_ROAD( "ofr", { listOf( WOODLAND_REALM, WESTERN_MIRKWOOD, CARROCK, RHOSGOBEL, NARROWS_OF_THE_FOREST, EASTERN_MIRKWOOD, NORTHERN_RHOVANION, DALE ) }, NationName.NORTHMEN ), ORTHANC( "or", { listOf(GAP_OF_ROHAN, FORDS_OF_ISEN) }, NationName.ISENGARD, LocationType.STRONGHOLD ), OSGILIATH( "os", { listOf( DEAD_MARSHES, DRUADAN_FOREST, MINAS_TIRITH, LOSSARNACH, PELARGIR, WEST_HARONDOR, SOUTH_ITHILIEN, NORTH_ITHILIEN ) }, null, LocationType.FORTIFICATION ), PARTH_CELEBRANT("pc", { listOf(LORIEN, FANGORN, EASTEMNET, WESTERN_BROWN_LANDS, SOUTH_ANDUIN_VALE, DIMRILL_DALE) }), PELARGIR( "pe", { listOf(LAMEDON, WEST_HARONDOR, LOSSARNACH, OSGILIATH) }, NationName.GONDOR, LocationType.CITY ), RHOSGOBEL( "rh", { listOf(CARROCK, OLD_FORD, GLADDEN_FIELDS, NORTH_ANDUIN_VALE, NARROWS_OF_THE_FOREST, OLD_FOREST_ROAD) }, NationName.NORTHMEN ), RIVENDELL( "ri", { listOf(TROLLSHAWS, FORDS_OF_BRUINEN) }, NationName.ELVES, LocationType.STRONGHOLD ), SOUTHERN_DORWINION("sd", { listOf(NORTHERN_DORWINION, SOUTHERN_RHOVANION, NOMAN_LANDS, ASH_MOUNTAINS, SOUTH_RHUN) }), SOUTHERN_MIRKWOOD( "sm", { listOf(EASTERN_MIRKWOOD, DOL_GULDUR, EASTERN_BROWN_LANDS, SOUTHERN_RHOVANION, NORTHERN_RHOVANION) }, NationName.SAURON ), SOUTHERN_RHOVANION("srv", { listOf(NORTHERN_RHOVANION, SOUTHERN_MIRKWOOD, EASTERN_BROWN_LANDS, NOMAN_LANDS, SOUTHERN_DORWINION, NORTHERN_DORWINION, VALE_OF_THE_CELDUIN) }), SOUTH_ANDUIN_VALE("sav", { listOf(NORTH_ANDUIN_VALE, DIMRILL_DALE, PARTH_CELEBRANT, WESTERN_BROWN_LANDS, DOL_GULDUR) }), SOUTH_DOWNS("sdo", { listOf(WEATHER_HILLS, BREE, BUCKLAND, CARDOLAN, NORTH_DUNLAND, HOLLIN, TROLLSHAWS) }), SOUTH_DUNLAND( "sdu", { listOf(NORTH_DUNLAND, THARBAD, ENEDWAITH, GAP_OF_ROHAN) }, NationName.ISENGARD, LocationType.VILLAGE ), SOUTH_ERED_LUIN("sel", { listOf(THE_SHIRE, TOWER_HILLS, HARLINDON, MINHIRIATH, CARDOLAN, OLD_FOREST) }), SOUTH_ITHILIEN("si", { listOf(NORTH_ITHILIEN, OSGILIATH, WEST_HARONDOR, EAST_HARONDOR, MINAS_MORGUL) }), SOUTH_RHUN( "srh", { listOf(EAST_RHUN, SOUTHERN_DORWINION, ASH_MOUNTAINS) }, NationName.SOUTHRONS_AND_EASTERLINGS, LocationType.VILLAGE ), THARBAD("thb", { listOf(CARDOLAN, MINHIRIATH, ENEDWAITH, SOUTH_DUNLAND, NORTH_DUNLAND) }), THE_SHIRE( "sh", { listOf(TOWER_HILLS, SOUTH_ERED_LUIN, OLD_FOREST, BUCKLAND, EVENDIM) }, NationName.NORTHMEN, LocationType.CITY ), TOWER_HILLS("th", { listOf(GREY_HAVENS, SOUTH_ERED_LUIN, THE_SHIRE, EVENDIM, ERED_LUIN) }), TROLLSHAWS("tr", { listOf(ETTENMOORS, WEATHER_HILLS, SOUTH_DOWNS, HOLLIN, FORDS_OF_BRUINEN, RIVENDELL) }), UMBAR( "um", { listOf(WEST_HARONDOR, NEAR_HARAD) }, NationName.SOUTHRONS_AND_EASTERLINGS, LocationType.STRONGHOLD ), VALE_OF_THE_CARNEN("vca", { listOf(IRON_HILLS, DALE, NORTHERN_RHOVANION, VALE_OF_THE_CELDUIN, NORTH_RHUN, EAST_RHUN) }), VALE_OF_THE_CELDUIN("vce", { listOf(VALE_OF_THE_CARNEN, NORTHERN_RHOVANION, SOUTHERN_RHOVANION, NORTHERN_DORWINION, NORTH_RHUN) }), WEATHER_HILLS("whi", { listOf(ETTENMOORS, NORTH_DOWNS, BREE, SOUTH_DOWNS, TROLLSHAWS) }), WESTEMNET( "we", { listOf(FANGORN, FORDS_OF_ISEN, HELMS_DEEP, EDORAS, FOLDE, EASTEMNET) }, NationName.ROHAN, LocationType.VILLAGE ), WESTERN_BROWN_LANDS("wbl", { listOf(DOL_GULDUR, SOUTH_ANDUIN_VALE, PARTH_CELEBRANT, EASTEMNET, WESTERN_EMYN_MUIL, EASTERN_BROWN_LANDS) }), WESTERN_EMYN_MUIL("wem", { listOf(WESTERN_BROWN_LANDS, EASTEMNET, DRUADAN_FOREST, DEAD_MARSHES, EASTERN_EMYN_MUIL, EASTERN_BROWN_LANDS) }), WESTERN_MIRKWOOD("wm", { listOf(NORTHERN_MIRKWOOD, CARROCK, OLD_FOREST_ROAD, WOODLAND_REALM) }), WEST_HARONDOR("wha", { listOf(PELARGIR, UMBAR, NEAR_HARAD, EAST_HARONDOR, SOUTH_ITHILIEN, OSGILIATH) }), WITHERED_HEATH("wh", { listOf(NORTHERN_MIRKWOOD, WOODLAND_REALM, DALE, EREBOR) }), WOODLAND_REALM( "wr", { listOf(NORTHERN_MIRKWOOD, WESTERN_MIRKWOOD, OLD_FOREST_ROAD, DALE, WITHERED_HEATH) }, NationName.ELVES, LocationType.STRONGHOLD ); val fullName = name.lowercase().replace("_", " ").replaceFirstChar { it.uppercaseChar() } override fun toString() = fullName companion object { fun search(prefix: String) = entries.flatMap { listOf(it.fullName, it.shortcut) } .filter { it.startsWith(prefix, ignoreCase = true) } .map { it.lowercase() } fun get(name: String) = entries.filter { it.fullName.equals(name, true) || it.shortcut.equals(name, true) } .let { if (it.isEmpty()) throw IllegalArgumentException("Invalid location $name") else if (it.size > 1) throw IllegalArgumentException("Multiple matching locations for $name: ${it.joinToString(", ")}") else it[0] } } }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/location/LocationCompletionProvider.kt
3628797149
package ch.chrigu.wotr.location import org.springframework.shell.CompletionContext import org.springframework.shell.CompletionProposal import org.springframework.shell.completion.CompletionProvider import org.springframework.stereotype.Component @Component class LocationCompletionProvider : CompletionProvider { override fun apply(t: CompletionContext) = LocationName.search(t.currentWord()) .map { CompletionProposal(it) } }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/location/LocationFinder.kt
1270596997
package ch.chrigu.wotr.location import java.util.* object LocationFinder { private val cache = Collections.synchronizedMap(HashMap<LocationName, List<GraphNode>>()) fun getDistance(from: LocationName, to: LocationName) = getShortestPath(from, to).first().getLength() fun getShortestPath(from: LocationName, to: LocationName): List<LocationPath> { val graph = cache[from] ?: initGraph(from) return visit(graph, from, graph.first { it.name == to }) } private fun visit(graph: List<GraphNode>, from: LocationName, to: GraphNode): List<LocationPath> = if (from == to.name) listOf(LocationPath(emptyList())) else to.previous.flatMap { visit(graph, from, it) }.map { it + LocationPath(listOf(to.name)) } private fun initGraph(from: LocationName): List<GraphNode> { val graph = LocationName.entries.map { if (it == from) GraphNode(it, distance = 0) else GraphNode(it) } val visit = LocationName.entries.toMutableSet() while (visit.isNotEmpty()) { val minDistance = graph.filter { visit.contains(it.name) && it.distance != null }.minBy { it.distance!! } visit.remove(minDistance.name) minDistance.name.adjacent() .map { neighbor -> graph.first { it.name == neighbor } } .forEach { neighbor -> val newDistance = minDistance.distance!! + 1 if (neighbor.distance == null || newDistance < neighbor.distance!!) { neighbor.distance = newDistance neighbor.previous = mutableListOf(minDistance) } else if (neighbor.distance == newDistance) { neighbor.previous.add(minDistance) } } } cache[from] = graph return graph } data class GraphNode(val name: LocationName, var previous: MutableList<GraphNode> = mutableListOf(), var distance: Int? = null) } data class LocationPath(val locations: List<LocationName>) { fun getLength() = locations.size operator fun plus(other: LocationPath) = LocationPath(locations + other.locations) }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/location/LocationType.kt
1958857619
package ch.chrigu.wotr.location enum class LocationType { NONE, VILLAGE, CITY, STRONGHOLD, FORTIFICATION; }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/figure/Figures.kt
737212900
package ch.chrigu.wotr.figure import ch.chrigu.wotr.gamestate.GameState import ch.chrigu.wotr.location.LocationName import ch.chrigu.wotr.nation.NationName import ch.chrigu.wotr.player.Player import kotlinx.serialization.Serializable import kotlin.math.min @Serializable data class Figures(val all: List<Figure>, val type: FiguresType = FiguresType.LOCATION) { init { require(all.distinct().size == all.size) { "Figures $all are not unique" } if (type != FiguresType.REINFORCEMENTS) { require(getArmy().all { it.nation.player == armyPlayer }) { "All army members must be of the same player: ${getArmy()}" } require((all - getArmy().toSet()).all { !it.type.isUnit && (it.nation.player != armyPlayer || !it.type.canBePartOfArmy) && it.isCharacterOrNazgul() }) { "All figures not belonging to an army must be the other's player unique character: ${all - getArmy().toSet()}" } require(numUnits() <= 10) { "There must not be more than 10 units, but was ${numUnits()}" } if (numUnits() == 0) { require(all.none { it.isFreePeopleLeader }) { "Free people leaders must not exist without army units: $all" } } } } val armyPlayer: Player? get() = getArmy().firstOrNull()?.nation?.player fun subSet(numRegular: Int, numElite: Int, numLeader: Int, nation: NationName?): Figures { return copy(all = take(numRegular, FigureType.REGULAR, nation) + take(numElite, FigureType.ELITE, nation) + take(numLeader, FigureType.LEADER_OR_NAZGUL, nation)) } fun subSet(characters: List<FigureType>) = copy(all = characters.map { take(it) }) fun isEmpty() = all.isEmpty() operator fun plus(other: Figures) = copy(all = all + other.all) operator fun minus(other: Figures): Figures { require(all.containsAll(other.all)) return copy(all = all - other.all.toSet()) } /** * Excludes characters that do not belong to [armyPlayer]. * @return Empty if there are no units that could form an army. */ fun getArmy(): List<Figure> { check(type == FiguresType.LOCATION) val units = getUnits() return if (units.isEmpty()) emptyList() else units + all.filter { !it.type.isUnit && it.nation.player == units.first().nation.player && it.type.canBePartOfArmy } } /** * @see getArmy */ fun getArmyPerNation() = getArmy().groupBy { it.nation } fun intersect(other: Figures) = copy(all = all.intersect(other.all.toSet()).toList()) fun union(other: Figures) = copy(all = all.union(other.all).toList()) fun numElites() = numElites(all) fun numRegulars() = numRegulars(all) fun numLeadersOrNazgul() = numLeadersOrNazgul(all) fun characters() = all.filter { it.type.isUniqueCharacter } fun containsAll(figures: Figures) = all.containsAll(figures.all) fun combatRolls() = min(5, numUnits()) fun maxReRolls() = min(leadership(), combatRolls()) override fun toString() = (all.groupBy { it.nation }.map { (nation, figures) -> printArmy(figures) + " ($nation)" } + all.mapNotNull { it.type.shortcut }) .joinToString(", ") private fun getUnits() = all.filter { it.type.isUnit } private fun leadership() = all.sumOf { it.type.leadership } private fun printArmy(figures: List<Figure>) = numRegulars(figures).toString() + numElites(figures) + numLeadersOrNazgul(figures) private fun numLeadersOrNazgul(figures: List<Figure>) = figures.count { it.type == FigureType.LEADER_OR_NAZGUL } private fun numElites(figures: List<Figure>) = figures.count { it.type == FigureType.ELITE } private fun numRegulars(figures: List<Figure>) = figures.count { it.type == FigureType.REGULAR } fun numUnits() = all.count { it.type.isUnit } private fun take(type: FigureType) = all.first { it.type == type } private fun take(num: Int, type: FigureType, nation: NationName?): List<Figure> { val allOfType = all.filter { it.type == type } val list = allOfType.filter { nation == null || nation == it.nation }.take(num) check(list.size == num) if (num > 0 && nation == null) { check(allOfType.all { it.nation == allOfType[0].nation }) { "No clear nation in $allOfType" } } return list } companion object { fun parse(who: Array<String>, locationName: LocationName, gameState: GameState) = parse(who, gameState.location[locationName]!!.nonBesiegedFigures) fun parse(who: Array<String>, figures: Figures, defaultNationName: NationName? = null): Figures { return if (who.isEmpty()) figures else FigureParser(who.toList()).select(figures, defaultNationName) } } }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/figure/AbstractFiguresCompletionProvider.kt
2343024539
package ch.chrigu.wotr.figure import ch.chrigu.wotr.gamestate.GameStateHolder import org.springframework.shell.CompletionContext import org.springframework.shell.CompletionProposal import org.springframework.shell.completion.CompletionProvider abstract class AbstractFiguresCompletionProvider(protected val gameStateHolder: GameStateHolder) : CompletionProvider { override fun apply(context: CompletionContext): List<CompletionProposal> { return FigureParser(getWhoValue(context)).getCompletionProposals(getAllFigures(context)) .map { CompletionProposal(it) } } abstract fun getAllFigures(context: CompletionContext): Figures abstract fun getWhoValue(context: CompletionContext): List<String> }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/figure/ReinforcementsCompletionProvider.kt
3433897811
package ch.chrigu.wotr.figure import ch.chrigu.wotr.gamestate.GameStateHolder import org.springframework.shell.CompletionContext import org.springframework.stereotype.Component @Component class ReinforcementsCompletionProvider(gameStateHolder: GameStateHolder) : AbstractFiguresCompletionProvider(gameStateHolder) { override fun getAllFigures(context: CompletionContext) = gameStateHolder.current.reinforcements override fun getWhoValue(context: CompletionContext): List<String> = if (context.words.first().startsWith("-")) context.words.drop(1) else context.words }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/figure/FiguresCompletionProvider.kt
916180956
package ch.chrigu.wotr.figure import ch.chrigu.wotr.gamestate.GameStateHolder import ch.chrigu.wotr.location.LocationName import org.springframework.shell.CompletionContext import org.springframework.stereotype.Component @Component class FiguresCompletionProvider(gameStateHolder: GameStateHolder) : AbstractFiguresCompletionProvider(gameStateHolder) { override fun getAllFigures(context: CompletionContext): Figures { val locationName = LocationName.get(getFromValue(context)) val location = gameStateHolder.current.location[locationName]!! return location.nonBesiegedFigures } override fun getWhoValue(context: CompletionContext) = context.words.dropWhile { it != "-w" && it != "--who" }.drop(1) private fun getFromValue(context: CompletionContext) = if (context.words.first().startsWith("-")) context.words[1] else context.words.first() }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/figure/FigureParser.kt
2415038852
package ch.chrigu.wotr.figure import ch.chrigu.wotr.nation.NationName class FigureParser(private val who: List<String>) { fun select(figures: Figures, defaultNationName: NationName? = null) = who.map { part -> check(part.isNotEmpty()) if (part[0].isDigit()) { val digits = part.takeWhile { it.isDigit() } require(digits.length in 1..3) val nation = if (part.contains("(") && part.contains(")")) NationName.find(part.substringAfter(")").substringBefore(")")) else null figures.subSet(digits[0].digitToInt(), digits.getOrNull(1)?.digitToInt() ?: 0, digits.getOrNull(2)?.digitToInt() ?: 0, nation ?: defaultNationName) } else { require(part.length == 2) val resolvedCharacters = part.chunked(2).map { FigureType.fromShortcut(it) } figures.subSet(resolvedCharacters) } } .fold(Figures(emptyList())) { a, b -> require(a.intersect(b).isEmpty()) a + b } fun getCompletionProposals(figures: Figures): List<String> { val prefix = who.take(who.size - 1) val before = FigureParser(prefix).select(figures) val remaining = figures - before val current = who.last() val armyOptions = (0..remaining.numRegulars()) .flatMap { regular -> (0..remaining.numElites()).map { regular.toString() + it } } .flatMap { units -> (0..remaining.numLeadersOrNazgul()).map { units + it } } val options = armyOptions + remaining.characters().map { it.type.shortcut!! } return options.filter { it.startsWith(current, true) } } }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/figure/FiguresType.kt
1189160878
package ch.chrigu.wotr.figure enum class FiguresType { REINFORCEMENTS, LOCATION }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/figure/FigureType.kt
4004012425
package ch.chrigu.wotr.figure enum class FigureType( val shortcut: String? = null, val isUnit: Boolean = false, val canBePartOfArmy: Boolean = true, val minion: Boolean = false, val leadership: Int = 0, val level: FigureLevel? = null, val enablesDice: Int = 0 ) { WITCH_KING("wk", minion = true, leadership = 2, level = FlyingLevel, enablesDice = 1), SARUMAN("sa", minion = true, leadership = 1, level = NumberedLevel(0), enablesDice = 1), MOUTH_OF_SAURON("ms", minion = true, leadership = 2, level = NumberedLevel(3), enablesDice = 1), GANDALF_THE_WHITE("gw", leadership = 1, level = NumberedLevel(3), enablesDice = 1), GANDALF_THE_GREY("gg", leadership = 1, level = NumberedLevel(3)), STRIDER("st", leadership = 1, level = NumberedLevel(3)), ARAGORN("ar", leadership = 2, level = NumberedLevel(3), enablesDice = 1), BOROMIR("bo", leadership = 1, level = NumberedLevel(2)), GIMLI("gi", leadership = 1, level = NumberedLevel(2)), LEGOLAS("le", leadership = 1, level = NumberedLevel(2)), MERIADOC("me", leadership = 1, level = NumberedLevel(1)), PEREGRIN("pe", leadership = 1, level = NumberedLevel(1)), REGULAR(isUnit = true), ELITE(isUnit = true), LEADER_OR_NAZGUL(leadership = 1), FELLOWSHIP("fs", canBePartOfArmy = false); val isUniqueCharacter = shortcut != null override fun toString() = name.replace("_", " ").lowercase().replaceFirstChar { it.uppercaseChar() } companion object { fun fromShortcut(s: String) = entries.first { it.shortcut.equals(s, true) } } }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/figure/Figure.kt
1883294470
package ch.chrigu.wotr.figure import ch.chrigu.wotr.nation.NationName import ch.chrigu.wotr.player.Player import kotlinx.serialization.Serializable @Serializable class Figure(val type: FigureType, val nation: NationName) { init { if (type == FigureType.LEADER_OR_NAZGUL) { require(nation.player == Player.FREE_PEOPLE || nation == NationName.SAURON) } } val isFreePeopleLeader: Boolean get() = type == FigureType.LEADER_OR_NAZGUL && nation.player == Player.FREE_PEOPLE val isNazgul: Boolean get() = type == FigureType.LEADER_OR_NAZGUL && nation.player == Player.SHADOW fun isNazgulOrWitchKing() = isNazgul || type == FigureType.WITCH_KING fun isCharacterOrNazgul() = isNazgul || type.isUniqueCharacter override fun toString() = "${getTypeString()} ($nation)" private fun getTypeString() = if (type == FigureType.LEADER_OR_NAZGUL) { if (nation.player == Player.FREE_PEOPLE) "Leader" else "Nazgul" } else type.toString() }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/figure/FigureLevel.kt
337913769
package ch.chrigu.wotr.figure sealed interface FigureLevel class NumberedLevel(val number: Int) : FigureLevel data object FlyingLevel : FigureLevel
wotr-cli/src/main/kotlin/ch/chrigu/wotr/dice/Dice.kt
1366434532
package ch.chrigu.wotr.dice import ch.chrigu.wotr.gamestate.GameState import ch.chrigu.wotr.player.Player import kotlinx.serialization.Serializable import kotlin.random.Random @Serializable data class Dice(val shadow: DiceAndRings = DiceAndRings(emptyList(), 0, Player.SHADOW), val freePeople: DiceAndRings = DiceAndRings(emptyList(), 3, Player.FREE_PEOPLE)) { fun useDie(dieUsage: DieUsage) = copy( shadow = if (dieUsage.player == Player.SHADOW) shadow.use(dieUsage) else shadow, freePeople = if (dieUsage.player == Player.FREE_PEOPLE) freePeople.use(dieUsage) else freePeople ) fun assignEyesAndRollDice(state: GameState, numEyes: Int) = copy( shadow = shadow.assignAndRoll(7 + state.numMinions(), numEyes), freePeople = freePeople.roll(4 + listOf(state.hasAragorn(), state.hasGandalfTheWhite()).sumOf { toInt(it) }) ) fun fakeShadowRoll(vararg die: DieType) = copy( shadow = shadow.fakeRoll(die.toList()) ) private fun toInt(it: Boolean) = if (it) 1 else 0 init { require(!shadow.rolled.contains(DieType.WILL_OF_THE_WEST)) require(!freePeople.rolled.contains(DieType.EYE)) } } @Serializable data class DiceAndRings(val rolled: List<DieType>, val rings: Int, val player: Player, val ringsUsed: Boolean = false, val huntBox: List<DieType> = emptyList()) { init { require(rings in 0..3) } fun isEmpty() = rolled.isEmpty() fun use(dieUsage: DieUsage): DiceAndRings { check(!dieUsage.useRing || !noRings()) return copy(rolled = removeOneDie(dieUsage.use), rings = if (dieUsage.useRing) rings - 1 else rings, ringsUsed = if (dieUsage.useRing) true else ringsUsed) } fun roll(num: Int) = copy(rolled = (0 until num).map { rollDie() }, ringsUsed = false, huntBox = emptyList()) fun fakeRoll(dice: List<DieType>) = copy(rolled = dice, ringsUsed = false, huntBox = emptyList()) fun assignAndRoll(num: Int, numEyes: Int): DiceAndRings { val roll = (0 until num - numEyes).map { rollDie() } val rolledEyes = roll.filter { it == DieType.EYE } return copy(rolled = roll - rolledEyes.toSet(), ringsUsed = false, huntBox = (0 until numEyes).map { DieType.EYE } + rolledEyes) } fun getDice(types: Set<DieType>): List<DieUsage> { val matchingDice = rolled.filter { types.contains(it) || it == DieType.WILL_OF_THE_WEST } val withRing = if (noRings()) emptyList() else (rolled - matchingDice.toSet()).map { DieUsage(it, true, player) } return matchingDice.map { DieUsage(it, false, player) } + withRing } override fun toString() = (rolled + (0 until rings).map { "X" }).joinToString(" ") + huntBoxToString() private fun removeOneDie(type: DieType): List<DieType> { val useIndex = rolled.indexOf(type) return rolled.subList(0, useIndex) + rolled.subList(useIndex + 1, rolled.size) } private fun huntBoxToString() = if (huntBox.isEmpty()) "" else " / " + huntBox.joinToString(" ") private fun rollDie() = player.dieFace[Random.nextInt(6)] private fun noRings() = rings == 0 || ringsUsed } enum class DieType(private val shortName: String? = null) { ARMY, MUSTER, ARMY_MUSTER("AM"), EYE, WILL_OF_THE_WEST, EVENT("P"), CHARACTER; override fun toString() = shortName ?: name.take(1) } data class DieUsage(val use: DieType, val useRing: Boolean, val player: Player) { override fun toString() = if (useRing) "ring" else use.toString() }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/nation/Nation.kt
277142012
package ch.chrigu.wotr.nation import kotlinx.serialization.Serializable @Serializable data class Nation(val box: Int, val active: Boolean, val name: NationName) { init { require(box >= 0) if (!active) require(box > 0) } fun isOnWar() = box == 0 fun moveDown() = copy(box = box - 1) }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/nation/NationName.kt
3016320726
package ch.chrigu.wotr.nation import ch.chrigu.wotr.player.Player import java.util.* enum class NationName(val player: Player, val shortcut: String) { GONDOR(Player.FREE_PEOPLE, "go"), ROHAN(Player.FREE_PEOPLE, "ro"), ELVES(Player.FREE_PEOPLE, "el"), DWARVES(Player.FREE_PEOPLE, "dw"), NORTHMEN(Player.FREE_PEOPLE, "no"), FREE_PEOPLE(Player.FREE_PEOPLE, "fp"), SAURON(Player.SHADOW, "sa"), ISENGARD(Player.SHADOW, "is"), SOUTHRONS_AND_EASTERLINGS(Player.SHADOW, "se"); val fullName = name.lowercase().split("_") .joinToString(" ") { part -> part.replaceFirstChar { it.titlecase(Locale.getDefault()) } } override fun toString() = fullName companion object { fun find(name: String) = entries.first { name.equals(it.fullName, true) || name.equals(it.shortcut, true) } } }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/action/AssignEyesAndThrowDiceAction.kt
2966072550
package ch.chrigu.wotr.action import ch.chrigu.wotr.gamestate.GameState class AssignEyesAndThrowDiceAction(private val numEyes: Int) : GameAction { override fun apply(oldState: GameState): GameState { return oldState.copy(dice = oldState.dice.assignEyesAndRollDice(oldState, numEyes), cards = oldState.cards.phase1()) } override fun toString() = "Assign $numEyes and roll dice" }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/action/MoveAction.kt
2424119226
package ch.chrigu.wotr.action import ch.chrigu.wotr.dice.DieType import ch.chrigu.wotr.figure.Figures import ch.chrigu.wotr.gamestate.GameState import ch.chrigu.wotr.location.LocationName import kotlin.math.max data class MoveAction(private val fromLocation: LocationName, private val toLocation: LocationName, val figures: Figures) : GameAction { init { require(!figures.isEmpty()) { "Move action requires at least one figure" } require(fromLocation != toLocation) { "Move action must have two different locations" } } override fun apply(oldState: GameState) = oldState.removeFrom(fromLocation, figures).addTo(toLocation, figures) override fun tryToCombine(other: GameAction): GameAction? { if (other is MoveAction && fromLocation == other.fromLocation && toLocation == other.toLocation) { val union = figures.union(other.figures) if (union.all.size == max(figures.all.size, other.figures.all.size)) return null return MoveAction(fromLocation, toLocation, union) } return null } override fun toString() = "Move $figures from $fromLocation to $toLocation" fun isCharacterMovement() = figures.all.all { it.isCharacterOrNazgul() } fun isArmyMovement() = figures.all.any { it.type.isUnit } override fun requiredDice() = setOf(DieType.CHARACTER, DieType.ARMY, DieType.ARMY_MUSTER) }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/action/GameAction.kt
1219560764
package ch.chrigu.wotr.action import ch.chrigu.wotr.dice.DieType import ch.chrigu.wotr.gamestate.GameState interface GameAction { fun apply(oldState: GameState): GameState /** * Like [apply], but used for evaluating a bot action. */ fun simulate(oldState: GameState): GameState = apply(oldState) fun tryToCombine(other: GameAction): GameAction? = null fun requiredDice(): Set<DieType> = throw IllegalStateException("The action ${javaClass.simpleName} does not support to be played within a die action") }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/action/PoliticsMarkerAction.kt
887056047
package ch.chrigu.wotr.action import ch.chrigu.wotr.dice.DieType import ch.chrigu.wotr.gamestate.GameState import ch.chrigu.wotr.nation.NationName data class PoliticsMarkerAction(private val name: NationName) : GameAction { override fun apply(oldState: GameState) = oldState.updateNation(name) { moveDown() } override fun requiredDice() = setOf(DieType.MUSTER, DieType.ARMY_MUSTER) override fun toString() = "Move politics marker of $name" }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/action/MusterAction.kt
1301979036
package ch.chrigu.wotr.action import ch.chrigu.wotr.figure.Figures import ch.chrigu.wotr.figure.FiguresType import ch.chrigu.wotr.gamestate.GameState import ch.chrigu.wotr.location.LocationName class MusterAction(private val figures: Figures, private val locationName: LocationName) : GameAction { override fun apply(oldState: GameState) = oldState.removeFromReinforcements(figures).addTo(locationName, figures.copy(type = FiguresType.LOCATION)) override fun toString() = "Muster $figures at $locationName" }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/action/PlayEventAction.kt
3452273411
package ch.chrigu.wotr.action import ch.chrigu.wotr.card.EventType import ch.chrigu.wotr.dice.DieType import ch.chrigu.wotr.gamestate.GameState import org.jline.terminal.Terminal data class PlayEventAction(private val type: EventType, private val terminal: Terminal) : GameAction { override fun apply(oldState: GameState): GameState { val newState = oldState.copy(cards = oldState.cards.play(type)) terminal.writer().println("Search your $type deck for the first card whose requirement can be met and that will alter the game state. Play it.") return newState } override fun simulate(oldState: GameState): GameState { return oldState.copy(cards = oldState.cards.play(type)) } override fun requiredDice() = setOf(DieType.EVENT) + if (type == EventType.CHARACTER) setOf(DieType.CHARACTER) else setOf(DieType.ARMY, DieType.ARMY_MUSTER, DieType.MUSTER) override fun toString() = "Play $type event" }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/action/MusterFiguresAction.kt
2680230958
package ch.chrigu.wotr.action import ch.chrigu.wotr.dice.DieType import ch.chrigu.wotr.figure.Figure import ch.chrigu.wotr.figure.Figures import ch.chrigu.wotr.gamestate.GameState import ch.chrigu.wotr.location.LocationName class MusterFiguresAction(private val musters: Map<Figures, LocationName>) : GameAction { private val actions = musters.map { (figures, location) -> MusterAction(figures, location) } constructor(figures: Figures, locationName: LocationName) : this(mapOf(figures to locationName)) constructor(vararg muster: Pair<Figure, LocationName>) : this(muster.associate { (f, l) -> Figures(listOf(f)) to l }) override fun apply(oldState: GameState): GameState = actions.fold(oldState) { state, action -> action.apply(state) } override fun requiredDice() = setOf(DieType.MUSTER, DieType.ARMY_MUSTER) operator fun plus(other: MusterFiguresAction?) = other?.let { MusterFiguresAction(musters + it.musters) } override fun toString() = actions.joinToString(", ") }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/action/AttackAction.kt
2431959116
package ch.chrigu.wotr.action import ch.chrigu.wotr.card.EventType import ch.chrigu.wotr.combat.CombatSimulator import ch.chrigu.wotr.combat.CombatType import ch.chrigu.wotr.dice.DieType import ch.chrigu.wotr.figure.FigureType import ch.chrigu.wotr.figure.Figures import ch.chrigu.wotr.gamestate.GameState import ch.chrigu.wotr.location.LocationName import org.jline.terminal.Terminal /** * @param defenderLocation If null, it is a sortie or a siege battle. */ data class AttackAction( private val terminal: Terminal, private val attacker: Figures, private val defender: Figures, private val attackerLocation: LocationName, private val defenderLocation: LocationName? = null ) : GameAction { override fun apply(oldState: GameState): GameState { terminal.writer().println(toString()) terminal.writer().println("Search an appropriate combat card from ${getNumCombatCards()} ${getDeckType()}") return oldState } override fun simulate(oldState: GameState): GameState { val casualties = CombatSimulator( attacker, defender, getCombatType(oldState), oldState.location[defenderLocation ?: attackerLocation]!!.type, attackerLocation, defenderLocation ?: attackerLocation ) .repeat(20) return casualties.fold(oldState) { a, b -> b.apply(a) } } override fun toString() = "$attacker ($attackerLocation) attacks $defender (${defenderLocation ?: attackerLocation})" override fun requiredDice() = setOf(DieType.ARMY, DieType.ARMY_MUSTER) + if (attacker.all.any { !it.type.isUnit }) setOf(DieType.CHARACTER) else emptySet() private fun getNumCombatCards() = if (figures().any { it.type == FigureType.WITCH_KING }) 3 else 2 private fun figures() = attacker.all + defender.all private fun getCombatType(state: GameState) = if (defenderLocation == null) { if (state.location[attackerLocation]!!.nonBesiegedFigures.containsAll(attacker)) CombatType.SIEGE else CombatType.SORTIE } else CombatType.FIELD_BATTLE private fun getDeckType() = if (figures().count { it.isNazgulOrWitchKing() } > 3) EventType.CHARACTER else EventType.STRATEGY }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/action/DieActionFactory.kt
348607082
package ch.chrigu.wotr.action import ch.chrigu.wotr.gamestate.GameState class DieActionFactory(private val state: GameState) { fun everyCombination(action: GameAction) = state.dice.shadow.getDice(action.requiredDice()) .map { DieAction(it, listOf(action)) } }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/action/DrawEventAction.kt
3135168014
package ch.chrigu.wotr.action import ch.chrigu.wotr.card.EventType import ch.chrigu.wotr.dice.DieType import ch.chrigu.wotr.gamestate.GameState data class DrawEventAction(private val type: EventType) : GameAction { override fun apply(oldState: GameState): GameState { return oldState.copy(cards = oldState.cards.draw(type)) } override fun requiredDice() = setOf(DieType.EVENT) override fun toString() = "Draw $type event" }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/action/ReplaceFiguresAction.kt
1241788879
package ch.chrigu.wotr.action import ch.chrigu.wotr.dice.DieType import ch.chrigu.wotr.figure.Figures import ch.chrigu.wotr.gamestate.GameState import ch.chrigu.wotr.location.LocationName class ReplaceFiguresAction(private val replace: Figures, private val by: Figures, private val location: LocationName) : GameAction { override fun apply(oldState: GameState) = oldState.removeFrom(location, replace) .addToReinforcements(replace) .removeFromReinforcements(by) .addTo(location, by) override fun requiredDice() = setOf(DieType.MUSTER, DieType.ARMY_MUSTER) override fun toString() = "Replace $replace by $by at $location" }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/action/KillAction.kt
4081202606
package ch.chrigu.wotr.action import ch.chrigu.wotr.figure.Figures import ch.chrigu.wotr.gamestate.GameState import ch.chrigu.wotr.location.LocationName import ch.chrigu.wotr.player.Player class KillAction(private val locationName: LocationName, private val figures: Figures) : GameAction { override fun apply(oldState: GameState) = oldState.removeFrom(locationName, figures) .addToReinforcements(Figures(figures.getArmy().filter { it.nation.player == Player.SHADOW && !it.type.isUniqueCharacter })) override fun toString() = "Kill $figures at $locationName" }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/action/BotAction.kt
3951088724
package ch.chrigu.wotr.action import ch.chrigu.wotr.bot.BotActionFactory import ch.chrigu.wotr.gamestate.GameState import org.jline.terminal.Terminal class BotAction(private val terminal: Terminal, private val botActionFactory: BotActionFactory) : GameAction { override fun apply(oldState: GameState): GameState { val nextAction = botActionFactory.getNext(oldState) terminal.writer().println(nextAction.toString()) return nextAction.apply(oldState) } override fun toString() = "Bot action" }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/action/DieAction.kt
506418036
package ch.chrigu.wotr.action import ch.chrigu.wotr.dice.DieType import ch.chrigu.wotr.dice.DieUsage import ch.chrigu.wotr.gamestate.GameState data class DieAction(private val use: DieUsage, private val actions: List<GameAction>) : GameAction { override fun apply(oldState: GameState): GameState { return oldState.useDie(use).let { initial -> actions.fold(initial) { state, action -> action.apply(state) } } } override fun simulate(oldState: GameState): GameState { return oldState.useDie(use).let { initial -> actions.fold(initial) { state, action -> action.simulate(state) } } } override fun tryToCombine(other: GameAction): GameAction? { if (other !is DieAction || use != other.use) return null val combined = if (actions.size == 1 && other.actions.size == 1) actions[0].tryToCombine(other.actions[0]) else null if (combined != null) return DieAction(use, listOf(combined)) val allActions = actions + other.actions if (!allActions.all { it is MoveAction }) return null if (allActions.sumOf { (it as MoveAction).figures.numUnits() } > 10) return null val figures1 = actions.map { (it as MoveAction).figures }.reduce { a, b -> a + b } val figures2 = other.actions.map { (it as MoveAction).figures }.reduce { a, b -> a + b } if (!figures1.intersect(figures2).isEmpty()) return null if (allActions.all { isCharacterMovement(it) }) { return DieAction(use, allActions) } else if (allActions.size == 2 && allActions.all { isArmyMovement(it) } && (use.use != DieType.CHARACTER || use.useRing)) { return DieAction(use, allActions) } return null } private fun isCharacterMovement(action: GameAction) = action is MoveAction && action.isCharacterMovement() private fun isArmyMovement(action: GameAction) = action is MoveAction && action.isArmyMovement() override fun toString() = "Use $use to $actions" }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/WotrCliApplication.kt
3630006125
package ch.chrigu.wotr import ch.chrigu.wotr.commands.BoardCommands import ch.chrigu.wotr.commands.BotCommands import ch.chrigu.wotr.commands.SaveLoadCommands import ch.chrigu.wotr.commands.UndoRedoCommands import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication import org.springframework.shell.command.annotation.EnableCommand @SpringBootApplication @EnableCommand(BoardCommands::class, UndoRedoCommands::class, BotCommands::class, SaveLoadCommands::class) class WotrCliApplication fun main(args: Array<String>) { runApplication<WotrCliApplication>(*args) }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/bot/ThrowDiceStrategy.kt
3102393102
package ch.chrigu.wotr.bot import ch.chrigu.wotr.action.AssignEyesAndThrowDiceAction import ch.chrigu.wotr.gamestate.GameState import org.springframework.core.annotation.Order import org.springframework.stereotype.Component import kotlin.math.max @Order(0) @Component class ThrowDiceStrategy : BotStrategy { override fun getActions(state: GameState) = if (state.dice.shadow.isEmpty()) listOf(AssignEyesAndThrowDiceAction(numEyes(state))) else emptyList() private fun numEyes(state: GameState) = if (state.fellowship.mordor == null) max(1, state.fellowship.numRerolls(state)) else if (state.fellowship.remainingCorruption() < 5) state.fellowship.remainingCorruption() else 2 }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/bot/AttackStrategy.kt
3848674210
package ch.chrigu.wotr.bot import ch.chrigu.wotr.action.AttackAction import ch.chrigu.wotr.gamestate.GameState import ch.chrigu.wotr.location.Location import ch.chrigu.wotr.player.Player import org.jline.terminal.Terminal import org.springframework.core.annotation.Order import org.springframework.stereotype.Component @Order(4) @Component class AttackStrategy(private val terminal: Terminal) : BotStrategy { override fun getActions(state: GameState) = state.location.values.flatMap { location -> val nonBesiegedFigures = location.nonBesiegedFigures if (location.besiegedFigures.armyPlayer == Player.SHADOW) { listOf(AttackAction(terminal, location.besiegedFigures, nonBesiegedFigures, location.name)) } else if (nonBesiegedFigures.armyPlayer == Player.SHADOW) { getSiegeAttack(location) + location.adjacentLocations.mapNotNull { adjacent -> getFieldBattle(location, state.location[adjacent]!!) } } else { emptyList() } } private fun getFieldBattle(location: Location, adjacent: Location): AttackAction? { val defender = adjacent.nonBesiegedFigures return if (defender.armyPlayer == Player.FREE_PEOPLE) AttackAction(terminal, location.nonBesiegedFigures, defender, location.name, adjacent.name) else null } private fun getSiegeAttack(location: Location) = if (location.besiegedFigures.armyPlayer == Player.FREE_PEOPLE) listOf(AttackAction(terminal, location.nonBesiegedFigures, location.besiegedFigures, location.name)) else emptyList() }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/bot/Combinations.kt
2460407788
package ch.chrigu.wotr.bot object Combinations { fun <T> allSizes(all: List<T>): List<List<T>> { if (all.isEmpty()) return listOf(emptyList()) else { val first = listOf(all.first()) val other = allSizes(all.drop(1)) return other.map { first + it } + other } } fun <T> ofSize(all: List<T>, size: Int): List<List<T>> { if (all.size < size) return emptyList() if (size == 1) return all.map { listOf(it) } return all.flatMapIndexed { index, pick -> ofSize(all.drop(index + 1), size - 1).map { listOf(pick) + it } } } }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/bot/MusterStrategy.kt
1896012176
package ch.chrigu.wotr.bot import ch.chrigu.wotr.action.* import ch.chrigu.wotr.card.EventType import ch.chrigu.wotr.figure.FigureType import ch.chrigu.wotr.figure.Figures import ch.chrigu.wotr.gamestate.GameState import ch.chrigu.wotr.location.Location import ch.chrigu.wotr.location.LocationName import ch.chrigu.wotr.location.LocationType import ch.chrigu.wotr.nation.NationName import ch.chrigu.wotr.player.Player import org.jline.terminal.Terminal import org.springframework.core.annotation.Order import org.springframework.stereotype.Component /** * Includes playing event card. */ @Order(2) @Component class MusterStrategy(private val terminal: Terminal) : BotStrategy { override fun getActions(state: GameState): List<GameAction> { val nations = state.nation.values.filter { it.name.player == Player.SHADOW } val onWar = nations.filter { it.isOnWar() }.map { it.name } val settlements = state.location.values.filter { it.nation in onWar && !it.captured } val combinations = Combinations.ofSize(settlements, 2) return (nations.map { it.name } - onWar.toSet()).map { PoliticsMarkerAction(it) } + combinations.flatMap { (a, b) -> val regularA = regular(a, state) val regularB = regular(b, state) val nazgulA = nazgul(a, state) val nazgulB = nazgul(b, state) listOfNotNull( regularA?.plus(regularB), nazgulA?.plus(nazgulB), regularA?.plus(nazgulB), nazgulA?.plus(regularB) ) } + settlements.mapNotNull { elite(it, state) } + sarumansVoice(state) + listOf(PlayEventAction(EventType.STRATEGY, terminal)) } private fun elite(location: Location, state: GameState) = unit(state, location, FigureType.ELITE) private fun regular(location: Location, state: GameState) = unit(state, location, FigureType.REGULAR) private fun nazgul(location: Location, state: GameState) = if (location.type == LocationType.STRONGHOLD && location.nation == NationName.SAURON) unit(state, location, FigureType.LEADER_OR_NAZGUL) else null private fun sarumansVoice(state: GameState): List<GameAction> { if (!state.hasSaruman()) return emptyList() val orthancRegulars = state.location[LocationName.ORTHANC]!!.nonBesiegedFigures.all.filter { it.nation == NationName.ISENGARD && it.type == FigureType.REGULAR }.take(2) val elites = state.reinforcements.all.filter { it.nation == NationName.ISENGARD && it.type == FigureType.ELITE }.take(2) val orthanc = if (orthancRegulars.size == 2 && elites.size == 2) ReplaceFiguresAction(Figures(orthancRegulars), Figures(elites), LocationName.ORTHANC) else null val threeRegulars = state.reinforcements.all.filter { it.nation == NationName.ISENGARD && it.type == FigureType.REGULAR }.take(3) .let { if (it.size == 3) MusterFiguresAction(it[0] to LocationName.ORTHANC, it[1] to LocationName.SOUTH_DUNLAND, it[2] to LocationName.NORTH_DUNLAND) else null } return listOfNotNull(orthanc, threeRegulars) } private fun unit(state: GameState, location: Location, type: FigureType): MusterFiguresAction? { val unit = state.reinforcements.all.firstOrNull { it.type == type && it.nation == location.nation } return unit?.let { MusterFiguresAction(Figures(listOf(unit)), location.name) } } }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/bot/BotEvaluationService.kt
3448876176
package ch.chrigu.wotr.bot import ch.chrigu.wotr.card.Cards import ch.chrigu.wotr.dice.Dice import ch.chrigu.wotr.dice.DiceAndRings import ch.chrigu.wotr.dice.DieType import ch.chrigu.wotr.fellowship.Fellowship import ch.chrigu.wotr.figure.Figure import ch.chrigu.wotr.figure.FigureType import ch.chrigu.wotr.figure.Figures import ch.chrigu.wotr.figure.NumberedLevel import ch.chrigu.wotr.gamestate.GameState import ch.chrigu.wotr.location.Location import ch.chrigu.wotr.location.LocationType import ch.chrigu.wotr.nation.Nation import ch.chrigu.wotr.player.Player import kotlin.math.max import kotlin.math.min object BotEvaluationService { fun count(state: GameState) = countDice(state.dice) + countVp(state) + countFellowship(state.fellowship, state) + state.location.values.sumOf { countLocation(it, state) } + countCards(state.cards) + countNations(state.nation.values) private fun countNations(nations: Collection<Nation>) = nations.sumOf { if (it.name.player == Player.SHADOW) countNation(it) else -countNation(it) } private fun countNation(nation: Nation) = if (nation.isOnWar()) 10 else if (nation.active) 8 - nation.box else 4 - nation.box private fun countVp(state: GameState) = if (state.vpShadow() >= 10) 100 else if (state.vpFreePeople() >= 4) 90 else 5 * state.vpShadow() - 10 * state.vpFreePeople() private fun countDice(dice: Dice) = count(dice.shadow, Player.SHADOW) - count(dice.freePeople, Player.FREE_PEOPLE) private fun count(diceAndRings: DiceAndRings, player: Player) = 10 * diceAndRings.rings + diceAndRings.rolled .groupBy { it }.entries.sumOf { (type, list) -> when (type) { DieType.WILL_OF_THE_WEST -> 3 DieType.ARMY_MUSTER -> max(3, list.size) DieType.ARMY -> if (player == Player.SHADOW) 2 else 1 DieType.CHARACTER -> if (player == Player.FREE_PEOPLE) 2 else 1 else -> 1 } } private fun countFellowship(fellowship: Fellowship, state: GameState) = if (fellowship.corruption >= Fellowship.MAX_CORRUPTION) 100 else if (fellowship.mordor != null && fellowship.mordor >= Fellowship.MORDOR_STEPS) -100 else fellowship.corruption * 2 - fellowship.progress - (fellowship.mordor ?: 0) * 2 + (if (fellowship.discovered) 5 else 0) + fellowship.numRerolls(state) * 5 - state.companions.sumOf { (it.type.level as? NumberedLevel)?.number ?: 0 } * 2 private fun countLocation(location: Location, state: GameState): Int { val figurePoints = location.allFigures().sumOf { countFigure(it) } val figures = location.nonBesiegedFigures val armyPlayer = figures.armyPlayer val playerModifier = if (armyPlayer == Player.SHADOW) 1 else -1 val siegeModifier = if (location.besiegedFigures.isEmpty()) 1 else 3 val nearestLocationsToOccupy = location.distanceTo(state) { it.currentlyOccupiedBy()?.opponent == armyPlayer } val nearestArmies = if (location.besiegedFigures.isEmpty()) location.distanceTo(state) { it.nonBesiegedFigures.armyPlayer?.opponent == armyPlayer } .map { (l, distance) -> Triple(l, l.nonBesiegedFigures, distance) } else listOf(Triple(location, location.besiegedFigures, 0)) val nearArmyThreat = nearestArmies.sumOf { (location, defender, distance) -> pointsAgainstArmy(figures, defender, distance, location) } val nearSettlementThreat = nearestLocationsToOccupy.entries.sumOf { (l, distance) -> pointsForOccupation(figures, l, distance) } return figurePoints + nearArmyThreat * playerModifier * siegeModifier + nearSettlementThreat * playerModifier } private fun pointsForOccupation(attacker: Figures, location: Location, distance: Int): Int { val defender = if (distance == 0) location.besiegedFigures else location.nonBesiegedFigures return if (defender.armyPlayer == null) max(50 - distance * 2, 0) * (location.victoryPoints * 10 + 1) else pointsAgainstArmy(attacker, defender, distance, location) * (location.victoryPoints * 2 + 1) } private fun pointsAgainstArmy(attacker: Figures, defender: Figures, distance: Int, location: Location): Int { val stronghold = distance == 0 || location.type == LocationType.STRONGHOLD val defenderBonus = if (stronghold) 2.5f else if (location.type == LocationType.CITY || location.type == LocationType.FORTIFICATION) 1.5f else 1.0f return max(0, armyValue(attacker) - Math.round(armyValue(defender) * defenderBonus)) } private fun armyValue(army: Figures) = army.combatRolls() + army.maxReRolls() + army.numElites() * 2 + army.numRegulars() private fun countFigure(figure: Figure): Int { val modifier = if (figure.nation.player == Player.SHADOW) 1 else -1 val type = figure.type val points = if (type.isUniqueCharacter) ((type.level as? NumberedLevel)?.number ?: 0) * 2 + type.enablesDice * 10 else if (type == FigureType.ELITE) 3 else 1 return modifier * points } private fun countCards(cards: Cards) = min(4, cards.numCards()) }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/bot/BotActionFactory.kt
287059214
package ch.chrigu.wotr.bot import ch.chrigu.wotr.action.AssignEyesAndThrowDiceAction import ch.chrigu.wotr.action.DieActionFactory import ch.chrigu.wotr.action.GameAction import ch.chrigu.wotr.gamestate.GameState import org.springframework.stereotype.Component import java.util.* import kotlin.math.min @Component class BotActionFactory(private val strategies: List<BotStrategy>) { fun getNext(state: GameState): GameAction { val dieActionFactory = DieActionFactory(state) val singleActions = strategies.asSequence().flatMap { it.getActions(state) } .flatMap { withDice(it, dieActionFactory) } .toSet() .mapNotNull { EvaluatedAction.create(it, state) } .toSortedSet() check(singleActions.isNotEmpty()) { "There is no possible bot action" } val combinedActions = combineFirst(min(10, singleActions.size), singleActions) return combinedActions.first().action } private fun combineFirst(num: Int, actions: SortedSet<EvaluatedAction>): SortedSet<EvaluatedAction> { val combinations = (0 until num).flatMap { index -> val action = actions.drop(index).first() actions.drop(index + 1).mapNotNull { a -> a.tryToCombine(action) } } actions.addAll(combinations) return if (num == 1) actions else combineFirst(num - 1, actions) } private fun withDice(action: GameAction, dieActionFactory: DieActionFactory) = if (action is AssignEyesAndThrowDiceAction) listOf(action) else dieActionFactory.everyCombination(action) companion object { private fun evaluate(action: GameAction, state: GameState): Int? { val newState: GameState try { newState = action.simulate(state) } catch (e: IllegalArgumentException) { return null } return BotEvaluationService.count(newState) } } data class EvaluatedAction(val action: GameAction, val score: Int, val state: GameState) : Comparable<EvaluatedAction> { override fun compareTo(other: EvaluatedAction): Int { return score.compareTo(other.score) } override fun toString() = "Score $score: $action" fun tryToCombine(other: EvaluatedAction): EvaluatedAction? { val combined = action.tryToCombine(other.action) return if (combined == null) null else create(combined, state) } companion object { fun create(action: GameAction, state: GameState) = evaluate(action, state)?.let { EvaluatedAction(action, it, state) } } } }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/bot/DrawEventStrategy.kt
2574604361
package ch.chrigu.wotr.bot import ch.chrigu.wotr.action.DrawEventAction import ch.chrigu.wotr.card.EventType import ch.chrigu.wotr.gamestate.GameState import org.springframework.core.annotation.Order import org.springframework.stereotype.Component @Component @Order(10) class DrawEventStrategy : BotStrategy { override fun getActions(state: GameState) = EventType.entries.map { DrawEventAction(it) } }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/bot/HarmFellowshipStrategy.kt
722775874
package ch.chrigu.wotr.bot import ch.chrigu.wotr.card.EventType import ch.chrigu.wotr.action.GameAction import ch.chrigu.wotr.action.MoveAction import ch.chrigu.wotr.action.PlayEventAction import ch.chrigu.wotr.figure.Figure import ch.chrigu.wotr.figure.FigureType import ch.chrigu.wotr.figure.Figures import ch.chrigu.wotr.gamestate.GameState import ch.chrigu.wotr.player.Player import org.jline.terminal.Terminal import org.springframework.core.annotation.Order import org.springframework.stereotype.Component @Order(1) @Component class HarmFellowshipStrategy(private val terminal: Terminal) : BotStrategy { override fun getActions(state: GameState) = getEventAction() + getNazgulAction(state) + getArmyAction(state) private fun getNazgulAction(state: GameState) = state.findAll { it.isNazgulOrWitchKing() } .filter { (location, _) -> location != state.fellowshipLocation } .map { (location, figure) -> MoveAction(location.name, state.fellowshipLocation.name, Figures(listOf(figure))) } private fun getArmyAction(state: GameState): List<GameAction> { val fellowshipLocation = state.fellowshipLocation val armies = fellowshipLocation.adjacentArmies(Player.SHADOW, state) return armies.map { val from = state.getLocationWith(it)!! MoveAction(from.name, fellowshipLocation.name, Figures(listOf(regularIfPossible(it)))) } } private fun getEventAction() = listOf(PlayEventAction(EventType.CHARACTER, terminal)) private fun regularIfPossible(figures: List<Figure>) = figures.firstOrNull { it.type == FigureType.REGULAR } ?: figures.first { it.type.isUnit } }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/bot/MoveArmyStrategy.kt
3043173096
package ch.chrigu.wotr.bot import ch.chrigu.wotr.action.GameAction import ch.chrigu.wotr.action.MoveAction import ch.chrigu.wotr.action.PlayEventAction import ch.chrigu.wotr.card.EventType import ch.chrigu.wotr.figure.Figure import ch.chrigu.wotr.figure.FigureType import ch.chrigu.wotr.figure.Figures import ch.chrigu.wotr.gamestate.GameState import ch.chrigu.wotr.location.Location import ch.chrigu.wotr.player.Player import org.jline.terminal.Terminal import org.springframework.core.annotation.Order import org.springframework.stereotype.Component @Order(3) @Component class MoveArmyStrategy(private val terminal: Terminal) : BotStrategy { override fun getActions(state: GameState): List<GameAction> { return (state.location.values .filter { it.nonBesiegedFigures.armyPlayer == Player.SHADOW } .flatMap { toMoveActions(it, state) }) + listOf(PlayEventAction(EventType.STRATEGY, terminal)) } private fun toMoveActions(location: Location, state: GameState) = combinations(location.nonBesiegedFigures, state) .flatMap { figures -> location.adjacentLocations.map { MoveAction(location.name, it, figures) } } private fun combinations(of: Figures, gameState: GameState): List<Figures> { val characterCombinations = Combinations.allSizes(of.characters().map { it.type }) .map { of.subSet(it) } val figuresSortedByPriority = of.getArmyPerNation().entries.sortedByDescending { (nation, army) -> val onWar = if (gameState.nation[nation]!!.isOnWar()) 100 else 0 onWar + army.size } .flatMap { (_, army) -> army } return (0..of.numRegulars()).flatMap { numRegular -> (0..of.numElites()).flatMap { numElite -> (0..of.numLeadersOrNazgul()).map { numLeader -> take(figuresSortedByPriority, numRegular, numElite, numLeader) } } } .filter { !it.isEmpty() } .flatMap { combineWithCharacters(it, characterCombinations) } } private fun take(figuresSortedByPriority: List<Figure>, numRegular: Int, numElite: Int, numLeader: Int) = Figures( figuresSortedByPriority.filter { it.type == FigureType.REGULAR }.take(numRegular) + figuresSortedByPriority.filter { it.type == FigureType.ELITE }.take(numElite) + figuresSortedByPriority.filter { it.type == FigureType.LEADER_OR_NAZGUL }.take(numLeader) ) private fun combineWithCharacters(figuresWithoutCharacters: Figures, characterCombinations: List<Figures>) = characterCombinations.map { figuresWithoutCharacters + it } }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/bot/BotStrategy.kt
2990647503
package ch.chrigu.wotr.bot import ch.chrigu.wotr.action.GameAction import ch.chrigu.wotr.gamestate.GameState interface BotStrategy { /** * All actions that make sense for this strategy. */ fun getActions(state: GameState): List<GameAction> }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/commands/CustomExceptionResolver.kt
3810777422
package ch.chrigu.wotr.commands import org.springframework.shell.command.CommandExceptionResolver import org.springframework.shell.command.CommandHandlingResult import org.springframework.stereotype.Component import java.lang.Exception @Component class CustomExceptionResolver : CommandExceptionResolver { override fun resolve(e: Exception): CommandHandlingResult = CommandHandlingResult.of(e.message + "\n", 1) }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/commands/SaveLoadCommands.kt
3844548556
package ch.chrigu.wotr.commands import ch.chrigu.wotr.gamestate.GameStateHolder import ch.chrigu.wotr.gamestate.GameStateLoader import org.springframework.shell.command.annotation.Command import org.springframework.shell.command.annotation.Option import java.io.File @Command(group = "Save/Load") class SaveLoadCommands(private val gameStateHolder: GameStateHolder) { @Command(command = ["save"], description = "Save current game") fun save(@Option file: File = File("wotr.json")) = GameStateLoader.saveFile(file, gameStateHolder.current) @Command(command = ["load"], description = "Load game") fun load(@Option file: File = File("wotr.json")) = gameStateHolder.reset( GameStateLoader.loadFile(file) ) }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/commands/BotCommands.kt
1786998460
package ch.chrigu.wotr.commands import ch.chrigu.wotr.action.BotAction import ch.chrigu.wotr.bot.BotActionFactory import ch.chrigu.wotr.gamestate.GameStateHolder import org.jline.terminal.Terminal import org.springframework.shell.command.annotation.Command @Command(group = "Bot") class BotCommands(private val gameStateHolder: GameStateHolder, private val terminal: Terminal, private val botActionFactory: BotActionFactory) { @Command(command = ["bot"], alias = ["b"], description = "Shadow bot takes its next move") fun botCommand() = gameStateHolder.apply(BotAction(terminal, botActionFactory)) }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/commands/UndoRedoCommands.kt
2703974838
package ch.chrigu.wotr.commands import ch.chrigu.wotr.gamestate.GameStateHolder import org.springframework.context.annotation.Bean import org.springframework.shell.Availability import org.springframework.shell.AvailabilityProvider import org.springframework.shell.command.annotation.Command import org.springframework.shell.command.annotation.CommandAvailability @Command(group = "Undo/Redo") class UndoRedoCommands(private val gameStateHolder: GameStateHolder) { @Command(command = ["undo"], description = "Undo last command") @CommandAvailability(provider = ["undoAvailability"]) fun undo() = gameStateHolder.undo() @Bean fun undoAvailability() = AvailabilityProvider { if (gameStateHolder.allowUndo()) Availability.available() else Availability.unavailable("Nothing to undo") } @Command(command = ["redo"], description = "Redo undone command") @CommandAvailability(provider = ["redoAvailability"]) fun redo() = gameStateHolder.redo() @Bean fun redoAvailability() = AvailabilityProvider { if (gameStateHolder.allowRedo()) Availability.available() else Availability.unavailable("Nothing to redo") } }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/commands/WotrPromptProvider.kt
105362269
package ch.chrigu.wotr.commands import ch.chrigu.wotr.gamestate.GameStateHolder import org.jline.utils.AttributedString import org.jline.utils.AttributedStyle import org.springframework.shell.jline.PromptProvider import org.springframework.stereotype.Component @Component class WotrPromptProvider(private val gameStateHolder: GameStateHolder) : PromptProvider { override fun getPrompt() = AttributedString("${gameStateHolder.current}>", AttributedStyle.DEFAULT.foreground(AttributedStyle.RED)) }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/commands/BoardCommands.kt
720133782
package ch.chrigu.wotr.commands import ch.chrigu.wotr.action.KillAction import ch.chrigu.wotr.action.MoveAction import ch.chrigu.wotr.action.MusterAction import ch.chrigu.wotr.figure.Figures import ch.chrigu.wotr.gamestate.GameStateHolder import ch.chrigu.wotr.location.Location import ch.chrigu.wotr.location.LocationName import org.springframework.shell.command.CommandRegistration import org.springframework.shell.command.annotation.Command import org.springframework.shell.command.annotation.Option import org.springframework.shell.command.annotation.OptionValues @Command(group = "Board", description = "Commands that modify the board state") class BoardCommands(private val gameStateHolder: GameStateHolder) { @Command(command = ["move"], alias = ["mo"], description = "Move figures from one location to another") fun moveCommand( @Option(shortNames = ['f']) @OptionValues(provider = ["locationCompletionProvider"]) from: String, @Option(shortNames = ['t']) @OptionValues(provider = ["locationCompletionProvider"]) to: String, @Option(shortNames = ['w'], arity = CommandRegistration.OptionArity.ZERO_OR_MORE) @OptionValues(provider = ["figuresCompletionProvider"]) who: Array<String>? ): Location { val fromLocation = LocationName.get(from) val toLocation = LocationName.get(to) val figures = Figures.parse(who ?: emptyArray(), fromLocation, gameStateHolder.current) val newState = gameStateHolder.apply(MoveAction(fromLocation, toLocation, figures)) return newState.location[toLocation]!! } @Command(command = ["kill"], alias = ["k"], description = "Remove figures from location") fun killCommand( @Option(shortNames = ['l']) @OptionValues(provider = ["locationCompletionProvider"]) location: String, @Option(shortNames = ['w'], arity = CommandRegistration.OptionArity.ZERO_OR_MORE) @OptionValues(provider = ["figuresCompletionProvider"]) who: Array<String>? ): Location { val locationName = LocationName.get(location) val figures = Figures.parse(who ?: emptyArray(), locationName, gameStateHolder.current) val newState = gameStateHolder.apply(KillAction(locationName, figures)) return newState.location[locationName]!! } @Command(command = ["muster"], alias = ["mu"], description = "Move figures from reinforcements to location") fun musterCommand( @Option(shortNames = ['l']) @OptionValues(provider = ["locationCompletionProvider"]) location: String, @Option(shortNames = ['w'], arityMin = 1) @OptionValues(provider = ["reinforcementsCompletionProvider"]) who: Array<String> ): Location { val locationName = LocationName.get(location) val figures = Figures.parse(who, gameStateHolder.current.reinforcements, gameStateHolder.current.location[locationName]!!.nation) val newState = gameStateHolder.apply(MusterAction(figures, locationName)) return newState.location[locationName]!! } }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/gamestate/GameStateFactory.kt
1502682967
package ch.chrigu.wotr.gamestate import ch.chrigu.wotr.figure.Figure import ch.chrigu.wotr.figure.FigureType import ch.chrigu.wotr.figure.Figures import ch.chrigu.wotr.figure.FiguresType import ch.chrigu.wotr.location.Location import ch.chrigu.wotr.location.LocationName import ch.chrigu.wotr.location.LocationName.* import ch.chrigu.wotr.nation.Nation import ch.chrigu.wotr.nation.NationName import ch.chrigu.wotr.nation.NationName.* import ch.chrigu.wotr.player.Player object GameStateFactory { private val initFigures = mapOf( f(ERED_LUIN, 1, 0, 0), f(EREBOR, 1, 2, 1), f(IRON_HILLS, 1, 0, 0), f(THE_SHIRE, 1, 0, 0), f(NORTH_DOWNS, 0, 1, 0), f(DALE, 1, 0, 1), f(CARROCK, 1, 0, 0), f(BREE, 1, 0, 0), f(GREY_HAVENS, 1, 1, 1), f(RIVENDELL, 0, 2, 1), f(WOODLAND_REALM, 1, 1, 1), f(LORIEN, 1, 2, 1), f(EDORAS, 1, 1, 0), f(FORDS_OF_ISEN, 2, 0, 1), f(HELMS_DEEP, 1, 0, 0), f(MINAS_TIRITH, 3, 1, 1), f(DOL_AMROTH, 3, 0, 0), f(OSGILIATH, 2, 0, 0, GONDOR), f(PELARGIR, 1, 0, 0), f(ORTHANC, 4, 1, 0), f(NORTH_DUNLAND, 1, 0, 0), f(SOUTH_DUNLAND, 1, 0, 0), f(FAR_HARAD, 3, 1, 0), f(NEAR_HARAD, 3, 1, 0), f(NORTH_RHUN, 2, 0, 0), f(SOUTH_RHUN, 3, 1, 0), f(UMBAR, 3, 0, 0), f(BARAD_DUR, 4, 1, 1), f(DOL_GULDUR, 5, 1, 1), f(GORGOROTH, 3, 0, 0), f(MINAS_MORGUL, 5, 0, 1), f(MORIA, 2, 0, 0), f(MOUNT_GUNDABAD, 2, 0, 0), f(NURN, 2, 0, 0), f(MORANNON, 5, 0, 1) ) fun newGame() = GameState(LocationName.entries.associateWith { getLocation(it) }, createNations(), createReinforcements(), createCompanions()) private fun createNations() = NationName.entries.filter { it != FREE_PEOPLE } .associateWith { Nation(getBoxNumber(it), getNationActive(it), it) } private fun getBoxNumber(nationName: NationName) = when (nationName) { SAURON, ISENGARD -> 1 GONDOR, SOUTHRONS_AND_EASTERLINGS -> 2 else -> 3 } private fun getNationActive(nationName: NationName) = nationName.player == Player.SHADOW || nationName == ELVES private fun getLocation(location: LocationName) = Location(location, getFigures(location)) private fun getFigures(name: LocationName): Figures { if (initFigures.containsKey(name)) { val notNullNation: NationName = initFigures[name]!!.second ?: name.nation!! val all = initFigures[name]!!.first .map { Figure(it, notNullNation) } val fs = if (name == RIVENDELL) listOf(Figure(FigureType.FELLOWSHIP, FREE_PEOPLE)) else emptyList() return Figures(all + fs) } else { return Figures(emptyList()) } } private fun createReinforcements() = Figures( createFiguresFromNationName(DWARVES, 2, 3, 3) + createFiguresFromNationName(ELVES, 2, 4) + createFiguresFromNationName(GONDOR, 6, 4, 3) + createFiguresFromNationName(NORTHMEN, 6, 4, 3) + createFiguresFromNationName(ROHAN, 6, 4, 3) + createFiguresFromNationName(ISENGARD, 6, 5) + createFiguresFromNationName(SAURON, 8, 4, 4) + createFiguresFromNationName(SOUTHRONS_AND_EASTERLINGS, 10, 3) + listOf(Figure(FigureType.WITCH_KING, SAURON), Figure(FigureType.MOUTH_OF_SAURON, SAURON), Figure(FigureType.SARUMAN, ISENGARD)) + listOf(Figure(FigureType.ARAGORN, FREE_PEOPLE), Figure(FigureType.GANDALF_THE_WHITE, FREE_PEOPLE)), FiguresType.REINFORCEMENTS ) private fun createCompanions() = listOf( Figure(FigureType.GANDALF_THE_GREY, FREE_PEOPLE), Figure(FigureType.STRIDER, NORTHMEN), Figure(FigureType.GIMLI, DWARVES), Figure(FigureType.LEGOLAS, ELVES), Figure(FigureType.BOROMIR, GONDOR), Figure(FigureType.PEREGRIN, FREE_PEOPLE), Figure(FigureType.MERIADOC, FREE_PEOPLE) ) private fun f(name: LocationName, numRegular: Int, numElite: Int, numLeaderOrNazgul: Int, nation: NationName? = null) = name to Pair(createFigures(numRegular, numElite, numLeaderOrNazgul), nation) private fun createFiguresFromNationName(nation: NationName, numRegular: Int, numElite: Int, numLeaderOrNazgul: Int = 0) = createFigures(numRegular, numElite, numLeaderOrNazgul) .map { Figure(it, nation) } private fun createFigures(numRegular: Int, numElite: Int, numLeaderOrNazgul: Int) = (0 until numRegular).map { FigureType.REGULAR } + (0 until numElite).map { FigureType.ELITE } + (0 until numLeaderOrNazgul).map { FigureType.LEADER_OR_NAZGUL } }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/gamestate/GameStateLoader.kt
3186729073
package ch.chrigu.wotr.gamestate import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import java.io.File object GameStateLoader { fun saveFile(file: File, gameState: GameState) = file.run { createNewFile() writeText(Json.encodeToString(gameState)) } fun loadFile(file: File) = Json.decodeFromString<GameState>(file.readText()) }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/gamestate/GameStateHolder.kt
1011103815
package ch.chrigu.wotr.gamestate import ch.chrigu.wotr.action.GameAction import org.springframework.stereotype.Component @Component class GameStateHolder { private val history = mutableListOf(GameStateFactory.newGame()) private var currentIndex = 0 val current get() = history[currentIndex] fun apply(action: GameAction): GameState { val newState = action.apply(current) removeFutureActions() history.add(newState) currentIndex++ return newState } fun undo(): GameState { check(allowUndo()) currentIndex-- return current } fun redo(): GameState { check(allowRedo()) currentIndex++ return current } fun allowUndo() = currentIndex > 0 fun allowRedo() = currentIndex < history.size - 1 fun reset(newState: GameState) { history.clear() history.add(newState) currentIndex = 0 } private fun removeFutureActions() { repeat(history.size - currentIndex - 1) { history.removeLast() } } }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/gamestate/GameState.kt
2496564801
package ch.chrigu.wotr.gamestate import ch.chrigu.wotr.card.Cards import ch.chrigu.wotr.dice.Dice import ch.chrigu.wotr.dice.DieUsage import ch.chrigu.wotr.fellowship.Fellowship import ch.chrigu.wotr.figure.Figure import ch.chrigu.wotr.figure.FigureType import ch.chrigu.wotr.figure.Figures import ch.chrigu.wotr.figure.FiguresType import ch.chrigu.wotr.location.Location import ch.chrigu.wotr.location.LocationName import ch.chrigu.wotr.nation.Nation import ch.chrigu.wotr.nation.NationName import ch.chrigu.wotr.player.Player import kotlinx.serialization.Serializable @Serializable data class GameState( val location: Map<LocationName, Location>, val nation: Map<NationName, Nation>, val reinforcements: Figures, val companions: List<Figure>, val fellowship: Fellowship = Fellowship(), val dice: Dice = Dice(), val cards: Cards = Cards() ) { init { require(reinforcements.type == FiguresType.REINFORCEMENTS) } val fellowshipLocation get() = fellowship.getFellowshipLocation(this) fun getLocationWith(figures: List<Figure>) = location.values.firstOrNull { it.allFigures().containsAll(figures) } fun findAll(filter: (Figure) -> Boolean) = location.values.flatMap { location -> location.allFigures().filter(filter).map { location to it } } fun vpFreePeople() = location.values.filter { it.captured && it.currentlyOccupiedBy() == Player.FREE_PEOPLE }.sumOf { it.victoryPoints } fun vpShadow() = location.values.filter { it.captured && it.currentlyOccupiedBy() == Player.SHADOW }.sumOf { it.victoryPoints } fun removeFrom(locationName: LocationName, figures: Figures) = location(locationName) { remove(figures) } fun addTo(locationName: LocationName, figures: Figures) = location(locationName) { add(figures) } fun addToReinforcements(figures: Figures) = copy(reinforcements = reinforcements + figures) fun removeFromReinforcements(figures: Figures) = copy(reinforcements = reinforcements - figures) fun useDie(use: DieUsage) = copy(dice = dice.useDie(use)) fun numMinions() = location.values.sumOf { it.allFigures().count { figure -> figure.type.minion } } fun hasAragorn() = has(FigureType.ARAGORN) fun hasGandalfTheWhite() = has(FigureType.GANDALF_THE_WHITE) fun hasSaruman() = has(FigureType.SARUMAN) fun updateNation(name: NationName, modifier: Nation.() -> Nation) = copy(nation = nation + (name to nation[name]!!.run(modifier))) override fun toString() = "FP: ${dice.freePeople} [VP: ${getVictoryPoints(Player.FREE_PEOPLE)}, Pr: ${fellowship.progress}]\n" + "SH: ${dice.shadow} [VP: ${getVictoryPoints(Player.SHADOW)}, Co: ${fellowship.corruption}, $cards]" private fun has(figureType: FigureType) = location.values.any { l -> l.allFigures().any { f -> f.type == figureType } } private fun location(locationName: LocationName, modifier: Location.() -> Location) = copy(location = location + (locationName to location[locationName]!!.run(modifier))) private fun getVictoryPoints(player: Player) = location.values.filter { it.nation?.player != player && it.captured } .fold(0) { a, b -> a + b.victoryPoints } }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/fellowship/Fellowship.kt
701249924
package ch.chrigu.wotr.fellowship import ch.chrigu.wotr.figure.FigureType import ch.chrigu.wotr.gamestate.GameState import ch.chrigu.wotr.location.LocationName import ch.chrigu.wotr.player.Player import kotlinx.serialization.Serializable @Serializable data class Fellowship(val progress: Int = 0, val corruption: Int = 0, val mordor: Int? = null, val discovered: Boolean = false) { init { require(progress in 0..MAX_CORRUPTION) { "Progress should be between 0 and 12, but was $progress" } require(corruption in 0..MAX_CORRUPTION) { "Corruption should be between 0 and 12, but was $corruption" } if (mordor != null) { require(progress == 0) require(mordor in 0..MORDOR_STEPS) } } fun numStepsLeft(state: GameState) = if (mordor == null) getFellowshipLocation(state).getShortestPath(LocationName.MORANNON, LocationName.MINAS_MORGUL) .first().getLength() + MORDOR_STEPS else MORDOR_STEPS - mordor fun remainingCorruption() = MAX_CORRUPTION - corruption fun numRerolls(state: GameState): Int { val fellowshipLocation = getFellowshipLocation(state) return listOf( fellowshipLocation.allFigures().any { it.isNazgul }, fellowshipLocation.nonBesiegedFigures.armyPlayer == Player.SHADOW || fellowshipLocation.besiegedFigures.armyPlayer == Player.SHADOW, fellowshipLocation.currentlyOccupiedBy() == Player.SHADOW ) .count { it } } fun getFellowshipLocation(state: GameState) = state.location.values.first { it.contains(FigureType.FELLOWSHIP) } companion object { const val MORDOR_STEPS = 5 const val MAX_CORRUPTION = 12 } }
wotr-cli/src/main/kotlin/ch/chrigu/wotr/player/Player.kt
2237794717
package ch.chrigu.wotr.player import ch.chrigu.wotr.dice.DieType enum class Player(val dieFace: List<DieType>) { SHADOW(listOf(DieType.ARMY, DieType.ARMY_MUSTER, DieType.MUSTER, DieType.EYE, DieType.EVENT, DieType.CHARACTER)), FREE_PEOPLE(listOf(DieType.ARMY, DieType.ARMY_MUSTER, DieType.MUSTER, DieType.WILL_OF_THE_WEST, DieType.EVENT, DieType.CHARACTER)); val opponent: Player get() = entries.first { it != this } }
coin-gecko/app/src/androidTest/java/com/example/coingecko/ExampleInstrumentedTest.kt
2783401706
package com.example.coingecko import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.coingecko", appContext.packageName) } }
coin-gecko/app/src/test/java/com/example/coingecko/ExampleUnitTest.kt
2036695190
package com.example.coingecko import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
coin-gecko/app/src/main/java/com/example/coingecko/di/CoinGeckoModule.kt
2576891611
package com.example.coingecko.di import com.example.coingecko.data.repository.CoinRepositoryImpl import com.example.coingecko.data.source.CoinGeckoApi import com.example.coingecko.domain.repository.CoinRepository import com.example.coingecko.util.Constants import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object CoinGeckoModule { @Provides @Singleton fun provideJokesApi(): CoinGeckoApi { return Retrofit.Builder() .baseUrl(Constants.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() .create(CoinGeckoApi::class.java) } @Provides @Singleton fun provideCoinGeckoRepository(api:CoinGeckoApi): CoinRepository { return CoinRepositoryImpl(api=api) } }
coin-gecko/app/src/main/java/com/example/coingecko/util/ResponseState.kt
2076729680
package com.example.coingecko.util sealed class ResponseState<T>(val data :T?=null,val message:String?=null){ class Loading<T>(data:T?=null):ResponseState<T>(data) class Success<T>(data:T):ResponseState<T>(data) class Error<T>(message:String,data:T?=null):ResponseState<T>(data,message) }
coin-gecko/app/src/main/java/com/example/coingecko/util/Constants.kt
4072296858
package com.example.coingecko.util object Constants { const val BASE_URL = "https://api.coingecko.com/" }