file_name stringlengths 6 86 | file_path stringlengths 45 249 | content stringlengths 47 6.26M | file_size int64 47 6.26M | language stringclasses 1 value | extension stringclasses 1 value | repo_name stringclasses 767 values | repo_stars int64 8 14.4k | repo_forks int64 0 1.17k | repo_open_issues int64 0 788 | repo_created_at stringclasses 767 values | repo_pushed_at stringclasses 767 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
SensorsTest.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/androidTest/java/org/flyve/inventory/SensorsTest.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import org.flyve.inventory.categories.Sensors;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.List;
import static org.junit.Assert.assertNotEquals;
@RunWith(AndroidJUnit4.class)
public class SensorsTest {
Context appContext = InstrumentationRegistry.getTargetContext();
Sensors csensors = new Sensors(appContext);
@Test
public void getName() throws Exception {
SensorManager sensorManager = (SensorManager) appContext.getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor s : sensors) {
assertNotEquals("", csensors.getName(s));
}
}
@Test
public void getManufacturer() throws Exception {
SensorManager sensorManager = (SensorManager) appContext.getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor s : sensors) {
assertNotEquals("", csensors.getManufacturer(s));
}
}
@Test
public void getType() throws Exception {
SensorManager sensorManager = (SensorManager) appContext.getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor s : sensors) {
assertNotEquals("", csensors.getType(s));
}
}
@Test
public void getPower() throws Exception {
SensorManager sensorManager = (SensorManager) appContext.getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor s : sensors) {
assertNotEquals("", csensors.getPower(s));
}
}
@Test
public void getVersion() throws Exception {
SensorManager sensorManager = (SensorManager) appContext.getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor s : sensors) {
assertNotEquals("", csensors.getVersion(s));
}
}
} | 3,488 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
ExampleUnitTest.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/example_java/src/test/java/org/flyve/example_java/ExampleUnitTest.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.example_java;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | 1,556 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
MainActivity.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/example_java/src/main/java/org/flyve/example_java/MainActivity.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.example_java;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import org.flyve.inventory.InventoryLog;
import org.flyve.inventory.InventoryTask;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "inventory.example";
private InventoryTask inventoryTask;
public void showDialogShare(final Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(this );
builder.setTitle(R.string.dialog_share_title);
final int[] type = new int[1];
//list of items
String[] items = context.getResources().getStringArray(R.array.export_list);
builder.setSingleChoiceItems(items, 0,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
type[0] = which;
}
});
String positiveText = context.getString(android.R.string.ok);
builder.setPositiveButton(positiveText,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// positive button logic
new InventoryTask(MainActivity.this, TAG, false).shareInventory(type[0]);
}
});
String negativeText = context.getString(android.R.string.cancel);
builder.setNegativeButton(negativeText,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// negative button logic
}
});
AlertDialog dialog = builder.create();
// display dialog
dialog.show();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA,
Manifest.permission.READ_PHONE_STATE,
},
1);
final RadioButton btnComputer = findViewById(R.id.radioButton_computer);
btnComputer.setChecked(true);
final Button btnShare = findViewById(R.id.btnShare);
btnShare.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
showDialogShare(getApplicationContext());
}
});
btnShare.setVisibility(View.INVISIBLE);
Button btnRun = findViewById(R.id.btnRun);
btnRun.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
inventoryTask = new InventoryTask(MainActivity.this, "example-app-java", true);
if(btnComputer.isChecked()){
inventoryTask.setAssetItemtype("Computer");
} else {
inventoryTask.setAssetItemtype("Phone");
}
inventoryTask.getXML(new InventoryTask.OnTaskCompleted() {
@Override
public void onTaskSuccess(String data) {
InventoryLog.d(data);
Toast.makeText(MainActivity.this, "Inventory Success, check the log", Toast.LENGTH_SHORT).show();
}
@Override
public void onTaskError(Throwable error) {
InventoryLog.e(error.getMessage());
Toast.makeText(MainActivity.this, "Inventory fail, check the log", Toast.LENGTH_SHORT).show();
}
});
inventoryTask.getJSON(new InventoryTask.OnTaskCompleted() {
@Override
public void onTaskSuccess(String data) {
InventoryLog.d(data);
//show btn share
btnShare.setVisibility(View.VISIBLE);
}
@Override
public void onTaskError(Throwable error) {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
});
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED
&& grantResults[2] == PackageManager.PERMISSION_GRANTED
&& grantResults[3] == PackageManager.PERMISSION_GRANTED) {
}
}
}
}
public static String base64encode(String text) {
String rtext = "";
if(text == null) { return ""; }
try {
byte[] data = text.getBytes("UTF-8");
rtext = Base64.encodeToString(data, Base64.NO_WRAP | Base64.URL_SAFE);
rtext = rtext.replaceAll("-", "+");
rtext = rtext.replaceAll(" ", "+");
} catch (UnsupportedEncodingException e) {
Log.e(TAG, e.getMessage());
}
return rtext;
}
public static String getSyncWebData(final String url, final String data, final Map<String, String> header) {
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
URL dataURL = new URL(url);
Log.d(TAG, "URL: " + url);
HttpURLConnection conn = (HttpURLConnection)dataURL.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(50000);
conn.setReadTimeout(500000);
// for (Map.Entry<String, String> entry : header.entrySet()) {
// conn.setRequestProperty(entry.getKey(), entry.getValue());
// }
// Send post request
conn.setDoOutput(true);
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
os.writeBytes(data);
os.flush();
os.close();
if(conn.getResponseCode() >= 400) {
InputStream is = conn.getErrorStream();
return inputStreamToString(is);
}
InputStream is = conn.getInputStream();
return inputStreamToString(is);
}
catch (final Exception ex) {
String error = ex.getMessage();
Log.e(TAG, error);
return error;
}
}
private static String inputStreamToString(final InputStream stream) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
return sb.toString();
}
}
| 9,383 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
ExampleInstrumentedTest.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/example_java/src/androidTest/java/org/flyve/example_java/ExampleInstrumentedTest.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.example_java;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("org.flyve.example_java", appContext.getPackageName());
}
}
| 1,888 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
ActivityMain.java | /FileExtraction/Java_unseen/shivam141296_Android-Firewall/app/src/main/java/com/example/firewallminor/ActivityMain.java | package com.example.firewallminor;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.VpnService;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.SwitchCompat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Toast;
import java.util.List;
public class ActivityMain extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
private static final String TAG = "Firewall.Main";
private boolean running = false;
private RuleAdapter adapter = null;
private MenuItem searchItem = null;
private static final int REQUEST_VPN = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "Create");
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
setTheme(prefs.getBoolean("dark_theme", false) ? R.style.AppThemeDark : R.style.AppTheme);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
running = true;
// Action bar
View view = getLayoutInflater().inflate(R.layout.actionbar, null);
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setCustomView(view);
// On/off switch
SwitchCompat swEnabled = (SwitchCompat) view.findViewById(R.id.swEnabled);
swEnabled.setChecked(prefs.getBoolean("enabled", false));
swEnabled.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Log.i(TAG, "Switch on");
Intent prepare = VpnService.prepare(ActivityMain.this);
if (prepare == null) {
Log.e(TAG, "Prepare done");
onActivityResult(REQUEST_VPN, RESULT_OK, null);
} else {
Log.i(TAG, "Start intent=" + prepare);
try {
startActivityForResult(prepare, REQUEST_VPN);
} catch (Throwable ex) {
Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
onActivityResult(REQUEST_VPN, RESULT_CANCELED, null);
Toast.makeText(ActivityMain.this, ex.toString(), Toast.LENGTH_LONG).show();
}
}
} else {
Log.i(TAG, "Switch off");
prefs.edit().putBoolean("enabled", false).apply();
BlackHoleService.stop(ActivityMain.this);
}
}
});
// Listen for preference changes
prefs.registerOnSharedPreferenceChangeListener(this);
// Fill application list
fillApplicationList();
// Listen for connectivity updates
IntentFilter ifConnectivity = new IntentFilter();
ifConnectivity.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(connectivityChangedReceiver, ifConnectivity);
// Listen for added/removed applications
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
intentFilter.addDataScheme("package");
registerReceiver(packageChangedReceiver, intentFilter);
}
@Override
public void onDestroy() {
Log.i(TAG, "Destroy");
running = false;
PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(this);
unregisterReceiver(connectivityChangedReceiver);
unregisterReceiver(packageChangedReceiver);
super.onDestroy();
}
private BroadcastReceiver connectivityChangedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Received " + intent);
Util.logExtras(TAG, intent);
invalidateOptionsMenu();
}
};
private BroadcastReceiver packageChangedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Received " + intent);
Util.logExtras(TAG, intent);
fillApplicationList();
}
};
private void fillApplicationList() {
// Get recycler view
final RecyclerView rvApplication = (RecyclerView) findViewById(R.id.rvApplication);
rvApplication.setHasFixedSize(true);
rvApplication.setLayoutManager(new LinearLayoutManager(this));
// Get/set application list
new AsyncTask<Object, Object, List<Rule>>() {
@Override
protected List<Rule> doInBackground(Object... arg) {
return Rule.getRules(ActivityMain.this);
}
@Override
protected void onPostExecute(List<Rule> result) {
if (running) {
if (searchItem != null)
MenuItemCompat.collapseActionView(searchItem);
adapter = new RuleAdapter(result, ActivityMain.this);
rvApplication.setAdapter(adapter);
}
}
}.execute();
}
@Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String name) {
Log.i(TAG, "Preference " + name + "=" + prefs.getAll().get(name));
if ("enabled".equals(name)) {
// Get enabled
boolean enabled = prefs.getBoolean(name, false);
// Check switch state
SwitchCompat swEnabled = (SwitchCompat) getSupportActionBar().getCustomView().findViewById(R.id.swEnabled);
if (swEnabled.isChecked() != enabled)
swEnabled.setChecked(enabled);
}
}
@Override+
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
// Search
searchItem = menu.findItem(R.id.menu_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
if (adapter != null)
adapter.getFilter().filter(query);
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
if (adapter != null)
adapter.getFilter().filter(newText);
return true;
}
});
searchView.setOnCloseListener(new SearchView.OnCloseListener() {
@Override
public boolean onClose() {
if (adapter != null)
adapter.getFilter().filter(null);
return true;
}
});
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
MenuItem network = menu.findItem(R.id.menu_network);
network.setIcon(Util.isWifiActive(this) ? R.drawable.ic_network_wifi_white_24dp : R.drawable.ic_network_cell_white_24dp);
MenuItem wifi = menu.findItem(R.id.menu_whitelist_wifi);
wifi.setChecked(prefs.getBoolean("whitelist_wifi", true));
MenuItem other = menu.findItem(R.id.menu_whitelist_other);
other.setChecked(prefs.getBoolean("whitelist_other", true));
MenuItem dark = menu.findItem(R.id.menu_dark);
dark.setChecked(prefs.getBoolean("dark_theme", false));
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
// Handle item selection
switch (item.getItemId()) {
case R.id.menu_network:
Intent settings = new Intent(Util.isWifiActive(this)
? Settings.ACTION_WIFI_SETTINGS : Settings.ACTION_WIRELESS_SETTINGS);
if (settings.resolveActivity(getPackageManager()) != null)
startActivity(settings);
else
Log.w(TAG, settings + " not available");
return true;
case R.id.menu_refresh:
fillApplicationList();
return true;
case R.id.menu_whitelist_wifi:
prefs.edit().putBoolean("whitelist_wifi", !prefs.getBoolean("whitelist_wifi", true)).apply();
fillApplicationList();
BlackHoleService.reload("wifi", this);
return true;
case R.id.menu_whitelist_other:
prefs.edit().putBoolean("whitelist_other", !prefs.getBoolean("whitelist_other", true)).apply();
fillApplicationList();
BlackHoleService.reload("other", this);
return true;
case R.id.menu_reset_wifi:
new AlertDialog.Builder(this)
.setMessage(R.string.msg_sure)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
reset("wifi");
}
})
.setNegativeButton(android.R.string.no, null)
.show();
return true;
case R.id.menu_reset_other:
new AlertDialog.Builder(this)
.setMessage(R.string.msg_sure)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
reset("other");
}
})
.setNegativeButton(android.R.string.no, null)
.show();
return true;
case R.id.menu_dark:
prefs.edit().putBoolean("dark_theme", !prefs.getBoolean("dark_theme", false)).apply();
recreate();
return true;
case R.id.menu_vpn_settings:
// Open VPN settings
Intent vpn = new Intent("android.net.vpn.SETTINGS");
if (vpn.resolveActivity(getPackageManager()) != null)
startActivity(vpn);
else
Log.w(TAG, vpn + " not available");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void reset(String network) {
SharedPreferences other = getSharedPreferences(network, Context.MODE_PRIVATE);
SharedPreferences.Editor edit = other.edit();
for (String key : other.getAll().keySet())
edit.remove(key);
edit.apply();
fillApplicationList();
BlackHoleService.reload(network, ActivityMain.this);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_VPN) {
// Update enabled state
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().putBoolean("enabled", resultCode == RESULT_OK).apply();
// Start service
if (resultCode == RESULT_OK)
BlackHoleService.start(this);
} else
super.onActivityResult(requestCode, resultCode, data);
}
}
| 12,799 | Java | .java | shivam141296/Android-Firewall | 44 | 16 | 1 | 2017-11-30T17:20:10Z | 2018-12-13T06:32:12Z |
RuleAdapter.java | /FileExtraction/Java_unseen/shivam141296_Android-Firewall/app/src/main/java/com/example/firewallminor/RuleAdapter.java | package com.example.firewallminor;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class RuleAdapter extends RecyclerView.Adapter<RuleAdapter.ViewHolder> implements Filterable {
private static final String TAG = "Firewall.Adapter";
private Context context;
private int colorText;
private int colorAccent;
private List<Rule> listAll;
private List<Rule> listSelected;
public static class ViewHolder extends RecyclerView.ViewHolder {
public View view;
public ImageView ivIcon;
public TextView tvName;
public TextView tvPackage;
public CheckBox cbWifi;
public CheckBox cbOther;
public ViewHolder(View itemView) {
super(itemView);
view = itemView;
ivIcon = (ImageView) itemView.findViewById(R.id.ivIcon);
tvName = (TextView) itemView.findViewById(R.id.tvName);
tvPackage = (TextView) itemView.findViewById(R.id.tvPackage);
cbWifi = (CheckBox) itemView.findViewById(R.id.cbWifi);
cbOther = (CheckBox) itemView.findViewById(R.id.cbOther);
}
}
public RuleAdapter(List<Rule> listRule, Context context) {
this.context = context;
colorAccent = ContextCompat.getColor(context, R.color.colorAccent);
TypedArray ta = context.getTheme().obtainStyledAttributes(new int[]{android.R.attr.textColorSecondary});
try {
colorText = ta.getColor(0, 0);
} finally {
ta.recycle();
}
listAll = listRule;
listSelected = new ArrayList<>();
listSelected.addAll(listRule);
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
// Get rule
final Rule rule = listSelected.get(position);
// Rule change listener
CompoundButton.OnCheckedChangeListener cbListener = new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
String network;
if (buttonView == holder.cbWifi) {
network = "wifi";
rule.wifi_blocked = isChecked;
} else {
network = "other";
rule.other_blocked = isChecked;
}
Log.i(TAG, rule.info.packageName + ": " + network + "=" + isChecked);
SharedPreferences prefs = context.getSharedPreferences(network, Context.MODE_PRIVATE);
prefs.edit().putBoolean(rule.info.packageName, isChecked).apply();
BlackHoleService.reload(network, context);
}
};
int color = rule.system ? colorAccent : colorText;
if (rule.disabled)
color = Color.argb(100, Color.red(color), Color.green(color), Color.blue(color));
holder.ivIcon.setImageDrawable(rule.getIcon(context));
holder.tvName.setText(rule.name);
holder.tvName.setTextColor(color);
holder.tvPackage.setText(rule.info.packageName);
holder.tvPackage.setTextColor(color);
holder.cbWifi.setOnCheckedChangeListener(null);
holder.cbWifi.setChecked(rule.wifi_blocked);
holder.cbWifi.setOnCheckedChangeListener(cbListener);
holder.cbOther.setOnCheckedChangeListener(null);
holder.cbOther.setChecked(rule.other_blocked);
holder.cbOther.setOnCheckedChangeListener(cbListener);
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence query) {
List<Rule> listResult = new ArrayList<>();
if (query == null)
listResult.addAll(listAll);
else {
query = query.toString().toLowerCase();
for (Rule rule : listAll)
if (rule.name.toLowerCase().contains(query))
listResult.add(rule);
}
FilterResults result = new FilterResults();
result.values = listResult;
result.count = listResult.size();
return result;
}
@Override
protected void publishResults(CharSequence query, FilterResults result) {
listSelected.clear();
if (result == null)
listSelected.addAll(listAll);
else
for (Rule rule : (List<Rule>) result.values)
listSelected.add(rule);
notifyDataSetChanged();
}
};
}
@Override
public RuleAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.rule, parent, false));
}
@Override
public int getItemCount() {
return listSelected.size();
}
}
| 5,585 | Java | .java | shivam141296/Android-Firewall | 44 | 16 | 1 | 2017-11-30T17:20:10Z | 2018-12-13T06:32:12Z |
BlackHoleService.java | /FileExtraction/Java_unseen/shivam141296_Android-Firewall/app/src/main/java/com/example/firewallminor/BlackHoleService.java | package com.example.firewallminor;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.VpnService;
import android.os.ParcelFileDescriptor;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
public class BlackHoleService extends VpnService {
private static final String TAG = "NetGuard.Service";
private ParcelFileDescriptor vpn = null;
private static final String EXTRA_COMMAND = "Command";
private enum Command {start, reload, stop}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Get enabled
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean enabled = prefs.getBoolean("enabled", false);
// Get command
Command cmd = (intent == null ? Command.start : (Command) intent.getSerializableExtra(EXTRA_COMMAND));
Log.i(TAG, "Start intent=" + intent + " command=" + cmd + " enabled=" + enabled + " vpn=" + (vpn != null));
// Process command
switch (cmd) {
case start:
if (enabled && vpn == null)
vpn = vpnStart();
break;
case reload:
// Seamless handover
ParcelFileDescriptor prev = vpn;
if (enabled)
vpn = vpnStart();
if (prev != null)
vpnStop(prev);
break;
case stop:
if (vpn != null) {
vpnStop(vpn);
vpn = null;
}
stopSelf();
break;
}
return START_STICKY;
}
private ParcelFileDescriptor vpnStart() {
Log.i(TAG, "Starting");
// Check if Wi-Fi
boolean wifi = Util.isWifiActive(this);
Log.i(TAG, "wifi=" + wifi);
// Build VPN service
final Builder builder = new Builder();
builder.setSession(getString(R.string.app_name));
builder.addAddress("10.1.10.1", 32);
builder.addAddress("fd00:1:fd00:1:fd00:1:fd00:1", 128);
builder.addRoute("0.0.0.0", 0);
builder.addRoute("0:0:0:0:0:0:0:0", 0);
// Add list of allowed applications
for (Rule rule : Rule.getRules(this))
if (!(wifi ? rule.wifi_blocked : rule.other_blocked)) {
Log.i(TAG, "Allowing " + rule.info.packageName);
try {
builder.addDisallowedApplication(rule.info.packageName);
} catch (PackageManager.NameNotFoundException ex) {
Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
}
}
// Build configure intent
Intent configure = new Intent(this, ActivityMain.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, configure, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setConfigureIntent(pi);
// Start VPN service
try {
return builder.establish();
} catch (Throwable ex) {
Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
// Disable firewall
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().putBoolean("enabled", false).apply();
// Feedback
Util.toast(ex.toString(), Toast.LENGTH_LONG, this);
return null;
}
}
private void vpnStop(ParcelFileDescriptor pfd) {
Log.i(TAG, "Stopping");
try {
pfd.close();
} catch (IOException ex) {
Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
}
}
private BroadcastReceiver connectivityChangedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Received " + intent);
Util.logExtras(TAG, intent);
if (intent.hasExtra(ConnectivityManager.EXTRA_NETWORK_TYPE) &&
intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_DUMMY) == ConnectivityManager.TYPE_WIFI)
reload(null, BlackHoleService.this);
}
};
private BroadcastReceiver packageAddedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Received " + intent);
Util.logExtras(TAG, intent);
reload(null, BlackHoleService.this);
}
};
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Create");
// Listen for connectivity updates
IntentFilter ifConnectivity = new IntentFilter();
ifConnectivity.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(connectivityChangedReceiver, ifConnectivity);
// Listen for added applications
IntentFilter ifPackage = new IntentFilter();
ifPackage.addAction(Intent.ACTION_PACKAGE_ADDED);
ifPackage.addDataScheme("package");
registerReceiver(packageAddedReceiver, ifPackage);
}
@Override
public void onDestroy() {
Log.i(TAG, "Destroy");
if (vpn != null) {
vpnStop(vpn);
vpn = null;
}
unregisterReceiver(connectivityChangedReceiver);
unregisterReceiver(packageAddedReceiver);
super.onDestroy();
}
@Override
public void onRevoke() {
Log.i(TAG, "Revoke");
if (vpn != null) {
vpnStop(vpn);
vpn = null;
}
// Disable firewall
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().putBoolean("enabled", false).apply();
super.onRevoke();
}
public static void start(Context context) {
Intent intent = new Intent(context, BlackHoleService.class);
intent.putExtra(EXTRA_COMMAND, Command.start);
context.startService(intent);
}
public static void reload(String network, Context context) {
if (network == null || ("wifi".equals(network) ? Util.isWifiActive(context) : !Util.isWifiActive(context))) {
Intent intent = new Intent(context, BlackHoleService.class);
intent.putExtra(EXTRA_COMMAND, Command.reload);
context.startService(intent);
}
}
public static void stop(Context context) {
Intent intent = new Intent(context, BlackHoleService.class);
intent.putExtra(EXTRA_COMMAND, Command.stop);
context.startService(intent);
}
}
| 6,996 | Java | .java | shivam141296/Android-Firewall | 44 | 16 | 1 | 2017-11-30T17:20:10Z | 2018-12-13T06:32:12Z |
Receiver.java | /FileExtraction/Java_unseen/shivam141296_Android-Firewall/app/src/main/java/com/example/firewallminor/Receiver.java | package com.example.firewallminor;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.VpnService;
import android.util.Log;
public class Receiver extends BroadcastReceiver {
private static final String TAG = "NetGuard.Receiver";
@Override
public void onReceive(final Context context, Intent intent) {
Log.i(TAG, "Received " + intent);
Util.logExtras(TAG, intent);
// Start service
if (VpnService.prepare(context) == null)
BlackHoleService.start(context);
}
} | 594 | Java | .java | shivam141296/Android-Firewall | 44 | 16 | 1 | 2017-11-30T17:20:10Z | 2018-12-13T06:32:12Z |
Rule.java | /FileExtraction/Java_unseen/shivam141296_Android-Firewall/app/src/main/java/com/example/firewallminor/Rule.java | package com.example.firewallminor;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.preference.PreferenceManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Rule implements Comparable<Rule> {
public PackageInfo info;
public String name;
public boolean system;
public boolean disabled;
public boolean wifi_blocked;
public boolean other_blocked;
public boolean changed;
private Rule(PackageInfo info, boolean wifi_blocked, boolean other_blocked, boolean changed, Context context) {
PackageManager pm = context.getPackageManager();
this.info = info;
this.name = info.applicationInfo.loadLabel(pm).toString();
this.system = ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
int setting = pm.getApplicationEnabledSetting(info.packageName);
if (setting == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT)
this.disabled = !info.applicationInfo.enabled;
else
this.disabled = (setting != PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
this.wifi_blocked = wifi_blocked;
this.other_blocked = other_blocked;
this.changed = changed;
}
public static List<Rule> getRules(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences wifi = context.getSharedPreferences("wifi", Context.MODE_PRIVATE);
SharedPreferences other = context.getSharedPreferences("other", Context.MODE_PRIVATE);
boolean wlWifi = prefs.getBoolean("whitelist_wifi", true);
boolean wlOther = prefs.getBoolean("whitelist_other", true);
List<Rule> listRules = new ArrayList<>();
for (PackageInfo info : context.getPackageManager().getInstalledPackages(0)) {
boolean blWifi = wifi.getBoolean(info.packageName, wlWifi);
boolean blOther = other.getBoolean(info.packageName, wlOther);
boolean changed = (blWifi != wlWifi || blOther != wlOther);
listRules.add(new Rule(info, blWifi, blOther, changed, context));
}
Collections.sort(listRules);
return listRules;
}
public Drawable getIcon(Context context) {
return info.applicationInfo.loadIcon(context.getPackageManager());
}
@Override
public int compareTo(Rule other) {
if (changed == other.changed) {
int i = name.compareToIgnoreCase(other.name);
return (i == 0 ? info.packageName.compareTo(other.info.packageName) : i);
}
return (changed ? -1 : 1);
}
}
| 2,853 | Java | .java | shivam141296/Android-Firewall | 44 | 16 | 1 | 2017-11-30T17:20:10Z | 2018-12-13T06:32:12Z |
Util.java | /FileExtraction/Java_unseen/shivam141296_Android-Firewall/app/src/main/java/com/example/firewallminor/Util.java | package com.example.firewallminor;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import java.util.Set;
public class Util {
public static String getSelfVersionName(Context context) {
try {
PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
return pInfo.versionName;
} catch (PackageManager.NameNotFoundException ex) {
return ex.toString();
}
}
public static boolean isWifiActive(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return (ni != null && ni.getType() == ConnectivityManager.TYPE_WIFI);
}
public static void toast(final String text, final int length, final Context context) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
Toast.makeText(context, text, length).show();
}
});
}
public static void logExtras(String tag, Intent intent) {
logBundle(tag, intent.getExtras());
}
public static void logBundle(String tag, Bundle data) {
if (data != null) {
Set<String> keys = data.keySet();
StringBuilder stringBuilder = new StringBuilder();
for (String key : keys)
stringBuilder.append(key).append("=").append(data.get(key)).append("\r\n");
Log.d(tag, stringBuilder.toString());
}
}
}
| 1,879 | Java | .java | shivam141296/Android-Firewall | 44 | 16 | 1 | 2017-11-30T17:20:10Z | 2018-12-13T06:32:12Z |
SuperCCTest.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/test/java/emulator/SuperCCTest.java | package emulator;
import game.Level;
import game.Tile;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Arrays;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
class SuperCCTest {
private final SuperCC emulator = new SuperCC(false);
/**
* If solution is stored in TWS file, provide the exact filename.
* If solution is stored in JSON file, provide only base filename (without level number and extension)
*/
boolean[] solveLevelset(String solutionName) {
int levels = emulator.lastLevelNumber() - 1;
boolean[] solved = new boolean[levels];
Arrays.fill(solved, Boolean.FALSE);
if (solutionName.endsWith(".tws")) {
emulator.setTWSFile(new File(solutionName));
}
for (int i = 1; i <= levels; i++) {
emulator.loadLevel(i);
Level level = emulator.getLevel();
try {
Solution s = getSolution(solutionName, i);
if (s == null) {
continue;
}
s.load(emulator, TickFlags.LIGHT);
level = emulator.getLevel();
if (level.getLayerFG().get(level.getChip().getPosition()) != Tile.EXITED_CHIP && !level.isCompleted()) {
System.out.println("failed level " + level.getLevelNumber() + " " + level.getTitle());
} else {
solved[i - 1] = true;
}
} catch (Exception exc) {
System.out.println("Error loading " + level.getLevelNumber() + " " + level.getTitle());
exc.printStackTrace();
}
}
return solved;
}
Solution getSolution(String solutionName, int level) {
try {
if (emulator.twsReader != null) {
return emulator.twsReader.readSolution(emulator.getLevel());
}
else {
byte[] fileBytes = Files.readAllBytes((new File(solutionName + level + ".json")).toPath());
return Solution.fromJSON(new String(fileBytes, UTF_8));
}
} catch (IOException e) {
return null;
}
}
@Test
void solveCHIPS() {
emulator.openLevelset(new File("./testData/sets/CHIPS.DAT"));
boolean[] solved = solveLevelset("./testData/tws/public_CHIPS.dac.tws");
boolean[] expectedSolved = new boolean[149];
Arrays.fill(expectedSolved, Boolean.TRUE);
assertArrayEquals(expectedSolved, solved);
}
@Test
void solveCCLP1() {
emulator.openLevelset(new File("./testData/sets/CCLP1.DAT"));
boolean[] solved = solveLevelset("./testData/tws/public_CCLP1.dac.tws");
boolean[] expectedSolved = new boolean[149];
Arrays.fill(expectedSolved, Boolean.TRUE);
assertArrayEquals(expectedSolved, solved);
}
@Test
void solveCCLP2() {
emulator.openLevelset(new File("./testData/sets/CCLP2.DAT"));
boolean[] solved = solveLevelset("./testData/tws/public_CCLP2.dac.tws");
boolean[] expectedSolved = new boolean[149];
Arrays.fill(expectedSolved, Boolean.TRUE);
assertArrayEquals(expectedSolved, solved);
}
@Test
void solveCCLP3() {
emulator.openLevelset(new File("./testData/sets/CCLP3.DAT"));
boolean[] solved = solveLevelset("testData/tws/public_CCLP3.dac.tws");
boolean[] expectedSolved = new boolean[149];
Arrays.fill(expectedSolved, Boolean.TRUE);
assertArrayEquals(expectedSolved, solved);
}
@Test
void solveCCLP4() {
emulator.openLevelset(new File("./testData/sets/CCLP4.DAT"));
boolean[] solved = solveLevelset("./testData/tws/public_CCLP4.dac.tws");
boolean[] expectedSolved = new boolean[149];
Arrays.fill(expectedSolved, Boolean.TRUE);
assertArrayEquals(expectedSolved, solved);
}
@Test
void solveCHIPSLynx() {
emulator.openLevelset(new File("./testData/sets/CHIPS-Lynx.DAT"));
boolean[] solved = solveLevelset("./testData/tws/public_CHIPS-lynx.dac.tws");
solved[144] = true; //"Thanks to...", not playable in Lynx, so we give it a free pass
boolean[] expectedSolved = new boolean[149];
Arrays.fill(expectedSolved, Boolean.TRUE);
assertArrayEquals(expectedSolved, solved);
}
@Test
void solveCCLP1Lynx() {
emulator.openLevelset(new File("./testData/sets/CCLP1-Lynx.DAT"));
boolean[] solved = solveLevelset("./testData/tws/public_CCLP1-lynx.dac.tws");
boolean[] expectedSolved = new boolean[149];
Arrays.fill(expectedSolved, Boolean.TRUE);
assertArrayEquals(expectedSolved, solved);
}
@Test
void solveCCLXP2() {
emulator.openLevelset(new File("./testData/sets/CCLXP2.DAT"));
boolean[] solved = solveLevelset("./testData/tws/public_CCLXP2.dac.tws");
boolean[] expectedSolved = new boolean[149];
Arrays.fill(expectedSolved, Boolean.TRUE);
assertArrayEquals(expectedSolved, solved);
}
@Test
void solveCCLP3Lynx() {
emulator.openLevelset(new File("./testData/sets/CCLP3-Lynx.DAT"));
boolean[] solved = solveLevelset("./testData/tws/public_CCLP3-lynx.dac.tws");
boolean[] expectedSolved = new boolean[149];
Arrays.fill(expectedSolved, Boolean.TRUE);
assertArrayEquals(expectedSolved, solved);
}
@Test
void solveCCLP4Lynx() {
emulator.openLevelset(new File("./testData/sets/CCLP4-Lynx.DAT"));
boolean[] solved = solveLevelset("./testData/tws/public_CCLP4-lynx.dac.tws");
boolean[] expectedSolved = new boolean[149];
Arrays.fill(expectedSolved, Boolean.TRUE);
assertArrayEquals(expectedSolved, solved);
}
@Test
void solveUnitTests() {
emulator.openLevelset(new File("./testData/sets/unitTest.DAT"));
boolean[] solved = solveLevelset("./testData/json/unitTest/unitTest");
boolean[] expectedSolved = new boolean[emulator.lastLevelNumber() - 1];
Arrays.fill(expectedSolved, Boolean.TRUE);
assertArrayEquals(expectedSolved, solved);
}
} | 6,348 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
TSPSolverTest.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/test/java/tools/tsp/TSPSolverTest.java | package tools.tsp;
import emulator.SuperCC;
import game.Tile;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import tools.TSPGUI;
import javax.swing.*;
import java.io.File;
import java.util.ArrayList;
import static org.junit.jupiter.api.Assertions.*;
class TSPSolverTest {
private final SuperCC emulator = new SuperCC(false);
private final TSPGUI tspgui = new TSPGUI(emulator, false);
private final JTextPane output = new JTextPane();
private final SimulatedAnnealingParameters simulatedAnnealingParameters = new SimulatedAnnealingParameters(100, 0.1, 0.9, 100);
private final ActingWallParameters actingWallParameters = new ActingWallParameters(false, false, false, false, false);
@BeforeEach
void setup() {
emulator.openLevelset(new File("testData/sets/TSPSolverTest.DAT"));
}
@Test
void simpleDistances() {
emulator.loadLevel(1);
ArrayList<TSPGUI.ListNode> inputNodes = tspgui.getAllChips();
ArrayList<TSPGUI.ListNode> exitNodes = tspgui.getAllExits();
ArrayList<TSPGUI.RestrictionNode> restrictionNodes = new ArrayList<>();
TSPSolver solver = new TSPSolver(emulator, tspgui, inputNodes, exitNodes, restrictionNodes,
simulatedAnnealingParameters, actingWallParameters, output);
solver.gatherNormal();
int[][] distances = solver.getDistances();
int[][] expectedDistances = {
{ 0, 8, 6, 2, 4 },
{ 8, 0, 14, 10, 12 },
{ 6, 14, 0, 8, 10 },
{ 2, 10, 8, 0, 6 },
{ 9999, 9999, 9999, 9999, 9999 },
};
assertArrayEquals(expectedDistances, distances);
}
@Test
void handlesIce() {
emulator.loadLevel(2);
ArrayList<TSPGUI.ListNode> inputNodes = tspgui.getAllChips();
ArrayList<TSPGUI.ListNode> exitNodes = tspgui.getAllExits();
ArrayList<TSPGUI.RestrictionNode> restrictionNodes = new ArrayList<>();
TSPSolver solver = new TSPSolver(emulator, tspgui, inputNodes, exitNodes, restrictionNodes,
simulatedAnnealingParameters, actingWallParameters, output);
solver.gatherNormal();
int[][] distances = solver.getDistances();
int[][] expectedDistances = {
{ 0, 26, 4 },
{ 26, 0, 30 },
{ 9999, 9999, 9999 }
};
assertArrayEquals(expectedDistances, distances);
}
@Test
void handlesForceFloor() {
emulator.loadLevel(3);
ArrayList<TSPGUI.ListNode> inputNodes = tspgui.getAllChips();
ArrayList<TSPGUI.ListNode> exitNodes = tspgui.getAllExits();
ArrayList<TSPGUI.RestrictionNode> restrictionNodes = new ArrayList<>();
TSPSolver solver = new TSPSolver(emulator, tspgui, inputNodes, exitNodes, restrictionNodes,
simulatedAnnealingParameters, actingWallParameters, output);
solver.gatherNormal();
int[][] distances = solver.getDistances();
int[][] expectedDistances = {
{ 0, 10, 6, 16, 22 },
{ 9999, 0, 9999, 6, 12 },
{ 9999, 4, 0, 10, 16 },
{ 9999, 9999, 9999, 0, 6 },
{ 9999, 9999, 9999, 9999, 9999 }
};
assertArrayEquals(expectedDistances, distances);
}
@Test
void handlesTeleports() {
emulator.loadLevel(4);
ArrayList<TSPGUI.ListNode> inputNodes = tspgui.getAllChips();
ArrayList<TSPGUI.ListNode> exitNodes = tspgui.getAllExits();
ArrayList<TSPGUI.RestrictionNode> restrictionNodes = new ArrayList<>();
TSPSolver solver = new TSPSolver(emulator, tspgui, inputNodes, exitNodes, restrictionNodes,
simulatedAnnealingParameters, actingWallParameters, output);
solver.gatherNormal();
int[][] distances = solver.getDistances();
int[][] expectedDistances = {
{ 0, 14, 12, 14 },
{ 12, 0, 12, 14 },
{ 14, 12, 0, 12 },
{ 9999, 9999, 9999, 9999 }
};
assertArrayEquals(expectedDistances, distances);
}
@Test
void handlesBoostingBetweenNodes() {
emulator.loadLevel(5);
ArrayList<TSPGUI.ListNode> inputNodes = tspgui.getAllChips();
ArrayList<TSPGUI.ListNode> exitNodes = tspgui.getAllExits();
ArrayList<TSPGUI.RestrictionNode> restrictionNodes = new ArrayList<>();
TSPSolver solver = new TSPSolver(emulator, tspgui, inputNodes, exitNodes, restrictionNodes,
simulatedAnnealingParameters, actingWallParameters, output);
solver.gatherNormal();
int[][] distances = solver.getDistances();
int[][] expectedDistances = {
{ 0, 18, 4 },
{ 18, 0, 22 },
{ 9999, 9999, 9999 }
};
assertArrayEquals(expectedDistances, distances);
}
@Test
void handlesCombined() {
emulator.loadLevel(6);
ArrayList<TSPGUI.ListNode> inputNodes = tspgui.getAllChips();
ArrayList<TSPGUI.ListNode> exitNodes = tspgui.getAllExits();
ArrayList<TSPGUI.RestrictionNode> restrictionNodes = new ArrayList<>();
TSPSolver solver = new TSPSolver(emulator, tspgui, inputNodes, exitNodes, restrictionNodes,
simulatedAnnealingParameters, actingWallParameters, output);
solver.gatherNormal();
int[][] distances = solver.getDistances();
int[][] expectedDistances = {
{ 0, 5, 6, 14 },
{ 8, 0, 11, 20 },
{ 10, 7, 0, 10 },
{ 9999, 9999, 9999, 9999 }
};
assertArrayEquals(expectedDistances, distances);
}
@Test
void handlesCombinedDistancesBoost() {
emulator.loadLevel(6);
ArrayList<TSPGUI.ListNode> inputNodes = tspgui.getAllChips();
ArrayList<TSPGUI.ListNode> exitNodes = tspgui.getAllExits();
ArrayList<TSPGUI.RestrictionNode> restrictionNodes = new ArrayList<>();
TSPSolver solver = new TSPSolver(emulator, tspgui, inputNodes, exitNodes, restrictionNodes,
simulatedAnnealingParameters, actingWallParameters, output);
solver.gatherBoost();
int[][] distancesBoost = solver.getDistancesBoost();
int[][] expectedDistancesBoost = {
{ 0, 4, 6, 15 },
{ 7, 0, 10, 19 },
{ 9, 6, 0, 9 },
{ 9999, 9999, 9999, 9999 }
};
assertArrayEquals(expectedDistancesBoost, distancesBoost);
}
@Test
void handlesMultipleExits() {
emulator.loadLevel(7);
ArrayList<TSPGUI.ListNode> inputNodes = tspgui.getAllChips();
ArrayList<TSPGUI.ListNode> exitNodes = tspgui.getAllExits();
ArrayList<TSPGUI.RestrictionNode> restrictionNodes = new ArrayList<>();
TSPSolver solver = new TSPSolver(emulator, tspgui, inputNodes, exitNodes, restrictionNodes,
simulatedAnnealingParameters, actingWallParameters, output);
solver.gatherNormal();
int[][] distances = solver.getDistances();
int[][] expectedDistances = {
{ 0, 4, 4, 4, 4, 8, 8, 8, 8 },
{ 4, 0, 4, 4, 8, 4, 8, 8, 12 },
{ 4, 4, 0, 8, 4, 8, 4, 12, 8 },
{ 4, 4, 8, 0, 4, 8, 12, 4, 8 },
{ 4, 8, 4, 4, 0, 12, 8, 8, 4 },
{ 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999 },
{ 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999 },
{ 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999 },
{ 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999 }
};
assertArrayEquals(expectedDistances, distances);
}
@Test
void coldFusionReactorDistances() {
emulator.loadLevel(8);
ArrayList<TSPGUI.ListNode> inputNodes = tspgui.getAllChips();
ArrayList<TSPGUI.ListNode> exitNodes = tspgui.getAllExits();
ArrayList<TSPGUI.RestrictionNode> restrictionNodes = new ArrayList<>();
TSPSolver solver = new TSPSolver(emulator, tspgui, inputNodes, exitNodes, restrictionNodes,
simulatedAnnealingParameters, actingWallParameters, output);
solver.gatherNormal();
int[][] distances = solver.getDistances();
int[][] expectedDistances = {
{ 0, 12, 14, 12, 12, 10, 12, 12, 8, 8, 6, 8, 4, 8, 7, 7, 7, 6, 8, 4, 10, 6, 8, 8, 14, 12, 12, 12, 14, 14, 12, 16, 18 },
{ 14, 0, 6, 7, 6, 6, 4, 12, 8, 10, 7, 12, 12, 14, 14, 14, 18, 16, 16, 16, 15, 16, 16, 13, 12, 12, 12, 12, 9, 10, 16, 12, 12 },
{ 15, 10, 0, 6, 8, 10, 6, 10, 10, 6, 12, 8, 12, 12, 10, 12, 18, 14, 18, 15, 14, 18, 16, 15, 14, 12, 14, 12, 10, 12, 16, 6, 12 },
{ 12, 6, 6, 0, 8, 6, 6, 8, 6, 9, 6, 10, 10, 12, 12, 14, 18, 14, 16, 16, 15, 14, 18, 13, 12, 14, 12, 12, 9, 12, 16, 10, 12 },
{ 11, 8, 8, 2, 0, 8, 6, 10, 7, 10, 8, 10, 7, 10, 10, 12, 14, 14, 14, 14, 13, 14, 14, 11, 10, 10, 10, 12, 10, 10, 14, 12, 10 },
{ 10, 8, 10, 6, 8, 0, 8, 10, 5, 8, 5, 10, 9, 10, 12, 12, 16, 14, 14, 13, 15, 16, 16, 13, 12, 12, 12, 14, 12, 12, 16, 10, 12 },
{ 13, 12, 6, 6, 6, 6, 0, 8, 8, 6, 7, 8, 9, 12, 11, 10, 16, 12, 12, 15, 16, 14, 18, 15, 14, 14, 14, 14, 12, 14, 18, 10, 14 },
{ 10, 12, 10, 8, 6, 8, 8, 0, 5, 8, 11, 6, 9, 10, 9, 12, 16, 10, 16, 13, 14, 16, 17, 17, 16, 16, 16, 18, 16, 16, 20, 14, 16 },
{ 6, 10, 8, 8, 8, 6, 6, 8, 0, 6, 8, 8, 4, 6, 8, 10, 12, 12, 14, 10, 16, 12, 14, 12, 16, 16, 16, 18, 15, 16, 18, 12, 16 },
{ 11, 10, 10, 8, 6, 10, 8, 8, 10, 0, 8, 4, 9, 8, 7, 6, 12, 10, 16, 11, 14, 14, 16, 17, 16, 14, 16, 16, 14, 14, 18, 12, 14 },
{ 13, 12, 12, 11, 10, 6, 10, 10, 9, 8, 0, 10, 8, 12, 9, 8, 12, 12, 10, 15, 16, 12, 16, 17, 16, 18, 16, 20, 17, 18, 20, 16, 18 },
{ 7, 12, 14, 8, 8, 10, 8, 6, 7, 9, 8, 0, 6, 4, 4, 9, 10, 8, 12, 7, 12, 10, 12, 14, 18, 14, 16, 15, 15, 16, 16, 16, 18 },
{ 5, 10, 10, 10, 8, 10, 8, 8, 8, 4, 6, 4, 0, 8, 8, 8, 10, 8, 10, 8, 12, 8, 14, 12, 16, 14, 14, 16, 14, 14, 14, 12, 14 },
{ 6, 10, 10, 10, 10, 10, 8, 10, 3, 8, 6, 8, 5, 0, 6, 7, 8, 8, 10, 7, 12, 12, 12, 14, 16, 16, 14, 15, 15, 16, 16, 12, 18 },
{ 6, 14, 14, 12, 10, 12, 10, 8, 7, 10, 8, 4, 6, 4, 0, 9, 8, 4, 10, 5, 8, 12, 10, 14, 16, 14, 14, 13, 15, 16, 16, 16, 18 },
{ 6, 14, 12, 11, 10, 12, 10, 10, 7, 8, 8, 4, 6, 4, 1, 0, 10, 4, 10, 7, 8, 12, 12, 14, 18, 14, 16, 15, 17, 16, 16, 16, 20 },
{ 8, 16, 14, 13, 12, 10, 12, 10, 9, 10, 8, 6, 8, 6, 3, 2, 0, 6, 10, 8, 6, 8, 10, 12, 12, 12, 16, 14, 16, 16, 14, 18, 20 },
{ 6, 14, 14, 12, 12, 14, 12, 10, 8, 12, 10, 6, 8, 6, 3, 9, 7, 0, 11, 4, 6, 10, 8, 12, 14, 12, 12, 12, 13, 16, 16, 16, 16 },
{ 11, 16, 16, 16, 14, 16, 14, 14, 12, 12, 12, 12, 12, 9, 9, 8, 8, 6, 0, 10, 9, 6, 10, 10, 8, 10, 8, 14, 10, 12, 12, 20, 14 },
{ 6, 14, 14, 15, 14, 12, 14, 14, 9, 10, 10, 10, 7, 8, 6, 5, 3, 7, 10, 0, 10, 6, 10, 10, 12, 14, 10, 9, 14, 16, 14, 16, 16 },
{ 6, 16, 16, 14, 16, 16, 16, 16, 11, 12, 12, 12, 9, 10, 9, 9, 7, 6, 9, 4, 0, 10, 4, 8, 12, 6, 10, 10, 10, 10, 14, 18, 14 },
{ 11, 18, 18, 16, 16, 14, 16, 14, 10, 14, 12, 10, 12, 7, 8, 12, 10, 5, 7, 9, 7, 0, 8, 8, 10, 10, 8, 12, 8, 12, 10, 20, 12 },
{ 10, 18, 18, 18, 16, 18, 18, 18, 13, 16, 14, 12, 13, 12, 11, 10, 9, 9, 8, 6, 8, 10, 0, 8, 10, 8, 10, 6, 6, 10, 10, 20, 10 },
{ 13, 22, 18, 18, 18, 18, 16, 16, 16, 14, 14, 14, 16, 14, 11, 14, 12, 8, 12, 10, 8, 10, 10, 0, 10, 11, 8, 6, 8, 12, 12, 22, 12 },
{ 12, 22, 20, 20, 18, 20, 18, 18, 15, 16, 14, 12, 15, 14, 11, 13, 11, 8, 13, 8, 8, 14, 8, 6, 0, 6, 10, 8, 8, 10, 12, 22, 8 },
{ 12, 22, 20, 20, 18, 20, 20, 20, 15, 18, 16, 16, 14, 14, 13, 13, 11, 10, 10, 8, 10, 10, 6, 8, 10, 0, 10, 8, 9, 4, 12, 22, 12 },
{ 14, 22, 22, 20, 18, 20, 18, 20, 16, 16, 16, 16, 16, 13, 13, 12, 12, 10, 8, 10, 9, 8, 11, 6, 6, 8, 0, 10, 6, 12, 8, 24, 10 },
{ 8, 20, 22, 18, 18, 18, 20, 20, 14, 16, 14, 14, 12, 15, 13, 13, 11, 10, 10, 8, 10, 8, 8, 6, 6, 8, 6, 0, 6, 10, 8, 24, 10 },
{ 11, 22, 22, 20, 20, 22, 22, 20, 17, 20, 16, 16, 16, 16, 13, 15, 13, 10, 12, 10, 8, 12, 10, 9, 8, 6, 10, 4, 0, 6, 8, 24, 4 },
{ 14, 24, 24, 22, 22, 22, 24, 22, 19, 22, 18, 16, 18, 16, 15, 14, 15, 14, 13, 12, 11, 14, 8, 8, 12, 6, 12, 8, 9, 0, 12, 26, 12 },
{ 14, 24, 24, 22, 22, 20, 22, 20, 19, 20, 18, 16, 17, 16, 14, 15, 13, 11, 14, 10, 10, 10, 9, 6, 6, 10, 8, 8, 8, 14, 0, 26, 10 },
{ 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999 },
{ 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999}
};
assertArrayEquals(expectedDistances, distances);
}
@Test
void coldFusionReactorDistancesBoost() {
emulator.loadLevel(8);
ArrayList<TSPGUI.ListNode> inputNodes = tspgui.getAllChips();
ArrayList<TSPGUI.ListNode> exitNodes = tspgui.getAllExits();
ArrayList<TSPGUI.RestrictionNode> restrictionNodes = new ArrayList<>();
TSPSolver solver = new TSPSolver(emulator, tspgui, inputNodes, exitNodes, restrictionNodes,
simulatedAnnealingParameters, actingWallParameters, output);
solver.gatherBoost();
int[][] distancesBoost = solver.getDistancesBoost();
int[][] expectedDistancesBoost = {
{ 0, 13, 13, 13, 11, 11, 13, 13, 8, 9, 7, 7, 5, 7, 8, 8, 6, 7, 9, 3, 9, 7, 9, 9, 15, 13, 13, 12, 13, 15, 11, 15, 17 },
{ 13, 0, 7, 7, 7, 5, 5, 13, 8, 11, 8, 13, 12, 13, 13, 15, 18, 16, 17, 15, 14, 17, 15, 14, 13, 11, 13, 11, 8, 9, 15, 13, 11 },
{ 14, 9, 0, 5, 7, 9, 5, 9, 10, 6, 11, 7, 13, 11, 11, 13, 17, 15, 17, 14, 13, 17, 15, 14, 13, 11, 13, 11, 9, 11, 15, 5, 11 },
{ 11, 5, 5, 0, 7, 7, 5, 9, 5, 9, 7, 11, 9, 11, 13, 13, 17, 15, 17, 15, 14, 15, 17, 14, 13, 13, 13, 11, 8, 11, 15, 11, 11 },
{ 10, 7, 7, 2, 0, 7, 5, 9, 6, 9, 8, 9, 6, 9, 9, 11, 13, 13, 13, 13, 14, 13, 15, 10, 9, 11, 9, 13, 10, 11, 15, 13, 11 },
{ 11, 7, 9, 6, 7, 0, 7, 11, 6, 8, 4, 9, 10, 11, 11, 11, 15, 14, 13, 14, 16, 15, 17, 12, 11, 13, 11, 15, 12, 13, 17, 9, 13 },
{ 12, 11, 5, 5, 5, 7, 0, 7, 7, 6, 6, 7, 8, 11, 10, 9, 15, 11, 13, 14, 15, 15, 17, 14, 13, 13, 13, 13, 11, 13, 17, 9, 13 },
{ 11, 11, 11, 8, 7, 7, 7, 0, 5, 7, 10, 5, 9, 9, 8, 13, 15, 9, 15, 12, 13, 15, 16, 16, 15, 15, 15, 17, 15, 15, 19, 15, 15 },
{ 5, 9, 7, 7, 7, 7, 5, 7, 0, 5, 8, 7, 4, 5, 9, 9, 12, 11, 13, 9, 15, 11, 13, 13, 17, 15, 17, 17, 14, 15, 17, 11, 15 },
{ 10, 9, 9, 9, 7, 9, 7, 7, 10, 0, 9, 3, 9, 7, 7, 7, 11, 11, 15, 10, 15, 13, 15, 17, 17, 13, 17, 15, 13, 13, 17, 11, 13 },
{ 12, 11, 11, 10, 9, 5, 9, 9, 8, 7, 0, 9, 7, 11, 8, 7, 11, 11, 9, 14, 15, 11, 15, 16, 15, 17, 15, 19, 16, 17, 19, 15, 17 },
{ 7, 13, 13, 9, 7, 9, 7, 5, 7, 8, 9, 0, 5, 5, 3, 10, 9, 7, 13, 6, 11, 11, 11, 13, 17, 15, 15, 14, 16, 17, 17, 15, 17 },
{ 4, 11, 9, 9, 9, 9, 7, 7, 7, 3, 5, 5, 0, 7, 7, 7, 9, 7, 9, 7, 11, 7, 13, 11, 15, 15, 13, 16, 15, 15, 13, 11, 15 },
{ 5, 11, 11, 11, 11, 9, 9, 11, 3, 9, 7, 9, 5, 0, 7, 8, 9, 9, 11, 6, 13, 11, 11, 13, 15, 15, 13, 14, 16, 17, 17, 13, 19 },
{ 5, 13, 13, 11, 11, 11, 11, 9, 6, 9, 7, 3, 5, 3, 0, 8, 9, 3, 9, 6, 9, 11, 11, 13, 17, 13, 15, 14, 16, 15, 15, 15, 19 },
{ 7, 15, 11, 10, 9, 13, 9, 9, 8, 7, 9, 5, 7, 5, 1, 0, 9, 5, 11, 6, 7, 11, 11, 15, 17, 13, 15, 14, 16, 17, 17, 15, 19 },
{ 9, 15, 13, 12, 11, 9, 11, 11, 10, 9, 7, 7, 9, 7, 3, 2, 0, 7, 11, 8, 7, 7, 11, 13, 13, 13, 15, 15, 15, 17, 15, 17, 19 },
{ 7, 15, 13, 11, 11, 13, 11, 9, 8, 11, 11, 5, 7, 7, 3, 9, 7, 0, 10, 4, 5, 11, 8, 11, 15, 11, 13, 11, 12, 15, 15, 15, 15 },
{ 10, 15, 15, 15, 13, 15, 13, 13, 11, 11, 11, 11, 11, 8, 8, 7, 9, 5, 0, 9, 9, 5, 9, 11, 9, 11, 7, 13, 11, 13, 13, 19, 15 },
{ 7, 13, 15, 15, 15, 13, 13, 13, 9, 11, 11, 9, 7, 9, 6, 5, 3, 6, 9, 0, 9, 7, 9, 9, 11, 13, 9, 8, 13, 15, 13, 17, 15 },
{ 5, 15, 15, 13, 15, 15, 15, 15, 10, 11, 11, 11, 8, 9, 8, 9, 7, 5, 8, 5, 0, 11, 3, 7, 11, 5, 11, 9, 9, 9, 13, 17, 13 },
{ 10, 17, 17, 15, 15, 13, 15, 13, 9, 13, 11, 9, 11, 6, 7, 11, 9, 4, 6, 8, 6, 0, 7, 7, 9, 9, 7, 11, 7, 11, 11, 19, 11 },
{ 9, 17, 17, 17, 15, 17, 17, 17, 12, 15, 13, 11, 12, 11, 10, 9, 8, 8, 7, 5, 7, 9, 0, 7, 9, 7, 9, 6, 7, 9, 9, 19, 9 },
{ 13, 21, 17, 17, 17, 17, 15, 15, 15, 13, 13, 13, 15, 13, 10, 13, 13, 7, 11, 11, 7, 11, 9, 0, 9, 11, 7, 7, 9, 11, 11, 21, 13 },
{ 13, 21, 19, 21, 19, 19, 19, 19, 14, 17, 15, 13, 14, 13, 12, 12, 10, 9, 13, 7, 9, 13, 8, 5, 0, 5, 9, 7, 7, 9, 11, 21, 7 },
{ 11, 21, 19, 19, 17, 19, 19, 19, 14, 17, 15, 15, 13, 13, 12, 12, 10, 9, 9, 7, 9, 9, 5, 9, 9, 0, 9, 7, 8, 3, 13, 21, 11 },
{ 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999 },
{ 8, 21, 21, 19, 17, 19, 19, 19, 14, 17, 13, 13, 13, 15, 14, 13, 12, 11, 10, 9, 9, 9, 7, 7, 5, 8, 5, 0, 5, 11, 9, 23, 9 },
{ 10, 23, 23, 19, 19, 21, 21, 19, 16, 19, 15, 15, 15, 15, 14, 15, 13, 11, 13, 11, 8, 11, 10, 8, 7, 7, 9, 3, 0, 7, 7, 25, 5 },
{ 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999 },
{ 13, 23, 23, 21, 21, 21, 21, 19, 18, 19, 17, 17, 16, 15, 14, 14, 12, 11, 13, 9, 9, 11, 8, 5, 7, 11, 7, 7, 9, 15, 0, 25, 9 },
{ 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999 },
{ 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999 }
};
assertArrayEquals(expectedDistancesBoost, distancesBoost);
}
@Test
void solveWithSimulatedAnnealing() {
emulator.loadLevel(1);
ArrayList<TSPGUI.ListNode> inputNodes = tspgui.getAllChips();
ArrayList<TSPGUI.ListNode> exitNodes = tspgui.getAllExits();
ArrayList<TSPGUI.RestrictionNode> restrictionNodes = new ArrayList<>();
TSPSolver solver = new TSPSolver(emulator, tspgui, inputNodes, exitNodes, restrictionNodes,
simulatedAnnealingParameters, actingWallParameters, output);
try {
solver.solve();
} catch (Exception e) {
fail();
}
assertTrue(emulator.getLevel().isCompleted());
}
@Test
void handleActingWalls() {
emulator.loadLevel(9);
ArrayList<TSPGUI.ListNode> inputNodes = tspgui.getAllChips();
ArrayList<TSPGUI.ListNode> exitNodes = tspgui.getAllExits();
ArrayList<TSPGUI.RestrictionNode> restrictionNodes = new ArrayList<>();
TSPSolver solver = new TSPSolver(emulator, tspgui, inputNodes, exitNodes, restrictionNodes,
simulatedAnnealingParameters, new ActingWallParameters(true, true, true, true, true), output);
solver.gatherNormal();
try {
solver.solve();
} catch (Exception e) {
fail();
}
int[][] distances = solver.getDistances();
int[][] expectedDistances = {
{0, 68},
{9999, 9999}
};
assertArrayEquals(expectedDistances, distances);
assertTrue(emulator.getLevel().isCompleted());
}
@Test
void solveStartingOnChip() {
emulator.loadLevel(10);
ArrayList<TSPGUI.ListNode> inputNodes = tspgui.getAllChips();
ArrayList<TSPGUI.ListNode> exitNodes = tspgui.getAllExits();
ArrayList<TSPGUI.RestrictionNode> restrictionNodes = new ArrayList<>();
TSPSolver solver = new TSPSolver(emulator, tspgui, inputNodes, exitNodes, restrictionNodes,
simulatedAnnealingParameters, actingWallParameters, output);
try {
solver.solve();
} catch (Exception e) {
fail();
}
int[][] distances = solver.getDistances();
assertEquals(4, distances[0][1]);
assertTrue(emulator.getLevel().isCompleted());
}
@Test
void solveStartingOnExit() {
emulator.loadLevel(11);
ArrayList<TSPGUI.ListNode> inputNodes = tspgui.getAllChips();
ArrayList<TSPGUI.ListNode> exitNodes = tspgui.getAllExits();
ArrayList<TSPGUI.RestrictionNode> restrictionNodes = new ArrayList<>();
TSPSolver solver = new TSPSolver(emulator, tspgui, inputNodes, exitNodes, restrictionNodes,
simulatedAnnealingParameters, actingWallParameters, output);
try {
solver.solve();
} catch (Exception e) {
fail();
}
int[][] distances = solver.getDistances();
assertEquals(12, distances[1][2]);
assertTrue(emulator.getLevel().isCompleted());
}
} | 21,910 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
TokenizerTest.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/test/java/tools/variation/TokenizerTest.java | package tools.variation;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class TokenizerTest {
private final Token SPACE = new Token(TokenType.SPACE, " ", null, 1);
@Test
void tokenizeStructural() {
String code = "[](){},;:";
Tokenizer tokenizer = new Tokenizer(code);
List<Token> tokens = tokenizer.getAllTokens();
List<Token> expectedTokens = Arrays.asList(
new Token(TokenType.LEFT_BRACKET, "[", null, 1),
new Token(TokenType.RIGHT_BRACKET, "]", null, 1),
new Token(TokenType.LEFT_PAREN, "(", null, 1),
new Token(TokenType.RIGHT_PAREN, ")", null, 1),
new Token(TokenType.LEFT_BRACE, "{", null, 1),
new Token(TokenType.RIGHT_BRACE, "}", null, 1),
new Token(TokenType.COMMA, ",", null, 1),
new Token(TokenType.SEMICOLON, ";", null, 1),
new Token(TokenType.COLON, ":", null, 1),
new Token(TokenType.EOF, "", null, 1)
);
assertEquals(expectedTokens, tokens);
}
@Test
void tokenizeWhitespace() {
String code = " \t\r\n";
Tokenizer tokenizer = new Tokenizer(code);
List<Token> tokens = tokenizer.getAllTokens();
List<Token> expectedTokens = Arrays.asList(
new Token(TokenType.SPACE, " ", null, 1),
new Token(TokenType.TAB, "\t", null, 1),
new Token(TokenType.CARRIAGE_RETURN, "\r", null, 1),
new Token(TokenType.NEW_LINE, "\n", null, 2),
new Token(TokenType.EOF, "", null, 2)
);
assertEquals(expectedTokens, tokens);
}
@Test
void tokenizeNumbers() {
String code = "3 234 12.345";
Tokenizer tokenizer = new Tokenizer(code);
List<Token> tokens = tokenizer.getAllTokens();
List<Token> expectedTokens = Arrays.asList(
new Token(TokenType.NUMBER, "3", 3.0, 1), SPACE,
new Token(TokenType.NUMBER, "234", 234.0, 1), SPACE,
new Token(TokenType.NUMBER, "12.345", 12.345, 1),
new Token(TokenType.EOF, "", null, 1)
);
assertEquals(expectedTokens, tokens);
}
@Test
void tokenizeMoves() {
String code = "r urdw 4h 12lr";
Tokenizer tokenizer = new Tokenizer(code);
List<Token> tokens = tokenizer.getAllTokens();
List<Token> expectedTokens = Arrays.asList(
new Token(TokenType.MOVE, "r", "r", 1), SPACE,
new Token(TokenType.MOVE, "urdw", "urdw", 1), SPACE,
new Token(TokenType.MOVE, "4h", "4h", 1), SPACE,
new Token(TokenType.MOVE, "12lr", "12lr", 1),
new Token(TokenType.EOF, "", null, 1)
);
assertEquals(expectedTokens, tokens);
}
@Test
void tokenizeOperators() {
String code = "var1=3.5 var1+=7+3 var1-=7-3 var1/=7/3 var1*=7*3 var1%=7%3 var1++ var1--";
Tokenizer tokenizer = new Tokenizer(code);
List<Token> tokens = tokenizer.getAllTokens();
List<Token> expectedTokens = Arrays.asList(
new Token(TokenType.IDENTIFIER, "var1", "var1", 1),
new Token(TokenType.EQUAL, "=", null, 1),
new Token(TokenType.NUMBER, "3.5", 3.5, 1), SPACE,
new Token(TokenType.IDENTIFIER, "var1", "var1", 1),
new Token(TokenType.PLUS_EQUAL, "+=", null, 1),
new Token(TokenType.NUMBER, "7", 7.0, 1),
new Token(TokenType.PLUS, "+", null, 1),
new Token(TokenType.NUMBER, "3", 3.0, 1), SPACE,
new Token(TokenType.IDENTIFIER, "var1", "var1", 1),
new Token(TokenType.MINUS_EQUAL, "-=", null, 1),
new Token(TokenType.NUMBER, "7", 7.0, 1),
new Token(TokenType.MINUS, "-", null, 1),
new Token(TokenType.NUMBER, "3", 3.0, 1), SPACE,
new Token(TokenType.IDENTIFIER, "var1", "var1", 1),
new Token(TokenType.SLASH_EQUAL, "/=", null, 1),
new Token(TokenType.NUMBER, "7", 7.0, 1),
new Token(TokenType.SLASH, "/", null, 1),
new Token(TokenType.NUMBER, "3", 3.0, 1), SPACE,
new Token(TokenType.IDENTIFIER, "var1", "var1", 1),
new Token(TokenType.STAR_EQUAL, "*=", null, 1),
new Token(TokenType.NUMBER, "7", 7.0, 1),
new Token(TokenType.STAR, "*", null, 1),
new Token(TokenType.NUMBER, "3", 3.0, 1), SPACE,
new Token(TokenType.IDENTIFIER, "var1", "var1", 1),
new Token(TokenType.MODULO_EQUAL, "%=", null, 1),
new Token(TokenType.NUMBER, "7", 7.0, 1),
new Token(TokenType.MODULO, "%", null, 1),
new Token(TokenType.NUMBER, "3", 3.0, 1), SPACE,
new Token(TokenType.IDENTIFIER, "var1", "var1", 1),
new Token(TokenType.PLUS_PLUS, "++", null, 1), SPACE,
new Token(TokenType.IDENTIFIER, "var1", "var1", 1),
new Token(TokenType.MINUS_MINUS, "--", null, 1),
new Token(TokenType.EOF, "", null, 1)
);
assertEquals(expectedTokens, tokens);
}
@Test
void tokenizeLogical() {
String code = "7>3 && 7>=3 || 3<7 & 3<=7 | 3!=7 ! 3==3";
Tokenizer tokenizer = new Tokenizer(code);
List<Token> tokens = tokenizer.getAllTokens();
List<Token> expectedTokens = Arrays.asList(
new Token(TokenType.NUMBER, "7", 7.0, 1),
new Token(TokenType.GREATER, ">", null, 1),
new Token(TokenType.NUMBER, "3", 3.0, 1), SPACE,
new Token(TokenType.AND_AND, "&&", null, 1), SPACE,
new Token(TokenType.NUMBER, "7", 7.0, 1),
new Token(TokenType.GREATER_EQUAL, ">=", null, 1),
new Token(TokenType.NUMBER, "3", 3.0, 1), SPACE,
new Token(TokenType.OR_OR, "||", null, 1), SPACE,
new Token(TokenType.NUMBER, "3", 3.0, 1),
new Token(TokenType.LESS, "<", null, 1),
new Token(TokenType.NUMBER, "7", 7.0, 1), SPACE,
new Token(TokenType.OTHER, "&", null, 1), SPACE,
new Token(TokenType.NUMBER, "3", 3.0, 1),
new Token(TokenType.LESS_EQUAL, "<=", null, 1),
new Token(TokenType.NUMBER, "7", 7.0, 1), SPACE,
new Token(TokenType.OTHER, "|", null, 1), SPACE,
new Token(TokenType.NUMBER, "3", 3.0, 1),
new Token(TokenType.BANG_EQUAL, "!=", null, 1),
new Token(TokenType.NUMBER, "7", 7.0, 1), SPACE,
new Token(TokenType.BANG, "!", null, 1), SPACE,
new Token(TokenType.NUMBER, "3", 3.0, 1),
new Token(TokenType.EQUAL_EQUAL, "==", null, 1),
new Token(TokenType.NUMBER, "3", 3.0, 1),
new Token(TokenType.EOF, "", null, 1)
);
assertEquals(expectedTokens, tokens);
}
@Test
void tokenizeOther() {
String code = "?";
Tokenizer tokenizer = new Tokenizer(code);
List<Token> tokens = tokenizer.getAllTokens();
List<Token> expectedTokens = Arrays.asList(
new Token(TokenType.OTHER, "?", null, 1),
new Token(TokenType.EOF, "", null, 1)
);
assertEquals(expectedTokens, tokens);
}
@Test
void tokenizeCodeSample() {
String code = "all;\n" +
"[3ud](3){afterMove:{if(getForegroundTile(1,1)==DIRT)terminate;}}\n" +
"// Finishing\n" +
"move(4u,3r);";
Tokenizer tokenizer = new Tokenizer(code);
List<Token> tokens = tokenizer.getAllTokens();
List<Token> expectedTokens = Arrays.asList(
new Token(TokenType.ALL, "all", null, 1),
new Token(TokenType.SEMICOLON, ";", null, 1),
new Token(TokenType.NEW_LINE, "\n", null, 2),
new Token(TokenType.LEFT_BRACKET, "[", null, 2),
new Token(TokenType.MOVE, "3ud", "3ud", 2),
new Token(TokenType.RIGHT_BRACKET, "]", null, 2),
new Token(TokenType.LEFT_PAREN, "(", null, 2),
new Token(TokenType.NUMBER, "3", 3.0, 2),
new Token(TokenType.RIGHT_PAREN, ")", null, 2),
new Token(TokenType.LEFT_BRACE, "{", null, 2),
new Token(TokenType.AFTER_MOVE, "afterMove", null, 2),
new Token(TokenType.COLON, ":", null, 2),
new Token(TokenType.LEFT_BRACE, "{", null, 2),
new Token(TokenType.IF, "if", null, 2),
new Token(TokenType.LEFT_PAREN, "(", null, 2),
new Token(TokenType.FUNCTION, "getForegroundTile", null, 2),
new Token(TokenType.LEFT_PAREN, "(", null, 2),
new Token(TokenType.NUMBER, "1", 1.0, 2),
new Token(TokenType.COMMA, ",", null, 2),
new Token(TokenType.NUMBER, "1", 1.0, 2),
new Token(TokenType.RIGHT_PAREN, ")", null, 2),
new Token(TokenType.EQUAL_EQUAL, "==", null, 2),
new Token(TokenType.TILE, "DIRT", "DIRT", 2),
new Token(TokenType.RIGHT_PAREN, ")", null, 2),
new Token(TokenType.TERMINATE, "terminate", null, 2),
new Token(TokenType.SEMICOLON, ";", null, 2),
new Token(TokenType.RIGHT_BRACE, "}", null, 2),
new Token(TokenType.RIGHT_BRACE, "}", null, 2),
new Token(TokenType.NEW_LINE, "\n", null, 3),
new Token(TokenType.COMMENT, "// Finishing", null, 3),
new Token(TokenType.NEW_LINE, "\n", null, 4),
new Token(TokenType.FUNCTION, "move", null, 4),
new Token(TokenType.LEFT_PAREN, "(", null, 4),
new Token(TokenType.MOVE, "4u", "4u", 4),
new Token(TokenType.COMMA, ",", null, 4),
new Token(TokenType.MOVE, "3r", "3r", 4),
new Token(TokenType.RIGHT_PAREN, ")", null, 4),
new Token(TokenType.SEMICOLON, ";", null, 4),
new Token(TokenType.EOF, "", null, 4)
);
assertEquals(expectedTokens, tokens);
}
@Test
void prepareForInterpreter() {
String code = "var x = 1 // Init\n" +
"x+=1 var y = 2 z = 3";
Tokenizer tokenizer = new Tokenizer(code);
ArrayList<Token> tokens = tokenizer.getParsableTokens();
HashMap<String, Object> variables = tokenizer.getVariables();
List<Token> expectedTokens = Arrays.asList(
new Token(TokenType.IDENTIFIER, "x", "x", 1),
new Token(TokenType.EQUAL, "=", null, 1),
new Token(TokenType.NUMBER, "1", 1.0, 1),
new Token(TokenType.IDENTIFIER, "x", "x", 2),
new Token(TokenType.PLUS_EQUAL, "+=", null, 2),
new Token(TokenType.NUMBER, "1", 1.0, 2),
new Token(TokenType.IDENTIFIER, "y", "y", 2),
new Token(TokenType.EQUAL, "=", null, 2),
new Token(TokenType.NUMBER, "2", 2.0, 2),
new Token(TokenType.IDENTIFIER, "z", "z", 2),
new Token(TokenType.EQUAL, "=", null, 2),
new Token(TokenType.NUMBER, "3", 3.0, 2),
new Token(TokenType.EOF, "", null, 2)
);
HashMap<String, Object> expectedVariables = new HashMap<>();
expectedVariables.put("x", null);
expectedVariables.put("y", null);
assertEquals(expectedTokens, tokens);
assertEquals(expectedVariables, variables);
}
} | 11,977 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
MovePoolTest.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/test/java/tools/variation/MovePoolTest.java | package tools.variation;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import static org.junit.jupiter.api.Assertions.*;
class MovePoolTest {
@Test
void addSingleMove() {
MovePool movePool = new MovePool();
movePool.add(new Move("4ud"));
HashMap<String, Integer> moves = movePool.moves;
HashMap<String, Integer> expectedMoves = new HashMap<>();
expectedMoves.put("ud", 4);
assertEquals(4, movePool.size);
assertEquals(expectedMoves, moves);
}
@Test
void addMultipleMoves() {
MovePool movePool = new MovePool();
movePool.add(new Move("r"));
movePool.add(new Move("2d"));
movePool.add(new Move("3r"));
movePool.add(new Move("4dd"));
HashMap<String, Integer> moves = movePool.moves;
HashMap<String, Integer> expectedMoves = new HashMap<>();
expectedMoves.put("r", 4);
expectedMoves.put("d", 2);
expectedMoves.put("dd", 4);
assertEquals(10, movePool.size);
assertEquals(expectedMoves, moves);
}
@Test
void addMovePool() {
MovePool otherMovePool = new MovePool();
otherMovePool.add(new Move("2ud"));
otherMovePool.add(new Move("3w"));
MovePool movePool = new MovePool();
movePool.add(new Move("4ud"));
movePool.add(otherMovePool);
HashMap<String, Integer> moves = movePool.moves;
HashMap<String, Integer> expectedMoves = new HashMap<>();
expectedMoves.put("ud", 6);
expectedMoves.put("w", 3);
assertEquals(9, movePool.size);
assertEquals(expectedMoves, moves);
}
} | 1,673 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
ParserTest.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/test/java/tools/variation/ParserTest.java | package tools.variation;
import game.Tile;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class ParserTest {
@Test
void parseBlockStatement() {
String code = "{1; 2;}";
Parser parser = new Parser();
List<Stmt> statements = parser.parseCode(code);
List<Stmt> expectedStatements = Arrays.asList(
new Stmt.Block(new ArrayList<>(Arrays.asList(
new Stmt.Expression(new Expr.Literal(1.0)),
new Stmt.Expression(new Expr.Literal(2.0))
)))
);
assertEquals(expectedStatements, statements);
}
@Test
void parseIfStatement() {
String code = "if(1) 2; else if(3) 4; else 5;";
Parser parser = new Parser();
List<Stmt> statements = parser.parseCode(code);
List<Stmt> expectedStatements = Arrays.asList(
new Stmt.If(
new Expr.Literal(1.0),
new Stmt.Expression(new Expr.Literal(2.0)),
new Stmt.If(
new Expr.Literal(3.0),
new Stmt.Expression(new Expr.Literal(4.0)),
new Stmt.Expression(new Expr.Literal(5.0))
)
)
);
assertEquals(expectedStatements, statements);
}
@Test
void parseForStatement() {
String code = "for(1; 2; 3) 4;";
Parser parser = new Parser();
List<Stmt> statements = parser.parseCode(code);
List<Stmt> expectedStatements = Arrays.asList(
new Stmt.For(
new Stmt.Expression(new Expr.Literal(1.0)),
new Expr.Literal(2.0),
new Stmt.Expression(new Expr.Literal(3.0)),
new Stmt.Expression(new Expr.Literal(4.0))
)
);
assertEquals(expectedStatements, statements);
}
@Test
void parseForStatementWithOnlyCondition() {
String code = "for(;1;) 2;";
Parser parser = new Parser();
List<Stmt> statements = parser.parseCode(code);
assertFalse(parser.hadError);
}
@Test
void parseForStatementEmpty() {
String code = "for(;;) 1;";
Parser parser = new Parser();
List<Stmt> statements = parser.parseCode(code);
assertFalse(parser.hadError);
}
@Test
void parsePrintStatement() {
String code = "print 1;";
Parser parser = new Parser();
List<Stmt> statements = parser.parseCode(code);
List<Stmt> expectedStatements = Arrays.asList(
new Stmt.Print(new Expr.Literal(1.0))
);
assertEquals(expectedStatements, statements);
}
@Test
void parseSequenceStatement() {
String code = "[d][u](1,2){order udrlwh; start: 3; beforeMove: 4; afterMove: 5; beforeStep: 6; afterStep: 7; end: 8;}";
Parser parser = new Parser();
List<Stmt> statements = parser.parseCode(code);
MovePoolContainer movePools = new MovePoolContainer();
movePools.optional.add(new Move("u"));
movePools.forced.add(new Move("d"));
BoundLimit limits = new BoundLimit(1, 2);
SequenceLifecycle lifecycle = new SequenceLifecycle();
lifecycle.start = new Stmt.Expression(new Expr.Literal(3.0));
lifecycle.beforeMove = new Stmt.Expression(new Expr.Literal(4.0));
lifecycle.afterMove = new Stmt.Expression(new Expr.Literal(5.0));
lifecycle.beforeStep = new Stmt.Expression(new Expr.Literal(6.0));
lifecycle.afterStep = new Stmt.Expression(new Expr.Literal(7.0));
lifecycle.end = new Stmt.Expression(new Expr.Literal(8.0));
List<Stmt> expectedStatements = Arrays.asList(
new Stmt.Sequence(movePools, limits, "udrlwh", lifecycle)
);
assertEquals(expectedStatements, statements);
}
@Test
void parseSequenceStatementOneBound() {
String code = "[d][u](1){}";
Parser parser = new Parser();
List<Stmt> statements = parser.parseCode(code);
MovePoolContainer movePools = new MovePoolContainer();
movePools.optional.add(new Move("u"));
movePools.forced.add(new Move("d"));
BoundLimit limits = new BoundLimit(1, null);
List<Stmt> expectedStatements = Arrays.asList(
new Stmt.Sequence(movePools, limits, "", new SequenceLifecycle())
);
assertEquals(expectedStatements, statements);
}
@Test
void parseEmptyStatement() {
String code = ";";
Parser parser = new Parser();
List<Stmt> statements = parser.parseCode(code);
List<Stmt> expectedStatements = Arrays.asList(
new Stmt.Empty()
);
assertEquals(expectedStatements, statements);
}
@Test
void parseBreakStatement() {
String code = "break;";
Parser parser = new Parser();
List<Stmt> statements = parser.parseCode(code);
List<Stmt> expectedStatements = Arrays.asList(
new Stmt.Break()
);
assertEquals(expectedStatements, statements);
}
@Test
void parseReturnStatement() {
String code = "return;";
Parser parser = new Parser();
List<Stmt> statements = parser.parseCode(code);
List<Stmt> expectedStatements = Arrays.asList(
new Stmt.Return()
);
assertEquals(expectedStatements, statements);
}
@Test
void parseTerminateStatement() {
String code = "terminate 1;";
Parser parser = new Parser();
List<Stmt> statements = parser.parseCode(code);
List<Stmt> expectedStatements = Arrays.asList(
new Stmt.Terminate(new Expr.Literal(1.0))
);
assertEquals(expectedStatements, statements);
}
@Test
void parseContinueStatement() {
String code = "continue;";
Parser parser = new Parser();
List<Stmt> statements = parser.parseCode(code);
List<Stmt> expectedStatements = Arrays.asList(
new Stmt.Continue()
);
assertEquals(expectedStatements, statements);
}
@Test
void parseAllStatement() {
String code = "all 1;";
Parser parser = new Parser();
List<Stmt> statements = parser.parseCode(code);
List<Stmt> expectedStatements = Arrays.asList(
new Stmt.All(new Expr.Literal(1.0))
);
assertEquals(expectedStatements, statements);
}
@Test
void parseExpressionStatements() {
String code = "null; true; false; 3.7; 2du; var1; DIRT; (d);";
Parser parser = new Parser();
List<Stmt> statements = parser.parseCode(code);
List<Stmt> expectedStatements = Arrays.asList(
new Stmt.Expression(new Expr.Literal(null)),
new Stmt.Expression(new Expr.Literal(true)),
new Stmt.Expression(new Expr.Literal(false)),
new Stmt.Expression(new Expr.Literal(3.7)),
new Stmt.Expression(new Expr.Literal(new Move("2du"))),
new Stmt.Expression(new Expr.Variable(new Token(TokenType.IDENTIFIER, "var1", "var1", 1))),
new Stmt.Expression(new Expr.Literal(Tile.valueOf("DIRT"))),
new Stmt.Expression(new Expr.Group(new Expr.Literal(new Move("d"))))
);
assertEquals(expectedStatements, statements);
}
@Test
void parseLogicalWithPrecedence() {
String code = "if(7>3 && 7>=3 || 3<7 and 3<=7 or 3!=7 and !(3==7)) 1;";
Parser parser = new Parser();
List<Stmt> statements = parser.parseCode(code);
List<Stmt> expectedStatements = Arrays.asList(
new Stmt.If(
new Expr.Logical(
new Expr.Logical(
new Expr.Logical(
new Expr.Binary(
new Expr.Literal(7.0),
new Token(TokenType.GREATER, ">", null, 1),
new Expr.Literal(3.0)
),
new Token(TokenType.AND_AND, "&&", null, 1),
new Expr.Binary(
new Expr.Literal(7.0),
new Token(TokenType.GREATER_EQUAL, ">=", null, 1),
new Expr.Literal(3.0)
)
),
new Token(TokenType.OR_OR, "||", null, 1),
new Expr.Logical(
new Expr.Binary(
new Expr.Literal(3.0),
new Token(TokenType.LESS, "<", null, 1),
new Expr.Literal(7.0)
),
new Token(TokenType.AND, "and", null, 1),
new Expr.Binary(
new Expr.Literal(3.0),
new Token(TokenType.LESS_EQUAL, "<=", null, 1),
new Expr.Literal(7.0)
)
)
),
new Token(TokenType.OR, "or", null, 1),
new Expr.Logical(
new Expr.Binary(
new Expr.Literal(3.0),
new Token(TokenType.BANG_EQUAL, "!=", null, 1),
new Expr.Literal(7.0)
),
new Token(TokenType.AND, "and", null, 1),
new Expr.Unary(
new Token(TokenType.BANG, "!", null, 1),
new Expr.Group(new Expr.Binary(
new Expr.Literal(3.0),
new Token(TokenType.EQUAL_EQUAL, "==", null, 1),
new Expr.Literal(7.0)
))
)
)
),
new Stmt.Expression(new Expr.Literal(1.0)),
new Stmt.Empty()
)
);
assertEquals(expectedStatements, statements);
}
@Test
void parseArithmeticWithPrecedence() {
String code = "1 + 2 - 3 * 4 / 5 % 6;";
Parser parser = new Parser();
List<Stmt> statements = parser.parseCode(code);
List<Stmt> expectedStatements = Arrays.asList(
new Stmt.Expression(
new Expr.Binary(
new Expr.Binary(
new Expr.Literal(1.0),
new Token(TokenType.PLUS, "+", null, 1),
new Expr.Literal(2.0)
),
new Token(TokenType.MINUS, "-", null, 1),
new Expr.Binary(
new Expr.Binary(
new Expr.Binary(
new Expr.Literal(3.0),
new Token(TokenType.STAR, "*", null, 1),
new Expr.Literal(4.0)
),
new Token(TokenType.SLASH, "/", null, 1),
new Expr.Literal(5.0)
),
new Token(TokenType.MODULO, "%", null, 1),
new Expr.Literal(6.0)
)
)
)
);
assertEquals(expectedStatements, statements);
}
@Test
void parseAssignments() {
String code = "var1 = 1; var2 += 2; var3 -= 3; var4 *= 4; var5 /= 5; var6 %= 6;";
Parser parser = new Parser();
List<Stmt> statements = parser.parseCode(code);
List<Stmt> expectedStatements = Arrays.asList(
new Stmt.Expression(new Expr.Assign(
new Token(TokenType.IDENTIFIER, "var1", "var1", 1),
new Token(TokenType.EQUAL, "=", null, 1),
new Expr.Literal(1.0)
)),
new Stmt.Expression(new Expr.Assign(
new Token(TokenType.IDENTIFIER, "var2", "var2", 1),
new Token(TokenType.PLUS_EQUAL, "+=", null, 1),
new Expr.Literal(2.0)
)),
new Stmt.Expression(new Expr.Assign(
new Token(TokenType.IDENTIFIER, "var3", "var3", 1),
new Token(TokenType.MINUS_EQUAL, "-=", null, 1),
new Expr.Literal(3.0)
)),
new Stmt.Expression(new Expr.Assign(
new Token(TokenType.IDENTIFIER, "var4", "var4", 1),
new Token(TokenType.STAR_EQUAL, "*=", null, 1),
new Expr.Literal(4.0)
)),
new Stmt.Expression(new Expr.Assign(
new Token(TokenType.IDENTIFIER, "var5", "var5", 1),
new Token(TokenType.SLASH_EQUAL, "/=", null, 1),
new Expr.Literal(5.0)
)),
new Stmt.Expression(new Expr.Assign(
new Token(TokenType.IDENTIFIER, "var6", "var6", 1),
new Token(TokenType.MODULO_EQUAL, "%=", null, 1),
new Expr.Literal(6.0)
))
);
assertEquals(expectedStatements, statements);
}
@Test
void parseFunction() {
String code = "move(2u, 4ud, w);";
Parser parser = new Parser();
List<Stmt> statements = parser.parseCode(code);
List<Stmt> expectedStatements = Arrays.asList(
new Stmt.Expression(new Expr.Function(
"move",
new ArrayList<Expr>(Arrays.asList(
new Expr.Literal(new Move("2u")),
new Expr.Literal(new Move("4ud")),
new Expr.Literal(new Move("w"))
)),
new Token(TokenType.FUNCTION, "move", null, 1)
))
);
assertEquals(expectedStatements, statements);
}
@Test
void syntaxErrorMissingSemicolon() {
String code = "1";
Parser parser = new Parser();
List<Stmt> statements = parser.parseCode(code);
assertTrue(parser.hadError);
}
@Test
void syntaxErrorTooShortLexicographic() {
String code = "[u](){order udlr;}";
Parser parser = new Parser();
List<Stmt> statements = parser.parseCode(code);
assertTrue(parser.hadError);
}
@Test
void syntaxErrorInvalidLexicographic() {
String code = "[u](){order udlriw;}";
Parser parser = new Parser();
List<Stmt> statements = parser.parseCode(code);
assertTrue(parser.hadError);
}
@Test
void syntaxErrorNoMoves() {
String code = "[](){}";
Parser parser = new Parser();
List<Stmt> statements = parser.parseCode(code);
assertTrue(parser.hadError);
}
@Test
void syntaxErrorInvalidAssignment() {
String code = "1 = 2";
Parser parser = new Parser();
List<Stmt> statements = parser.parseCode(code);
assertTrue(parser.hadError);
}
@Test
void syntaxErrorSynchronization() {
String code = "1 = 2; 3;";
Parser parser = new Parser();
List<Stmt> statements = parser.parseCode(code);
assertTrue(parser.hadError);
assertNull(statements.get(0));
assertEquals(2, statements.size());
}
@Test
void syntaxErrorSequenceOnlyInTopLevel() {
String code = "if(1) [u](){}";
Parser parser = new Parser();
List<Stmt> statements = parser.parseCode(code);
assertTrue(parser.hadError);
}
@Test
void syntaxErrorExpectedExpression() {
String code = "if(if(1)) 2;";
Parser parser = new Parser();
List<Stmt> statements = parser.parseCode(code);
assertTrue(parser.hadError);
}
} | 17,727 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
PermutationTest.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/test/java/tools/variation/PermutationTest.java | package tools.variation;
import org.junit.jupiter.api.Test;
import util.CharList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
class PermutationTest {
@Test
void boundWhenBothBoundsNull() {
MovePoolContainer movePools = new MovePoolContainer();
movePools.optional.add(new Move("5u"));
Permutation permutation = new Permutation(movePools, new BoundLimit(), "urdlwh");
assertEquals(5, permutation.limits.lower);
assertEquals(5, permutation.limits.upper);
}
@Test
void boundWhenUpperBoundNull() {
MovePoolContainer movePools = new MovePoolContainer();
movePools.optional.add(new Move("5u"));
Permutation permutation = new Permutation(movePools, new BoundLimit(4), "urdlwh");
assertEquals(4, permutation.limits.lower);
assertEquals(4, permutation.limits.upper);
}
@Test
void boundSwap() {
MovePoolContainer movePools = new MovePoolContainer();
movePools.optional.add(new Move("5u"));
Permutation permutation = new Permutation(movePools, new BoundLimit(5, 3), "urdlwh");
assertEquals(3, permutation.limits.lower);
assertEquals(5, permutation.limits.upper);
}
@Test
void boundClip() {
MovePoolContainer movePools = new MovePoolContainer();
movePools.optional.add(new Move("5u"));
Permutation permutation = new Permutation(movePools, new BoundLimit(6, 7), "urdlwh");
assertEquals(5, permutation.limits.lower);
assertEquals(5, permutation.limits.upper);
}
@Test
void boundClipForced() {
MovePoolContainer movePools = new MovePoolContainer();
movePools.optional.add(new Move("5u"));
movePools.forced.add(new Move("3d"));
Permutation permutation = new Permutation(movePools, new BoundLimit(1, 2), "urdlwh");
assertEquals(3, permutation.limits.lower);
assertEquals(3, permutation.limits.upper);
}
@Test
void initialPermutation() {
MovePoolContainer movePools = new MovePoolContainer();
movePools.optional.add(new Move("r"));
movePools.optional.add(new Move("2u"));
movePools.optional.add(new Move("3du"));
Permutation permutation = new Permutation(movePools, new BoundLimit(6), "urdlwh");
int[] permutationRaw = permutation.getRawPermutation();
int[] expectedPermutationRaw = {0, 0, 1, 2, 2, 2};
assertArrayEquals(expectedPermutationRaw, permutationRaw);
}
@Test
void initialPermutationForced() {
MovePoolContainer movePools = new MovePoolContainer();
movePools.optional.add(new Move("r"));
movePools.optional.add(new Move("2u"));
movePools.optional.add(new Move("3du"));
movePools.forced.add(new Move("4lr"));
Permutation permutation = new Permutation(movePools, new BoundLimit(8, 10), "urdlwh");
int[] permutationRaw = permutation.getRawPermutation();
int[] expectedPermutationRaw = {0, 0, 1, 2, 3, 3, 3, 3};
assertArrayEquals(expectedPermutationRaw, permutationRaw);
}
@Test
void nextPermutation() {
MovePoolContainer movePools = new MovePoolContainer();
movePools.optional.add(new Move("r"));
movePools.optional.add(new Move("2u"));
movePools.optional.add(new Move("3du"));
Permutation permutation = new Permutation(movePools, new BoundLimit(6), "urdlwh");
permutation.nextPermutation();
int[] permutationRaw = permutation.getRawPermutation();
int[] expectedPermutationRaw = {0, 0, 2, 1, 2, 2};
assertArrayEquals(expectedPermutationRaw, permutationRaw);
}
@Test
void permutationCount() {
MovePoolContainer movePools = new MovePoolContainer();
movePools.optional.add(new Move("r"));
movePools.optional.add(new Move("2u"));
movePools.optional.add(new Move("3du"));
Permutation permutation = new Permutation(movePools, new BoundLimit(5, 6), "urdlwh");
assertEquals(120, permutation.permutationCount);
}
@Test
void permutationCountForced() {
MovePoolContainer movePools = new MovePoolContainer();
movePools.optional.add(new Move("r"));
movePools.optional.add(new Move("2u"));
movePools.forced.add(new Move("3du"));
Permutation permutation = new Permutation(movePools, new BoundLimit(5, 6), "urdlwh");
assertEquals(90, permutation.permutationValidCount);
}
@Test
void reset() {
MovePoolContainer movePools = new MovePoolContainer();
movePools.optional.add(new Move("5u"));
Permutation permutation = new Permutation(movePools, new BoundLimit(4, 5), "urdlwh");
permutation.nextPermutation();
permutation.reset();
int[] permutationRaw = permutation.getRawPermutation();
int[] expectedPermutationRaw = {0, 0, 0, 0};
assertArrayEquals(expectedPermutationRaw, permutationRaw);
}
@Test
void terminate() {
MovePoolContainer movePools = new MovePoolContainer();
movePools.optional.add(new Move("r"));
movePools.optional.add(new Move("2u"));
movePools.optional.add(new Move("3du"));
Permutation permutation = new Permutation(movePools, new BoundLimit(6), "urdlwh");
permutation.terminate(0);
int[] permutationRaw = permutation.getRawPermutation();
int[] expectedPermutationRaw = {0, 2, 2, 2, 1, 0};
assertArrayEquals(expectedPermutationRaw, permutationRaw);
}
@Test
void end() {
MovePoolContainer movePools = new MovePoolContainer();
movePools.optional.add(new Move("r"));
movePools.optional.add(new Move("2u"));
movePools.optional.add(new Move("3du"));
Permutation permutation = new Permutation(movePools, new BoundLimit(6), "urdlwh");
permutation.end();
int[] permutationRaw = permutation.getRawPermutation();
int[] expectedPermutationRaw = {2, 2, 2, 1, 0, 0};
assertArrayEquals(expectedPermutationRaw, permutationRaw);
}
@Test
void getPermutation() {
MovePoolContainer movePools = new MovePoolContainer();
movePools.optional.add(new Move("r"));
movePools.optional.add(new Move("2u"));
movePools.optional.add(new Move("3du"));
Permutation permutation = new Permutation(movePools, new BoundLimit(6), "urdlwh");
List<CharList> charList = Arrays.asList(permutation.getPermutation());
List<String> moveStrings = charList.stream()
.map(list -> list.toString())
.collect(Collectors.toList());
List<String> expectedMoveStrings = Arrays.asList("u", "u", "r", "du", "du", "du");
assertEquals(expectedMoveStrings, moveStrings);
}
@Test
void allPermutationsSingleSubset() {
MovePoolContainer movePools = new MovePoolContainer();
movePools.optional.add(new Move("u"));
movePools.optional.add(new Move("2r"));
movePools.optional.add(new Move("d"));
Permutation permutation = new Permutation(movePools, new BoundLimit(4), "urdlwh");
int[] permutationRaw = permutation.getRawPermutation();
List<List<Integer>> result = new ArrayList<>();
while(!permutation.finished) {
result.add(Arrays.stream(permutationRaw).boxed().collect(Collectors.toList()));
permutation.nextPermutation();
}
List<List<Integer>> exprectedResult = new ArrayList<>();
exprectedResult.add(Arrays.asList(0, 1, 1, 2));
exprectedResult.add(Arrays.asList(0, 1, 2, 1));
exprectedResult.add(Arrays.asList(0, 2, 1, 1));
exprectedResult.add(Arrays.asList(1, 0, 1, 2));
exprectedResult.add(Arrays.asList(1, 0, 2, 1));
exprectedResult.add(Arrays.asList(1, 1, 0, 2));
exprectedResult.add(Arrays.asList(1, 1, 2, 0));
exprectedResult.add(Arrays.asList(1, 2, 0, 1));
exprectedResult.add(Arrays.asList(1, 2, 1, 0));
exprectedResult.add(Arrays.asList(2, 0, 1, 1));
exprectedResult.add(Arrays.asList(2, 1, 0, 1));
exprectedResult.add(Arrays.asList(2, 1, 1, 0));
assertEquals(exprectedResult, result);
}
@Test
void allPermutationsMultipleSubsets() {
MovePoolContainer movePools = new MovePoolContainer();
movePools.optional.add(new Move("u"));
movePools.optional.add(new Move("2r"));
movePools.optional.add(new Move("d"));
Permutation permutation = new Permutation(movePools, new BoundLimit(2, 3), "urdlwh");
List<List<Integer>> result = new ArrayList<>();
while(!permutation.finished) {
int[] permutationRaw = permutation.getRawPermutation();
result.add(Arrays.stream(permutationRaw).boxed().collect(Collectors.toList()));
permutation.nextPermutation();
}
List<List<Integer>> exprectedResult = new ArrayList<>();
exprectedResult.add(Arrays.asList(0, 1));
exprectedResult.add(Arrays.asList(1, 0));
exprectedResult.add(Arrays.asList(0, 2));
exprectedResult.add(Arrays.asList(2, 0));
exprectedResult.add(Arrays.asList(1, 1));
exprectedResult.add(Arrays.asList(1, 2));
exprectedResult.add(Arrays.asList(2, 1));
exprectedResult.add(Arrays.asList(0, 1, 1));
exprectedResult.add(Arrays.asList(1, 0, 1));
exprectedResult.add(Arrays.asList(1, 1, 0));
exprectedResult.add(Arrays.asList(0, 1, 2));
exprectedResult.add(Arrays.asList(0, 2, 1));
exprectedResult.add(Arrays.asList(1, 0, 2));
exprectedResult.add(Arrays.asList(1, 2, 0));
exprectedResult.add(Arrays.asList(2, 0, 1));
exprectedResult.add(Arrays.asList(2, 1, 0));
exprectedResult.add(Arrays.asList(1, 1, 2));
exprectedResult.add(Arrays.asList(1, 2, 1));
exprectedResult.add(Arrays.asList(2, 1, 1));
assertEquals(exprectedResult, result);
}
@Test
void allPermutationsMultipleSubsetsForced() {
MovePoolContainer movePools = new MovePoolContainer();
movePools.optional.add(new Move("u"));
movePools.optional.add(new Move("2r"));
movePools.forced.add(new Move("d"));
Permutation permutation = new Permutation(movePools, new BoundLimit(2, 3), "urdlwh");
List<List<Integer>> result = new ArrayList<>();
while(!permutation.finished) {
int[] permutationRaw = permutation.getRawPermutation();
result.add(Arrays.stream(permutationRaw).boxed().collect(Collectors.toList()));
permutation.nextPermutation();
}
List<List<Integer>> exprectedResult = new ArrayList<>();
exprectedResult.add(Arrays.asList(0, 2));
exprectedResult.add(Arrays.asList(2, 0));
exprectedResult.add(Arrays.asList(1, 2));
exprectedResult.add(Arrays.asList(2, 1));
exprectedResult.add(Arrays.asList(0, 1, 2));
exprectedResult.add(Arrays.asList(0, 2, 1));
exprectedResult.add(Arrays.asList(1, 0, 2));
exprectedResult.add(Arrays.asList(1, 2, 0));
exprectedResult.add(Arrays.asList(2, 0, 1));
exprectedResult.add(Arrays.asList(2, 1, 0));
exprectedResult.add(Arrays.asList(1, 1, 2));
exprectedResult.add(Arrays.asList(1, 2, 1));
exprectedResult.add(Arrays.asList(2, 1, 1));
assertEquals(exprectedResult, result);
}
} | 11,710 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
MultisetTest.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/test/java/tools/variation/MultisetTest.java | package tools.variation;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.*;
class MultisetTest {
@Test
void initialSubset() {
MovePoolContainer movePools = new MovePoolContainer();
movePools.optional.add(new Move("u"));
movePools.optional.add(new Move("2r"));
Multiset multiset = new Multiset(movePools, new BoundLimit(3), "urdlwh");
int[] subset = multiset.getSubset();
int[] expectedSubset = {1, 2};
assertArrayEquals(expectedSubset, subset);
}
@Test
void initialSubsetForced() {
MovePoolContainer movePools = new MovePoolContainer();
movePools.optional.add(new Move("u"));
movePools.optional.add(new Move("2r"));
movePools.forced.add(new Move("3l"));
Multiset multiset = new Multiset(movePools, new BoundLimit(4, 6), "urdlwh");
int[] subset = multiset.getSubset();
int[] expectedSubset = {1, 0, 3};
assertArrayEquals(expectedSubset, subset);
}
@Test
void initialSubsetLexicographic() {
MovePoolContainer movePools = new MovePoolContainer();
movePools.optional.add(new Move("h"));
movePools.optional.add(new Move("2d"));
movePools.optional.add(new Move("3ud"));
movePools.optional.add(new Move("4uu"));
movePools.optional.add(new Move("5u"));
Multiset multiset = new Multiset(movePools, new BoundLimit(15), "urdlwh");
int[] subset = multiset.getSubset();
int[] expectedSubset = {5, 4, 3, 2, 1};
assertArrayEquals(expectedSubset, subset);
}
@Test
void initialSubsetLowerbound() {
MovePoolContainer movePools = new MovePoolContainer();
movePools.optional.add(new Move("u"));
movePools.optional.add(new Move("2r"));
Multiset multiset = new Multiset(movePools, new BoundLimit(2, 3), "urdlwh");
int[] subset = multiset.getSubset();
int[] expectedSubset = {1, 1};
assertArrayEquals(expectedSubset, subset);
}
@Test
void nextSubset() {
MovePoolContainer movePools = new MovePoolContainer();
movePools.optional.add(new Move("u"));
movePools.optional.add(new Move("2r"));
Multiset multiset = new Multiset(movePools, new BoundLimit(2, 3), "urdlwh");
multiset.nextSubset();
int[] subset = multiset.getSubset();
int[] expectedSubset = {0, 2};
assertArrayEquals(expectedSubset, subset);
}
@Test
void nextSubsetForced() {
MovePoolContainer movePools = new MovePoolContainer();
movePools.optional.add(new Move("u"));
movePools.optional.add(new Move("2r"));
movePools.forced.add(new Move("3l"));
Multiset multiset = new Multiset(movePools, new BoundLimit(4, 6), "urdlwh");
multiset.nextSubset();
int[] subset = multiset.getSubset();
int[] expectedSubset = {0, 1, 3};
assertArrayEquals(expectedSubset, subset);
}
@Test
void subsetCount() {
MovePoolContainer movePools = new MovePoolContainer();
movePools.optional.add(new Move("u"));
movePools.optional.add(new Move("2r"));
movePools.optional.add(new Move("3w"));
Multiset multiset = new Multiset(movePools, new BoundLimit(4, 6), "urdlwh");
int subsetCount = 0;
while(!multiset.finished) {
subsetCount++;
multiset.nextSubset();
}
assertEquals(9, subsetCount);
}
@Test
void subsetCountSingle() {
MovePoolContainer movePools = new MovePoolContainer();
movePools.optional.add(new Move("u"));
Multiset multiset = new Multiset(movePools, new BoundLimit(1), "urdlwh");
int subsetCount = 0;
while(!multiset.finished) {
subsetCount++;
multiset.nextSubset();
}
assertEquals(1, subsetCount);
}
@Test
void subsetCountForced() {
MovePoolContainer movePools = new MovePoolContainer();
movePools.optional.add(new Move("u"));
movePools.optional.add(new Move("2r"));
movePools.forced.add(new Move("3w"));
Multiset multiset = new Multiset(movePools, new BoundLimit(4, 6), "urdlwh");
int subsetCount = 0;
while(!multiset.finished) {
subsetCount++;
multiset.nextSubset();
}
assertEquals(5, subsetCount);
}
@Test
void reset() {
MovePoolContainer movePools = new MovePoolContainer();
movePools.optional.add(new Move("u"));
movePools.optional.add(new Move("2r"));
Multiset multiset = new Multiset(movePools, new BoundLimit(2, 3), "urdlwh");
multiset.nextSubset();
multiset.reset();
int[] subset = multiset.getSubset();
int[] expectedSubset = {1, 1};
assertArrayEquals(expectedSubset, subset);
}
@Test
void allSubsets() {
MovePoolContainer movePools = new MovePoolContainer();
movePools.optional.add(new Move("2u"));
movePools.optional.add(new Move("r"));
movePools.optional.add(new Move("3d"));
Multiset multiset = new Multiset(movePools, new BoundLimit(3, 4), "urdlwh");
int[] subset = multiset.getSubset();
List<List<Integer>> result = new ArrayList<>();
while(!multiset.finished) {
result.add(Arrays.stream(subset).boxed().collect(Collectors.toList()));
multiset.nextSubset();
}
List<List<Integer>> expectedResult = new ArrayList<>();
expectedResult.add(Arrays.asList(2, 1, 0));
expectedResult.add(Arrays.asList(2, 0, 1));
expectedResult.add(Arrays.asList(1, 1, 1));
expectedResult.add(Arrays.asList(1, 0, 2));
expectedResult.add(Arrays.asList(0, 1, 2));
expectedResult.add(Arrays.asList(0, 0, 3));
expectedResult.add(Arrays.asList(2, 1, 1));
expectedResult.add(Arrays.asList(2, 0, 2));
expectedResult.add(Arrays.asList(1, 1, 2));
expectedResult.add(Arrays.asList(1, 0, 3));
expectedResult.add(Arrays.asList(0, 1, 3));
assertEquals(expectedResult, result);
}
@Test
void allSubsetsForced() {
MovePoolContainer movePools = new MovePoolContainer();
movePools.optional.add(new Move("u"));
movePools.optional.add(new Move("r"));
movePools.optional.add(new Move("3d"));
movePools.forced.add(new Move("u"));
Multiset multiset = new Multiset(movePools, new BoundLimit(3, 4), "urdlwh");
int[] subset = multiset.getSubset();
List<List<Integer>> result = new ArrayList<>();
while(!multiset.finished) {
result.add(Arrays.stream(subset).boxed().collect(Collectors.toList()));
multiset.nextSubset();
}
List<List<Integer>> expectedResult = new ArrayList<>();
expectedResult.add(Arrays.asList(2, 1, 0));
expectedResult.add(Arrays.asList(2, 0, 1));
expectedResult.add(Arrays.asList(1, 1, 1));
expectedResult.add(Arrays.asList(1, 0, 2));
expectedResult.add(Arrays.asList(2, 1, 1));
expectedResult.add(Arrays.asList(2, 0, 2));
expectedResult.add(Arrays.asList(1, 1, 2));
expectedResult.add(Arrays.asList(1, 0, 3));
assertEquals(expectedResult, result);
}
} | 7,511 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
InterpreterTest.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/test/java/tools/variation/InterpreterTest.java | package tools.variation;
import emulator.SuperCC;
import emulator.TickFlags;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import tools.VariationTesting;
import javax.swing.*;
import java.io.File;
import static org.junit.jupiter.api.Assertions.*;
class InterpreterTest {
private final SuperCC emulator = new SuperCC(false);
private final VariationTesting variationTesting = new VariationTesting(emulator, false);
private final JTextPane console = variationTesting.getConsole();
private final String newLine = System.getProperty("line.separator");
@BeforeEach
void setup() {
emulator.openLevelset(new File("testData/sets/variationScriptTest.DAT"));
variationTesting.clearConsole();
}
@Test
void printLiterals() {
emulator.loadLevel(1);
String code = "[u](){} print 1; print null; print 3.14; print true; print 4ud; print GLIDER_LEFT;";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
String consoleText = console.getText();
assertTrue(consoleText.contains("1" + newLine + "null" + newLine + "3.14" + newLine + "true" + newLine + "4ud" + newLine + "Glider - Left"));
}
@Test
void interpretArithmetic() {
emulator.loadLevel(1);
String code = "[u](){} print 4*2 + 6/3 - 5%2; print 12 * (7-2) / 3; print 3.6 * 2.1;";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
String consoleText = console.getText();
assertTrue(consoleText.contains("9" + newLine + "20" + newLine + "7.56"));
}
@Test
void interpretAssignment() {
emulator.loadLevel(1);
String code = "[u](){} var v1 = 0; v1 += 5; v1 -= 2; v1 *= 6; v1 /= 2; v1 %= 5; print v1; print v1;";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
String consoleText = console.getText();
assertTrue(consoleText.contains("4" + newLine + "4"));
}
@Test
void interpretConditionalOperators() {
emulator.loadLevel(1);
String code = "[u](){} print 1 < 2; print 2 > 1; print 3 == 3; print 4 != 5; print 6 >= 6; print 7 <= 8; print !true;";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
String consoleText = console.getText();
assertTrue(consoleText.contains("true" + newLine + "true" + newLine + "true" + newLine + "true" + newLine + "true" + newLine + "true" + newLine + "false"));
}
@Test
void interpretBooleanOperators() {
emulator.loadLevel(1);
String code = "[u](){} print true or false; print true and false; print false || false; print true && true;";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
String consoleText = console.getText();
assertTrue(consoleText.contains("true" + newLine + "false" + newLine + "false" + newLine + "true"));
}
@Test
void interpretConditionals() {
emulator.loadLevel(1);
String code = "[u](){} if(true) print 1; else print 2; if(false) print 3; else if(true) print 4; else print 5;";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
String consoleText = console.getText();
assertTrue(consoleText.contains("1" + newLine + "4"));
}
@Test
void interpretNonBooleanConditionals() {
emulator.loadLevel(1);
String code = "[u](){} if(1) print 1; if(null) print 2; if(0) print 3; if(2ud) print 4; \n" +
"if(v1) print 5; if(DIRT) print 6; if(0.0002) print 7; if(0.0) print 8; if(2.5*2/5-1) print 9; if(-1) print 10;";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
String consoleText = console.getText();
assertTrue(consoleText.contains("1" + newLine + "4" + newLine + "6" + newLine + "7" + newLine + "10"));
}
@Test
void interpretLoop() {
emulator.loadLevel(1);
String code = "[u](){} for(var i = 0; i < 10; i += 2) { print i; }" +
"for(var i = 0; i < 10; i += 2) { print i; if(i > 3) break; } print 0;";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
String consoleText = console.getText();
assertTrue(consoleText.contains("0" + newLine + "2" + newLine + "4" + newLine + "6" + newLine + "8" + newLine + "0" + newLine + "2" + newLine + "4" + newLine + "0"));
}
@Test
void variableHandling() {
emulator.loadLevel(1);
String code = "var v1 = 0; [u,d](){ afterMove: { v1 += 1; print v1; }} " +
"var v2 = 10; [u,d](){ afterMove: { v2 += 1; print v2; } }";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
String consoleText = console.getText();
assertTrue(consoleText.contains("1" + newLine + "2" + newLine + "11" + newLine + "12" + newLine + "11" + newLine + "12" + newLine + "1" + newLine + "2" + newLine + "11" + newLine + "12" + newLine + "11" + newLine + "12"));
}
@Test
void findSolution() {
emulator.loadLevel(1);
String code = "[2u, 2r](){}";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
assertEquals(1, interpreter.solutions.size());
}
@Test
void findMultipleSolutions() {
emulator.loadLevel(1);
String code = "all; [2u, 2r](){}";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
assertEquals(6, interpreter.solutions.size());
}
@Test
void findSolutionWithExistingMoves() {
emulator.loadLevel(1);
emulator.tick(SuperCC.UP, TickFlags.PRELOADING);
emulator.tick(SuperCC.RIGHT, TickFlags.PRELOADING);
emulator.tick(SuperCC.DOWN, TickFlags.PRELOADING);
emulator.tick(SuperCC.WAIT, TickFlags.PRELOADING);
emulator.tick(SuperCC.LEFT, TickFlags.PRELOADING);
emulator.tick(SuperCC.LEFT, TickFlags.PRELOADING);
emulator.tick(SuperCC.UP, TickFlags.PRELOADING);
String code = "print getPlayerX(); print getPlayerY(); [u, 2r](){}";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
String consoleText = console.getText();
assertEquals(1, interpreter.solutions.size());
assertTrue(consoleText.contains("14" + newLine + "13"));
}
@Test
void findSolutionMultipleSequences() {
emulator.loadLevel(1);
String code = "[u, r](){} [u, r](){}";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
assertEquals(1, interpreter.solutions.size());
}
@Test
void findMultipleSolutionsMultipleSequences() {
emulator.loadLevel(1);
String code = "all; [u, r](){} [u, r](){}";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
assertEquals(4, interpreter.solutions.size());
}
@Test
void findSolutionMultipleSubsets() {
emulator.loadLevel(1);
String code = "[3u, 2r](2,5){}";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
assertEquals(1, interpreter.solutions.size());
}
@Test
void findMultipleSolutionsMultipleSubsets() {
emulator.loadLevel(1);
String code = "all; [3u, 2r](2, 5){}";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
assertEquals(16, interpreter.solutions.size());
}
@Test
void getPlayerPosition() {
emulator.loadLevel(1);
String code = "[u](){} print getPlayerX(); print getPlayerY();";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
String consoleText = console.getText();
assertTrue(consoleText.contains("14" + newLine + "13"));
}
@Test
void getMoves() {
emulator.loadLevel(1);
String code = "[dl, r, l](){start: { print seqLength(); for(var i = 0; i < seqLength(); i += 1) print getMove(i); terminate; } }";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
String consoleText = console.getText();
assertTrue(consoleText.contains("3" + newLine + "r" + newLine + "d" + newLine + "l"));
}
@Test
void getRelativeMovesBeforeMove() {
emulator.loadLevel(1);
String code = "[dl, r, l](){ beforeMove: { print previousMove(); print nextMove(); } end: terminate -1; }";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
String consoleText = console.getText();
assertTrue(consoleText.contains("null" + newLine + "r" + newLine + "r" + newLine + "d" + newLine + "l" + newLine + "l"));
}
@Test
void getRelativeMovesAfterMove() {
emulator.loadLevel(1);
String code = "[dl, r, l](){ afterMove: { print previousMove(); print nextMove(); } end: terminate -1; }";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
String consoleText = console.getText();
assertTrue(consoleText.contains("r" + newLine + "d" + newLine + "l" + newLine + "l" + newLine + "l" + newLine + "null"));
}
@Test
void oppositeMovesAndExecutedMoves() {
emulator.loadLevel(1);
String code = "[dl, r, l](){ beforeMove: { print movesExecuted(); print getOppositeMove(nextMove()); } end: terminate -1; }";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
String consoleText = console.getText();
assertTrue(consoleText.contains("0" + newLine + "l" + newLine + "1" + newLine + "u" + newLine + "2" + newLine + "r"));
}
@Test
void moveCount() {
emulator.loadLevel(1);
String code = "[2d, 3lr](2,4){ start: { print moveCount(lr); terminate -1; } }";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
String consoleText = console.getText();
assertTrue(consoleText.contains("0" + newLine + "1" + newLine + "2" + newLine + "1" + newLine + "2" + newLine + "3" + newLine + "2" + newLine + "3"));
}
@Test
void chipCount() {
emulator.loadLevel(1);
String code = "print getChipsLeft(); [ur](){} print getChipsLeft();";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
String consoleText = console.getText();
assertTrue(consoleText.contains("1" + newLine + "0"));
}
@Test
void tileLayers() {
emulator.loadLevel(1);
String code = "[u](){} print getForegroundTile(15, 9); print getBackgroundTile(15, 9);";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
String consoleText = console.getText();
assertTrue(consoleText.contains("Block" + newLine + "Fire"));
}
@Test
void timeLeft() {
emulator.loadLevel(1);
String code = "print getTimeLeft(); [u](){} move(2l, 2u, d, rdrdr); print getTimeLeft();";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
String consoleText = console.getText();
assertTrue(consoleText.contains("100.9" + newLine + "98.8"));
}
@Test
void manhattanDistance() {
emulator.loadLevel(1);
String code = "[u](){} print distanceTo(14, 13); print distanceTo(11, 13); print distanceTo(18, 10); print distanceTo(16, 16);";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
String consoleText = console.getText();
assertTrue(consoleText.contains("0" + newLine + "3" + newLine + "7" + newLine + "5"));
}
@Test
void noSequenceError() {
emulator.loadLevel(1);
String code = "print null;";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
String consoleText = console.getText();
assertTrue(consoleText.contains("Script must contain at least 1 sequence"));
assertFalse(consoleText.contains("null"));
}
@Test
void invalidBoundError() {
emulator.loadLevel(1);
String code = "[u](0){}";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
String consoleText = console.getText();
assertTrue(consoleText.contains("Sequence upper bound must be at least 1"));
}
@Test
void undefinedVariableError() {
emulator.loadLevel(1);
String code = "v1 += 1; [u](){}";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
String consoleText = console.getText();
assertTrue(consoleText.contains("[Line 1 near 'v1'] Variable undefined"));
}
@Test
void operandMustBeNumberError() {
emulator.loadLevel(1);
String code = "u + 1; [u](){}";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
String consoleText = console.getText();
assertTrue(consoleText.contains("[Line 1 near '+'] Operand must be a number"));
}
@Test
void functionArgumentNotNumberError() {
emulator.loadLevel(1);
String code = "getForegroundTile(1, d); [u](){}";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
String consoleText = console.getText();
assertTrue(consoleText.contains("[Line 1 near 'getForegroundTile'] Argument must be a number"));
}
@Test
void functionArgumentNotMoveError() {
emulator.loadLevel(1);
String code = "getOppositeMove(1); [u](){}";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
String consoleText = console.getText();
assertTrue(consoleText.contains("[Line 1 near 'getOppositeMove'] Argument must be a move"));
}
@Test
void functionArgumentWrongCountError() {
emulator.loadLevel(1);
String code = "getForegroundTile(1); [u](){}";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
String consoleText = console.getText();
assertTrue(consoleText.contains("[Line 1 near 'getForegroundTile'] Expected 2 arguments, got 1"));
}
@Test
void ItemCount() {
emulator.loadLevel(2);
String code = "print getRedKeyCount(); print getYellowKeyCount(); print getGreenKeyCount(); print getBlueKeyCount(); " +
"print hasFlippers(); print hasFireBoots(); print hasSuctionBoots(); print hasIceSkates(); " +
"[u](){} move(u, 3r, 4d, 3l); " +
"print getRedKeyCount(); print getYellowKeyCount(); print getGreenKeyCount(); print getBlueKeyCount(); " +
"print hasFlippers(); print hasFireBoots(); print hasSuctionBoots(); print hasIceSkates(); ";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
String consoleText = console.getText();
assertTrue(consoleText.contains("0" + newLine + "0" + newLine + "0" + newLine + "0" + newLine + "false" + newLine + "false" + newLine + "false" + newLine + "false" + newLine + "" +
"1" + newLine + "1" + newLine + "1" + newLine + "1" + newLine + "true" + newLine + "true" + newLine + "true" + newLine + "true"));
}
@Test
void deathHandling() {
emulator.loadLevel(3);
String code = "[4r](){ beforeMove: print getPlayerX(); }";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
String consoleText = console.getText();
assertTrue(consoleText.contains("12" + newLine + "13"));
assertEquals(0, interpreter.solutions.size());
}
@Test
void deathHandlingMultipleSolutions() {
emulator.loadLevel(3);
String code = "all; [4r, u, d](){}";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
assertEquals(2, interpreter.solutions.size());
}
@Test
void fullExample() {
emulator.loadLevel(4);
String code = "all; [10ud, 5w](4, 15){}" +
"for(var i = 0; i < 10; i += 1) {" +
"if(getForegroundTile(3, 3) == GLIDER_LEFT) { move(7r, 2u); } move(w); }";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
String consoleText = console.getText();
assertEquals(655, interpreter.solutions.size());
assertTrue(consoleText.contains("12,360 variations"));
}
@Test
void zeroSequenceDeath() {
emulator.loadLevel(5);
String code = "all; move(r); [2w](0,2){} move(3r);";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
String consoleText = console.getText();
assertEquals(2, interpreter.solutions.size());
assertTrue(consoleText.contains("3 variations"));
}
@Test
void multipleSequenceFullMexample() {
emulator.loadLevel(6);
String code = """
all;
[3ud][ud, 3w](4){}
for(;getPlayerX() != 12;) move(r);
move(4u, 3r, d);
[2l, 2r](1,4){}
move(u);
for(;getPlayerX() != 17;) move(r);
move(d, 2r, 3d, r);
[2ww](0,2){}
[3r](1,3){}
[urd](0,1){}
move(4u);
if(getPlayerX() > 23) move(l);
for(;getPlayerX() != 23;) move(r);
move(udrru);
[w](0,1){}
move(ddrlddrr);""";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
String consoleText = console.getText();
assertEquals(37, interpreter.solutions.size());
assertTrue(consoleText.contains("3,240 variations"));
assertTrue(consoleText.contains("241 variations"));
}
@Test
void findingSolutionPrematurelyShouldntCrash() {
emulator.loadLevel(3);
String code = "all; move(rdrr); [u,r,d,l](){}";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
}
@Test
void sequencesAfterFindingSolutionShouldntCrash() {
emulator.loadLevel(3);
String code = "all; move(rdrr); [u,r,d,l](){} [u,r](){}";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
}
@Test
void terminatingAtSequenceBorderShouldntCrash() {
emulator.loadLevel(3);
String code = """
all;
[u,r,d,l](3){}
[u,r,d,l](3){}
[u,r,d,l](3){}""";
Interpreter interpreter = new Interpreter(emulator, variationTesting, console, code);
interpreter.interpret();
}
} | 20,642 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
SavestateReader.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/game/SavestateReader.java | package game;
import game.Lynx.LynxCreature;
import game.MS.MSCreature;
import java.io.ByteArrayInputStream;
public class SavestateReader extends ByteArrayInputStream {
public int readUnsignedByte(){
return read() & 0xFF;
}
public int readShort(){
int n = readUnsignedByte() << 8;
return n | readUnsignedByte();
}
public int readInt(){
int n = readUnsignedByte() << 24;
n |= readUnsignedByte() << 16;
n |= readUnsignedByte() << 8;
return n | readUnsignedByte();
}
public byte[] readBytes(int length){
byte[] out = new byte[length];
read(out, 0, length);
return out;
}
public short[] readShorts(int length){
short[] out = new short[length];
for (int i = 0; i < length; i++){
out[i] = (short) readShort();
}
return out;
}
public byte[] readLayerRLE(){
byte[] layerBytes = new byte[32*32];
int tileIndex = 0;
byte b;
while ((b = (byte) read()) != Savestate.RLE_END){
if (b == Savestate.RLE_MULTIPLE){
int rleLength = readUnsignedByte() + 1;
byte t = (byte) read();
for (int i = 0; i < rleLength; i++){
layerBytes[tileIndex++] = t;
}
}
else layerBytes[tileIndex++] = b;
}
return layerBytes;
}
public byte[] readLayer(int version){
if (version == Savestate.COMPRESSED_V1 || version == Savestate.COMPRESSED_V2) return readLayerRLE();
else return readBytes(32*32);
}
public Creature[] readMSMonsterArray(int length){
Creature[] monsters = new Creature[length];
for (int i = 0; i < length; i++){
monsters[i] = new MSCreature(readShort());
}
return monsters;
}
public Creature[] readLynxMonsterArray(int length){
Creature[] monsters = new Creature[length];
for (int i = 0; i < length; i++){
monsters[i] = new LynxCreature(readInt());
}
return monsters;
}
public boolean readBool() {
return read() == 1;
}
public boolean[] readBools(int length) {
boolean[] list = new boolean[length];
for (int i = 0; i < length; i++) {
list[i] = readBool();
}
return list;
}
public SavestateReader(byte[] b){
super(b);
}
} | 2,453 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
Ruleset.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/game/Ruleset.java | package game;
public enum Ruleset { //For the love of god do not use this outside of solution/JSONs,
// and only use level.getTicksPerMove unless its in Solution
CURRENT(0),
MS(2),
LYNX(4);
public final int ticksPerMove;
public static final Ruleset[] PLAYABLES = new Ruleset[] {MS, LYNX};
Ruleset(int ticksPerMove) {
this.ticksPerMove = ticksPerMove;
}
public Ruleset swap() {
if (this == MS) return LYNX;
if (this == LYNX) return MS;
return CURRENT;
}
public String prettyPrint() {
return switch (this) {
case MS -> "MS";
case LYNX -> "Lynx";
default -> null;
};
}
}
| 706 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
Position.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/game/Position.java | package game;
import emulator.SuperCC;
import static game.Direction.*;
import static java.lang.Math.abs;
public class Position {
private static final int
MOVE_DOWN = 0b100000,
MOVE_UP = -0b100000,
MOVE_RIGHT = 0b000001,
MOVE_LEFT = -0b000001;
public static final byte UNCLICKABLE = 127;
public int index;
public int x;
public int y;
public boolean isValid() {
return x >= 0 && x < 32 && y >= 0 && y < 32;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public int getIndex(){
return index;
}
@Deprecated
public void setIndex(int index){
this.index = index;
x = index & 0b11111;
y = index >>> 5;
}
private void moveUp(){
y--;
index += MOVE_UP;
}
private void moveLeft(){
x--;
index += MOVE_LEFT;
}
private void moveDown(){
y++;
index += MOVE_DOWN;
}
private void moveRight(){
x++;
index += MOVE_RIGHT;
}
public Position move(Direction direction){
Position p = clone();
switch (direction) {
case UP -> p.moveUp();
case LEFT -> p.moveLeft();
case DOWN -> p.moveDown();
case RIGHT -> p.moveRight();
}
return p;
}
public Position add(int x, int y){
return new Position(this.x + x, this.y + y);
}
public static Position screenPosition(Position chipPosition){
int screenX, screenY;
int chipX = chipPosition.getX();
int chipY = chipPosition.getY();
if (chipX < 5) screenX = 0;
else if (chipX >= 27) screenX = 23;
else screenX = chipX - 4;
if (chipY < 5) screenY = 0;
else if (chipY >= 27) screenY = 23;
else screenY = chipY - 4;
return new Position(screenX, screenY);
}
public static Position clickPosition(Position screenPosition, char clickChar){
int n = -(clickChar - SuperCC.MAX_CLICK_LOWERCASE);
return new Position(screenPosition.getX() + n % 9, screenPosition.getY() + n / 9);
}
public char clickChar(Position chipPosition){
Position screen = screenPosition(chipPosition);
if (y - screen.getY() < 9 && y - screen.getY() >= 0 &&
x - screen.getX() < 9 && x - screen.getX() >= 0){
return (char) (SuperCC.MAX_CLICK_LOWERCASE - (9 * (y - screen.getY()) + (x - screen.getX())));
}
return UNCLICKABLE;
}
public Direction[] seek(Position seekedPosition){
int verticalDifference = y - seekedPosition.y;
int horizontalDifference = x - seekedPosition.x;
Direction verticalDirection = NONE;
if (verticalDifference > 0) verticalDirection = UP;
else if (verticalDifference < 0) verticalDirection = DOWN;
Direction horizontalDirection = NONE;
if (horizontalDifference > 0) horizontalDirection = LEFT;
else if (horizontalDifference < 0) horizontalDirection = RIGHT;
if (abs(verticalDifference) >= abs(horizontalDifference))
return new Direction[] {verticalDirection, horizontalDirection};
else return new Direction[] {horizontalDirection, verticalDirection};
}
public Position(int x, int y){
this.x = x;
this.y = y;
index = (y << 5) | x;
}
public Position(int index){
this.index = index;
x = index & 0b11111;
y = index >>> 5;
}
public Position(int x, int y, int index) {
this.x = x;
this.y = y;
this.index = index;
}
@Override
public String toString() {
return "("+x+", "+y+")";
}
@Override
public Position clone(){
return new Position(index);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Position position = (Position) o;
return index == position.index &&
x == position.x &&
y == position.y;
}
public boolean equals(Position pos) {
return (index == pos.index && x == pos.x && y == pos.y);
}
@Override
public int hashCode() {
//Whilst this is just the index equation it is possible for index to be set manually so its just run again here
return (y << 5) | x;
}
}
| 4,571 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
SavestateWriter.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/game/SavestateWriter.java | package game;
import java.util.List;
public class SavestateWriter {
private final byte[] bytes;
private int index;
public void write(int n) {
bytes[index] = (byte) n;
index++;
}
public void write(byte[] b) {
System.arraycopy(b, 0, bytes, index, b.length);
index += b.length;
}
public void writeShort(int n){
write(n >>> 8);
write(n);
}
public void writeInt(int n){
write(n >>> 24);
write(n >>> 16);
write(n >>> 8);
write(n);
}
public void writeShorts(short[] a){
for (short s : a){
writeShort(s);
}
}
public void writeShortMonsterArray(Creature[] monsters){
for (Creature monster : monsters) writeShort(monster.bits());
}
public void writeIntMonsterArray(Creature[] monsters){
for (Creature monster : monsters) writeInt(monster.bits());
}
public void writeShortMonsterList(List<Creature> monsters){
for (Creature monster : monsters) writeShort(monster.bits());
}
public void writeIntMonsterList(List<Creature> monsters){
for (Creature monster : monsters) writeInt(monster.bits());
}
public void writeBool(boolean n) {
if (n) write(1);
else write(0);
}
public void writeBools(boolean[] list) {
for (boolean b : list) {
if (b)
write(1);
else
write(0);
}
}
public byte[] toByteArray() {
return bytes;
}
public SavestateWriter(int size) {
bytes = new byte[size];
}
} | 1,624 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
Direction.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/game/Direction.java | package game;
public enum Direction {
UP(0b0000),
LEFT(0b0001),
DOWN(0b0010),
RIGHT(0b0011),
UP_LEFT(0b0100),
DOWN_LEFT(0b0101),
DOWN_RIGHT(0b0110),
UP_RIGHT(0b0111),
NONE(0b1000),
WALKER_TURN(0b1001), //WOW! This is extremely hacky!
BLOB_TURN(0b1010);
public static final Direction TURN_LEFT = LEFT, TURN_RIGHT = RIGHT,
TURN_AROUND = DOWN, TURN_FORWARD = UP;
public static final Direction[] CARDINALS = new Direction[] {UP, LEFT, DOWN, RIGHT};
private static final Direction[] MOVEMENTS = new Direction[] {UP, LEFT, DOWN, RIGHT, UP_LEFT, DOWN_LEFT,
DOWN_RIGHT, UP_RIGHT};
public static Direction fromOrdinal(int ordinal){
return values()[ordinal];
}
private final int bits;
public int getBits() {
return bits;
}
public Direction turn(Direction turn) {
if (turn.bits > RIGHT.bits || this.bits > RIGHT.bits) //meaningless for non cardinal directions on either side
return this;
return fromOrdinal((ordinal() + turn.ordinal()) & 0b11);
}
public Direction[] turn(Direction[] turns) {
Direction[] dirs = new Direction[turns.length];
for (int i = 0; i < turns.length; i++){
dirs[i] = turn(turns[i]);
}
return dirs;
}
public boolean isDiagonal() {
return bits >= UP_LEFT.bits && bits <= UP_RIGHT.bits;
}
public boolean isComponent(Direction comp) {
if (!isDiagonal()) //only makes sense for diags
return false;
return switch (this) {
case UP_LEFT -> comp == UP || comp == LEFT;
case DOWN_LEFT -> comp == DOWN || comp == LEFT;
case DOWN_RIGHT -> comp == DOWN || comp == RIGHT;
case UP_RIGHT -> comp == UP || comp == RIGHT;
default -> false;
};
}
public Direction[] decompose() {
if (!isDiagonal())
return new Direction[] {this};
return switch (this) {
case UP_LEFT -> new Direction[] {UP, LEFT};
case DOWN_LEFT -> new Direction[] {DOWN, LEFT};
case DOWN_RIGHT -> new Direction[] {DOWN, RIGHT};
case UP_RIGHT -> new Direction[] {UP, RIGHT};
default -> new Direction[] {NONE};
};
}
public static Direction fromTWS(int n) {
n &= 0b11;
return switch (n) {
case 0b00 -> RIGHT;
case 0b01 -> UP;
case 0b10 -> LEFT;
default -> DOWN;
};
}
public int toTWS() {
return switch (this) {
case UP -> 0;
case LEFT -> 1;
case DOWN -> 2;
case RIGHT -> 3;
default -> 0; //failsafe
};
}
Direction(int bits) {
this.bits = bits;
}
}
| 2,836 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
Cheats.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/game/Cheats.java | package game;
import game.MS.MSCreatureList;
import game.button.*;
import util.MultiHashMap;
import java.util.HashMap;
import java.util.Map;
public class Cheats {
private final Level level;
// Button related cheats
public void pressGreenButton() {
new GreenButton(null).press(level);
}
public void pressGreenButton(GreenButton button) {
button.press(level);
}
public void pressRedButton(RedButton button) {
level.getMonsterList().initialise();
button.press(level);
level.getMonsterList().finalise();
}
public void clone(Position clonerPosition) {
level.getMonsterList().initialise();
level.getMonsterList().addClone(clonerPosition);
level.getMonsterList().finalise();
}
public void pressBrownButton(BrownButton button) {
button.press(level);
}
public void setTrap(Position trapPosition, boolean open) {
level.setTrap(trapPosition, open);
}
public void pressBlueButton() {
new BlueButton(null).press(level);
}
public void pressBlueButton(BlueButton button) {
button.press(level);
}
public void pressButton(Button button) {
if (button instanceof RedButton)
pressRedButton((RedButton) button);
else
button.press(level);
}
public void pressButton(Position position) {
Button button = level.getButton(position);
if (button != null) pressButton(button);
}
// Monster related cheats
public void setDirection(Creature creature, Direction direction) {
if (level.supportsLayerBG())
level.popTile(creature.getPosition());
if (creature.getCreatureType() == CreatureID.BLOB) creature.setNextMoveDirectionCheat(direction);
creature.setDirection(direction);
if (level.supportsLayerBG())
level.insertTile(creature.getPosition(), creature.toTile());
}
public void setPosition(Creature creature, Position position) {
if (level.supportsLayerBG())
level.popTile(creature.getPosition());
creature.setPosition(position);
if (level.supportsLayerBG())
level.insertTile(creature.getPosition(), creature.toTile());
}
public void kill(Creature creature) {
level.getMonsterList().initialise();
creature.kill();
if (level.supportsSliplist()) {
level.getSlipList().remove(creature);
((MSCreatureList)(level.getMonsterList())).incrementDeadMonsters();
}
if (level.supportsLayerBG())
level.popTile(creature.getPosition());
level.getMonsterList().finalise();
}
public void animateMonster(Position position) {
level.getMonsterList().addClone(position);
level.getMonsterList().finalise();
}
public void reviveChip() {
Creature chip = level.getChip();
chip.kill();
chip.kill(); //remove any animations and timers
chip.setCreatureType(CreatureID.CHIP);
if (level.supportsLayerBG())
level.getLayerFG().set(chip.getPosition(), Tile.CHIP_DOWN);
}
public void moveChip(Position position) {
if (level.supportsLayerBG())
level.popTile(level.getChip().getPosition());
level.getChip().setPosition(position);
if (level.supportsLayerBG())
level.insertTile(position, level.getChip().toTile());
}
// Layer related cheats
public void setLayerBG(Position position, Tile tile) {
level.getLayerBG().set(position, tile);
}
public void setLayerFG(Position position, Tile tile) {
level.getLayerBG().set(position, tile);
}
public void popTile(Position position) {
level.popTile(position);
}
public void insertTile(Position position, Tile tile) {
level.insertTile(position, tile);
if (tile == Tile.BUTTON_GREEN) { //All this just to avoid a null pointer when you use insert tile to add a blue or green button
GreenButton button = new GreenButton(position);
MultiHashMap<Position, GreenButton> greenButtons = new MultiHashMap<>(level.getGreenButtons());
greenButtons.put(position ,button);
level.setGreenButtons(greenButtons);
}
if (tile == Tile.BUTTON_BLUE) {
BlueButton button = new BlueButton(position);
MultiHashMap<Position, BlueButton> blueButtons = new MultiHashMap<>(level.getBlueButtons());
blueButtons.put(position, button);
level.setBlueButtons(blueButtons);
}
}
public void insertCreature(Direction dir, CreatureID creatureType, Position position) {
Creature creature = level.newCreature(dir, creatureType, position);
if (level.creaturesAreTiles())
level.insertTile(position, creature.toTile());
level.getMonsterList().addCreature(creature);
level.getMonsterList().finalise();
}
// Level related cheats
public void setTimer(int timer) {
level.setTimer(timer);
}
public void setChipsLeft(int chipsLeft) {
level.setChipsLeft(chipsLeft);
}
public void setKeys(short[] keys) {
level.setKeys(keys);
}
public void setBoots(byte[] boots) {
level.setBoots(boots);
}
public void setRng(int rng) {
level.getRNG().setCurrentValue(rng);
}
public Cheats(Level level) {
this.level = level;
}
}
| 5,540 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
ByteLayer.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/game/ByteLayer.java | package game;
import java.util.Iterator;
import java.util.function.Consumer;
public class ByteLayer implements Layer {
private final byte[] layer;
public Tile get(int i){
return Tile.fromOrdinal(layer[i]);
}
public Tile get(Position p){
if (!p.isValid()) return Tile.WALL;
return get(p.getIndex());
}
public void set(int i, Tile t){
layer[i] = (byte) t.ordinal();
}
public void set(Position p, Tile t){
set(p.getIndex(), t);
}
public byte[] getBytes() {
return layer;
}
public Tile[] getTiles() {
Tile[] out = new Tile[32*32];
for (int i = 0; i < 32 * 32; i++) {
out[i] = get(i);
}
return out;
}
public void load(byte[] b) {
System.arraycopy(b, 0, layer, 0, layer.length);
}
public ByteLayer(byte[] layer){
for (int i=0; i < layer.length; i++) {
byte b = layer[i];
if (b < Tile.FLOOR.ordinal() || b > Tile.CHIP_RIGHT.ordinal()) layer[i] = (byte) Tile.WALL.ordinal();
}
this.layer = layer;
}
public Iterator<Tile> iterator() {
return new Iterator<>() {
private int i;
@Override
public boolean hasNext() {
return i < 32 * 32;
}
@Override
public Tile next() {
return get(i++);
}
};
}
public void forEach(Consumer<? super Tile> action) {
for (byte b : layer) action.accept(Tile.fromOrdinal(b));
}
}
| 1,631 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
Layer.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/game/Layer.java | package game;
/**
*
*
* Benchmarks:
*
* Time taken to run pain, without writing savesates:
* ByteLayer: 12.42920485ms
* TileLayer: 12.07655951ms
*
* Time taken to run pain, with writing savesates:
* ByteLayer: 20.73663555ms
* TileLayer: 26.42774384ms
*
*/
public interface Layer extends Iterable<Tile> {
public Tile get(int i);
public Tile get(Position p);
public void set(int i, Tile t);
public void set(Position p, Tile t);
public byte[] getBytes();
public Tile[] getTiles();
public void load(byte[] b);
}
| 591 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
Level.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/game/Level.java | package game;
import game.MS.*;
import game.button.*;
import util.MultiHashMap;
import java.util.BitSet;
import java.util.Map;
public interface Level extends Savestate {
int MASK_TICK_MULTI = 0b01;
int MASK_DISCARD_INPUT = 0b10;
int getLevelNumber();
int getStartTime();
String getTitle();
String getPassword();
String getHint();
String getAuthor();
Position[] getToggleDoors();
Position[] getTeleports();
MultiHashMap<Position, GreenButton> getGreenButtons();
MultiHashMap<Position, RedButton> getRedButtons();
MultiHashMap<Position, BrownButton> getBrownButtons();
MultiHashMap<Position, BlueButton> getBlueButtons();
/**
* While brown buttons returns a map of button-position:button mappings,
* this returns a map of trap-position:button mappings.
* @return A Trap-Position:Brown-Button mapping.
*/
MultiHashMap<Position, BrownButton> getTrapButtons();
void setGreenButtons(MultiHashMap<Position, GreenButton> greenButtons);
void setBlueButtons(MultiHashMap<Position, BlueButton> blueButtons);
int getRngSeed();
Step getStep();
boolean supportsLayerBG();
boolean supportsClick();
boolean supportsSliplist();
boolean supportsDiagonal();
boolean hasCyclicRFF();
boolean chipInMonsterList();
/**
* Represents if a trap's button has to be held for the trap to be open.
*/
boolean trapRequiresHeldButton();
boolean creaturesAreTiles();
boolean hasStillTanks();
boolean swimmingChipIsCreature();
boolean blocksInMonsterList();
int ticksPerMove();
Layer getLayerBG();
Layer getLayerFG();
boolean isUntimed();
/**
*
* @return The current value of the timer that is displayed on screen.
* Returns a negative value on untimed levels.
*/
int getTimer();
void setTimer(int n);
/**
*
* @return The current value of the timer if we are using TChip timing
* (where the time starts at 999.9).
*/
int getTChipTime();
int getChipsLeft();
void setChipsLeft(int chipsLeft);
Creature getChip();
/**
* Returns chip's keys
* <p>
* Chip's keys are short array with 4 entries containing the number of
* blue, red, green and yellow keys in that order.
* </p>
* @return chip's keys
*/
short[] getKeys();
/**
* Set chip's keys
* <p>
* Chip's keys are short array with 4 entries containing the number of
* blue, red, green and yellow keys in that order.
* </p>
*/
void setKeys(short[] keys);
/**
* Returns chip's boots
* <p>
* Chip's boots are byte array with 4 entries containing the number of
* flippers, fire boots, skates and suction boots in that order.
* </p>
* @return chip's boots
*/
byte[] getBoots();
void setBoots(byte[] boots);
CreatureList getMonsterList();
SlipList getSlipList();
void setTrap(Position trapPos, boolean open);
int getLevelsetLength();
Cheats getCheats();
RNG getRNG();
Button getButton(Position position, Class<? extends Button> buttonType);
Button getButton(Position position);
boolean isTrapOpen(Position position);
int getTickNumber();
Ruleset getRuleset();
Direction getInitialRFFDirection();
Direction getRFFDirection(boolean advance);
/**
* @param position the last clicked position.
*/
void setClick(int position);
void setLevelWon(boolean won);
boolean isCompleted();
/**
* Advances a tick (10th of a second).
* <p>
* This method is not responsible for setting the click position, or
* for checking whether chip can move (in case chip moved the previous
* tick).
* </p>
* @param c The direction in which to move. If c is positive it should be
* one of UP, LEFT, DOWN, RIGHT and WAIT. If c is negative, it is
* interpreted as a mouse click. Note that the click itself is not
* set here - use {@link #setClick(int)} for that.
* @param directions The directions in which chip should try to move
* @return An int with bit 0 representing if the next move should be made automatically without input
* and bit 1 representing if the input given to this move should be discarded.
*/
int tick(char c, Direction[] directions);
void insertTile(Position position, Tile tile);
void popTile(Position position);
/**
* @param creature the creature in question.
* @return a boolean representing if the monsterlist number of this creature should be drawn.
*/
boolean shouldDrawCreatureNumber(Creature creature);
void turnTanks();
Creature newCreature(Direction dir, CreatureID creatureType, Position position);
}
| 4,895 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
Creature.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/game/Creature.java | package game;
import static game.CreatureID.DEAD;
public abstract class Creature {
protected Level level;
protected Position position;
protected CreatureID creatureType;
protected Direction direction;
protected Direction tDirection = Direction.NONE;
protected Direction fDirection = Direction.NONE;
protected boolean sliding, teleportFlag;
protected Direction nextMoveDirectionCheat = null;
public Direction getDirection() {
return direction;
}
public void setDirection(Direction direction) {
this.direction = direction;
}
public Direction getTDirection() {
return tDirection;
}
public void setTDirection(Direction tDirection) {
this.tDirection = tDirection;
}
public Direction getFDirection() {
return fDirection;
}
public void setFDirection(Direction fDirection) {
this.fDirection = fDirection;
}
public boolean getTeleportFlag() {
return teleportFlag;
}
public void setTeleportFlag(boolean teleportFlag) {
this.teleportFlag = teleportFlag;
}
public void setNextMoveDirectionCheat(Direction nextMoveDirectionCheat) {
this.nextMoveDirectionCheat = nextMoveDirectionCheat;
}
public Direction getNextMoveDirectionCheat() {
return nextMoveDirectionCheat;
}
public CreatureID getCreatureType() {
return creatureType;
}
public abstract Direction[] getDirectionPriority(Creature chip, RNG rng);
public abstract Direction getSlideDirection(Direction direction, Tile tile, RNG rng, boolean advanceRFF);
/** Returns a direction besides NONE if the creature's move will be forced.
* Side effects such as setting the creature's direction can occur.
*
* @param tile The tile the creature is currently on (may be ignored).
* @return true if the next move is forced, false otherwise.
*/
public abstract boolean getForcedMove(Tile tile);
public void setCreatureType(CreatureID creatureType) {
this.creatureType = creatureType;
}
public void kill() {
creatureType = CreatureID.DEAD;
}
public boolean isDead() {
return creatureType == CreatureID.DEAD;
}
public Position getPosition() {
return position;
}
public void setPosition(Position position) {
this.position = position;
}
/** Turns the creature to face a specified direction.
*
* @param turn the direction the creature should turn.
*/
public void turn(Direction turn) {
direction = direction.turn(turn);
}
public abstract Tile toTile();
@Override
public String toString() {
if (creatureType == DEAD) return "Dead monster at position " + position;
return creatureType+" facing "+direction+" at position "+position;
}
/** Returns a number representing how long the creature has been traveling between tiles.
* Of note is that this is only useful for lynx and will always be 0 in MS.
*
* @return An int between 0 and 7 (inclusive)
* that represents how long the creature has been traveling between tiles
*/
public abstract int getTimeTraveled();
/** Returns a number representing how many ticks are left in an effect animation.
* Of note is that this is only useful for DEAD Lynx monsters as they are the only things that play
* animations.
* @return An int between 0 and 12 (inclusive)
*/
public abstract int getAnimationTimer();
/** Returns a boolean representing if a creature can make a move with the given direction into the given position.
* Checking both that it can leave its current position and enter the given one.
* Side effects can and will occur, some based on the flags passed.
*
* @param direction The direction the creature should try to move in.
* @param position The position the creature should try to enter.
* @param clearAnims If any animations found should be stopped.
* @param pushBlocks If any blocks found should be prepped to move.
* @param pushBlocksNow If any blocks found should be prepped AND moved at this time.
* @param releasing If the creature is releasing from a trap.
* @return A boolean representing that the creature can make this move.
*/
public abstract boolean canMakeMove(Direction direction, Position position, boolean clearAnims, boolean pushBlocks, boolean pushBlocksNow, boolean releasing);
/** Returns a boolean representing if the given creature can override a force floor move.
* Really only useful for Chip and even then only in Lynx.
*
* @return A boolean representing if the creature can override a force floor at this moment.
*/
public abstract boolean canOverride();
/** Advances a creature 1 tick according to their internal state.
*
* @param releasing if the creature is releasing from a trap.
* @return If the move was successful or not.
*/
public abstract boolean tick(boolean releasing);
/** Returns an int representing a creature.
*
* @return An int with the bits arranged according to the creature bit encoding.
*/
public abstract int bits();
/**
* @return A boolean representing if the creature is sliding.
*/
public boolean isSliding() {
return sliding;
}
public void setSliding(boolean sliding) {
this.sliding = sliding;
}
public void setLevel(Level level) {
this.level = level;
}
public abstract Creature clone();
}
| 5,620 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
CreatureList.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/game/CreatureList.java | package game;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Spliterator;
import java.util.function.Consumer;
/**
* The monster list. The list attribute is the actual list.
*/
public abstract class CreatureList implements Iterable<Creature> {
public Direction direction;
protected Level level;
protected Creature[] list;
protected List<Creature> newClones;
protected boolean teethStep;
protected Creature chipToCr; //not used for MS but eh
public CreatureList(Creature[] monsters) {
list = monsters;
}
public Creature creatureAt(Position position, boolean includeChip){
for (Creature c : list) {
if (((c.getCreatureType() == CreatureID.CHIP || c == level.getChip()) && !includeChip)
|| c.getCreatureType() == CreatureID.DEAD) {
continue;
}
if (c.getPosition().equals(position)) {
return c;
}
}
return null;
}
public int size() {
return list.length;
}
public Creature get(int i) {
return list[i];
}
public Creature[] getCreatures() {
return list;
}
public int getIndexOfCreature(Creature creature) {
for (int i=0; i < list.length; i++) {
if (creature == list[i]) return i;
}
return -1;
}
public boolean getTeethStep() {
return teethStep;
}
public List<Creature> getNewClones() {
return newClones;
}
public Creature getChipToCr() {
return chipToCr;
}
public void setChipToCr(Creature cr) {
chipToCr = cr;
}
public void setCreatures(Creature[] creatures) {
list = creatures;
for (Creature c : list)
c.setLevel(level);
}
/** Returns true if a position is claimed by a creature (usually meaning a creature occupies the tile)
*
* @param position The position to check (must be a valid position between 0 and 31 on x and y).
* @return If the position is claimed.
*/
public abstract boolean claimed(Position position);
/** Attach or detach a claim to a position.
*
* @param position The position to claim.
* @param claim the state to set the position claim to.
*/
public abstract void adjustClaim(Position position, boolean claim);
/**
* @return the array of claimed positions.
*/
public abstract boolean[] getClaimedArray();
public abstract void setClaimedArray(boolean[] claimedArray);
/** Returns the animation currently occurring at the given position (null if there is no animation).
*
* @param position The position to check.
* @return A animation at the given position (null if there is no such creature).
*/
public abstract Creature animationAt(Position position);
public abstract void initialise();
public abstract void finalise();
public abstract void tick();
public abstract void addClone(Position position);
public abstract void springTrappedCreature(Position position);
public abstract void addCreature(Creature creature);
@Override
public String toString(){
StringBuilder sb = new StringBuilder();
for (int i = 0; i < list.length; i++){
sb.append(i+1);
sb.append('\t');
sb.append(list[i]);
sb.append('\n');
}
return sb.toString();
}
@Override
public Iterator<Creature> iterator() {
return new Iterator<Creature>() {
private int i = 0;
@Override
public boolean hasNext() {
return i < list.length;
}
@Override
public Creature next() {
return list[i++];
}
};
}
public void setLevel(Level level){
this.level = level;
newClones = new ArrayList<>();
}
@Override
public void forEach(Consumer<? super Creature> action) {
for (Creature c : list) action.accept(c);
}
@Override
public Spliterator<Creature> spliterator() {
throw new UnsupportedOperationException("Not implemented");
}
}
| 4,259 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
Tile.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/game/Tile.java | package game;
public enum Tile {
/* 00 EMPTY SPACE */ FLOOR("Floor"),
/* 01 WALL */ WALL("Wall"),
/* 02 CHIP */ CHIP("Chip"),
/* 03 WATER */ WATER("Water"),
/* 04 FIRE */ FIRE("Fire"),
/* 05 INVISIBLE WALL_PERM. */ INVISIBLE_WALL("Invisible Wall"),
/* 06 BLOCKED NORTH */ THIN_WALL_UP("Thin Wall - Up"),
/* 07 BLOCKED WEST */ THIN_WALL_LEFT("Thin Wall - Left"),
/* 08 BLOCKED SOUTH */ THIN_WALL_DOWN("Thin Wall - Down"),
/* 09 BLOCKED EAST */ THIN_WALL_RIGHT("Thin Wall - Right"),
/* 0A BLOCK */ BLOCK("Block"),
/* 0B DIRT */ DIRT("Dirt"),
/* 0C ICE */ ICE("Ice"),
/* 0D FORCE SOUTH */ FF_DOWN("Force Floor - Down"),
/* 0E CLONING BLOCK N */ BLOCK_UP("Block - Up"),
/* 0F CLONING BLOCK W */ BLOCK_LEFT("Block - Left"),
/* 10 CLONING BLOCK S */ BLOCK_DOWN("Block - Down"),
/* 11 CLONING BLOCK E */ BLOCK_RIGHT("Block - Right"),
/* 12 FORCE NORTH */ FF_UP("Force Floor - Up"),
/* 13 FORCE EAST */ FF_RIGHT("Force Floor - Right"),
/* 14 FORCE WEST */ FF_LEFT("Force Floor - Left"),
/* 15 EXIT */ EXIT("Exit"),
/* 16 BLUE DOOR */ DOOR_BLUE("Blue Door"),
/* 17 RED DOOR */ DOOR_RED("Red Door"),
/* 18 GREEN DOOR */ DOOR_GREEN("Green Door"),
/* 19 YELLOW DOOR */ DOOR_YELLOW("Yellow Door"),
/* 1A SE ICE SLIDE */ ICE_SLIDE_SOUTHEAST("Ice Turn - Down/Right"),
/* 1B SW ICE SLIDE */ ICE_SLIDE_SOUTHWEST("Ice Turn - Down/Left"),
/* 1C NW ICE SLIDE */ ICE_SLIDE_NORTHWEST("Ice Turn - Up/Left"),
/* 1D NE ICE SLIDE */ ICE_SLIDE_NORTHEAST("Ice Turn - Up/Right"),
/* 1E BLUE BLOCK_TILE */ BLUEWALL_FAKE("Fake Blue Wall"),
/* 1F BLUE BLOCK_WALL */ BLUEWALL_REAL("Real Blue Wall"),
/* 20 NOT USED */ OVERLAY_BUFFER("Unused"),
/* 21 THIEF */ THIEF("Thief"),
/* 22 SOCKET */ SOCKET("Socket"),
/* 23 GREEN BUTTON */ BUTTON_GREEN("Green Button"),
/* 24 RED BUTTON */ BUTTON_RED("Red Button"),
/* 25 SWITCH BLOCK_CLOSED */ TOGGLE_CLOSED("Closed Toggle Door"),
/* 26 SWITCH BLOCK_OPEN */ TOGGLE_OPEN("Open Toggle Door"),
/* 27 BROWN BUTTON */ BUTTON_BROWN("Brown Button"),
/* 28 BLUE BUTTON */ BUTTON_BLUE("Blue Button"),
/* 29 TELEPORT */ TELEPORT("Teleporter"),
/* 2A BOMB */ BOMB("Bomb"),
/* 2B TRAP */ TRAP("Trap"),
/* 2C INVISIBLE WALL_TEMP. */ HIDDENWALL_TEMP("Appearing Wall"),
/* 2D GRAVEL */ GRAVEL("Gravel"),
/* 2E PASS ONCE */ POP_UP_WALL("Pop Up Wall"),
/* 2F HINT */ HINT("Hint"),
/* 30 BLOCKED SE */ THIN_WALL_DOWN_RIGHT("Thin Wall - Down Right"),
/* 31 CLONING MACHINE */ CLONE_MACHINE("Clone Machine"),
/* 32 FORCE ALL DIRECTIONS */ FF_RANDOM("Force Floor - Random"),
/* 33 DROWNING CHIP */ DROWNED_CHIP("Drowned Chip"),
/* 34 BURNED CHIP */ BURNED_CHIP("Burned Chip"),
/* 35 BURNED CHIP */ BOMBED_CHIP("Bombed Chip"),
/* 36 NOT USED */ UNUSED_36("Unused"),
/* 37 NOT USED */ UNUSED_37("Unused"),
/* 38 ICE BLOCK */ ICE_BLOCK("Ice Block"),
/* 39 CHIP IN EXIT */ EXITED_CHIP("Exited Chip"),
/* 3A EXIT - END GAME */ EXIT_EXTRA_1("Exit Animation 2"),
/* 3B EXIT - END GAME */ EXIT_EXTRA_2("Exit Animation 3"),
/* 3C CHIP SWIMMING N */ CHIP_SWIMMING_UP("Swimming Chip - Up"),
/* 3D CHIP SWIMMING W */ CHIP_SWIMMING_LEFT("Swimming Chip - Left"),
/* 3E CHIP SWIMMING S */ CHIP_SWIMMING_DOWN("Swimming Chip - Down"),
/* 3F CHIP SWIMMING E */ CHIP_SWIMMING_RIGHT("Swimming Chip - Right"),
/* 40 BUG N */ BUG_UP("Bug - Up"),
/* 41 BUG W */ BUG_LEFT("Bug - Left"),
/* 42 BUG S */ BUG_DOWN("Bug - Down"),
/* 43 BUG E */ BUG_RIGHT("Bug - Right"),
/* 44 FIREBALL N */ FIREBALL_UP("Fireball - Up"),
/* 45 FIREBALL W */ FIREBALL_LEFT("Fireball - Left"),
/* 46 FIREBALL S */ FIREBALL_DOWN("Fireball - Down"),
/* 47 FIREBALL E */ FIREBALL_RIGHT("Fireball - Right"),
/* 48 PINK BALL N */ BALL_UP("Pink Ball - Up"),
/* 49 PINK BALL W */ BALL_LEFT("Pink Ball - Left"),
/* 4A PINK BALL S */ BALL_DOWN("Pink Ball - Down"),
/* 4B PINK BALL E */ BALL_RIGHT("Pink Ball - Right"),
/* 4C TANK N */ TANK_UP("Tank - Up"),
/* 4D TANK W */ TANK_LEFT("Tank - Left"),
/* 4E TANK S */ TANK_DOWN("Tank - Down"),
/* 4F TANK E */ TANK_RIGHT("Tank - Right"),
/* 50 GLIDER N */ GLIDER_UP("Glider - Up"),
/* 51 GLIDER W */ GLIDER_LEFT("Glider - Left"),
/* 52 GLIDER S */ GLIDER_DOWN("Glider - Down"),
/* 53 GLIDER E */ GLIDER_RIGHT("Glider - Right"),
/* 54 TEETH N */ TEETH_UP("Teeth - Up"),
/* 55 TEETH W */ TEETH_LEFT("Teeth - Left"),
/* 56 TEETH S */ TEETH_DOWN("Teeth - Down"),
/* 57 TEETH E */ TEETH_RIGHT("Teeth - Right"),
/* 58 WALKER N */ WALKER_UP("Walker - Up"),
/* 59 WALKER W */ WALKER_LEFT("Walker - Left"),
/* 5A WALKER S */ WALKER_DOWN("Walker - Down"),
/* 5B WALKER E */ WALKER_RIGHT("Walker - Right"),
/* 5C BLOB N */ BLOB_UP("Blob - Up"),
/* 5D BLOB W */ BLOB_LEFT("Blob - Left"),
/* 5E BLOB S */ BLOB_DOWN("Blob - Down"),
/* 5F BLOB E */ BLOB_RIGHT("Blob - Right"),
/* 60 PARAMECIUM N */ PARAMECIUM_UP("Paramecium - Up"),
/* 61 PARAMECIUM W */ PARAMECIUM_LEFT("Paramecium - Left"),
/* 62 PARAMECIUM S */ PARAMECIUM_DOWN("Paramecium - Down"),
/* 63 PARAMECIUM E */ PARAMECIUM_RIGHT("Paramecium - Right"),
/* 64 BLUE KEY */ KEY_BLUE("Blue Key"),
/* 65 RED KEY */ KEY_RED("Red Key"),
/* 66 GREEN KEY */ KEY_GREEN("Green Key"),
/* 67 YELLOW KEY */ KEY_YELLOW("Yellow Key"),
/* 68 FLIPPERS */ BOOTS_WATER("Flippers"),
/* 69 FIRE BOOTS */ BOOTS_FIRE("Fire Boots"),
/* 6A ICE SKATES */ BOOTS_ICE("Ice Skates"),
/* 6B SUCTION BOOTS */ BOOTS_FF("Suction Boots"),
/* 6C CHIP N */ CHIP_UP("Chip - Up"),
/* 6D CHIP W */ CHIP_LEFT("Chip - Left"),
/* 6E CHIP S */ CHIP_DOWN("Chip - Down"),
/* 6F CHIP E */ CHIP_RIGHT("Chip - Right");
public static final int NUM_BOOTS = 4;
public static final int NUM_KEYS = 4;
private static final Tile[] allTiles = Tile.values();
public static Tile fromOrdinal(int ordinal){
if (ordinal >= 0 && ordinal < allTiles.length)
return allTiles[ordinal];
return WALL;
}
public boolean isIce(){
return this.ordinal() == ICE.ordinal() ||
(ICE_SLIDE_SOUTHEAST.ordinal() <= this.ordinal() && this.ordinal() <= ICE_SLIDE_NORTHEAST.ordinal());
}
public boolean isIceCorner() {
return (ICE_SLIDE_SOUTHEAST.ordinal() <= this.ordinal() && this.ordinal() <= ICE_SLIDE_NORTHEAST.ordinal());
}
public boolean isFF(){
return this == FF_UP || this == FF_LEFT || this == FF_DOWN || this == FF_RIGHT || this == FF_RANDOM;
}
public boolean isSliding(){
return isIce() || isFF() || this == TELEPORT;
}
public boolean isChip(){
return CHIP_UP.ordinal() <= ordinal() && ordinal() <= CHIP_RIGHT.ordinal();
}
public boolean isSwimmingChip(){
return CHIP_SWIMMING_UP.ordinal() <= ordinal() && ordinal() <= CHIP_SWIMMING_RIGHT.ordinal();
}
public boolean isCloneBlock(){
return BLOCK_UP.ordinal() <= ordinal() && ordinal() <= BLOCK_RIGHT.ordinal();
}
public boolean isMonster(){
return BUG_UP.ordinal() <= ordinal() && ordinal() <= PARAMECIUM_RIGHT.ordinal();
}
public boolean isCreature(){
return isMonster() || isCloneBlock();
}
public boolean isTransparent(){
return ordinal() >= BUG_UP.ordinal();
}
public boolean isKey() {
return KEY_BLUE.ordinal() <= ordinal() && ordinal() <= KEY_YELLOW.ordinal();
}
public boolean isBoot() {
return BOOTS_WATER.ordinal() <= ordinal() && ordinal() <= BOOTS_FF.ordinal();
}
public boolean isPickup() {
return KEY_BLUE.ordinal() <= ordinal() && ordinal() <= BOOTS_FF.ordinal();
}
public boolean isButton() {
return this == BUTTON_BROWN || this == BUTTON_BLUE || this == BUTTON_RED || this == BUTTON_GREEN;
}
public boolean isBlock() {
return this == BLOCK || this == ICE_BLOCK;
}
private String str;
@Override public String toString() {
return str;
}
Tile(String s) {
this.str = s;
}
}
| 9,687 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
CreatureID.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/game/CreatureID.java | package game;
public enum CreatureID {
BUG (0b00_0000_0000000000, "Bug"),
FIREBALL (0b00_0001_0000000000, "Fireball"),
PINK_BALL (0b00_0010_0000000000, "Ball"),
TANK_MOVING (0b00_0011_0000000000, "Tank (Moving)"),
GLIDER (0b00_0100_0000000000, "Glider"),
TEETH (0b00_0101_0000000000, "Teeth"),
WALKER (0b00_0110_0000000000, "Walker"),
BLOB (0b00_0111_0000000000, "Blob"),
PARAMECIUM (0b00_1000_0000000000, "Paramecium"),
TANK_STATIONARY (0b00_1001_0000000000, "Tank (Still)"),
BLOCK (0b00_1010_0000000000, "Block"),
CHIP (0b00_1011_0000000000, "Chip"),
ICE_BLOCK (0b00_1100_0000000000, "Ice Block"),
CHIP_SLIDING (0b00_1101_0000000000, "Chip (Sliding)"),
CHIP_SWIMMING (0b00_1110_0000000000, "Swimming Chip"),
DEAD (0b00_1111_0000000000, "Dead");
private final int bits;
private final String name;
public int getBits() {
return bits;
}
public String prettyPrint() {
return name;
}
private static final CreatureID[] allCreatures = values();
public static CreatureID fromOrdinal(int ordinal) {
return allCreatures[ordinal];
}
public boolean isAffectedByCB(){
return this == TEETH || this == BUG || this == PARAMECIUM;
}
public boolean isChip(){
return this == CHIP || this == CHIP_SLIDING;
}
public boolean isMonster(){
return this.ordinal() <= TANK_STATIONARY.ordinal();
}
public boolean isBlock(){
return this == BLOCK || this == ICE_BLOCK;
}
public boolean isTank() {
return this == TANK_MOVING || this == TANK_STATIONARY;
}
CreatureID (int bits, String name) {
this.bits = bits;
this.name = name;
}
}
| 1,875 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
RNG.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/game/RNG.java | package game;
public class RNG{
public static final int LAST_SEED = 0x7FFFFFFF;
private int currentValue, prngValue1, prngValue2;
private int nextValue(){
return currentValue = (currentValue * 1103515245 + 12345) & 0x7FFFFFFF;
}
public void setCurrentValue(int value){
currentValue = value & 0x7FFFFFFF;
}
public int getCurrentValue() {
return currentValue;
}
public void setPRNG1(int value) {
prngValue1 = value;
}
public int getPRNG1() {
return prngValue1;
}
public void setPRNG2(int value) {
prngValue2 = value;
}
public int getPRNG2() {
return prngValue2;
}
/**
* Choose a random number from 0 to 3 inclusive. This is used by random
* force floors and Lynx blobs. This advances the RNG once.
* @return An int from 0-3 .
*/
public int random4(){
return nextValue() >>> 29;
}
/**
* Randomly permute an array with 3 elements in place. This is used by
* walkers on the array {left, backwards, right}. This advances the rng
* once.
* @param a The array to permute
*/
public void randomPermutation3(Object[] a){
nextValue();
Object swap;
int n;
n = currentValue >>> 30; // 0 or 1
swap = a[n]; a[n] = a[1]; a[1] = swap;
n = (int) ((3.0 * (currentValue & 0x3FFFFFFF)) / (double) 0x40000000); // 0, 1 or 2
swap = a[n]; a[n] = a[2]; a[2] = swap;
}
/**
* Randomly permute an array with 4 elements in place. This is used by
* blobs on the array {forwards, left, backwards, right}. This advances the
* rng once.
* @param a The array to permute
*/
public void randomPermutation4(Object[] a){
nextValue();
Object swap;
int n;
n = currentValue >>> 30; // 0 or 1
swap = a[n]; a[n] = a[1]; a[1] = swap;
n = (int) ((3.0 * (currentValue & 0x0FFFFFFF)) / (double) 0x10000000); // 0, 1 or 2
swap = a[n]; a[n] = a[2]; a[2] = swap;
n = (currentValue >>> 28) & 3; // 0, 1, 2 or 3
swap = a[n]; a[n] = a[3]; a[3] = swap;
}
/**
* Choose a pseudo random number (normally a pre-chosen cycle that's known to be constant)
* from 0 to 3 inclusive. This is used by Lynx walkers.
* @return An int from 0-3 .
*/
public int pseudoRandom4() {
int n = (prngValue1 >> 2) - prngValue1;
if ((prngValue1 & 0x02) == 0)
--n;
prngValue1 = (prngValue1 >> 1) | (prngValue2 & 0x80);
prngValue2 = (prngValue2 << 1) | (n & 0x01);
return ((prngValue1 ^ prngValue2) & 0xFF) & 0x03;
}
public RNG(int startingSeed, int prngValue1, int prngValue2) {
currentValue = startingSeed;
}
}
| 2,968 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
Step.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/game/Step.java | package game;
public enum Step{
EVEN,
EVEN1,
EVEN2,
EVEN3,
ODD,
ODD1,
ODD2,
ODD3;
public static Step fromTWS(int n) {
n &= 0b11111000;
n >>>= 3;
return values()[n];
}
public Step next() {
return values()[(ordinal() + 1) % values().length];
}
public byte toTWS() {
int n = ordinal();
return (byte) (n << 3);
}
public boolean isEven() {
return (ordinal() < 4);
}
@Override
public String toString() {
if (this != EVEN && this != ODD) {
return (isEven() ? "EVEN" : "ODD") + " + " + ordinal() % 4;
}
else return name();
}
}
| 698 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
Savestate.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/game/Savestate.java | package game;
import game.Lynx.LynxCreature;
import game.MS.MSCreature;
public interface Savestate {
int NO_CLICK = 1025;
int RLE_MULTIPLE = 0x7F;
int RLE_END = 0x7E;
byte UNCOMPRESSED_V2 = 6;
byte UNCOMPRESSED_V1 = 4;
byte COMPRESSED_V2 = 7;
byte COMPRESSED_V1 = 5;
/**
* Get chip from a savestate
* @param savestate a byte[] savestate
* @return A creature containing chip
*/
static Creature getChip(byte[] savestate){
if (savestate[1] == Ruleset.MS.ordinal())
return new MSCreature(((savestate[2] & 0xFF) << 8) | (savestate[3] & 0xFF));
else if (savestate[1] == Ruleset.LYNX.ordinal()) { //Yeah yeah hardcoded values into an array, Chip is always present so its safe
int x = (savestate[1059] & 0xFF) << 24 | (savestate[1060] & 0xFF) << 16
| (savestate[1061] & 0xFF) << 8 | (savestate[1062] & 0xFF);
return new LynxCreature(x);
}
return null;
}
/**
* Write an uncompressed savestate
* @return a savestate
*/
byte[] save();
/**
* load a savestate
* @param savestate the savestate to load
*/
void load(byte[] savestate);
}
| 1,222 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
LynxCreatureList.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/game/Lynx/LynxCreatureList.java | package game.Lynx;
import game.*;
import game.button.BrownButton;
import static game.CreatureID.*;
public class LynxCreatureList extends CreatureList {
private boolean[] creatureLayer;
private int phase;
@Override
public void setCreatures(Creature[] creatures) {
list = creatures;
creatureLayer = new boolean[1024];
for (Creature c : creatures) {
if (c.getCreatureType() == CHIP)
continue;
if (c.getCreatureType() != DEAD)
creatureLayer[c.getPosition().index] = true;
}
for (Creature c : list)
c.setLevel(level);
}
@Override
public void initialise() {
teethStep = ((level.getTickNumber()-1 + level.getStep().ordinal()) & 4) == 0;
chipToCr = null;
newClones.clear();
}
@Override
public void finalise() {
if (newClones.size() == 0)
return;
int length = list.length + newClones.size();
Creature[] newList = new Creature[length];
System.arraycopy(list, 0, newList, 0, list.length);
for (int i=0; i < newClones.size(); i++) {
newList[i + list.length] = newClones.get(i);
}
list = newList;
newClones.clear();
}
@Override
public void tick() {
Creature chip = level.getChip();
if (phase == 0) {
for (int i = list.length - 1; i >= 0; i--) {
Creature creature = list[i];
creature.setFDirection(Direction.NONE);
creature.setTDirection(Direction.NONE);
if (creature.getTimeTraveled() != 0 || creature.getCreatureType() == CHIP)
continue;
if (creature.isDead()) {
if (creature.getAnimationTimer() != 0)
creature.tick(false);
continue;
}
Tile currentTile = level.getLayerFG().get(creature.getPosition());
if (creature.getForcedMove(currentTile))
continue;
if (creature.getCreatureType() == BLOCK)
continue;
if (currentTile == Tile.CLONE_MACHINE || currentTile == Tile.TRAP) {
creature.setTDirection(creature.getDirection());
continue;
}
Direction[] moves = creature.getDirectionPriority(chip, level.getRNG());
boolean canMove = false;
for (Direction dir : moves) {
if (dir == Direction.NONE)
break;
if (dir == Direction.WALKER_TURN) {
int turns = level.getRNG().pseudoRandom4();
dir = creature.getDirection();
while (turns-- != 0)
dir = dir.turn(Direction.RIGHT);
}
else if (dir == Direction.BLOB_TURN) {
dir = new Direction[] {Direction.UP, Direction.RIGHT, Direction.DOWN, Direction.LEFT}[level.getRNG().random4()];
}
Position crPos = creature.getPosition();
Position newPos = crPos.move(dir);
creature.setTDirection(dir);
if (creature.canMakeMove(dir, newPos, true, false, false, false)) {
canMove = true;
break;
}
}
if (!canMove && creature.getCreatureType() == TEETH)
creature.setTDirection(moves[0]); //emulation of TW's pdir as teeth were the only thing that used it
}
phase = 1;
return;
}
if (phase == 1) {
for (int i = list.length - 1; i >= 0; i--) {
//Actual movement should be done here
Creature creature = list[i];
if (creature.getCreatureType() == CHIP || level.getLayerFG().get(creature.getPosition()) == Tile.CLONE_MACHINE
|| creature.getCreatureType() == DEAD)
continue;
creature.tick(false);
creature.setFDirection(Direction.NONE);
creature.setTDirection(Direction.NONE);
if (creature.getTimeTraveled() == 0 && level.getLayerFG().get(creature.getPosition()) == Tile.BUTTON_BROWN) {
BrownButton b = level.getBrownButtons().get(creature.getPosition());
if (b != null)
springTrappedCreature(b.getTargetPosition());
}
}
phase = 2;
return;
}
if (phase == 2) {
for (int i = list.length - 1; i >= 0; i--) {
Creature creature = list[i];
if (level.getLayerFG().get(creature.getPosition()) == Tile.TELEPORT) {
if (creature.getTimeTraveled() != 0 || creature.isDead())
continue;
if (level.getLayerFG().get(creature.getPosition()) == Tile.TELEPORT)
teleportCreature(creature);
}
}
phase = 0;
return;
}
}
@Override
public boolean claimed(Position position) {
if (!position.isValid())
return false;
return creatureLayer[position.index];
}
@Override
public void adjustClaim(Position position, boolean claim) {
if (!position.isValid())
return;
creatureLayer[position.index] = claim;
}
@Override
public boolean[] getClaimedArray() {
return creatureLayer;
}
@Override
public void setClaimedArray(boolean[] claimedArray) {
this.creatureLayer = claimedArray;
}
@Override
public Creature animationAt(Position position) {
if (!position.isValid())
return null;
for (Creature creature : list)
if (creature.getPosition().equals(position) && creature.getCreatureType() == DEAD && creature.getAnimationTimer() != 0)
return creature;
return null;
}
@Override
public void addClone(Position position) {
if (!position.isValid() || level.getLayerFG().get(position) != Tile.CLONE_MACHINE)
return;
Creature creature = creatureAt(position, true);
if (creature == null)
return;
//equivalent to TW's newcreature
Creature clone = null;
for (int i = 1; i < list.length; i++) {
Creature c = list[i];
if (c.isDead() && c.getAnimationTimer() == 0) {
clone = creature.clone();
list[i] = clone;
break;
}
}
if (clone == null && list.length + newClones.size() >= 2048) { //MAX_CREATURES in TW
creature.tick(true);
return;
}
boolean newClone = false;
if (clone == null) {
clone = creature.clone();
newClones.add(clone);
newClone = true;
}
if (!creature.tick(true)) {
if (newClone)
newClones.remove(clone);
clone.kill();
clone.kill(); //kill creature and anim
}
}
@Override
public void springTrappedCreature(Position position) {
if (position == null || !position.isValid() || level.getLayerFG().get(position) != Tile.TRAP)
return;
Creature creature = creatureAt(position, true);
if (creature == null || creature.getDirection() == Direction.NONE)
return;
creature.tick(true);
}
@Override
public void addCreature(Creature creature) {
if (list.length + newClones.size() >= 2048)
return;
newClones.add(creature);
if (!creature.isDead())
adjustClaim(creature.getPosition(), true);
}
private void teleportCreature(Creature creature) {
Position[] teleports = level.getTeleports();
int teleportIndex = -1;
for (int i = 0; i < level.getTeleports().length; i++) {
if (teleports[i].equals(creature.getPosition())) {
teleportIndex = i;
break;
}
}
if (teleportIndex == -1) //not found
return;
int origIndex = teleportIndex; //use then dec
while (true) {
--teleportIndex;
if (teleportIndex == -1)
teleportIndex = teleports.length - 1;
Position telePos = teleports[teleportIndex];
if (creature.getCreatureType() != CHIP)
adjustClaim(creature.getPosition(), false);
creature.setPosition(telePos);
if (!claimed(telePos) && creature.canMakeMove(creature.getDirection(), telePos.move(creature.getDirection()),
false, false, false, false)) {
break;
}
if (teleportIndex == origIndex) {
if (creature.getCreatureType() == CHIP) //TW sets chipstuck() to true here but its a death sentence
creature.kill();
else
adjustClaim(telePos, true);
return;
}
//note: TW has something about else if (ismarkedteleport(pos)) around this part, find out why maybe
}
if (creature.getCreatureType() != CHIP)
adjustClaim(creature.getPosition(), true);
creature.setTeleportFlag(true);
return;
}
public LynxCreatureList(Creature[] creatures) {
super(creatures);
setCreatures(creatures);
}
}
| 9,771 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
LynxLevel.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/game/Lynx/LynxLevel.java | package game.Lynx;
import game.*;
import game.Cheats;
import game.MS.SlipList;
import game.button.*;
import util.MultiHashMap;
import java.util.List;
import java.util.Map;
import static game.Direction.*;
public class LynxLevel extends LynxSavestate implements Level {
private static final int HALF_WAIT = 0, KEY = 1;
private final int LEVELSET_LENGTH;
private final int levelNumber;
private int startTime;
private final String title, password, hint, author;
private final Position[] toggleDoors, teleports;
private MultiHashMap<Position, GreenButton> greenButtons;
private MultiHashMap<Position, RedButton> redButtons;
private MultiHashMap<Position, BrownButton> brownButtons;
private MultiHashMap<Position, BlueButton> blueButtons;
private MultiHashMap<Position, BrownButton> trapButtons;
private int rngSeed;
private Step step;
private final Direction INITIAL_SLIDE;
private final Ruleset RULESET = Ruleset.LYNX;
private boolean levelWon, turnTanks;
private final Cheats cheats;
@Override
public int getLevelNumber() {
return levelNumber;
}
@Override
public int getStartTime() {
return startTime;
}
@Override
public String getTitle() {
return title;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getHint() {
return hint;
}
@Override
public String getAuthor() {
return author;
}
@Override
public Position[] getToggleDoors() {
return toggleDoors;
}
@Override
public Position[] getTeleports() {
return teleports;
}
@Override
public MultiHashMap<Position, GreenButton> getGreenButtons() {
return greenButtons;
}
@Override
public MultiHashMap<Position, RedButton> getRedButtons() {
return redButtons;
}
@Override
public MultiHashMap<Position, BrownButton> getBrownButtons() {
return brownButtons;
}
@Override
public MultiHashMap<Position, BlueButton> getBlueButtons() {
return blueButtons;
}
@Override
public MultiHashMap<Position, BrownButton> getTrapButtons() {
return trapButtons;
}
@Override
public void setGreenButtons(MultiHashMap<Position, GreenButton> greenButtons) {
this.greenButtons = greenButtons;
}
@Override
public void setBlueButtons(MultiHashMap<Position, BlueButton> blueButtons) {
this.blueButtons = blueButtons;
}
@Override
public int getRngSeed() {
return rngSeed;
}
@Override
public Step getStep() {
return step;
}
@Override
public boolean supportsLayerBG() {
return false;
}
@Override
public boolean supportsClick() {
return false;
}
@Override
public boolean supportsSliplist() {
return false;
}
@Override
public boolean supportsDiagonal() {
return true;
}
@Override
public boolean hasCyclicRFF() {
return true;
}
@Override
public boolean chipInMonsterList() {
return true;
}
@Override
public boolean trapRequiresHeldButton() {
return true;
}
@Override
public boolean creaturesAreTiles() {
return false;
}
@Override
public boolean hasStillTanks() {
return false;
}
@Override
public boolean swimmingChipIsCreature() {
return true;
}
@Override
public boolean blocksInMonsterList() {
return true;
}
@Override
public int ticksPerMove() {
return RULESET.ticksPerMove;
}
@Override
public Layer getLayerBG() {
throw new UnsupportedOperationException("Background Layer does not exist under Lynx");
}
@Override
public Layer getLayerFG() {
return layerFG;
}
@Override
public boolean isUntimed() {
return startTime < 0;
}
@Override
public int getTimer(){
if (tickNumber == 0) return startTime;
else return startTime - tickNumber*5 + 5; //first tick does not change timer
}
@Override
public void setTimer(int n) {
startTime = n + tickNumber - 1;
}
@Override
public int getTChipTime() {
if (tickNumber == 0) return 99995;
else return 99995 - tickNumber*5 + 5; //first tick does not change timer
}
@Override
public int getChipsLeft() {
return chipsLeft;
}
@Override
public void setChipsLeft(int chipsLeft) {
this.chipsLeft = chipsLeft;
}
@Override
public Creature getChip() {
return chip;
}
@Override
public short[] getKeys() {
return keys;
}
@Override
public void setKeys(short[] keys) {
this.keys = keys;
}
@Override
public byte[] getBoots() {
return boots;
}
@Override
public void setBoots(byte[] boots){
this.boots = boots;
}
@Override
public CreatureList getMonsterList() {
return monsterList;
}
@Override
public SlipList getSlipList() {
throw new UnsupportedOperationException("Sliplist does not exist under Lynx");
}
@Override
public void setTrap(Position trapPos, boolean open) {
if (open) {
monsterList.springTrappedCreature(trapPos);
}
}
@Override
public int getLevelsetLength() {
return LEVELSET_LENGTH;
}
@Override
public Cheats getCheats() {
return cheats;
}
@Override
public RNG getRNG() {
return rng;
}
@Override
public Button getButton(Position position, Class<? extends Button> buttonType) {
if (buttonType.equals(GreenButton.class))
return greenButtons.get(position);
else if (buttonType.equals(RedButton.class))
return redButtons.get(position);
else if (buttonType.equals(BrownButton.class))
return brownButtons.get(position);
else if (buttonType.equals(BlueButton.class))
return blueButtons.get(position);
else throw new RuntimeException("Invalid class");
}
@Override
public Button getButton(Position position) {
for (Map<Position, ? extends Button> buttons : List.of(greenButtons, redButtons, brownButtons, blueButtons)) {
if (buttons.get(position) != null)
return buttons.get(position);
}
return null;
}
@Override
public boolean isTrapOpen(Position position) {
for (BrownButton b : trapButtons.getList(position)) {
if (monsterList.creatureAt(b.getButtonPosition(), true) != null)
return true;
}
return false;
}
@Override
public int getTickNumber() {
return tickNumber;
}
@Override
public Ruleset getRuleset() {
return RULESET;
}
@Override
public Direction getInitialRFFDirection() {
return INITIAL_SLIDE;
}
@Override
public Direction getRFFDirection(boolean advance) {
if (advance)
rffDirection = rffDirection.turn(Direction.RIGHT);
return rffDirection;
}
@Override
public void setClick(int position) {
throw new UnsupportedOperationException("Mouse clicks do not exist under Lynx");
}
@Override
public void setLevelWon(boolean won) {
this.levelWon = won;
}
@Override
public boolean isCompleted() {
return levelWon;
}
@Override
public int tick(char c, Direction[] directions) {
tickNumber++;
setLevelWon(false); //Each tick sets the level won state to false so that even when rewinding unless you stepped into the exit the level is not won
turnTanks = false;
monsterList.initialise();
monsterList.tick(); //select monster moves
Tile chipTileOld = layerFG.get(chip.getPosition());
int discard = 0;
if (chip.getTimeTraveled() == 0) {
if (selectChipMove(directions[0]))
discard = MASK_DISCARD_INPUT;
}
else
discard = MASK_DISCARD_INPUT;
Direction chipTDir = chip.getTDirection();
monsterList.tick(); //move monsters
boolean result = moveChip();
Tile chipTileNew = layerFG.get(chip.getPosition());
monsterList.tick(); //teleport monsters
monsterList.finalise();
if (turnTanks) {
for (Creature m : monsterList) {
Tile floor = layerFG.get(m.getPosition());
if (m.getCreatureType() == CreatureID.TANK_MOVING && m.getTimeTraveled() == 0
&& floor != Tile.CLONE_MACHINE && !floor.isIce())
m.turn(TURN_AROUND);
}
}
if (layerFG.get(chip.getPosition()) == Tile.EXIT && chip.getTimeTraveled() == 0
&& chip.getAnimationTimer() == 1) { //this is a hack but it ensures that starting on an exit won't win the level
tickNumber++;
chip.kill();
chip.kill(); //destroys the animation as well
layerFG.set(chip.getPosition(), Tile.EXITED_CHIP);
setLevelWon(true);
return discard;
}
boolean sliding = chipTileOld.isSliding() || chipTileNew.isSliding()
|| chipTileOld == Tile.TRAP || chipTileNew == Tile.TRAP;
boolean ff = (chipTileNew.isFF() || chipTileOld.isFF()) && boots[3] == 0;
boolean ice = (chipTileNew.isIce() || chipTileOld.isIce()) && boots[2] == 0;
if (result && !chip.isSliding() && !(sliding && (ff || ice)
|| chipTileOld == Tile.TRAP || chipTileNew == Tile.TRAP))
return MASK_TICK_MULTI | discard;
else
return discard;
//traps perform forced moves but aren't counted as sliding tiles as it would fuck some logic up
}
//return true if the input given to make this move should be discarded
private boolean selectChipMove(Direction direction) {
chip.setTDirection(NONE);
chip.setFDirection(NONE);
Position chipPos = chip.getPosition();
if (chip.getForcedMove(layerFG.get(chipPos))) {
return true;
}
if (direction == NONE) {
return false;
}
if (direction.isDiagonal()) {
Direction chipDir = chip.getDirection();
if (direction.isComponent(chipDir)) {
boolean canMoveMain = chip.canMakeMove(chipDir, chipPos.move(chipDir), false, true, false, false);
Direction other = direction.decompose()[0] == chipDir ? direction.decompose()[1] : direction.decompose()[0];
boolean canMoveOther = chip.canMakeMove(other, chipPos.move(other), false, true, false, false);
if (!canMoveMain && canMoveOther) {
chip.setTDirection(other);
return false;
}
chip.setTDirection(chipDir);
}
else {
Direction vert = direction.decompose()[0];
Direction horz = direction.decompose()[1]; //horz dir is always second in decompose
if (chip.canMakeMove(horz, chipPos.move(horz), false, true, false, false)) {
chip.setTDirection(horz);
}
else {
chip.setTDirection(vert);
}
}
return false;
}
chip.canMakeMove(direction, chipPos.move(direction), false, true, false, false); //for side effects
chip.setTDirection(direction);
return false;
}
private boolean moveChip() {
boolean result = chip.tick(false) && chip.getTDirection() != Direction.NONE;
chip.setTDirection(NONE); //mirror TW clearing the dirs at the end of the monster loop
chip.setFDirection(NONE);
if (chip.getTimeTraveled() == 0 && layerFG.get(chip.getPosition()) == Tile.BUTTON_BROWN) {
BrownButton b = brownButtons.get(chip.getPosition());
if (b != null)
monsterList.springTrappedCreature(b.getTargetPosition());
}
return result;
}
@Override
public void insertTile(Position position, Tile tile) {
layerFG.set(position, tile);
}
@Override
public void popTile(Position position) {
layerFG.set(position, Tile.FLOOR);
}
@Override
public boolean shouldDrawCreatureNumber(Creature creature) {
return !(creature.isDead() && creature.getAnimationTimer() == 0);
}
@Override
public void turnTanks() {
turnTanks ^= true;
}
@Override
//for the love of god make SURE to override this if anything extends this class
public Creature newCreature(Direction dir, CreatureID creatureType, Position position) {
Creature creature = new LynxCreature(dir, creatureType, position);
creature.setLevel(this);
return creature;
}
public LynxLevel(int levelNumber, String title, String password, String hint, String author,
Position[] toggleDoors, Position[] teleports,
MultiHashMap<Position, GreenButton> greenButtons, MultiHashMap<Position, RedButton> redButtons,
MultiHashMap<Position, BrownButton> brownButtons, MultiHashMap<Position, BlueButton> blueButtons,
Layer layerFG, CreatureList monsterList,
Creature chip, int time, int chips, RNG rng, int rngSeed, Step step, int levelsetLength, Direction INITIAL_SLIDE){
super(layerFG, monsterList, chip,
chips, new short[4], new byte[4], rng);
this.levelNumber = levelNumber;
this.startTime = time;
this.title = title;
this.password = password;
this.hint = hint;
this.author = author;
this.toggleDoors = toggleDoors;
this.teleports = teleports;
this.greenButtons = greenButtons;
this.redButtons = redButtons;
this.brownButtons = brownButtons;
this.blueButtons = blueButtons;
this.rngSeed = rngSeed;
this.rffDirection = INITIAL_SLIDE.turn(TURN_LEFT); //Yup, easier to rotate left here than have every other section rotate right
this.step = step;
this.cheats = new Cheats(this);
this.LEVELSET_LENGTH = levelsetLength;
this.INITIAL_SLIDE = INITIAL_SLIDE;
for (Creature c : monsterList)
c.setLevel(this);
this.monsterList.setLevel(this);
this.trapButtons = new MultiHashMap<>(this.brownButtons.size());
for (List<BrownButton> buttons : this.brownButtons.rawValues()) {
for (BrownButton b : buttons) {
trapButtons.put(b.getTargetPosition(), b);
}
}
}
}
| 14,940 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
LynxSavestate.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/game/Lynx/LynxSavestate.java | package game.Lynx;
import game.*;
public class LynxSavestate implements Savestate {
private static final byte UNCOMPRESSED_V2 = 6;
private static final byte UNCOMPRESSED_V1 = 4;
public Layer layerFG;
public Creature chip;
public int tickNumber;
public int chipsLeft;
public short[] keys;
public byte[] boots;
public RNG rng;
public Direction rffDirection;
public CreatureList monsterList;
protected boolean lastMoveForced;
@Override
public byte[] save() {
int length =
1 + // version
1 + // ruleset
1024 + // layerFG
4 + // tick number
2 + // chips left
4 * 2 + // keys
4 * 1 + // boots
3 * 4 + // rng
1 + // RFF
2 + // monsterlist size
monsterList.size() * 4 + // monsterlist
1024 + // claimed array
1; // lastMoveForced
SavestateWriter writer = new SavestateWriter(length);
writer.write(UNCOMPRESSED_V2); //Every time this is updated also update compress() in SavestateManager.java
writer.write(Ruleset.LYNX.ordinal());
writer.write(layerFG.getBytes());
writer.writeInt(tickNumber);
writer.writeShort(chipsLeft);
writer.writeShorts(keys);
writer.write(boots);
writer.writeInt(rng.getCurrentValue());
writer.writeInt(rng.getPRNG1());
writer.writeInt(rng.getPRNG2());
writer.write(rffDirection.ordinal());
writer.writeShort(monsterList.size());
writer.writeIntMonsterArray(monsterList.getCreatures());
writer.writeBools(monsterList.getClaimedArray());
writer.writeBool(lastMoveForced);
return writer.toByteArray();
}
@Override
public void load(byte[] savestate) {
SavestateReader reader = new SavestateReader(savestate);
int version = reader.read();
if (version == UNCOMPRESSED_V2 || version == COMPRESSED_V2) {
if (reader.read() != Ruleset.LYNX.ordinal())
throw new UnsupportedOperationException("Can only load lynx savestates!");
layerFG.load(reader.readLayer(version));
tickNumber = reader.readInt();
chipsLeft = (short) reader.readShort();
keys = reader.readShorts(4);
boots = reader.readBytes(4);
rng.setCurrentValue(reader.readInt());
rng.setPRNG1(reader.readInt());
rng.setPRNG2(reader.readInt());
rffDirection = Direction.fromOrdinal(reader.read());
monsterList.setCreatures(reader.readLynxMonsterArray(reader.readShort()));
monsterList.setClaimedArray(reader.readBools(1024));
lastMoveForced = reader.readBool();
chip = monsterList.get(0);
}
}
protected LynxSavestate(Layer layerFG, CreatureList monsterList, Creature chip,
int chipsLeft, short[] keys, byte[] boots, RNG rng){
this.layerFG = layerFG;
this.monsterList = monsterList;
this.chip = chip;
this.tickNumber = 0;
this.chipsLeft = chipsLeft;
this.keys = keys;
this.boots = boots;
this.rng = rng;
}
}
| 3,643 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
LynxCreature.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/game/Lynx/LynxCreature.java | package game.Lynx;
import game.*;
import game.button.Button;
import java.util.Objects;
import static game.CreatureID.*;
import static game.Direction.*;
import static game.Direction.TURN_AROUND;
import static game.Tile.*;
/**
* Lynx creatures are encoded as follows:
*
* 0 | 0 | 0 | 0 0 0 0 | 0 0 0 | 0 0 0 0 | 0 0 0 0 | 0 0 0 0 0 | 0 0 0 0 0 |
* TELEPORT | OVERRIDE | SLIDING | ANIMATION | TIME TRAVEL | DIRECTION | MONSTER | ROW | COL |
*/
public class LynxCreature extends Creature {
protected int timeTraveled;
protected int animationTimer; //Exists primarily for death effect and Chip in exit timing, but adds future ability to implement actual animations
protected boolean overrideToken;
@Override
public Tile toTile() { //Used exclusively for drawing creatures, please do not use for anything else
return switch (creatureType) {
case BLOCK -> Tile.BLOCK;
case CHIP -> Tile.fromOrdinal(Tile.CHIP_UP.ordinal() | direction.ordinal());
case TANK_MOVING, TANK_STATIONARY -> Tile.fromOrdinal(TANK_UP.ordinal() | direction.ordinal());
case CHIP_SWIMMING -> Tile.fromOrdinal(CHIP_SWIMMING_UP.ordinal() | direction.ordinal());
default -> Tile.fromOrdinal((creatureType.ordinal() << 2) + 0x40 | direction.ordinal());
};
}
@Override
public int getTimeTraveled() {
return timeTraveled % 9; //timeTraveled should always be between 0 and 8 anyways but just to be safe
}
@Override
public int getAnimationTimer() {
return animationTimer % 13; //it should always be between 0 and 12 but safety
}
@Override
public boolean tick(boolean releasing) {
Direction direction;
Direction tdir = NONE;
if (animationTimer != 0) {
animationTimer--;
return false;
}
if (timeTraveled == 0) { //analog to TW's startmovement()
sliding = false;
if (releasing) {
tdir = this.tDirection;
this.tDirection = this.direction;
} else if (tDirection == NONE && fDirection == NONE)
return false;
//equiv. to TW's startmovement
if (tDirection != NONE)
direction = tDirection;
else if (fDirection != NONE) {
direction = fDirection;
sliding = true;
}
else {
if (releasing)
tDirection = tdir;
return false;
}
this.direction = direction;
Position from = position;
Position to = position.move(direction);
Tile tileFrom = level.getLayerFG().get(from);
if (creatureType == CreatureID.CHIP) {
if (level.getBoots()[3] == 0) {
if (tileFrom.isFF() && tDirection == NONE)
overrideToken = true;
else if (!tileFrom.isIce() || level.getBoots()[2] != 0)
overrideToken = false;
}
}
boolean isChip = creatureType == CreatureID.CHIP;
if (!canMakeMove(direction, to, !isChip, isChip, isChip, releasing)) {
if (level.getLayerFG().get(from).isIce() && (!isChip || level.getBoots()[2] == 0)) {
direction = direction.turn(TURN_AROUND);
this.direction = getSlideDirection(direction, level.getLayerFG().get(from), null, false);
}
if (releasing)
tDirection = tdir;
return false;
}
if (creatureType != CreatureID.CHIP) {
level.getMonsterList().adjustClaim(from, false);
//this is a semi-hacky implimentation of TW's chiptocr() and chiptopos()
Creature chip = level.getChip();
if (creatureType != CreatureID.BLOCK && position.equals(chip.getPosition().move(chip.getTDirection())))
level.getMonsterList().setChipToCr(this);
}
else if (level.getMonsterList().getChipToCr() != null) {
kill();
level.getMonsterList().getChipToCr().kill();
return false;
}
position = to;
if (creatureType != CreatureID.CHIP)
level.getMonsterList().adjustClaim(to, true);
timeTraveled = 8;
if (creatureType != CreatureID.CHIP && level.getChip().getPosition().equals(position)) {
level.getChip().kill();
kill();
return false;
}
else if (creatureType == CreatureID.CHIP && level.getMonsterList().creatureAt(position, false) != null) {
kill();
level.getMonsterList().creatureAt(position, false).kill();
return false;
}
}
if (creatureType != DEAD) { //analog to TW's continue movement
int speed = creatureType == BLOB ? 1 : 2;
Tile tile = level.getLayerFG().get(position);
if (tile.isIce() && (creatureType != CreatureID.CHIP || level.getBoots()[2] == 0))
speed *= 2;
else if (tile.isFF() && (creatureType != CreatureID.CHIP || level.getBoots()[3] == 0))
speed *= 2;
timeTraveled -= speed;
}
if (timeTraveled > 0)
return true;
Tile newTile = level.getLayerFG().get(position);
switch (newTile) {
case WATER:
if (creatureType == CreatureID.BLOCK)
level.getLayerFG().set(position, DIRT);
if (creatureType != GLIDER && !(creatureType == CreatureID.CHIP && level.getBoots()[0] != 0))
kill();
break;
case ICE_SLIDE_SOUTHEAST:
case ICE_SLIDE_SOUTHWEST:
case ICE_SLIDE_NORTHWEST:
case ICE_SLIDE_NORTHEAST:
if (creatureType != CreatureID.CHIP || level.getBoots()[2] == 0) {
this.direction = getSlideDirection(this.direction, newTile, null, false);
}
break;
case BUTTON_GREEN:
case BUTTON_RED:
// case BUTTON_BROWN left out intentionally, handled later
case BUTTON_BLUE:
Button button = level.getButton(position);
if (button != null)
button.press(level);
break;
case FIRE:
if (creatureType == CreatureID.CHIP && level.getBoots()[1] == 0)
kill();
break;
case BOMB:
kill();
level.getLayerFG().set(position, FLOOR);
break;
case POP_UP_WALL:
level.getLayerFG().set(position, WALL);
break;
case BLUEWALL_FAKE:
case SOCKET:
case DIRT:
level.getLayerFG().set(position, FLOOR);
break;
case CHIP:
if (creatureType == CreatureID.CHIP) {
level.setChipsLeft(level.getChipsLeft() - 1);
level.getLayerFG().set(position, FLOOR);
}
break;
case KEY_BLUE:
if (creatureType == CreatureID.CHIP)
level.getKeys()[0]++;
level.getLayerFG().set(position, FLOOR);
break;
case KEY_RED:
if (creatureType == CreatureID.CHIP) {
level.getKeys()[1]++;
level.getLayerFG().set(position, FLOOR);
}
break;
case KEY_GREEN:
if (creatureType == CreatureID.CHIP) {
level.getKeys()[2]++;
level.getLayerFG().set(position, FLOOR);
}
break;
case KEY_YELLOW:
if (creatureType == CreatureID.CHIP) {
level.getKeys()[3]++;
level.getLayerFG().set(position, FLOOR);
}
break;
case DOOR_BLUE:
level.getKeys()[0]--;
level.getLayerFG().set(position, FLOOR);
break;
case DOOR_RED:
level.getKeys()[1]--;
level.getLayerFG().set(position, FLOOR);
break;
case DOOR_GREEN:
level.getLayerFG().set(position, FLOOR);
break;
case DOOR_YELLOW:
level.getKeys()[3]--;
level.getLayerFG().set(position, FLOOR);
break;
case BOOTS_WATER:
if (creatureType == CreatureID.CHIP) {
level.getBoots()[0] = 1;
level.getLayerFG().set(position, FLOOR);
}
break;
case BOOTS_FIRE:
if (creatureType == CreatureID.CHIP) {
level.getBoots()[1] = 1;
level.getLayerFG().set(position, FLOOR);
}
break;
case BOOTS_ICE:
if (creatureType == CreatureID.CHIP) {
level.getBoots()[2] = 1;
level.getLayerFG().set(position, FLOOR);
}
break;
case BOOTS_FF:
if (creatureType == CreatureID.CHIP) {
level.getBoots()[3] = 1;
level.getLayerFG().set(position, FLOOR);
}
break;
case EXIT:
if (creatureType == CreatureID.CHIP)
animationTimer = 1; //see the relevant comment in LynxLevel.java's tick() method
break;
case THIEF:
if (creatureType == CreatureID.CHIP)
level.setBoots(new byte[]{0, 0, 0, 0});
break;
}
return true;
}
@Override
public Direction[] getDirectionPriority(Creature chip, RNG rng) {
if (tDirection != NONE)
return new Direction[] {NONE};
if (nextMoveDirectionCheat != null) {
Direction[] directions = new Direction[] {nextMoveDirectionCheat};
nextMoveDirectionCheat = null;
if (creatureType == BLOB)
rng.random4();
if (creatureType == WALKER)
rng.pseudoRandom4();
return directions;
}
switch (creatureType) {
case BUG:
return direction.turn(new Direction[] {TURN_LEFT, TURN_FORWARD, TURN_RIGHT, TURN_AROUND});
case FIREBALL:
return direction.turn(new Direction[] {TURN_FORWARD, TURN_RIGHT, TURN_LEFT, TURN_AROUND});
case PINK_BALL:
return direction.turn(new Direction[] {TURN_FORWARD, TURN_AROUND});
case TANK_MOVING:
return new Direction[] {getDirection()};
case GLIDER:
return direction.turn(new Direction[] {TURN_FORWARD, TURN_LEFT, TURN_RIGHT, TURN_AROUND});
case TEETH:
if (!level.getMonsterList().getTeethStep())
return new Direction[] {NONE};
return position.seek(chip.getPosition());
case WALKER:
return new Direction[] {direction, WALKER_TURN};
case BLOB:
return new Direction[] {BLOB_TURN};
case PARAMECIUM:
return direction.turn(new Direction[] {TURN_RIGHT, TURN_FORWARD, TURN_LEFT, TURN_AROUND});
default:
return new Direction[] {NONE};
}
}
@Override
public Direction getSlideDirection(Direction direction, Tile tile, RNG rng, boolean advanceRFF){
switch (tile){
case FF_DOWN:
return DOWN;
case FF_UP:
return UP;
case FF_RIGHT:
return RIGHT;
case FF_LEFT:
return LEFT;
case FF_RANDOM:
if (advanceRFF)
return level.getRFFDirection(true);
else
return level.getRFFDirection(false);
case ICE_SLIDE_SOUTHEAST:
if (direction == UP) return RIGHT;
else if (direction == LEFT) return DOWN;
else return direction;
case ICE_SLIDE_NORTHEAST:
if (direction == DOWN) return RIGHT;
else if (direction == LEFT) return UP;
else return direction;
case ICE_SLIDE_NORTHWEST:
if (direction == DOWN) return LEFT;
else if (direction == RIGHT) return UP;
else return direction;
case ICE_SLIDE_SOUTHWEST:
if (direction == UP) return LEFT;
else if (direction == RIGHT) return DOWN;
else return direction;
case TRAP:
return direction;
}
return direction;
}
@Override
public boolean getForcedMove(Tile tile) {
fDirection = NONE;
if (level.getTickNumber() == 1)
return false;
if (tile.isSliding()) { //replication of TW's getforcedmove()
if (tile.isIce()) {
if (direction == Direction.NONE)
return false;
if (creatureType == CreatureID.CHIP && level.getBoots()[2] != 0)
return false;
fDirection = direction;
return true;
}
else if (tile.isFF()) {
if (creatureType == CreatureID.CHIP && level.getBoots()[3] != 0)
return false;
fDirection = getSlideDirection(direction, tile, null, true);
return !overrideToken;
}
else if (teleportFlag) { //please find how the CS_TELEPORTED flag works in TW
teleportFlag = false;
fDirection = direction;
return true;
}
}
return false;
}
@Override
public void kill() {
if (creatureType != DEAD) {
if (creatureType != CreatureID.CHIP)
level.getMonsterList().adjustClaim(position, false);
creatureType = DEAD;
animationTimer = ((level.getTickNumber() + level.getStep().ordinal()) & 1) == 0 ? 12 : 11; //basically copied out of TW's source
timeTraveled = 0;
switch (level.getLayerFG().get(position)) { //direction is used for determining which graphic to draw
case WATER, DIRT -> direction = UP;
case FIRE, BOMB -> direction = LEFT;
default -> direction = DOWN;
}
}
else
animationTimer = 0;
}
@Override
public boolean canMakeMove(Direction direction, Position position, boolean clearAnims, boolean pushBlocks, boolean pushBlocksNow, boolean releasing) {
if (timeTraveled != 0) //this is more defensive than TW which only checks for Blocks, see if that's an issue anywhere
return false;
if (!canLeave(direction, this.position, releasing) || !position.isValid())
return false;
Tile enteringTile = level.getLayerFG().get(position);
if (!canEnter(direction, enteringTile))
return false;
if (creatureType == CreatureID.CHIP) {
if (level.getMonsterList().animationAt(position) != null)
return false;
Creature other = level.getMonsterList().creatureAt(position, false);
if (other != null && other.getCreatureType() == CreatureID.BLOCK) {
Position blockPos = other.getPosition(); //equiv. to TW's canpushblock()
if (!other.canMakeMove(direction, blockPos.move(direction), true, false, false, false)) {
if (other.getTimeTraveled() == 0 && (pushBlocks || pushBlocksNow))
other.setDirection(direction);
return false;
}
if (pushBlocks || pushBlocksNow) {
other.setDirection(direction);
other.setTDirection(direction);
if (pushBlocksNow)
other.tick(false);
}
}
if (enteringTile == HIDDENWALL_TEMP || enteringTile == BLUEWALL_REAL) {
if (timeTraveled == 0 && level.getLayerFG().get(this.position) != TELEPORT)
level.getLayerFG().set(position, WALL);
return false;
}
}
else {
if (level.getMonsterList().claimed(position))
return false;
Creature anim = level.getMonsterList().animationAt(position);
if (anim != null && clearAnims)
anim.kill();
}
return true;
}
private boolean canEnter(Direction direction, Tile tile) {
boolean isChip = creatureType.isChip();
return switch (tile) {
case FLOOR -> true;
case WALL -> false;
case CHIP -> isChip;
case WATER -> true;
case FIRE -> creatureType == FIREBALL || isChip || creatureType == CreatureID.BLOCK;
case INVISIBLE_WALL -> false;
case THIN_WALL_UP -> direction != DOWN;
case THIN_WALL_LEFT -> direction != RIGHT;
case THIN_WALL_DOWN -> direction != UP;
case THIN_WALL_RIGHT -> direction != LEFT;
case DIRT -> isChip;
case ICE, FF_DOWN, FF_UP, FF_RIGHT, FF_LEFT -> true;
case EXIT -> isChip;
case DOOR_BLUE -> isChip && level.getKeys()[0] > 0;
case DOOR_RED -> isChip && level.getKeys()[1] > 0;
case DOOR_GREEN -> isChip && level.getKeys()[2] > 0;
case DOOR_YELLOW -> isChip && level.getKeys()[3] > 0;
case ICE_SLIDE_SOUTHEAST -> direction != DOWN && direction != RIGHT;
case ICE_SLIDE_SOUTHWEST -> direction != DOWN && direction != LEFT;
case ICE_SLIDE_NORTHWEST -> direction != UP && direction != LEFT;
case ICE_SLIDE_NORTHEAST -> direction != UP && direction != RIGHT;
case BLUEWALL_FAKE -> isChip;
case BLUEWALL_REAL -> isChip;
case OVERLAY_BUFFER -> false;
case THIEF -> isChip;
case SOCKET -> isChip && level.getChipsLeft() <= 0;
case BUTTON_GREEN, BUTTON_RED -> true;
case TOGGLE_CLOSED -> false;
case TOGGLE_OPEN, BUTTON_BROWN, BUTTON_BLUE, TELEPORT, BOMB, TRAP -> true;
case HIDDENWALL_TEMP -> isChip;
case GRAVEL -> isChip || creatureType == CreatureID.BLOCK;
case POP_UP_WALL, HINT -> isChip;
case THIN_WALL_DOWN_RIGHT -> direction != UP && direction != LEFT;
case CLONE_MACHINE -> false;
case FF_RANDOM -> true;
case DROWNED_CHIP, BURNED_CHIP, BOMBED_CHIP, UNUSED_36, UNUSED_37, ICE_BLOCK, EXITED_CHIP, EXIT_EXTRA_1, EXIT_EXTRA_2 -> false; //Doesn't exist in lynx
case KEY_BLUE, KEY_RED -> true;
case KEY_GREEN, KEY_YELLOW, BOOTS_WATER, BOOTS_FIRE, BOOTS_ICE, BOOTS_FF -> isChip; //Probably shouldn't exist as a tile
case CHIP_UP, CHIP_LEFT, CHIP_DOWN, CHIP_RIGHT -> !isChip;
default -> false;
};
}
private boolean canLeave(Direction direction, Position position, boolean releasing) {
Tile tile = level.getLayerFG().get(position);
switch (tile){
case THIN_WALL_UP: return direction != UP;
case THIN_WALL_RIGHT: return direction != RIGHT;
case THIN_WALL_DOWN: return direction != DOWN;
case THIN_WALL_LEFT: return direction != LEFT;
case THIN_WALL_DOWN_RIGHT: return direction != DOWN && direction != RIGHT;
case ICE_SLIDE_SOUTHEAST: return direction != UP && direction != LEFT;
case ICE_SLIDE_SOUTHWEST: return direction != UP && direction != RIGHT;
case ICE_SLIDE_NORTHWEST: return direction != DOWN && direction != RIGHT;
case ICE_SLIDE_NORTHEAST: return direction != DOWN && direction != LEFT;
case CLONE_MACHINE:
case TRAP: return releasing;
}
if (tile.isFF()) {
if (creatureType != CreatureID.CHIP || level.getBoots()[3] == 0)
return direction.turn(TURN_AROUND) != getSlideDirection(NONE, tile, null, false);
}
return true;
}
@Override
public boolean canOverride() {
return overrideToken;
}
@Override
public int bits() {
return ((teleportFlag ? 1 : 0) << 28) | ((overrideToken ? 1 : 0) << 27) | ((sliding ? 1 : 0) << 26)
| (animationTimer << 22) | (timeTraveled << 18) | (direction.getBits() << 14) | creatureType.getBits()
| position.getIndex();
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
LynxCreature that = (LynxCreature) o;
if (position != that.position)
return false;
if (creatureType != that.creatureType)
return false;
if (direction != that.direction)
return false;
if (sliding != that.sliding)
return false;
if (timeTraveled != that.timeTraveled)
return false;
return animationTimer == that.animationTimer;
}
@Override
public int hashCode() {
return Objects.hash(position, creatureType, direction, sliding, timeTraveled, animationTimer);
}
@Override
public Creature clone() {
LynxCreature c = new LynxCreature(bits());
c.setLevel(level);
return c;
}
public LynxCreature(Direction dir, CreatureID creatureType, Position position) {
this.direction = dir;
this.creatureType = creatureType;
this.position = position;
}
public LynxCreature(Position position, Tile tile) {
this.position = position;
if (BLOCK_UP.ordinal() <= tile.ordinal() && tile.ordinal() <= BLOCK_RIGHT.ordinal()){
direction = Direction.fromOrdinal((tile.ordinal() + 2) % 4);
creatureType = CreatureID.BLOCK;
}
else {
direction = Direction.fromOrdinal(tile.ordinal() % 4);
switch (tile) {
case BLOCK -> {
direction = UP;
creatureType = CreatureID.BLOCK;
}
case CHIP_SWIMMING_UP, CHIP_SWIMMING_LEFT, CHIP_SWIMMING_DOWN, CHIP_SWIMMING_RIGHT -> creatureType = CHIP_SWIMMING;
default -> creatureType = CreatureID.fromOrdinal((tile.ordinal() - 0x40) >>> 2);
}
}
if (creatureType == TANK_STATIONARY)
creatureType = TANK_MOVING;
}
public LynxCreature(int bitMonster) {
teleportFlag = ((bitMonster >>> 28) & 0b1) == 1;
overrideToken = ((bitMonster >>> 27) & 0b1) == 1;
sliding = ((bitMonster >>> 26) & 0b1) == 1;
animationTimer = (bitMonster >>> 22) & 0b1111;
timeTraveled = (bitMonster >>> 18) & 0b111;
direction = Direction.fromOrdinal((bitMonster >>> 14) & 0b1111);
creatureType = CreatureID.fromOrdinal((bitMonster >>> 10) & 0b1111);
if (creatureType == CHIP_SLIDING) {
sliding = true;
creatureType = CreatureID.CHIP;
}
if (creatureType == TANK_STATIONARY)
creatureType = TANK_MOVING;
position = new Position(bitMonster & 0b00_0000_1111111111);
}
} | 24,025 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
MSSavestate.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/game/MS/MSSavestate.java | package game.MS;
import game.*;
import java.io.IOException;
import java.util.BitSet;
public class MSSavestate implements Savestate {
public Layer layerBG;
public Layer layerFG;
public MSCreature chip;
public int tickNumber;
public int chipsLeft;
public short[] keys;
public byte[] boots;
public RNG rng;
public CreatureList monsterList;
public SlipList slipList;
protected int mouseGoal;
protected BitSet traps;
protected short idleMoves;
protected boolean voluntaryMoveAllowed;
/**
* Write an uncompressed savestate
* @return a savestate
*/
@Override public byte[] save(){
byte[] traps = this.traps.toByteArray();
int length =
1 + // version
1 + // ruleset
2 + // chip
1024 + // layerBG
1024 + // layerFG
4 + // tick number
2 + // chips left
4 * 2 + // keys
4 * 1 + // boots
4 + // rng
2 + // mouse click
2 + // traps length
traps.length + // traps
2 + // monsterlist size
monsterList.size() * 2 + // monsterlist
2 + // sliplist size
slipList.size() * 2 + // sliplist
2 + // idle moves
1; // previous move type
SavestateWriter writer = new SavestateWriter(length);
writer.write(UNCOMPRESSED_V2); //Every time this is updated also update compress() in SavestateManager.java
writer.write(Ruleset.MS.ordinal());
writer.writeShort((short) chip.bits());
writer.write(layerBG.getBytes());
writer.write(layerFG.getBytes());
writer.writeInt(tickNumber);
writer.writeShort(chipsLeft);
writer.writeShorts(keys);
writer.write(boots);
writer.writeInt(rng.getCurrentValue());
writer.writeShort(mouseGoal);
writer.writeShort(traps.length);
writer.write(traps);
writer.writeShort(monsterList.size());
writer.writeShortMonsterArray(monsterList.getCreatures());
writer.writeShort(slipList.size());
writer.writeShortMonsterList(slipList);
writer.writeShort(idleMoves);
writer.writeBool(voluntaryMoveAllowed);
return writer.toByteArray();
}
/**
* load a savestate
* @param savestate the savestate to load
*/
@Override
public void load(byte[] savestate){
SavestateReader reader = new SavestateReader(savestate);
int version = reader.read();
if (version == UNCOMPRESSED_V2 || version == COMPRESSED_V2) {
if (reader.read() != Ruleset.MS.ordinal())
throw new UnsupportedOperationException("Can only load MS savestates!");
chip = new MSCreature(reader.readShort());
chip.setLevel((Level) this);
layerBG.load(reader.readLayer(version));
layerFG.load(reader.readLayer(version));
tickNumber = reader.readInt();
chipsLeft = (short) reader.readShort();
keys = reader.readShorts(4);
boots = reader.readBytes(4);
rng.setCurrentValue(reader.readInt());
mouseGoal = reader.readShort();
traps = BitSet.valueOf(reader.readBytes(reader.readShort()));
monsterList.setCreatures(reader.readMSMonsterArray(reader.readShort()));
slipList.setSliplist(reader.readMSMonsterArray(reader.readShort()));
idleMoves = (short) reader.readShort();
voluntaryMoveAllowed = reader.readBool();
}
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
protected MSSavestate(Layer layerBG, Layer layerFG, CreatureList monsterList, SlipList slipList, MSCreature chip,
int chipsLeft, short[] keys, byte[] boots, RNG rng, int mouseGoal, BitSet traps){
this.layerBG = layerBG;
this.layerFG = layerFG;
this.monsterList = monsterList;
this.slipList = slipList;
this.chip = chip;
this.tickNumber = 0;
this.chipsLeft = chipsLeft;
this.keys = keys;
this.boots = boots;
this.rng = rng;
this.mouseGoal = mouseGoal;
this.traps = traps;
}
} | 4,841 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
MSCreatureList.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/game/MS/MSCreatureList.java | package game.MS;
import game.*;
import static game.CreatureID.*;
import static game.Tile.*;
public class MSCreatureList extends game.CreatureList {
private int numDeadMonsters;
@Override
public void initialise() {
newClones.clear();
numDeadMonsters = 0;
chipToCr = null;
teethStep = (level.getStep().isEven()) != (level.getTickNumber() % 4 == 2);
}
@Override
public void tick(){
direction = null;
for(Creature m : list){
MSCreature monster = (MSCreature) m;
if (monster.getCreatureType().isBlock()){
numDeadMonsters++;
continue;
}
if (!teethStep && (monster.getCreatureType() == TEETH || monster.getCreatureType() == BLOB)){
continue;
}
if (!monster.isSliding()){
if (monster.getNextMoveDirectionCheat() != null) direction = monster.getNextMoveDirectionCheat();
else if (!monster.getCreatureType().isAffectedByCB()) direction = monster.getDirection();
Tile bgTile = level.getLayerBG().get(monster.getPosition());
if (bgTile == CLONE_MACHINE) tickClonedMonster(monster);
else if (bgTile == TRAP) tickTrappedMonster(monster);
else tickFreeMonster(monster);
}
}
}
private void tickClonedMonster(MSCreature monster){
Position clonerPosition = monster.getPosition().clone();
Tile tile = monster.toTile();
if (monster.getCreatureType().isBlock()) tile = Tile.fromOrdinal(BLOCK_UP.ordinal() + monster.getDirection().ordinal());
if (!monster.getCreatureType().isAffectedByCB() && monster.getCreatureType() != CreatureID.ICE_BLOCK) direction = monster.getDirection();
if (direction == null) return;
if (monster.getCreatureType() == BLOB){
Position p = monster.getPosition().clone();
Direction[] directions = monster.getDirectionPriority(level.getChip(), level.getRNG());
monster.tick(directions, false);
if (!monster.getPosition().equals(p)) level.insertTile(clonerPosition, tile);
}
else if (monster.canEnter(direction, level.getLayerFG().get(monster.getPosition().move(direction)))){
if (monster.tick(new Direction[] {direction}, false)) level.insertTile(clonerPosition, tile);
if (monster.getCreatureType() == CreatureID.BLOCK && level.getLayerBG().get(clonerPosition) != CLONE_MACHINE) {
level.popTile(clonerPosition);
}
}
}
private void tickTrappedMonster(MSCreature monster){
if (!monster.getCreatureType().isAffectedByCB()) direction = monster.getDirection();
if (direction == null) return;
if (monster.getCreatureType() == TANK_STATIONARY) monster.setCreatureType(TANK_MOVING);
if (monster.getCreatureType() == BLOB){
Direction[] directions = monster.getDirectionPriority(level.getChip(), level.getRNG());
monster.tick(directions, false);
}
else monster.tick(new Direction[] {direction}, false);
}
private void tickFreeMonster(MSCreature monster){
Direction[] directionPriorities = monster.getDirectionPriority(level.getChip(), level.getRNG());
boolean success = monster.tick(directionPriorities, false);
if (!success && monster.getCreatureType() == TEETH && !monster.isSliding()){
monster.setDirection(directionPriorities[0]);
direction = directionPriorities[0];
level.getLayerFG().set(monster.getPosition(), monster.toTile());
}
}
public void incrementDeadMonsters() {
numDeadMonsters++;
}
@Override
public void addClone(Position position){
for (Creature c: list){
if (c.getPosition().equals(position)) return;
}
for (Creature c: newClones){
if (c.getPosition().equals(position)) return;
}
MSCreature clone;
//Data resetting
if (position.y == 32) {
Position row0Position = new Position(position.x, 0);
if (level.getLayerBG().get(row0Position).isCreature()) {
clone = new MSCreature(new Position(position.x, 32), level.getLayerBG().get(row0Position));
clone.setLevel(level);
Tile newTile = level.getLayerFG().get(new Position(position.x, 31));
if (clone.getDirection() == Direction.UP && clone.canEnter(clone.getDirection(), newTile)) {
((MSLevel) level).resetData(row0Position.x);
}
direction = clone.getDirection();
}
else
return;
}
else {
Tile tile = level.getLayerFG().get(position);
Tile tilebg = level.getLayerBG().get(position);
if (!tile.isCreature() ^ (tile == Tile.ICE_BLOCK && tilebg.isCloneBlock()))
return;
clone = new MSCreature(position, tile);
clone.setLevel(level);
if (tile == Tile.ICE_BLOCK)
direction = Direction.fromOrdinal((tilebg.ordinal() + 2) % 4);
else
direction = clone.getDirection();
}
Position newPosition = clone.getPosition().move(direction);
Tile newTile = level.getLayerFG().get(newPosition);
if (clone.canEnter(direction, newTile) || newTile == clone.toTile()) {
if (clone.getCreatureType().isBlock()) tickClonedMonster(clone);
else newClones.add(clone);
if (clone.getCreatureType() == CreatureID.ICE_BLOCK) level.getLayerFG().set(position, Tile.ICE_BLOCK);
}
}
@Override
public void springTrappedCreature(Position position) { //ideally shouldn't be used as this will mess up monster order stuff for ms
if (level.getLayerBG().get(position) != TRAP || creatureAt(position, false) == null
|| !level.isTrapOpen(position))
return;
tickTrappedMonster((MSCreature) creatureAt(position, false));
}
@Override
public void addCreature(Creature creature) {
newClones.add(creature);
}
@Override
public void finalise(){
if (numDeadMonsters == 0 && newClones.size() == 0) return;
int length = list.length - numDeadMonsters + newClones.size();
Creature[] newMonsterList = new MSCreature[length];
// Re-add everything except dead monsters. Non-sliding blocks count as dead.
int index = 0;
for (Creature m : list){
MSCreature monster = (MSCreature) m;
if (!monster.isDead() && !(monster.getCreatureType().isBlock() && !monster.isSliding())) newMonsterList[index++] = monster;
}
// Add all cloned monsters
for (Creature clone : newClones){
newMonsterList[index++] = clone;
}
list = newMonsterList;
newClones.clear();
numDeadMonsters = 0;
}
@Override
public boolean claimed(Position position) {
throw new UnsupportedOperationException("MS does not have a concept of claims.");
}
@Override
public void adjustClaim(Position position, boolean claim) {
throw new UnsupportedOperationException("MS does not have a concept of claims.");
}
@Override
public boolean[] getClaimedArray() {
return new boolean[0];
}
@Override
public void setClaimedArray(boolean[] claimedArray) {
return;
}
@Override
public Creature animationAt(Position position) {
throw new UnsupportedOperationException("MS does not have a concept of animations.");
}
public MSCreatureList(MSCreature[] monsters, Layer layerFG, Layer layerBG){
super(monsters);
}
}
| 7,942 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
MSCreature.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/game/MS/MSCreature.java | package game.MS;
import game.*;
import game.button.*;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import static game.CreatureID.BLOCK;
import static game.CreatureID.*;
import static game.CreatureID.CHIP;
import static game.Direction.*;
import static game.Tile.*;
/**
* MS Creatures are encoded as follows:
*
* 0 0 | 0 0 0 0 | 0 0 0 0 0 | 0 0 0 0 0
* DIRECTION | MONSTER | ROW | COL
*/
public class MSCreature extends Creature {
// Direction-related methods
@Override
public Direction[] getDirectionPriority(Creature chip, RNG rng){
if (nextMoveDirectionCheat != null) {
Direction[] directions = new Direction[] {nextMoveDirectionCheat};
nextMoveDirectionCheat = null;
if (creatureType == WALKER || creatureType == BLOB)
rng.random4();
return directions;
}
if (isSliding())
return direction.turn(new Direction[] {TURN_FORWARD, TURN_AROUND});
switch (creatureType){
case BUG: return direction.turn(new Direction[] {TURN_LEFT, TURN_FORWARD, TURN_RIGHT, TURN_AROUND});
case FIREBALL: return direction.turn(new Direction[] {TURN_FORWARD, TURN_RIGHT, TURN_LEFT, TURN_AROUND});
case PINK_BALL: return direction.turn(new Direction[] {TURN_FORWARD, TURN_AROUND});
case TANK_STATIONARY: return new Direction[] {};
case GLIDER: return direction.turn(new Direction[] {TURN_FORWARD, TURN_LEFT, TURN_RIGHT, TURN_AROUND});
case TEETH: return position.seek(chip.getPosition());
case WALKER:
Direction[] directions = new Direction[] {TURN_LEFT, TURN_AROUND, TURN_RIGHT};
rng.randomPermutation3(directions);
return direction.turn(new Direction[] {TURN_FORWARD, directions[0], directions[1], directions[2]});
case BLOB:
directions = new Direction[] {TURN_FORWARD, TURN_LEFT, TURN_AROUND, TURN_RIGHT};
rng.randomPermutation4(directions);
return direction.turn(directions);
case PARAMECIUM: return direction.turn(new Direction[] {TURN_RIGHT, TURN_FORWARD, TURN_LEFT, TURN_AROUND});
case TANK_MOVING: return new Direction[] {getDirection()};
default: return new Direction[] {};
}
}
public Direction[] seek(Position position){
return this.position.seek(position);
}
@Override
public Direction getSlideDirection(Direction direction, Tile tile, RNG rng, boolean advanceRFF){
switch (tile){
case FF_DOWN:
return DOWN;
case FF_UP:
return UP;
case FF_RIGHT:
return RIGHT;
case FF_LEFT:
return LEFT;
case FF_RANDOM:
if (!advanceRFF) {
int rngValue = rng.getCurrentValue();
Direction slideDir = Direction.fromOrdinal(rng.random4());
rng.setCurrentValue(rngValue);
return slideDir;
}
return Direction.fromOrdinal(rng.random4());
case ICE_SLIDE_SOUTHEAST:
if (direction == UP) return RIGHT;
else if (direction == LEFT) return DOWN;
else return direction;
case ICE_SLIDE_NORTHEAST:
if (direction == DOWN) return RIGHT;
else if (direction == LEFT) return UP;
else return direction;
case ICE_SLIDE_NORTHWEST:
if (direction == DOWN) return LEFT;
else if (direction == RIGHT) return UP;
else return direction;
case ICE_SLIDE_SOUTHWEST:
if (direction == UP) return LEFT;
else if (direction == RIGHT) return DOWN;
else return direction;
case TRAP:
return direction;
}
return direction;
}
@Override
public boolean getForcedMove(Tile tile) {
return sliding;
}
Direction[] getSlideDirectionPriority(Tile tile, RNG rng, boolean changeOnRFF){
if (nextMoveDirectionCheat != null) {
Direction[] directions = new Direction[] {nextMoveDirectionCheat};
nextMoveDirectionCheat = null;
return directions;
}
if (tile.isIce() || (creatureType.isChip() && tile == TELEPORT)){
Direction[] directions = direction.turn(new Direction[] {TURN_FORWARD, TURN_AROUND});
directions[0] = getSlideDirection(directions[0], tile, rng, true);
directions[1] = getSlideDirection(directions[1], tile, rng, true);
return directions;
}
else if (tile == TELEPORT) return new Direction[] {direction};
else if (tile == FF_RANDOM && !changeOnRFF) return new Direction[] {direction};
else return new Direction[] {getSlideDirection(getDirection(), tile, rng, true)};
}
// Sliding-related functions
@Override
public boolean isSliding() {
return creatureType == CHIP_SLIDING || sliding;
}
public void setSliding(boolean wasSliding, boolean isSliding) {
setSliding(wasSliding, isSliding, false);
}
// The entered parameter is for checking if a block has just slid into a trap since in this case it shouldn't generate slide delay
public void setSliding(boolean wasSliding, boolean isSliding, boolean entered) {
if (!wasSliding && !isSliding) {
return;
}
MSLevel msLevel = (MSLevel) level;
if (wasSliding && !isSliding){
if (!isDead() && creatureType.isChip())
setCreatureType(CHIP);
else if (!creatureType.isBlock() || msLevel.getLayerBG().get(position) != TRAP)
msLevel.slipList.remove(this);
// Handles block colliding on trap
else if (creatureType.isBlock() && msLevel.getLayerBG().get(position) == TRAP) {
msLevel.slipList.remove(this);
if (canLeave(direction, position))
msLevel.slipList.add(this);
}
}
else if (!wasSliding){
if (creatureType.isChip())
setCreatureType(CHIP_SLIDING);
else if (msLevel.getSlipList().contains(this)) {
new RuntimeException("adding block twice on level "+msLevel.getLevelNumber()+" "+ msLevel.getTitle()).printStackTrace();
}
else {
msLevel.getSlipList().add(this);
if (!creatureType.isBlock()) {
direction = getSlideDirection(direction, msLevel.getLayerBG().get(position), msLevel.rng, true); //When a creature first enters a sliding tile its direction is updated to face whatever direction its going to move next after that tile takes effect
level.getMonsterList().direction = this.getDirection();
}
}
}
if (creatureType.isBlock() && isSliding && msLevel.getLayerBG().get(position) == TRAP
&& (!canLeave(direction, position)) && !entered){
msLevel.slipList.remove(this);
msLevel.slipList.add(this);
this.sliding = true;
return;
}
if (creatureType.isBlock() && wasSliding && msLevel.getLayerBG().get(position) == TRAP && canLeave(direction, position))
this.sliding = true; //This prevents errors about adding a block to the sliplist twice
else this.sliding = isSliding;
}
/**
* Get the Tile representation of this monster.
* @return The Tile representation of this monster.
*/
@Override
public Tile toTile(){
return switch (creatureType) {
case BLOCK -> Tile.BLOCK;
case ICE_BLOCK -> Tile.ICE_BLOCK;
case CHIP_SLIDING -> Tile.fromOrdinal(Tile.CHIP_UP.ordinal() | direction.ordinal());
case TANK_STATIONARY -> Tile.fromOrdinal(TANK_UP.ordinal() | direction.ordinal());
default -> Tile.fromOrdinal((creatureType.ordinal() << 2) + 0x40 | direction.ordinal());
};
}
@Override
public int getTimeTraveled() {
return 0; //See javadocs for this in Creature
}
@Override
public int getAnimationTimer() {
return 0; //See javadocs for this in Creature
}
private void teleport(Direction direction, Position position, List<Button> pressedButtons) {
Position chipPosition = level.getChip().getPosition();
if (creatureType.isChip()) level.popTile(chipPosition);
int teleportIndex;
for (teleportIndex = 0; true; teleportIndex++){
if (teleportIndex >= level.getTeleports().length) return;
if (level.getTeleports()[teleportIndex].equals(position)){
break;
}
}
int l = level.getTeleports().length;
int i = teleportIndex;
do{
i--;
if (i < 0) i += l;
position.setIndex(level.getTeleports()[i].getIndex());
if (level.getLayerFG().get(position) != TELEPORT) {
if (!creatureType.isChip()) { //Allows monsters to still partial post off themselves
continue;
} //Yeah weirdly monsters can partial post off themselves but Chip can't
else {
if (!level.getLayerFG().get(position).isChip()) continue; //So Chip doesn't partial post off himself
}
}
Position exitPosition = position.move(direction);
if (!exitPosition.isValid()) continue;
Tile exitTile = level.getLayerFG().get(exitPosition);
if (level.getLayerBG().get(exitPosition) == CLONE_MACHINE && level.getLayerFG().get(exitPosition) != Tile.BLOCK) exitTile = level.getLayerBG().get(exitPosition);
if (!creatureType.isChip() && exitTile.isChip()) exitTile = level.getLayerBG().get(exitPosition);
if (creatureType.isChip() && exitTile.isTransparent()) exitTile = level.getLayerBG().get(exitPosition);
if (creatureType.isChip() && exitTile == Tile.BLOCK){
MSCreature block = new MSCreature(direction, BLOCK, exitPosition);
block.setLevel(level);
for (Creature monster : level.getSlipList()) {
MSCreature m = (MSCreature) monster;
if (m.position.equals(exitPosition)){
block = m;
break;
}
}
if (canEnter(direction, level.getLayerBG().get(exitPosition)) && block.canLeave(direction, exitPosition)) {
Position blockPushPosition = exitPosition.move(direction);
if (blockPushPosition.getX() < 0 || blockPushPosition.getX() > 31 ||
blockPushPosition.getY() < 0 || blockPushPosition.getY() > 31) continue;
if (block.canEnter(direction, level.getLayerFG().get(blockPushPosition))){
if (block.tryMove(direction, false, pressedButtons)) break;
}
}
if (level.getLayerBG().get(exitPosition) == Tile.BLOCK) {
block.tryMove(direction, false, pressedButtons);
break;
}
if (level.getLayerBG().get(exitPosition) == CLONE_MACHINE) {
block.tryMove(direction, false, pressedButtons);
level.getLayerFG().set(exitPosition, CLONE_MACHINE); //Sets the block/clone_machine back to the way it was
level.insertTile(exitPosition, Tile.BLOCK);
continue; //Continues through the teleport array like in MSCC
}
if (block.tryMove(direction, false, pressedButtons) && (canEnter(direction, exitTile))) {
break; //The loop shouldn't break if Chip can't enter the tile, instead he should move onto the next teleport, AFTER pushing the block however, and this should in fact be done multiple times in a row if the situation allows
}
else if (block.isSliding() && level.getLayerBG().get(exitPosition) == TRAP && !level.isTrapOpen(exitPosition))
block.setSliding(true, false);
}
if (canEnter(direction, exitTile)) break;
if((getCreatureType() == BUG || getCreatureType() == WALKER) && exitTile == FIRE) {
break;
}
}
while (i != teleportIndex);
}
//the booleans go unused so they are given junk names
//This should not ever be used by MS logically speaking
public boolean canMakeMove(Direction direction, Position position, boolean a, boolean b, boolean c, boolean releasing) {
Tile fg = level.getLayerFG().get(position);
Tile tile = fg;
if (fg.isChip() && !creatureType.isBlock()) {
if (!creatureType.isChip())
tile = level.getLayerBG().get(position);
}
return canLeave(direction, this.position) && canEnter(direction, tile);
}
private boolean canLeave(Direction direction, Position position){
Tile tile = level.getLayerBG().get(position);
return switch (tile) {
case THIN_WALL_UP -> direction != UP;
case THIN_WALL_RIGHT -> direction != RIGHT;
case THIN_WALL_DOWN -> direction != DOWN;
case THIN_WALL_LEFT -> direction != LEFT;
case THIN_WALL_DOWN_RIGHT -> direction != DOWN && direction != RIGHT;
case TRAP -> level.isTrapOpen(position);
default -> true;
};
}
public boolean canEnter(Direction direction, Tile tile){
return switch (tile) {
case FLOOR -> true;
case WALL -> false;
case CHIP -> creatureType.isChip();
case WATER -> true;
case FIRE -> getCreatureType() != BUG && getCreatureType() != WALKER;
case INVISIBLE_WALL -> false;
case THIN_WALL_UP -> direction != DOWN;
case THIN_WALL_RIGHT -> direction != LEFT;
case THIN_WALL_DOWN -> direction != UP;
case THIN_WALL_LEFT -> direction != RIGHT;
case BLOCK -> false;
case DIRT -> creatureType.isChip();
case ICE, FF_DOWN -> true;
case BLOCK_UP, BLOCK_LEFT, BLOCK_RIGHT, BLOCK_DOWN -> false;
case FF_UP, FF_LEFT, FF_RIGHT -> true;
case EXIT -> !creatureType.isMonster();
case DOOR_BLUE -> creatureType.isChip() && level.getKeys()[0] > 0;
case DOOR_RED -> creatureType.isChip() && level.getKeys()[1] > 0;
case DOOR_GREEN -> creatureType.isChip() && level.getKeys()[2] > 0;
case DOOR_YELLOW -> creatureType.isChip() && level.getKeys()[3] > 0;
case ICE_SLIDE_SOUTHEAST -> direction == UP || direction == LEFT;
case ICE_SLIDE_NORTHEAST -> direction == DOWN || direction == LEFT;
case ICE_SLIDE_NORTHWEST -> direction == DOWN || direction == RIGHT;
case ICE_SLIDE_SOUTHWEST -> direction == UP || direction == RIGHT;
case BLUEWALL_FAKE -> creatureType.isChip();
case BLUEWALL_REAL -> false;
case OVERLAY_BUFFER -> false;
case THIEF -> creatureType.isChip();
case SOCKET -> creatureType.isChip() && level.getChipsLeft() <= 0;
case BUTTON_GREEN -> true;
case BUTTON_RED -> true;
case TOGGLE_CLOSED -> false;
case TOGGLE_OPEN -> true;
case BUTTON_BROWN, BUTTON_BLUE, TELEPORT, BOMB, TRAP -> true;
case HIDDENWALL_TEMP -> false;
case GRAVEL -> (!creatureType.isMonster());
case POP_UP_WALL -> creatureType.isChip();
case HINT -> true;
case THIN_WALL_DOWN_RIGHT -> direction == DOWN || direction == RIGHT;
case CLONE_MACHINE -> false;
case FF_RANDOM -> !creatureType.isMonster();
case DROWNED_CHIP, BURNED_CHIP, BOMBED_CHIP, UNUSED_36, UNUSED_37 -> false;
case ICE_BLOCK -> creatureType == CreatureID.ICE_BLOCK;
case EXITED_CHIP, EXIT_EXTRA_1, EXIT_EXTRA_2 -> false;
case CHIP_SWIMMING_UP, CHIP_SWIMMING_LEFT, CHIP_SWIMMING_DOWN, CHIP_SWIMMING_RIGHT -> !creatureType.isChip();
//monsters
default -> creatureType.isChip();
case KEY_BLUE, KEY_RED, KEY_GREEN, KEY_YELLOW -> true;
case BOOTS_WATER, BOOTS_FIRE, BOOTS_ICE, BOOTS_FF -> !creatureType.isMonster();
case CHIP_UP, CHIP_LEFT, CHIP_RIGHT, CHIP_DOWN -> !creatureType.isChip();
};
}
@Override
public boolean canOverride() {
return creatureType.isChip();
}
private boolean tryEnter(Direction direction, Position newPosition, Tile tile, List<Button> pressedButtons){
MSLevel msLevel = (MSLevel) level;
sliding = false;
switch (tile) {
case FLOOR: return true;
case WALL: return false;
case CHIP:
if (creatureType.isChip()) {
msLevel.chipsLeft--;
msLevel.getLayerFG().set(newPosition, FLOOR);
return true;
}
return false;
case WATER:
if (creatureType.isChip()){
if (msLevel.boots[0] == 0){
msLevel.getLayerFG().set(newPosition, DROWNED_CHIP);
kill();
}
}
else if (creatureType.isBlock()) {
if (creatureType == CreatureID.ICE_BLOCK) msLevel.getLayerFG().set(newPosition, ICE);
else msLevel.getLayerFG().set(newPosition, DIRT);
kill();
}
else if (creatureType != GLIDER) kill();
return true;
case FIRE:
if (creatureType.isChip()) {
if (msLevel.boots[1] == 0){
msLevel.getLayerFG().set(newPosition, BURNED_CHIP);
kill();
}
return true;
}
switch (creatureType) {
case BLOCK:
case FIREBALL:
return true;
case BUG:
case WALKER:
return false;
case ICE_BLOCK:
msLevel.getLayerFG().set(newPosition, WATER);
kill();
return true;
default:
kill();
return true;
}
case INVISIBLE_WALL: return false;
case THIN_WALL_UP: return direction != DOWN;
case THIN_WALL_RIGHT: return direction != LEFT;
case THIN_WALL_DOWN: return direction != UP;
case THIN_WALL_LEFT: return direction != RIGHT;
case BLOCK:
if (creatureType.isChip()) {
for (Creature monster : msLevel.slipList) {
MSCreature m = (MSCreature) monster;
if (m.position.equals(newPosition)) {
if (m.direction == direction || m.direction.turn(TURN_AROUND) == direction) return false;
if (m.tryMove(direction, false, pressedButtons)){
return tryEnter(direction, newPosition, msLevel.getLayerFG().get(newPosition), pressedButtons);
}
return false;
}
}
if (msLevel.getLayerBG().get(newPosition) == Tile.BLOCK) {
msLevel.popTile(newPosition);
}
MSCreature block = new MSCreature(newPosition, Tile.BLOCK);
block.setLevel(level);
if (msLevel.getLayerBG().get(newPosition) == CLONE_MACHINE) { //The weird block/clone_machine push block to clone thing now works
block.tryMove(direction, false, pressedButtons);
msLevel.getLayerFG().set(newPosition, CLONE_MACHINE); //Sets the block/clone_machine back to the way it was
msLevel.insertTile(newPosition, Tile.BLOCK);
return false; //Normally you would check if Chip could enter the resulting tile but seeing as its always a clone machine on the bottom it'll always be false, therefore i always have this return false
}
if (block.tryMove(direction, false, pressedButtons)){
for (BrownButton b : msLevel.getBrownButtons().values()) { //Ok so since blocks don't follow normal creature rules they don't get caught in the section of tick() further down that closes traps after creatures leave, so I had to manually do it here
if (b.getTargetPosition().equals(newPosition) && msLevel.getLayerFG().get(b.getButtonPosition()) == BUTTON_BROWN) {
b.release(msLevel);
}
}
return tryEnter(direction, newPosition, msLevel.getLayerFG().get(newPosition), pressedButtons);
}
}
return false;
case DIRT:
if (creatureType.isChip() || creatureType == CreatureID.ICE_BLOCK) {
msLevel.getLayerFG().set(newPosition, FLOOR);
return true;
}
return false;
case ICE:
if (!(creatureType.isChip() && msLevel.getBoots()[2] > 0)) sliding = true;
return true;
case FF_DOWN:
if (!(creatureType.isChip() && msLevel.getBoots()[3] > 0)) sliding = true;
return true;
case BLOCK_UP:
case BLOCK_LEFT:
case BLOCK_RIGHT:
case BLOCK_DOWN: return false;
case FF_UP:
case FF_LEFT:
case FF_RIGHT:
if (!(creatureType.isChip() && msLevel.getBoots()[3] > 0)) sliding = true;
return true;
case EXIT:
if (creatureType.isBlock()) return true;
if (creatureType.isChip()){
msLevel.getLayerFG().set(newPosition, EXITED_CHIP);
msLevel.setLevelWon(true);
kill();
return true;
}
return false;
case DOOR_BLUE:
if (creatureType.isChip() && msLevel.keys[0] > 0) {
msLevel.keys[0] -= 1;
msLevel.getLayerFG().set(newPosition, FLOOR);
return true;
}
return false;
case DOOR_RED:
if (creatureType.isChip() && msLevel.keys[1] > 0) {
msLevel.keys[1] -= 1;
msLevel.getLayerFG().set(newPosition, FLOOR);
return true;
}
return false;
case DOOR_GREEN:
if (creatureType.isChip() && msLevel.keys[2] > 0) {
msLevel.getLayerFG().set(newPosition, FLOOR);
return true;
}
return false;
case DOOR_YELLOW:
if (creatureType.isChip() && msLevel.keys[3] > 0) {
msLevel.keys[3] -= 1;
msLevel.getLayerFG().set(newPosition, FLOOR);
return true;
}
return false;
case ICE_SLIDE_SOUTHEAST:
if (direction == UP || direction == LEFT){
if (!(creatureType.isChip() && msLevel.getBoots()[2] > 0)) sliding = true;
return true;
}
else return false;
case ICE_SLIDE_NORTHEAST:
if(direction == DOWN || direction == LEFT){
if (!(creatureType.isChip() && msLevel.getBoots()[2] > 0)) sliding = true;
return true;
}
else return false;
case ICE_SLIDE_NORTHWEST:
if(direction == DOWN || direction == RIGHT){
if (!(creatureType.isChip() && msLevel.getBoots()[2] > 0)) sliding = true;
return true;
}
else return false;
case ICE_SLIDE_SOUTHWEST:
if(direction == UP || direction == RIGHT){
if (!(creatureType.isChip() && msLevel.getBoots()[2] > 0)) sliding = true;
return true;
}
else return false;
case BLUEWALL_FAKE:
if (creatureType.isChip()) {
msLevel.getLayerFG().set(newPosition, FLOOR);
return true;
}
else return false;
case BLUEWALL_REAL:
if (creatureType.isChip()) msLevel.getLayerFG().set(newPosition, WALL);
return false;
case OVERLAY_BUFFER: return false;
case THIEF:
if (creatureType.isChip()) {
msLevel.boots = new byte[]{0, 0, 0, 0};
return true;
}
return false;
case SOCKET:
if (creatureType.isChip() && msLevel.chipsLeft <= 0) {
msLevel.getLayerFG().set(newPosition, FLOOR);
return true;
}
return false;
case BUTTON_GREEN:
pressedButtons.add(msLevel.getButton(newPosition, GreenButton.class));
return true;
case BUTTON_RED:
Button b = msLevel.getButton(newPosition, RedButton.class);
if (b != null) pressedButtons.add(b);
return true;
case TOGGLE_CLOSED: return false;
case TOGGLE_OPEN: return true;
case BUTTON_BROWN:
Button b2 = msLevel.getButton(newPosition, BrownButton.class);
if (b2 != null) pressedButtons.add(b2);
return true;
case BUTTON_BLUE:
pressedButtons.add(msLevel.getButton(newPosition, BlueButton.class));
return true;
case TELEPORT:
sliding = true;
teleport(direction, newPosition, pressedButtons);
return true;
case BOMB:
if (!creatureType.isChip()) {
msLevel.getLayerFG().set(newPosition, FLOOR);
}
kill();
return true;
case TRAP:
List<BrownButton> buttons = level.getTrapButtons().getList(newPosition);
if (buttons != null) {
for (BrownButton button : buttons) {
if (msLevel.getLayerFG().get(button.getButtonPosition()) != BUTTON_BROWN) {
msLevel.traps.set(msLevel.trapIndexMap.get(button.getTargetPosition()), true);
break;
}
}
}
return true;
case HIDDENWALL_TEMP:
if (creatureType.isChip()) {
msLevel.getLayerFG().set(newPosition, WALL);
}
return false;
case GRAVEL: return !creatureType.isMonster();
case POP_UP_WALL:
if (creatureType.isChip()) {
msLevel.getLayerFG().set(newPosition, WALL);
return true;
}
return false;
case HINT: return true;
case THIN_WALL_DOWN_RIGHT: return direction == DOWN || direction == RIGHT;
case CLONE_MACHINE:
return false;
case FF_RANDOM:
if (creatureType.isMonster()) return false;
if (!(creatureType.isChip() && msLevel.getBoots()[3] > 0)) sliding = true;
return true;
case DROWNED_CHIP:
case BURNED_CHIP:
case BOMBED_CHIP:
case UNUSED_36:
case UNUSED_37: return false;
case ICE_BLOCK:
if (msLevel.getLayerBG().get(newPosition).isCloneBlock()) return false; //You know how if you have a clone machine under a monster you can't enter it? Well it's the same with ice blocks and the clone blocks under them
if (creatureType.isChip() || creatureType.isTank() || creatureType == TEETH || creatureType == CreatureID.ICE_BLOCK){
for (Creature monster : msLevel.slipList) {
MSCreature m = (MSCreature) monster;
if (m.position.equals(newPosition)) {
if (m.direction == direction || m.direction.turn(TURN_AROUND) == direction) return false;
if (m.tryMove(direction, false, pressedButtons)){
return tryEnter(direction, newPosition, msLevel.getLayerFG().get(newPosition), pressedButtons);
}
return false;
}
}
if (msLevel.getLayerBG().get(newPosition) == Tile.ICE_BLOCK) {
msLevel.popTile(newPosition);
}
MSCreature block = new MSCreature(newPosition, Tile.ICE_BLOCK);
block.setLevel(level);
if (msLevel.getLayerBG().get(newPosition) == CLONE_MACHINE) { //The weird block/clone_machine push block to clone thing now works
block.tryMove(direction, false, pressedButtons);
msLevel.getLayerFG().set(newPosition, CLONE_MACHINE); //Sets the block/clone_machine back to the way it was
msLevel.insertTile(newPosition, Tile.ICE_BLOCK);
return false; //Normally you would check if Chip could enter the resulting tile but seeing as its always a clone machine on the bottom it'll always be false, therefore i always have this return false
}
if (block.tryMove(direction, false, pressedButtons)){
for (BrownButton b3 : msLevel.getBrownButtons().values()) { //Ok so since blocks don't follow normal creature rules they don't get caught in the section of tick() further down that closes traps after creatures leave, so I had to manually do it here
if (b3.getTargetPosition().equals(newPosition) && msLevel.getLayerFG().get(b3.getButtonPosition()) == BUTTON_BROWN) {
b3.release(msLevel);
}
}
return tryEnter(direction, newPosition, msLevel.getLayerFG().get(newPosition), pressedButtons);
}
}
return false;
case EXITED_CHIP:
case EXIT_EXTRA_1:
case EXIT_EXTRA_2: return false;
case CHIP_SWIMMING_UP:
case CHIP_SWIMMING_LEFT:
case CHIP_SWIMMING_DOWN:
case CHIP_SWIMMING_RIGHT:
if (!creatureType.isChip()) {
msLevel.chip.kill();
return true;
}
return false;
default: // Monsters
if (creatureType.isChip()) {
kill();
return true;
}
return false;
case KEY_BLUE:
if (creatureType.isChip()) {
msLevel.getLayerFG().set(newPosition, FLOOR);
msLevel.keys[0]++;
}
return true;
case KEY_RED:
if (creatureType.isChip()) {
msLevel.getLayerFG().set(newPosition, FLOOR);
msLevel.keys[1]++;
}
return true;
case KEY_GREEN:
if (creatureType.isChip()) {
msLevel.getLayerFG().set(newPosition, FLOOR);
msLevel.keys[2]++;
}
return true;
case KEY_YELLOW:
if (creatureType.isChip()) {
msLevel.getLayerFG().set(newPosition, FLOOR);
msLevel.keys[3]++;
}
return true;
case BOOTS_WATER:
if (creatureType.isChip()) {
msLevel.getLayerFG().set(newPosition, FLOOR);
msLevel.boots[0] = 1;
}
return !creatureType.isMonster();
case BOOTS_FIRE:
if (creatureType.isChip()) {
msLevel.getLayerFG().set(newPosition, FLOOR);
msLevel.boots[1] = 1;
}
return !creatureType.isMonster();
case BOOTS_ICE:
if (creatureType.isChip()) {
msLevel.getLayerFG().set(newPosition, FLOOR);
msLevel.boots[2] = 1;
}
return !creatureType.isMonster();
case BOOTS_FF:
if (creatureType.isChip()) {
msLevel.getLayerFG().set(newPosition, FLOOR);
msLevel.boots[3] = 1;
}
return !creatureType.isMonster();
case CHIP_UP:
case CHIP_LEFT:
case CHIP_RIGHT:
case CHIP_DOWN:
if (!creatureType.isChip()) {
msLevel.getChip().kill();
return true;
}
return false;
}
}
private boolean tryMove(Direction direction, boolean slidingMove, List<Button> pressedButtons){
if (direction == null || direction == NONE) return false;
Direction oldDirection = this.direction;
setDirection(direction);
if (!canLeave(direction, position))
return false;
boolean wasSliding = sliding;
Position newPosition = position.move(direction);
if (!newPosition.isValid())
newPosition = new Position(-1);
Tile newTileFG = level.getLayerFG().get(newPosition);
Tile newTileBG = level.getLayerBG().get(newPosition);
boolean isChip = creatureType.isChip();
boolean isBlock = creatureType.isBlock();
boolean isMonster = creatureType.isMonster();
boolean pickupCheck = false;
boolean blockMachineCheck = true;
if (level.getLayerBG().get(newPosition) == CLONE_MACHINE && (level.getLayerFG().get(newPosition) == Tile.BLOCK || level.getLayerFG().get(newPosition) == Tile.ICE_BLOCK)) blockMachineCheck = true;
else if (level.getLayerBG().get(newPosition) == CLONE_MACHINE && !isBlock) blockMachineCheck = false;
if ((creatureType.isMonster()) && newTileFG.isChip()) newTileFG = newTileBG;
if (newTileFG.isPickup()) {
if (isChip) {
if (canEnter(direction, newTileBG) || newTileBG == Tile.BLOCK) pickupCheck = true;
}
else if (newTileFG.isKey()) pickupCheck = true;
}
if (canEnter(direction, newTileBG) ||
(!newTileFG.isTransparent() && (isBlock || blockMachineCheck)) //Look at this if statement, this is all just to get transparency to work
|| (pickupCheck && blockMachineCheck)
|| (isBlock && (newTileFG.isBoot() || newTileFG.isChip() || newTileFG.isSwimmingChip()))
|| newTileBG == CLONE_MACHINE) {
if (newTileBG == CLONE_MACHINE && (!isChip || newTileFG.isCreature())) newTileFG = newTileBG;
if (tryEnter(direction, newPosition, newTileFG, pressedButtons)) {
if (newTileFG != TELEPORT) level.popTile(position);
else if (!isChip) level.popTile(position); //You probably noticed that this works for every creature other than Chip, we handle this very specific case (Chip and teleport) over in the teleport method so we cancel it out here, and yes it does in fact cause some issues if we don't, possibly even crashes if you revert both this and the teleport method handle
position = newPosition;
//!!DIRTY HACK SECTION BEGINS!!//
if (isChip && newTileBG == EXIT && level.getLayerFG().get(newPosition) == FLOOR && level.getChip().getPosition() == newPosition) {
tryEnter(direction, newPosition, newTileBG, pressedButtons); //Quick little hack to make having Chip reveal an Exit on the lower layer take effect
level.getLayerFG().set(newPosition, EXITED_CHIP); //Fixed cosmetics, else you have an EXITED_CHIP/EXIT tile that looks ugly (no gameplay effect however)
level.getLayerBG().set(newPosition, FLOOR);
}
if (isBlock && slidingMove && level.getLayerFG().get(newPosition) == TRAP)
sliding = true; //A block that slides into a trap should be properly added or maintained in the sliplist, however tryenter doesn't register traps as sliding so i have to manually add a check here
//!!DIRTY HACK SECTION ENDS!!//
if (sliding && !isMonster)
setDirection(getSlideDirection(direction, level.getLayerFG().get(position), level.getRNG(), true));
if (!isDead()) level.insertTile(getPosition(), toTile());
else if (isMonster) {
((MSCreatureList) level.getMonsterList()).incrementDeadMonsters();
}
setSliding(wasSliding, sliding, true);
return true;
}
}
setSliding(wasSliding, sliding);
if (wasSliding && !creatureType.isMonster()) {
if (level.getLayerBG().get(this.position) == FF_RANDOM && !slidingMove) setDirection(oldDirection);
else setDirection(getSlideDirection(direction, level.getLayerBG().get(position), level.getRNG(), true));
}
return false;
}
boolean tick(Direction[] directions, boolean slidingMove){
MSLevel msLevel = (MSLevel) level;
MSCreature oldCreature = clone();
if (!creatureType.isChip() && !isSliding()) level.getMonsterList().direction = direction;
for (Direction newDirection : directions){
LinkedList<Button> pressedButtons = new LinkedList<>();
if (tryMove(newDirection, slidingMove, pressedButtons)){
for(int i = pressedButtons.size() - 1; i >= 0; i--) {
pressedButtons.get(i).press(msLevel);
}
if (msLevel.getLayerFG().get(oldCreature.position) == BUTTON_BROWN){
BrownButton b = ((BrownButton) msLevel.getButton(oldCreature.position, BrownButton.class));
if (b != null && msLevel.getLayerBG().get(b.getTargetPosition()) != TRAP && !b.getTargetPosition().equals(position)) {
b.release(msLevel);
}
if (b != null && b.getTargetPosition().equals(position)) {
b.release(msLevel);
}
}
if (msLevel.getLayerFG().get(oldCreature.position) == TRAP || msLevel.getLayerBG().get(oldCreature.position) == TRAP){
for (BrownButton b : msLevel.getBrownButtons().values()) {
if (b.getTargetPosition().equals(oldCreature.position) && msLevel.getLayerFG().get(b.getButtonPosition()) == BUTTON_BROWN) {
b.release(msLevel);
}
}
}
if (!creatureType.isChip()) {
if (msLevel.getLayerBG().get(position).isChip()) msLevel.getChip().kill();
if (!isSliding()) level.getMonsterList().direction = newDirection;
}
return true;
}
if (!creatureType.isChip() && !isSliding()) level.getMonsterList().direction = newDirection;
}
setSliding(this.sliding, oldCreature.sliding);
if (creatureType.isTank() && !isSliding()) setCreatureType(TANK_STATIONARY);
if (!creatureType.isChip() &&!(creatureType.isBlock() && msLevel.getLayerBG().get(position) == FF_RANDOM)) setDirection(oldCreature.direction);
else msLevel.getLayerFG().set(position, toTile());
return false;
}
@Override
public boolean tick(boolean releasing) { //Ideally shouldn't be used for MS, the method this calls should be used instead
return tick(new Direction[]{direction}, sliding);
}
public MSCreature(Direction direction, CreatureID creatureType, Position position){
this.direction = direction;
this.creatureType = creatureType;
this.position = position;
}
public MSCreature(Position position, Tile tile){
this.position = position;
if (BLOCK_UP.ordinal() <= tile.ordinal() && tile.ordinal() <= BLOCK_RIGHT.ordinal()){
direction = Direction.fromOrdinal((tile.ordinal() + 2) % 4);
creatureType = BLOCK;
}
else{
direction = Direction.fromOrdinal(tile.ordinal() % 4);
if (tile == Tile.BLOCK) creatureType = BLOCK;
else {
if (tile == Tile.ICE_BLOCK) creatureType = CreatureID.ICE_BLOCK;
else creatureType = CreatureID.fromOrdinal((tile.ordinal() - 0x40) >>> 2);
}
}
if (creatureType == TANK_STATIONARY) creatureType = TANK_MOVING;
}
public MSCreature(int bitMonster){
direction = Direction.fromOrdinal((bitMonster >>> 14) & 0b11);
creatureType = CreatureID.fromOrdinal((bitMonster >>> 10) & 0b1111);
if (creatureType == CHIP_SLIDING)
sliding = true;
position = new Position(bitMonster & 0b00_0000_1111111111);
}
@Override
public int bits(){
return ((direction.getBits() & 0b11) << 14) | creatureType.getBits() | position.getIndex();
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
MSCreature that = (MSCreature) o;
if (position != that.position)
return false;
if (creatureType != that.creatureType)
return false;
if (direction != that.direction)
return false;
return sliding == that.sliding;
}
@Override
public int hashCode() {
return Objects.hash(position, creatureType, direction, sliding);
}
@Override
public MSCreature clone(){
MSCreature c = new MSCreature(direction, creatureType, position);
c.sliding = sliding;
c.setLevel(level);
return c;
}
}
| 43,538 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
MSLevel.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/game/MS/MSLevel.java | package game.MS;
import emulator.SuperCC;
import game.*;
import game.button.*;
import util.MultiHashMap;
import java.util.*;
import static emulator.SuperCC.WAIT;
import static emulator.SuperCC.UP;
import static emulator.SuperCC.DOWN;
import static emulator.SuperCC.LEFT;
import static emulator.SuperCC.RIGHT;
import static game.CreatureID.TANK_MOVING;
import static game.Direction.TURN_AROUND;
import static game.Tile.*;
public class MSLevel extends MSSavestate implements Level {
private static final int HALF_WAIT = 0, KEY = 1, CLICK_EARLY = 2, CLICK_LATE = 3;
public final int INITIAL_MONSTER_LIST_SIZE = monsterList.size();
public final Position INITIAL_MONSTER_POSITION =
(monsterList.size() == 0) ? null : monsterList.get(0).getPosition(); //this is needed or else half the levels aren't playable due to a crash from having an empty monster list
public final int INITIAL_CHIPS_AMOUNT = chipsLeft;
private final int LEVELSET_LENGTH;
private final Ruleset RULESET = Ruleset.MS;
private int levelNumber, startTime;
private final String title, password, hint, author;
private final Position[] toggleDoors, teleports;
private MultiHashMap<Position, GreenButton> greenButtons;
private MultiHashMap<Position, RedButton> redButtons;
private MultiHashMap<Position, BrownButton> brownButtons;
private MultiHashMap<Position, BrownButton> trapButtons;
private MultiHashMap<Position, BlueButton> blueButtons;
private final int rngSeed;
private final Step step;
private boolean levelWon;
private final Cheats cheats;
protected Map<Position, Integer> trapIndexMap;
@Override
public int getLevelNumber() {
return levelNumber;
}
@Override
public int getStartTime() {
return startTime;
}
@Override
public String getTitle() {
return title;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getHint() {
return hint;
}
@Override
public String getAuthor() {
return author;
}
@Override
public Position[] getToggleDoors() {
return toggleDoors;
}
@Override
public Position[] getTeleports() {
return teleports;
}
@Override
public MultiHashMap<Position, GreenButton> getGreenButtons() {
return greenButtons;
}
@Override
public MultiHashMap<Position, RedButton> getRedButtons() {
return redButtons;
}
@Override
public MultiHashMap<Position, BrownButton> getBrownButtons() {
return brownButtons;
}
@Override
public MultiHashMap<Position, BlueButton> getBlueButtons() {
return blueButtons;
}
@Override
public MultiHashMap<Position, BrownButton> getTrapButtons() {
return trapButtons;
}
@Override
public void setGreenButtons(MultiHashMap<Position, GreenButton> greenButtons) {
this.greenButtons = greenButtons;
}
@Override
public void setBlueButtons(MultiHashMap<Position, BlueButton> blueButtons) {
this.blueButtons = blueButtons;
}
@Override
public int getRngSeed(){
return rngSeed;
}
@Override
public Step getStep(){
return step;
}
@Override
public boolean supportsLayerBG() {
return true;
}
@Override
public boolean supportsClick() {
return true;
}
@Override
public boolean supportsSliplist() {
return true;
}
@Override
public boolean supportsDiagonal() {
return false;
}
@Override
public boolean hasCyclicRFF() {
return false;
}
@Override
public boolean chipInMonsterList() {
return false;
}
@Override
public boolean trapRequiresHeldButton() {
return false;
}
@Override
public boolean creaturesAreTiles() {
return true;
}
@Override
public boolean hasStillTanks() {
return true;
}
@Override
public boolean swimmingChipIsCreature() {
return false;
}
@Override
public boolean blocksInMonsterList() {
return false;
}
@Override
public int ticksPerMove() {
return RULESET.ticksPerMove;
}
@Override
public Layer getLayerBG() {
return layerBG;
}
@Override
public Layer getLayerFG() {
return layerFG;
}
@Override
public boolean isUntimed() {
return startTime < 0;
}
/**
*
* @return The current value of the timer that is displayed on screen.
* Returns a negative value on untimed levels.
*/
@Override
public int getTimer(){
if (tickNumber == 0) return startTime;
else return startTime - tickNumber*10 + 10; // The first tick does not change the timer
}
@Override
public void setTimer(int n) {
startTime = n + tickNumber - 1;
}
/**
*
* @return The current value of the timer if we are using TChip timing
* (where the time starts at 999.9).
*/
@Override
public int getTChipTime() {
if (tickNumber == 0) return 99990;
else return 99990 - tickNumber*10 + 10; // The first tick does not change the timer
}
@Override
public int getChipsLeft(){
return chipsLeft;
}
@Override
public void setChipsLeft(int chipsLeft){
this.chipsLeft = chipsLeft;
}
@Override
public MSCreature getChip(){
return chip;
}
/**
* Returns chip's keys
* <p>
* Chip's keys are short array with 4 entries containing the number of
* blue, red, green and yellow keys in that order.
* </p>
* @return chip's keys
*/
@Override
public short[] getKeys(){
return keys;
}
/**
* Set chip's keys
* <p>
* Chip's keys are short array with 4 entries containing the number of
* blue, red, green and yellow keys in that order.
* </p>
*/
@Override
public void setKeys(short[] keys){
this.keys = keys;
}
/**
* Returns chip's boots
* <p>
* Chip's boots are byte array with 4 entries containing the number of
* flippers, fire boots, skates and suction boots in that order.
* </p>
* @return chip's boots
*/
@Override
public byte[] getBoots(){
return boots;
}
/**
* Sets chip's boots
* <p>
* Chip's boots are byte array with 4 entries containing the number of
* flippers, fire boots, skates and suction boots in that order.
* </p>
*/
@Override
public void setBoots(byte[] boots){
this.boots = boots;
}
@Override
public CreatureList getMonsterList(){
return monsterList;
}
@Override
public SlipList getSlipList(){
return slipList;
}
@Override
public void setTrap(Position trapPos, boolean open) {
BrownButton button = trapButtons.get(trapPos);
if (button != null)
traps.set(trapIndexMap.get(trapPos), open);
}
@Override
public int getLevelsetLength() {
return LEVELSET_LENGTH;
}
@Override
public Cheats getCheats() {
return cheats;
}
@Override
public RNG getRNG() {
return rng;
}
@Override
public int getTickNumber() {
return tickNumber;
}
@Override
public Ruleset getRuleset() {
return RULESET;
}
@Override
public Direction getInitialRFFDirection() {
return Direction.UP; //unused in MS, return the "default" value
}
@Override
public Direction getRFFDirection(boolean advance) {
int rngValue = rng.getCurrentValue();
Direction slideDir = Direction.fromOrdinal(rng.random4());
if (!advance)
rng.setCurrentValue(rngValue);
return slideDir;
}
/**
* @param position the last clicked position.
*/
@Override
public void setClick(int position){
this.mouseGoal = position;
}
@Override
public void setLevelWon(boolean won) {levelWon = won;}
@Override
public boolean isCompleted() {
return levelWon;
}
@Override
public void popTile(Position position){
if (!position.isValid())
return;
layerFG.set(position, layerBG.get(position));
layerBG.set(position, FLOOR);
}
@Override
public void insertTile(Position position, Tile tile){
if (!position.isValid())
return;
Tile fgTile = layerFG.get(position);
if (!(fgTile.equals(FLOOR) && !tile.isMonster())) layerBG.set(position, layerFG.get(position));
layerFG.set(position, tile);
}
@Override
public Button getButton(Position position, Class<? extends Button> buttonType) {
if (buttonType.equals(GreenButton.class))
return greenButtons.get(position);
else if (buttonType.equals(RedButton.class))
return redButtons.get(position);
else if (buttonType.equals(BrownButton.class))
return brownButtons.get(position);
else if (buttonType.equals(BlueButton.class))
return blueButtons.get(position);
else throw new RuntimeException("Invalid class");
}
@Override
public Button getButton(Position position) {
for (Map<Position, ? extends Button> buttons : List.of(greenButtons, redButtons, brownButtons, blueButtons)) {
if (buttons.get(position) != null)
return buttons.get(position);
}
return null;
}
@Override
public boolean isTrapOpen(Position position) {
BrownButton button = trapButtons.get(position);
if (button != null)
return traps.get(trapIndexMap.get(position));
return false;
}
private int moveType(char c, boolean halfMove, boolean chipSliding){
if (SuperCC.isClick(c) || c == WAIT){
if (mouseGoal != NO_CLICK) {
if (chipSliding)
return CLICK_EARLY;
if (halfMove)
return CLICK_LATE;
}
else return HALF_WAIT;
}
else if (c == UP || c == LEFT || c == DOWN || c == RIGHT){
return KEY;
}
return HALF_WAIT;
}
private void moveChipSliding(){
Direction direction = chip.getDirection();
Tile bgTile = layerBG.get(chip.getPosition());
if (bgTile.isFF()) chip.tick(new Direction[] {direction}, true);
else chip.tick(chip.getSlideDirectionPriority(bgTile, rng, true), true);
}
//returns true if both directions were attempted and failed
private boolean moveChip(Direction[] directions){
Position oldPosition = chip.getPosition().clone();
int attemptedDirs = 0;
for (Direction direction : directions) {
if (chip.isSliding()) {
if (!layerBG.get(chip.getPosition()).isFF())
continue;
if (direction == chip.getDirection())
continue;
}
attemptedDirs++;
chip.tick(new Direction[] {direction}, false);
if (!chip.getPosition().equals(oldPosition))
return false;
}
return attemptedDirs == directions.length;
}
private void finaliseTraps(){
HashSet<Position> pressedButtons = new HashSet<>();
for (List<BrownButton> buttons : brownButtons.rawValues()) {
for (BrownButton b : buttons) {
if (layerFG.get(b.getButtonPosition()) != BUTTON_BROWN && !pressedButtons.contains(b.getButtonPosition())) {
traps.set(trapIndexMap.get(b.getTargetPosition()), true);
pressedButtons.add(b.getButtonPosition());
}
else if (layerFG.get(b.getTargetPosition()) == TRAP) {
traps.set(trapIndexMap.get(b.getTargetPosition()), false);
}
}
}
}
private void initialiseSlidingMonsters(){
for (Creature m : monsterList) m.setSliding(false);
for (Creature m : slipList) m.setSliding(true);
}
private boolean endTick() {
if (layerBG.get(chip.getPosition()).equals(EXIT) && levelWon){
layerFG.set(chip.getPosition(), EXITED_CHIP);
chip.kill();
}
return chip.isDead();
}
public boolean shouldDrawCreatureNumber(Creature creature) {
return true; //method is only useful for lynx really
}
public void turnTanks() {
for (Creature m : monsterList) {
if (m.getCreatureType().isTank() && !m.isSliding()) {
m.setCreatureType(TANK_MOVING);
m.turn(TURN_AROUND);
layerFG.set(m.getPosition(), m.toTile());
}
}
for (Creature m : monsterList.getNewClones()) {
if (m.getCreatureType().isTank() && !m.isSliding()) {
m.setCreatureType(TANK_MOVING);
m.turn(TURN_AROUND);
}
}
}
@Override
public Creature newCreature(Direction dir, CreatureID creatureType, Position position) {
Creature creature = new MSCreature(dir, creatureType, position);
creature.setLevel(this);
return creature;
}
/**
* Advances a tick (10th of a second).
* <p>
* This method is not responsible for setting the click position, or
* for checking whether chip can move (in case chip moved the previous
* tick).
* </p>
* @param c The direction in which to move. If b is positive it should be
* one of UP, LEFT, DOWN, RIGHT and WAIT. If b is negative, it is
* interpreted as a mouse click. Note that the click itself is not
* set here - use {@link #setClick(int)} for that.
* @param directions The directions in which chip should try to move
* @return true if the next move should be made automatically without input
*/
@Override
public int tick(char c, Direction[] directions){
setLevelWon(false); //Each tick sets the level won state to false so that even when rewinding unless you stepped into the exit the level is not won
initialiseSlidingMonsters();
boolean isHalfMove = (tickNumber & 0x1) != 0; //odd tick
int moveType = moveType(c, isHalfMove, chip.isSliding());
boolean failedDirections = false;
monsterList.initialise();
if (isHalfMove) voluntaryMoveAllowed = true; //This is not used in finding out if the emulator should tick twice, that is instead handled by the value of this function's return, this is only used for TSG moves, yeah its bad
// if (!voluntaryMoveAllowed && idleMoves > 0) voluntaryMoveAllowed = true;
if (isHalfMove && mouseGoal == NO_CLICK && moveType == HALF_WAIT) {
idleMoves++;
if (idleMoves > 2) {
layerFG.set(chip.getPosition(), CHIP_DOWN);
}
}
if (tickNumber > 0 && !isHalfMove) monsterList.tick();
if (endTick()) return 0;
if (chip.isSliding()) moveChipSliding();
if (endTick()) return 0;
if (moveType == CLICK_EARLY && voluntaryMoveAllowed) { //todo: it seems like it should be impossible to do a key move onto an FF and then TSG right after
// System.out.println("tsg");
Direction sought = chip.seek(new Position(mouseGoal))[0];
/* CCLP4:34, the TWS Sharpeye provided has a discrepancy between TW and SuCC, the first click has an offset
from Chip of (-2, 1), in TW this is below the gravel, in SuCC its below and one to the right, much like how
TW-TSG can't load a lot of normal mouse solutions, we can't load a lot of TSG solutions */
if (!chip.isSliding() || !sought.equals(chip.getDirection())) {
failedDirections = moveChip(new Direction[]{sought});
idleMoves = 0;
voluntaryMoveAllowed = false;
}
// else if (isHalfMove) {
// moveType = CLICK_LATE;
// }
}
if (endTick()) return 0;
tickNumber++;
slipList.tick();
if (endTick()) return 0;
if (moveType == KEY) {
moveChip(directions);
idleMoves = 0;
voluntaryMoveAllowed = false;
}
else if (moveType == CLICK_LATE && !chip.isSliding() && voluntaryMoveAllowed) {
// System.out.println("normal");
failedDirections = moveChip(chip.seek(new Position(mouseGoal)));
idleMoves = 0;
// voluntaryMoveAllowed = false; //this causes the TSG unit test instances to desync, something is wrong here
if (failedDirections)
voluntaryMoveAllowed = true; //this way causes the bottom part of SuCCTest L 75 to desync, but why???
}
if (endTick())
return 0;
monsterList.finalise();
finaliseTraps();
if (moveType == KEY || chip.getPosition().getIndex() == mouseGoal)
mouseGoal = NO_CLICK;
else if ((moveType == CLICK_LATE || moveType == CLICK_EARLY) && failedDirections)
mouseGoal = NO_CLICK;
if ((moveType == KEY || moveType == CLICK_EARLY) && !isHalfMove && !chip.isSliding())
return MASK_TICK_MULTI;
return 0;
}
void resetData(int xPosition) {
Position position = new Position(xPosition, 0);
byte lowByte, highByte;
boolean lowOrder = xPosition % 2 == 0;
int shiftBy = xPosition % 2 == 0 ? 0 : 8;
switch (xPosition) {
case 0, 1 -> {
lowByte = (byte) levelNumber;
highByte = (byte) (levelNumber >>> 8);
if ((lowOrder ? lowByte : highByte) != 49)
layerBG.set(position, Tile.fromOrdinal((byte) (levelNumber >>> shiftBy)));
}
case 2, 3 -> {
lowByte = (byte) LEVELSET_LENGTH;
highByte = (byte) (LEVELSET_LENGTH >>> 8);
if ((lowOrder ? lowByte : highByte) != 49)
layerBG.set(position, Tile.fromOrdinal((byte) (LEVELSET_LENGTH >>> shiftBy)));
}
case 4, 5 -> {
int msccTime = startTime / 100;
lowByte = (byte) msccTime;
highByte = (byte) (msccTime >>> 8);
if ((lowOrder ? lowByte : highByte) != 49)
layerBG.set(position, Tile.fromOrdinal((byte) (msccTime >>> shiftBy)));
}
case 6, 7 -> {
lowByte = (byte) INITIAL_CHIPS_AMOUNT;
highByte = (byte) (INITIAL_CHIPS_AMOUNT >>> 8);
if ((lowOrder ? lowByte : highByte) != 49)
layerBG.set(position, Tile.fromOrdinal((byte) (INITIAL_CHIPS_AMOUNT >>> shiftBy)));
}
case 8, 9 -> {
layerBG.set(position, Tile.fromOrdinal((byte) (chip.getPosition().x >>> shiftBy)));
chip.setPosition(new Position(0, chip.getPosition().y));
}
case 10, 11 -> {
layerBG.set(position, Tile.fromOrdinal((byte) (chip.getPosition().y >>> shiftBy)));
chip.setPosition(new Position(chip.getPosition().x, 0));
}
case 12, 13 -> {
int sliding = chip.isSliding() ? 1 : 0;
layerBG.set(position, Tile.fromOrdinal((byte) (sliding >>> shiftBy)));
chip.setSliding(false);
}
//buffered input, unsupported by SuCC
//MSCC's level title visibility, unsupported by SuCC
//keystroke directions, unsupported by SuCC
case 14, 15, 16, 17, 18, 19, 20, 21 -> layerBG.set(position, FLOOR);
case 22, 23 -> {
int deathCause = 0;
Tile chipFG = layerFG.get(chip.getPosition());
Tile chipBG = layerBG.get(chip.getPosition());
if (chipFG.isChip() || chipFG.isSwimmingChip()) {
if (chipFG.isChip() && chipBG == BOMB)
deathCause = 3;
}
else if (chipFG == DROWNED_CHIP)
deathCause = 1;
else if (chipFG == BURNED_CHIP)
deathCause = 2;
else if (chipFG.isBlock())
deathCause = 4;
else if (chipFG.isMonster())
deathCause = 5;
layerBG.set(position, Tile.fromOrdinal((byte) (deathCause >>> shiftBy)));
chip.setCreatureType(CreatureID.CHIP);
}
case 24, 25 -> {
if (!chip.isSliding()) {
layerBG.set(position, FLOOR);
return;
}
short slipDirectionX = 0;
if (chip.getDirection() == Direction.RIGHT) {
slipDirectionX = 1;
chip.setSliding(false); //not accurate, must research more
}
else if (chip.getDirection() == Direction.LEFT) {
slipDirectionX = -1;
chip.setSliding(false);
}
layerBG.set(position, Tile.fromOrdinal((byte) (slipDirectionX >>> shiftBy)));
}
case 26, 27 -> {
if (!chip.isSliding()) {
layerBG.set(position, FLOOR);
return;
}
short slipDirectionY = 0;
if (chip.getDirection() == Direction.DOWN) {
slipDirectionY = 1;
chip.setSliding(false); //not accurate, must research more
}
else if (chip.getDirection() == Direction.UP) {
slipDirectionY = -1;
chip.setSliding(false);
}
layerBG.set(position, Tile.fromOrdinal((byte) (slipDirectionY >>> shiftBy)));
}
case 28, 29 -> {
lowByte = (byte) INITIAL_MONSTER_LIST_SIZE;
highByte = (byte) (INITIAL_MONSTER_LIST_SIZE >>> 8);
if ((lowOrder ? lowByte : highByte) != 49)
layerBG.set(position, Tile.fromOrdinal((byte) (INITIAL_MONSTER_LIST_SIZE >>> shiftBy)));
}
case 30 -> layerBG.set(position, Tile.fromOrdinal((byte) (INITIAL_MONSTER_POSITION.x)));
case 31 -> layerBG.set(position, Tile.fromOrdinal((byte) (INITIAL_MONSTER_POSITION.y)));
}
}
public MSLevel(int levelNumber, String title, String password, String hint, String author,
Position[] toggleDoors, Position[] teleports,
MultiHashMap<Position, GreenButton> greenButtons, MultiHashMap<Position, RedButton> redButtons,
MultiHashMap<Position, BrownButton> brownButtons, MultiHashMap<Position, BlueButton> blueButtons,
BitSet traps, Layer layerBG, Layer layerFG, CreatureList monsterList, SlipList slipList,
MSCreature chip, int time, int chips, RNG rng, int rngSeed, Step step, int levelsetLength){
super(layerBG, layerFG, monsterList, slipList, chip,
chips, new short[4], new byte[4], rng, NO_CLICK, traps);
this.levelNumber = levelNumber;
this.startTime = time;
this.title = title;
this.password = password;
this.hint = hint;
this.author = author;
this.toggleDoors = toggleDoors;
this.teleports = teleports;
this.greenButtons = greenButtons;
this.redButtons = redButtons;
this.brownButtons = brownButtons;
this.blueButtons = blueButtons;
this.rngSeed = rngSeed;
this.step = step;
this.cheats = new Cheats(this);
this.LEVELSET_LENGTH = levelsetLength;
for (Creature c : monsterList)
c.setLevel(this);
chip.setLevel(this);
this.slipList.setLevel(this);
this.monsterList.setLevel(this);
trapButtons = new MultiHashMap<>(brownButtons.size());
for (List<BrownButton> buttons : getBrownButtons().rawValues()) { //On level start every single trap is actually open in MSCC, this implements that so creatures and blocks starting on traps can exit them at any point in the level
for (BrownButton b : buttons) {
if (getLayerFG().get(b.getTargetPosition()).isChip() || getLayerFG().get(b.getTargetPosition()) == BLOCK || getLayerFG().get(b.getTargetPosition()) == ICE_BLOCK) {
b.press(this);
}
trapButtons.put(b.getTargetPosition(), b);
}
}
trapIndexMap = new HashMap<>(trapButtons.size());
Iterator<Position> iterator = trapButtons.keySet().iterator();
int i = 0;
while (iterator.hasNext()) {
trapIndexMap.put(iterator.next(), i);
i++;
}
}
}
| 25,219 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
SlipList.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/game/MS/SlipList.java | package game.MS;
import game.Creature;
import game.Level;
import java.util.ArrayList;
public class SlipList extends ArrayList<Creature> { //This should only ever be used for MS
protected Level level;
public void tick(){
// Iterating like this causes slide delay.
for (int i = size(); i > 0; i--){
MSCreature monster = (MSCreature) get(size()-i);
monster.tick(monster.getSlideDirectionPriority(level.getLayerBG().get(monster.getPosition()), level.getRNG(), false), true);
}
}
public void setLevel(Level level){
this.level = level;
}
Level getLevel(){
return level;
}
public void setSliplist(Creature[] slidingCreatures){
clear();
for (Creature slider : slidingCreatures){
Creature c = level.getMonsterList().creatureAt(slider.getPosition(), false);
if (c == null) c = slider;
add(c); // Blocks are not in the monster list, so they are added separately
}
for (Creature c : this)
c.setLevel(level);
}
@Override
public String toString(){
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size(); i++){
sb.append(i+1);
sb.append('\t');
sb.append(get(i));
sb.append('\n');
}
return sb.toString();
}
}
| 1,401 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
BrownButton.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/game/button/BrownButton.java | package game.button;
import game.Level;
import game.Position;
public class BrownButton extends ConnectionButton {
@Override
public void press(Level level) {
level.setTrap(targetPosition, true);
}
public boolean isOpen(Level level) {
return level.isTrapOpen(targetPosition);
}
public void release(Level level) {
level.setTrap(targetPosition, false);
}
public BrownButton(Position buttonPosition, Position trapPosition) {
super(buttonPosition, trapPosition);
}
}
| 551 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
Button.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/game/button/Button.java | package game.button;
import game.Level;
import game.Position;
public abstract class Button {
private final Position buttonLocation;
public Position getButtonPosition() {
return buttonLocation;
}
public abstract void press(Level level);
public Button(Position buttonLocation) {
this.buttonLocation = buttonLocation;
}
}
| 386 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
GreenButton.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/game/button/GreenButton.java | package game.button;
import game.Level;
import game.Position;
import static game.Tile.TOGGLE_CLOSED;
import static game.Tile.TOGGLE_OPEN;
public class GreenButton extends Button{
@Override
public void press(Level level) {
for (Position p : level.getToggleDoors()) {
if (level.getLayerFG().get(p) == TOGGLE_OPEN)
level.getLayerFG().set(p, TOGGLE_CLOSED);
else if (level.getLayerFG().get(p) == TOGGLE_CLOSED)
level.getLayerFG().set(p, TOGGLE_OPEN);
else if (level.supportsLayerBG()) {
if (level.getLayerBG().get(p) == TOGGLE_OPEN)
level.getLayerBG().set(p, TOGGLE_CLOSED);
else if (level.getLayerBG().get(p) == TOGGLE_CLOSED)
level.getLayerBG().set(p, TOGGLE_OPEN);
}
}
}
public GreenButton(Position buttonPosition) {
super(buttonPosition);
}
}
| 953 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
BlueButton.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/game/button/BlueButton.java | package game.button;
import game.Creature;
import game.Level;
import game.Position;
import static game.CreatureID.TANK_MOVING;
import static game.Direction.TURN_AROUND;
public class BlueButton extends Button {
@Override
public void press(Level level) {
level.turnTanks();
}
public BlueButton(Position buttonPosition) {
super(buttonPosition);
}
}
| 400 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
ConnectionButton.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/game/button/ConnectionButton.java | package game.button;
import game.Position;
public abstract class ConnectionButton extends Button {
final Position targetPosition;
public Position getTargetPosition() {
return targetPosition;
}
public ConnectionButton(Position buttonPosition, Position targetPosition) {
super(buttonPosition);
this.targetPosition = targetPosition;
}
}
| 396 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
RedButton.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/game/button/RedButton.java | package game.button;
import game.Level;
import game.Position;
public class RedButton extends ConnectionButton {
@Override
public void press(Level level) {
level.getMonsterList().addClone(targetPosition);
}
public RedButton(Position buttonPosition, Position clonerPosition) {
super(buttonPosition, clonerPosition);
}
}
| 371 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
SavestateCompressor.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/emulator/SavestateCompressor.java | package emulator;
import util.ByteList;
import util.TreeNode;
import java.util.Stack;
import static game.Savestate.*;
public class SavestateCompressor implements Runnable{
private static final int LAYER_BG_LOCATION = 3,
LAYER_FG_LOCATION = LAYER_BG_LOCATION + 32 * 32,
LAYER_FG_END = LAYER_FG_LOCATION + 32 * 32;
private Stack<TreeNode<byte[]>> uncompressedSavestates;
private ByteList list;
private final Thread thread;
void add(TreeNode<byte[]> n){
uncompressedSavestates.add(n);
synchronized(thread) {
thread.notify();
}
}
@Override
public void run(){
while (true) {
try {
if (uncompressedSavestates.isEmpty()) {
synchronized (thread) {
thread.wait();
}
}
else {
compress(uncompressedSavestates.pop());
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
private void rleCompress(byte[] uncompressed, ByteList out, int startIndex, int length){
int lastOrdinal = uncompressed[startIndex];
int ordinal;
int copyCount = -1;
for (int i = startIndex; i < startIndex + length; i++) {
ordinal = uncompressed[i];
if (ordinal == lastOrdinal){
if (copyCount == 255){
out.add(RLE_MULTIPLE);
out.add(copyCount);
copyCount = 0;
out.add(ordinal);
}
else copyCount++;
}
else {
if (copyCount != 0){
out.add(RLE_MULTIPLE);
out.add(copyCount);
}
out.add(lastOrdinal);
copyCount = 0;
lastOrdinal = ordinal;
}
}
if (copyCount != 0){
out.add(RLE_MULTIPLE);
out.add(copyCount);
}
out.add(lastOrdinal);
out.add(RLE_END);
}
private void compress(TreeNode<byte[]> n){
list.clear();
byte[] uncompressedState = n.getData();
rleCompress(uncompressedState, list, LAYER_BG_LOCATION, 32*32);
rleCompress(uncompressedState, list, LAYER_FG_LOCATION, 32*32);
byte[] out = new byte[uncompressedState.length - 2 * 32 * 32 + list.size()];
out[0] = COMPRESSED_V2;
out[1] = uncompressedState[1];
out[2] = uncompressedState[2];
list.copy(out, 3);
System.arraycopy(uncompressedState, LAYER_FG_END, out, 3+list.size(), uncompressedState.length - 2 * 32 * 32 - 3);
n.setData(out);
}
void initialise() {
uncompressedSavestates = new Stack<>();
list = new ByteList();
}
SavestateCompressor(){
initialise();
thread = new Thread(this);
thread.setPriority(Thread.MIN_PRIORITY);
thread.start();
}
}
| 3,064 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
SavestateManager.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/emulator/SavestateManager.java | package emulator;
import game.Level;
import game.Position;
import game.Savestate;
import graphics.Gui;
import graphics.SmallGamePanel;
import util.CharList;
import util.TreeNode;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.Serial;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.IntStream;
public class SavestateManager implements Serializable {
private HashMap<Integer, TreeNode<byte[]>> savestates = new HashMap<>();
private HashMap<Integer, CharList> savestateMoves = new HashMap<>();
private TreeNode<byte[]> currentNode;
private CharList moves;
private CharList[] macros = new CharList[10];
private transient SuperCC emulator;
private transient List<TreeNode<byte[]>> playbackNodes = new ArrayList<>();
private transient int playbackIndex = 0;
private transient boolean[] recordingMacros = new boolean[10];
private transient int[] macroStartIndices = new int[10];
private transient byte[] levelTitle;
private transient boolean pause = true;
private static final int STANDARD_WAIT_TIME = 100; // 100 ms means 10 half-ticks per second.
private transient int playbackWaitTime = STANDARD_WAIT_TIME;
private static final int[] waitTimes = new int[]{
STANDARD_WAIT_TIME * 8,
STANDARD_WAIT_TIME * 4,
STANDARD_WAIT_TIME * 2,
STANDARD_WAIT_TIME,
STANDARD_WAIT_TIME / 2,
STANDARD_WAIT_TIME / 4,
STANDARD_WAIT_TIME / 8
};
public static final int NUM_SPEEDS = waitTimes.length;
@Serial
private static final long serialVersionUID = -3232323211211410511L;
private static final int VERSION_V0 = 0;
public void setPlaybackSpeed(int i) {
playbackWaitTime = waitTimes[i];
}
public int getPlaybackSpeed() {
return IntStream.range(0, waitTimes.length)
.filter(i -> waitTimes[i] == playbackWaitTime)
.findFirst()
.orElse(-1);
}
public byte[] getLevelTitle() {
return levelTitle;
}
public void setNode(TreeNode<byte[]> node) {
currentNode = node;
}
@Serial
private void writeObject(java.io.ObjectOutputStream stream) throws IOException {
stream.write(VERSION_V0);
stream.writeObject(savestates);
stream.write(savestateMoves.size());
for (int i : savestateMoves.keySet()) {
stream.write(i);
stream.writeObject(savestateMoves.get(i).toArray());
}
stream.write(macros.length);
for (CharList m : macros) {
stream.writeObject(m.toArray());
}
stream.write(levelTitle.length);
for(byte b : levelTitle) {
stream.write(b);
}
}
@SuppressWarnings("unchecked")
private void readObject(java.io.ObjectInputStream stream)
throws IOException, ClassNotFoundException {
if (stream.read() == VERSION_V0) {
savestates = (HashMap<Integer, TreeNode<byte[]>>) stream.readObject();
savestateMoves = new HashMap<>();
int movesLength = stream.read();
for (int i=0; i < movesLength; i++) {
savestateMoves.put(stream.read(), (new CharList((char[]) stream.readObject())));
}
int macroListLength = stream.read();
macros = new CharList[macroListLength];
for (int i=0; i < macroListLength; i++) {
macros[i] = new CharList((char[]) stream.readObject());
}
int levelTitleLength = stream.read();
levelTitle = new byte[levelTitleLength];
for(int i = 0; i < levelTitleLength; i++) {
levelTitle[i] = (byte) stream.read();
}
}
}
public void addRewindState(Level level, char c){
pause = true;
while (playbackNodes.get(playbackNodes.size()-1) != currentNode) {
playbackNodes.remove(playbackNodes.size()-1);
moves.removeLast();
}
currentNode = new TreeNode<>(level.save(), currentNode);
// emulator.savestateCompressor.add(currentNode);
playbackNodes.add(currentNode);
moves.add(c);
playbackIndex = playbackNodes.size() - 1;
}
public void restart() {
pause = true;
while (currentNode.hasParent()) {
currentNode = currentNode.getParent();
playbackIndex--;
}
}
public void rewind(){
pause = true;
if (currentNode.hasParent()) {
currentNode = currentNode.getParent();
playbackIndex--;
}
}
public void playbackRewind(int index){
pause = true;
currentNode = playbackNodes.get(index);
playbackIndex = index;
}
public void replay(){
if (playbackIndex + 1 < playbackNodes.size()) {
currentNode = playbackNodes.get(++playbackIndex);
}
}
public void replayAll() {
pause = true;
while (playbackIndex + 1 < playbackNodes.size()) {
currentNode = playbackNodes.get(++playbackIndex);
}
}
public void togglePause() {
pause = !pause;
}
public boolean isPaused() {
return pause;
}
public void play(SuperCC emulator) {
pause = false;
try {
while (!pause && playbackIndex + 1 < playbackNodes.size()) {
emulator.getLevel().load(currentNode.getData());
char c = SuperCC.lowerCase(moves.get(playbackIndex));
boolean tickMulti = emulator.tick(c, TickFlags.REPLAY);
Thread.sleep(playbackWaitTime);
if (tickMulti) {
for (int i=0; i < emulator.getLevel().ticksPerMove() - 1; i++) {
emulator.tick(SuperCC.WAIT, TickFlags.REPLAY);
Thread.sleep(playbackWaitTime);
}
}
replay();
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
if (!pause) {
emulator.getMainWindow().getPlayButton().doClick();
emulator.showAction("Playback finished");
}
emulator.repaint(false);
}
public List<BufferedImage> play(SuperCC emulator, int numTicks) {
pause = true;
ArrayList<BufferedImage> images = new ArrayList<>();
Gui window = emulator.getMainWindow();
int tileWidth = window.getGamePanel().getTileWidth();
int tileHeight = window.getGamePanel().getTileHeight();
int windowSizeY = ((SmallGamePanel) window.getGamePanel()).getWindowSizeY();
int windowSizeX = ((SmallGamePanel) window.getGamePanel()).getWindowSizeX();
BufferedImage img = new BufferedImage(windowSizeX * tileWidth, windowSizeY * tileHeight, BufferedImage.TYPE_4BYTE_ABGR);
window.getGamePanel().paintComponent(img.getGraphics());
images.add(img);
while (numTicks-- > 0 && playbackIndex + 1 < playbackNodes.size()) {
char c = SuperCC.lowerCase(moves.get(playbackIndex));
boolean tickMulti = emulator.tick(c, TickFlags.REPLAY);
img = new BufferedImage(32 * 20, 32 * 20, BufferedImage.TYPE_4BYTE_ABGR);
window.getGamePanel().paintComponent(img.getGraphics());
images.add(img);
if (tickMulti && numTicks-- > 0) {
for (int i=0; i < emulator.getLevel().ticksPerMove() - 1; i++) {
emulator.tick(SuperCC.WAIT, TickFlags.REPLAY);
img = new BufferedImage(32 * 20, 32 * 20, BufferedImage.TYPE_4BYTE_ABGR);
window.getGamePanel().paintComponent(img.getGraphics());
images.add(img);
}
}
replay();
}
if (!pause) {
window.getPlayButton().doClick();
}
emulator.repaint(false);
return images;
}
public void addSavestate(int key){
savestates.put(key, currentNode);
savestateMoves.put(key, moves.clone());
}
/**
* Begins or ends 'recording' a move macro in the specified key slot.
* @param key an int value between 0 and 9 representing the macro slot to use.
* @return true if this is start of a recording, false if this the end and the recording has been saved.
*/
boolean macroRecorder(int key) {
if (!recordingMacros[key]) {
macroStartIndices[key] = playbackIndex; //Store the current position in the move array so we can come back to it later
recordingMacros[key] = true;
return true;
}
else {
macros[key] = moves.sublist(macroStartIndices[key], playbackIndex); //Puts all the moves recorded into this list
recordingMacros[key] = false;
return false;
}
}
void playMacro(int key) {
pause = true;
CharList macro = macros[key];
for (char c : macro) {
emulator.tick(SuperCC.lowerCase(c), TickFlags.PRELOADING);
}
}
public CharList[] getMacros() {
return macros;
}
public boolean load(int key, Level level){
pause = true;
TreeNode<byte[]> loadedNode = savestates.get(key);
if (loadedNode == null) return false;
currentNode = loadedNode;
level.load(currentNode.getData());
if (!playbackNodes.contains(currentNode)) {
playbackNodes = currentNode.getHistory();
playbackIndex = playbackNodes.size() - 1;
moves = savestateMoves.get(key).clone();
}
else {
playbackIndex = playbackNodes.indexOf(currentNode);
}
return true;
}
public List<TreeNode<byte[]>> getPlaybackNodes() {
return playbackNodes;
}
public void setPlaybackNodes(TreeNode<byte[]> node) {
pause = true;
this.playbackNodes = new ArrayList<>();
this.playbackNodes.addAll(node.getHistory());
}
public int getPlaybackIndex() {
return playbackIndex;
}
public void setPlaybackIndex(int index) {
pause = true;
this.playbackIndex = index;
}
public byte[] getSavestate(){
return currentNode.getData();
}
public byte[] getStartingState() {
TreeNode<byte[]> state = currentNode;
while (state.hasParent()) state = state.getParent();
return state.getData();
}
public CharList getMoveList(){
return moves;
}
public char[] getMoves(){
char[] moves = new char[playbackIndex];
this.moves.copy(0, moves, 0, playbackIndex);
return moves;
}
public void setMoves(CharList moves) {
pause = true;
this.moves = moves;
}
public String movesToString() {
return moves.toString(playbackIndex);
}
public TreeNode<byte[]> getNode(){
return currentNode;
}
SavestateManager(SuperCC emulator, Level level) throws UnsupportedEncodingException {
this.emulator = emulator;
levelTitle = level.getTitle().getBytes("Windows-1252");
// emulator.savestateCompressor.initialise();
currentNode = new TreeNode<>(level.save(), null);
playbackNodes.add(currentNode);
moves = new CharList();
for (int i = 0; i < macros.length; i++)
macros[i] = new CharList();
}
public LinkedList<Position> getChipHistory(){
LinkedList<Position> chipHistory = new LinkedList<>();
for (TreeNode<byte[]> node : currentNode.getHistory()) chipHistory.add(Savestate.getChip(node.getData()).getPosition());
return chipHistory;
}
public void setEmulator(SuperCC emulator) throws UnsupportedEncodingException {
pause = true;
this.emulator = emulator;
levelTitle = emulator.getLevel().getTitle().getBytes("Windows-1252");
emulator.repaint(true);
// emulator.savestateCompressor.initialise();
/* Yes having this here does make the method do more than its name implies, however seeing as the only reason
emulator is used is in order to have access to the compressor, and whenever emulator is changed it means that
a new savestate manager was created/read from a file, meaning that the compressor should be reset as well */
}
}
| 12,599 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
SuperCC.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/emulator/SuperCC.java | package emulator;
import game.*;
import graphics.Gui;
import graphics.SmallGamePanel;
import graphics.TileSheet;
import io.DatParser;
import io.SuccPaths;
import io.TWSReader;
import tools.SeedSearch;
import tools.TSPGUI;
import tools.VariationTesting;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Map;
public class SuperCC {
public static final char UP = 'u', LEFT = 'l', DOWN = 'd', RIGHT = 'r', WAIT = '-', UP_LEFT = '↖', DOWN_LEFT = '↙',
DOWN_RIGHT = '↘', UP_RIGHT = '↗', MIN_CLICK_LOWERCASE = '¯', MAX_CLICK_LOWERCASE = 'ÿ',
MIN_CLICK_UPPERCASE = 'Ā', MAX_CLICK_UPPERCASE = 'Ő';
private static final char[] CHAR_MOVEMENT_KEYS = {UP, LEFT, DOWN, RIGHT, UP_LEFT, DOWN_LEFT, DOWN_RIGHT, UP_RIGHT, WAIT};
private static final Map<Character, Direction> DIRECTIONS = Map.of(UP, Direction.UP, LEFT, Direction.LEFT,
DOWN, Direction.DOWN, RIGHT, Direction.RIGHT, UP_LEFT, Direction.UP_LEFT, DOWN_LEFT, Direction.DOWN_LEFT,
DOWN_RIGHT, Direction.DOWN_RIGHT, UP_RIGHT, Direction.UP_RIGHT, WAIT, Direction.NONE);
public static final byte CHIP_RELATIVE_CLICK = 1;
private SavestateManager savestates;
// SavestateCompressor savestateCompressor = new SavestateCompressor();
private Level level;
private Gui window;
private DatParser dat;
private Solution solution;
public TWSReader twsReader;
private SuccPaths paths;
private EmulatorKeyListener controls;
public boolean hasGui = true;
public void setControls(EmulatorKeyListener l) {
controls = l;
}
public EmulatorKeyListener getControls() {
return controls;
}
public SuccPaths getPaths() {
return paths;
}
public String getJSONPath() {
String levelName = level.getTitle().replaceAll("[^a-zA-Z0-9 ]",""); //Delete everything except letters, numbers, and spaces so you won't get issues with illegal filenames
//levelName = levelName.substring(0, levelName.length()-1).replaceAll("\\s","_"); //No longer needed as the previous line now takes care of this but kept commented in case its needed in future
return paths.getJSONPath(dat.getLevelsetName(), level.getLevelNumber(), levelName, level.getRuleset().name());
}
public String getSerPath() {
return getJSONPath().replace(".json", ".ser");
}
public String getLevelsetPath() {
return dat.getLevelsetPath();
}
public void repaint(boolean fromScratch) {
window.repaint(fromScratch);
}
public static char capital(char c){
if (isClick(c) && isLowercase(c))
return (char) (c + (MAX_CLICK_UPPERCASE - MAX_CLICK_LOWERCASE)); //puts it into the uppercase click range
return switch (c) {
case WAIT -> '_';
case UP_LEFT -> '⇖';
case DOWN_LEFT -> '⇙';
case DOWN_RIGHT -> '⇘';
case UP_RIGHT -> '⇗';
default -> Character.toUpperCase(c);
};
}
public static char lowerCase(char c) {
if (isClick(c) && isUppercase(c))
return (char) (c - (MAX_CLICK_UPPERCASE - MAX_CLICK_LOWERCASE)); //puts it into the lowercase click range
return switch (c) {
case 'U' -> UP;
case 'L' -> LEFT;
case 'D' -> DOWN;
case 'R' -> RIGHT;
case '_' -> WAIT;
case '⇖' -> UP_LEFT;
case '⇙' -> DOWN_LEFT;
case '⇘' -> DOWN_RIGHT;
case '⇗' -> UP_RIGHT;
default -> Character.toLowerCase(c);
};
}
public int lastLevelNumber() {
return dat.lastLevel();
}
public void setTWSFile(File twsFile){
try{
this.twsReader = new TWSReader(twsFile);
}
catch (IOException e){
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Could not read file:\n"+e.getLocalizedMessage());
}
}
public Level getLevel(){
return level;
}
public Solution getSolution() {
return solution;
}
public SavestateManager getSavestates(){
return savestates;
}
public void setSavestates(SavestateManager sm) {
this.savestates = sm;
}
public Gui getMainWindow(){
return window;
}
public SuperCC() {
try {
File f = new File("settings.ini");
paths = new SuccPaths(f);
}
catch (IOException e){
throwMessage("Could not find settings.ini file, creating"); //If it can't find the settings file make it with some defaults
SuccPaths.createSettingsFile();
//Now that the settings file exists we can call this again safely
File f = new File("settings.ini");
try {
paths = new SuccPaths(f);
} catch (IOException ex) {
ex.printStackTrace();
}
}
window = new Gui(this);
}
// GUI-less emulator - used for tests
public SuperCC(boolean hasGui) {
this.hasGui = hasGui;
}
public void openLevelset(File levelset){
try{
dat = new DatParser(levelset);
}
catch (IOException e){
throwError("Could not read file:\n"+e.getLocalizedMessage());
}
loadLevel(1, 0, Step.EVEN, false, dat.getRuleset(), Direction.UP);
if (hasGui)
window.swapRulesetTilesheet(level.getRuleset());
}
public synchronized void loadLevel(int levelNumber, int rngSeed, Step step, boolean keepMoves, Ruleset rules, Direction initialSlide){
if (levelNumber == 0) levelNumber = lastLevelNumber()-1; //If the level number is 0 (player goes back from level 1, load the last level)
if (levelNumber == lastLevelNumber()) levelNumber = 1; //And vice versa
try{
if (keepMoves && level != null && levelNumber == level.getLevelNumber()) {
solution = new Solution(getSavestates().getMoveList(), rngSeed, step, level.getRuleset(), initialSlide);
solution.load(this);
}
else {
level = dat.parseLevel(levelNumber, rngSeed, step, rules, initialSlide);
savestates = new SavestateManager(this, level);
solution = new Solution(new char[] {}, 0, Step.EVEN, Solution.BASIC_MOVES, level.getRuleset(), Direction.UP);
if(hasGui) {
window.repaint(true);
window.setTitle("SuperCC - " + level.getTitle());
}
}
}
catch (Exception e){
e.printStackTrace();
throwError("Could not load level: "+e.getMessage());
}
}
public synchronized void loadLevel(int levelNumber){
loadLevel(levelNumber, 0, Step.EVEN, true, Ruleset.CURRENT, Direction.UP);
}
public boolean tick(char c, Direction[] directions, TickFlags flags){
if (level == null)
return false;
if (directions[0].isDiagonal() && !level.supportsDiagonal()) {
directions[0] = directions[0].decompose()[0]; //take vertical
for (char c1 : DIRECTIONS.keySet()) { //switch the char part to vertical
if (directions[0] == DIRECTIONS.get(c1)) {
c = c1;
break;
}
}
}
int levelFlags = level.tick(c, directions);
boolean tickMulti = (levelFlags & Level.MASK_TICK_MULTI) != 0;
if (flags.multiTick && tickMulti) {
for (int i=0; i < level.ticksPerMove() - 1; i++) {
c = capital(c);
level.tick(c, new Direction[] {Direction.NONE});
}
}
if ((levelFlags & Level.MASK_DISCARD_INPUT) != 0)
c = WAIT;
if (flags.save) {
savestates.addRewindState(level, c);
}
if (flags.repaint) window.repaint(false);
return tickMulti;
}
public boolean tick(char c, TickFlags flags){
if (level == null) return false;
Direction[] directions;
if (isClick(c)){
Position screenPosition = Position.screenPosition(level.getChip().getPosition());
Position clickedPosition = Position.clickPosition(screenPosition, c);
directions = level.getChip().getPosition().seek(clickedPosition);
level.setClick(clickedPosition.getIndex());
return tick(c, directions, flags);
}
else{
for (char charMovementKey : CHAR_MOVEMENT_KEYS) {
if (charMovementKey == c) {
directions = new Direction[] {DIRECTIONS.get(c)};
return tick(c, directions, flags);
}
}
}
return false;
}
public boolean isLevelLoaded() {
return level != null;
}
public static boolean isClick(char c){
return c <= MAX_CLICK_UPPERCASE && c >= MIN_CLICK_LOWERCASE;
}
public static boolean isUppercase(char c) {
return c == 'U' || c == 'L' || c == 'D' || c == 'R' || c == '_' || c == '⇖' || c == '⇙' || c == '⇘' || c == '⇗'
|| (c <= MAX_CLICK_UPPERCASE && c >= MIN_CLICK_UPPERCASE);
}
public static boolean isLowercase(char c) {
return c == UP || c == LEFT || c == DOWN || c == RIGHT || c == UP_LEFT || c == DOWN_LEFT || c == WAIT
|| c == DOWN_RIGHT || c == UP_RIGHT || (c <= MAX_CLICK_LOWERCASE && c >= MIN_CLICK_LOWERCASE);
}
public void showAction(String s){
getMainWindow().getLastActionPanel().update(s);
getMainWindow().getLastActionPanel().repaint();
}
void testTWS() {
System.out.println(dat.getLevelsetName());
for (int j = 1; j <= level.getLevelsetLength(); j++) {
loadLevel(j);
try {
Solution s = twsReader.readSolution(level);
// System.out.println(s.efficiency);
s.load(this);
if (level.getLayerFG().get(level.getChip().getPosition()) != Tile.EXITED_CHIP && !level.isCompleted()) {
System.out.println("failed level "+level.getLevelNumber()+" "+ level.getTitle());
}
}
catch (Exception exc) {
System.out.println("Error loading "+level.getLevelNumber()+" "+ level.getTitle());
exc.printStackTrace();
}
}
}
private void runBenchmark(int levelNumber, int runs){
loadLevel(levelNumber);
Solution s;
try {
s = twsReader.readSolution(level);
System.out.println("Running test without writing.");
long startTime = System.nanoTime();
for (int i = 0; i < runs; i++) s.load(this, TickFlags.LIGHT);
long endTime = System.nanoTime();
double timePerIteration = (endTime - startTime) / (double) runs;
System.out.println("Time per iteration:");
System.out.println((timePerIteration / 1000000)+"ms");
System.out.println((timePerIteration / 1000000000)+"s\n");
System.out.println("Running test with writing.");
startTime = System.nanoTime();
for (int i = 0; i < runs; i++) s.load(this);
endTime = System.nanoTime();
timePerIteration = (endTime - startTime) / (double) runs;
System.out.println("Time per iteration:");
System.out.println((timePerIteration / 1000000)+"ms");
System.out.println((timePerIteration / 1000000000)+"s");
double numMoves = savestates.getMoves().length;
int size = savestates.getSavestate().length;
while (savestates.getNode().hasParent()){
savestates.rewind();
size += savestates.getSavestate().length;
}
System.out.println("\nTotal state size:");
System.out.println((size / (double) 1000)+" kb");
System.out.println("\nAverage state size:");
System.out.println((size / numMoves / 1000)+" kb");
}
catch (IOException e){
System.out.println("Benchmark of level "+level+"failed");
}
}
public static void initialise(String[] args){
SuperCC emulator = new SuperCC();
try {
ArgumentParser.parseArguments(emulator, args); //Parses any command line arguments given
} catch (IllegalArgumentException e) {
emulator.throwError(e.toString() + "\nSee stderr for flag use");
}
emulator.initialiseTilesheet();
}
private void initialiseTilesheet() {
Gui window = this.getMainWindow();
SuccPaths paths = this.getPaths();
TileSheet[] tileSheets = TileSheet.values();
TileSheet tileSheet = tileSheets[paths.getMSTilesetNum()];
int[] tileSizes = paths.getTileSizes();
int width = tileSizes[0];
int height = tileSizes[1];
SmallGamePanel gamePanel = (SmallGamePanel) window.getGamePanel();
this.getMainWindow().getGamePanel().setTileSheet(tileSheet);
BufferedImage[] tilesetImages = null;
try {
tilesetImages = tileSheet.getTileSheets(width, height);
} catch (IOException e) {
e.printStackTrace();
}
//see if all of this can't be refactored out of existence by pressing the buttons in MenuBar if their setting is changed
window.getGamePanel().initialise(this, tilesetImages, tileSheet, tileSizes[0], tileSizes[1]);
window.getInventoryPanel().initialise(this);
window.setSize(200+width*gamePanel.getWindowSizeX(), 200+height*gamePanel.getWindowSizeY());
window.getGamePanel().setPreferredSize(new Dimension(width * gamePanel.getWindowSizeX(), height * gamePanel.getWindowSizeY()));
window.getGamePanel().setSize(width*gamePanel.getWindowSizeX(), height*gamePanel.getWindowSizeY());
window.getLevelPanel().changeNotation(paths.getTWSNotation());
window.pack();
window.repaint(true);
}
public static boolean areToolsRunning() {
return (SeedSearch.isRunning() || TSPGUI.isRunning() || VariationTesting.isRunning());
}
public void throwError(String s){
if (hasGui)
JOptionPane.showMessageDialog(getMainWindow(), s, "Error", JOptionPane.ERROR_MESSAGE);
else
System.err.println("[SuperCC Error] " + s);
}
public void throwMessage(String s){
if (hasGui)
JOptionPane.showMessageDialog(getMainWindow(), s, "SuCC Message", JOptionPane.PLAIN_MESSAGE);
else
System.out.println("[SuperCC Message] " + s);
}
public boolean throwQuestion(String s) {
if (hasGui) {
return JOptionPane.showConfirmDialog(getMainWindow(), s, "SuCC Option",
JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION;
}
else {
System.err.println("Tried throwing question without GUI!");
return false;
}
}
public static void main(String[] args){
SwingUtilities.invokeLater(() -> initialise(args));
}
}
| 15,399 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
EmulatorKeyListener.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/emulator/EmulatorKeyListener.java | package emulator;
import io.SuccPaths;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.*;
public class EmulatorKeyListener extends KeyAdapter {
private final SuperCC emulator;
public enum Key {
UP(SuperCC.UP),
LEFT(SuperCC.LEFT),
DOWN(SuperCC.DOWN),
RIGHT(SuperCC.RIGHT),
UP_LEFT(SuperCC.UP_LEFT),
DOWN_LEFT(SuperCC.DOWN_LEFT),
DOWN_RIGHT(SuperCC.DOWN_RIGHT),
UP_RIGHT(SuperCC.UP_RIGHT),
HALF_WAIT(SuperCC.WAIT),
FULL_WAIT(SuperCC.WAIT),
REWIND,
FORWARD;
private char directionChar;
private int keyCode;
public int getKeyCode() {
return keyCode;
}
Key(char directionChar) {
this.directionChar = directionChar;
}
Key() {}
}
private final HashMap<Integer, Key> keyMap = new HashMap<>();
public void setKeyCode(Key key, int keyCode) {
keyMap.remove(key.keyCode);
key.keyCode = keyCode;
keyMap.put(keyCode, key);
}
void processKeyPress(Key k, int keyCode, boolean control, boolean shift) {
SavestateManager savestates = emulator.getSavestates();
if (savestates == null)
return;
if (k == null) {
if (keyCode != KeyEvent.VK_SHIFT && shift) {
if (control && KeyEvent.VK_0 <= keyCode && keyCode <= KeyEvent.VK_9) {
try {
boolean recording = savestates.macroRecorder(keyCode - KeyEvent.VK_0);
if (recording)
emulator.showAction("Started macro record");
else
emulator.showAction("Finished macro record");
}
catch (IllegalArgumentException e1) {
emulator.throwError("The macro start position was after the end.");
}
}
else {
if (!control) { //Just so you can't accidentally save a state into these
savestates.addSavestate(keyCode);
emulator.showAction("State " + KeyEvent.getKeyText(keyCode) + " saved");
}
}
}
else {
if (control && KeyEvent.VK_0 <= keyCode && keyCode <= KeyEvent.VK_9) {
savestates.playMacro(keyCode-KeyEvent.VK_0);
emulator.getMainWindow().repaint(false);
emulator.showAction("Macro " + KeyEvent.getKeyText(keyCode) + " loaded");
}
else if (savestates.load(keyCode, emulator.getLevel())) {
emulator.showAction("State " + KeyEvent.getKeyText(keyCode) + " loaded");
emulator.getMainWindow().repaint(false);
}
}
}
else {
switch (k) {
case UP:
case LEFT:
case DOWN:
case RIGHT:
case UP_LEFT:
case DOWN_LEFT:
case DOWN_RIGHT:
case UP_RIGHT:
case HALF_WAIT:
if (!emulator.getLevel().getChip().isDead() && !SuperCC.areToolsRunning())
emulator.tick(k.directionChar, TickFlags.GAME_PLAY);
break;
case FULL_WAIT:
for (int i=0; i < emulator.getLevel().ticksPerMove(); i++) {
if (!emulator.getLevel().getChip().isDead() && !SuperCC.areToolsRunning())
emulator.tick(k.directionChar, TickFlags.GAME_PLAY);
}
break;
case REWIND:
savestates.rewind();
emulator.getLevel().load(emulator.getSavestates().getSavestate());
emulator.showAction("Rewind");
emulator.getMainWindow().repaint(false);
break;
case FORWARD:
savestates.replay();
emulator.getLevel().load(emulator.getSavestates().getSavestate());
emulator.showAction("Replay");
emulator.getMainWindow().repaint(false);
break;
}
}
}
Set<Key> heldKeys = new HashSet<>();
boolean diagonalsWaitHappening = false;
@Override
public void keyPressed(KeyEvent e) {
Key k = keyMap.getOrDefault(e.getKeyCode(), null); //Checks if the pressed key is one of the 'action' keys
if (!emulator.getPaths().getControls().autoDiagonals || k == null) {
processKeyPress(k, e.getKeyCode(), e.isControlDown(), e.isShiftDown());
return;
}
heldKeys.add(k);
if (diagonalsWaitHappening) return;
diagonalsWaitHappening = true;
new Timer(true).schedule(new TimerTask () {
@Override
public void run() {
diagonalsWaitHappening = false;
List<Key> lHeldKeys = heldKeys.stream().toList();
if(lHeldKeys.isEmpty()) return;
Key activeKey = null;
if (lHeldKeys.contains(Key.UP) && lHeldKeys.contains(Key.RIGHT)) activeKey = Key.UP_RIGHT;
if (lHeldKeys.contains(Key.RIGHT) && lHeldKeys.contains(Key.DOWN)) activeKey = Key.DOWN_RIGHT;
if (lHeldKeys.contains(Key.DOWN) && lHeldKeys.contains(Key.LEFT)) activeKey = Key.DOWN_LEFT;
if (lHeldKeys.contains(Key.LEFT) && lHeldKeys.contains(Key.UP)) activeKey = Key.UP_LEFT;
if (activeKey == null) activeKey = lHeldKeys.get(0);
processKeyPress(activeKey, 0, false, false);
//heldKeys.clear();
}
}, 1000 / 20);
}
@Override
public void keyReleased(KeyEvent e) {
Key k = keyMap.getOrDefault(e.getKeyCode(), null);
if (!emulator.getPaths().getControls().autoDiagonals || k == null) return;
heldKeys.remove(k);
}
public EmulatorKeyListener(SuperCC emulator) {
this.emulator = emulator;
SuccPaths.Controls controls = emulator.getPaths().getControls();
Key[] allKeys = Key.values();
for (int i = 0; i < allKeys.length; i++) {
allKeys[i].keyCode = controls.keys[i];
keyMap.put(controls.keys[i], allKeys[i]);
}
}
}
| 6,534 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
Solution.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/emulator/Solution.java | package emulator;
import game.*;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import util.CharList;
import java.io.CharArrayWriter;
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import java.util.HashSet;
import static emulator.SuperCC.*;
public class Solution{
public static final String STEP = "Step", SEED = "Seed", MOVES = "Moves", ENCODE = "Encode", RULE = "Rule", SLIDE = "Initial Slide";
public static final int QUARTER_MOVES = 0,
BASIC_MOVES = 1,
SUCC_MOVES = 2;
public char[] basicMoves;
public int rngSeed;
public Step step;
public Ruleset ruleset;
public Direction initialSlide;
public final String encoding = "UTF-8";
public double efficiency = -1;
public boolean melindaRouterGenerated = false;
public JSONObject toJSON() {
JSONObject json = new JSONObject();
json.put(STEP, step.name());
json.put(SEED, Integer.toString(rngSeed));
json.put(SLIDE, initialSlide.toString());
json.put(RULE, ruleset.toString());
json.put(ENCODE, encoding);
json.put(MOVES, new String(basicMoves));
return json;
}
public static Solution fromJSON(String s){
try {
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(s);
Step step = Step.valueOf((String) json.get(STEP));
int rngSeed = Integer.parseInt((String) json.get(SEED));
char[] basicMoves = ((String) json.get(MOVES)).toCharArray();
String ruleString = (String) json.get(RULE);
String slideString = (String) json.get(SLIDE);
Ruleset ruleset = Ruleset.valueOf(ruleString == null ? "MS" : ruleString);
Direction slidingDirection = Direction.valueOf(slideString == null ? "UP" : slideString);
return new Solution(basicMoves, rngSeed, step, BASIC_MOVES, ruleset, slidingDirection);
}
catch (ParseException e){
throw new IllegalArgumentException("Invalid solution file:\n" + s);
}
}
public void load(SuperCC emulator){
load(emulator, TickFlags.PRELOADING);
}
public void load(SuperCC emulator, TickFlags tickFlags){
if (emulator.getLevel().getRuleset() != ruleset) {
if (!emulator.throwQuestion("Solution has a different ruleset than currently selected, change rulesets?"))
return;
if (emulator.hasGui)
emulator.getMainWindow().swapRulesetTilesheet(ruleset);
}
emulator.loadLevel(emulator.getLevel().getLevelNumber(), rngSeed, step, false, ruleset, initialSlide);
tickBasicMoves(emulator, tickFlags);
if(emulator.hasGui) {
emulator.getMainWindow().repaint(true);
}
}
public void loadMoves(SuperCC emulator, TickFlags tickFlags, boolean repaint){
tickBasicMoves(emulator, tickFlags);
if (repaint) emulator.getMainWindow().repaint(true);
}
private void tickBasicMoves(SuperCC emulator, TickFlags tickFlags) {
Level level = emulator.getLevel();
// try{
for (int move = 0; move < basicMoves.length; move++){
char c = basicMoves[move];
if (c == CHIP_RELATIVE_CLICK){
int x = basicMoves[++move] - 9;
int y = basicMoves[++move] - 9;
if (x == 0 && y == 0){ // idk about this but it fixes thief street
c = WAIT;
}
else {
Position chipPosition = level.getChip().getPosition();
Position clickPosition = chipPosition.add(x, y);
level.setClick(clickPosition.getIndex());
c = clickPosition.clickChar(chipPosition);
}
}
boolean tickedMulti = emulator.tick(c, tickFlags);
if (tickedMulti)
move += level.ticksPerMove() - 1;
if (level.getChip().isDead()) {
break;
}
}
// }
// catch (Exception e){
// e.printStackTrace();
// emulator.throwError("Something went wrong:\n" + e);
// }
}
private static char[] succToBasicMoves(char[] succMoves, Ruleset ruleset){
CharArrayWriter writer = new CharArrayWriter();
for (char c : succMoves){
if (SuperCC.isUppercase(c)) {
writer.write(SuperCC.lowerCase(c));
for (int i=0; i < ruleset.ticksPerMove - 1; i++)
writer.write(WAIT);
}
else writer.write(c);
}
return writer.toCharArray();
}
private static char[] succToBasicMoves(CharList succMoves, Ruleset ruleset){
return succToBasicMoves(succMoves.toArray(), ruleset);
}
private static char[] quarterToBasicMoves(char[] quarterMoves, Ruleset ruleset) {
switch (ruleset.ticksPerMove) {
case 2:
return quarterMovesToHalfMoves(quarterMoves);
case 4:
return quarterMovesToQuarterBasicMoves(quarterMoves);
default:
System.err.println("ENCOUNTERED BAD TICKS PER MOVE VALUES OF: " + ruleset.ticksPerMove);
return new char[]{};
}
}
private static char[] quarterMovesToHalfMoves(char[] quarterMoves) {
CharArrayWriter writer = new CharArrayWriter();
// System.out.println(Arrays.toString(quarterMoves));
Set<Character> directions = new HashSet<>(); //Makes it so that i don't have to write out 8 equality checks
Collections.addAll(directions, UP, DOWN, LEFT, RIGHT, UP_LEFT, DOWN_LEFT, UP_RIGHT, DOWN_RIGHT);
for (int i = 0; i < quarterMoves.length; i += 2) {
char a = quarterMoves[i];
char c = 0;
int j = i+1;
if (a == CHIP_RELATIVE_CLICK && j+2 < quarterMoves.length) j += 2;
//Since mouse moves take 3 bytes this just makes sure that c is always the intended move/wait
//and not part of the mouse bytes
if (j < quarterMoves.length) c = quarterMoves[j];
if (a == '~' && c == '~') { //It should only write a half wait if BOTH values read are quarter waits
writer.write(WAIT);
}
else { //Input priority things
if (directions.contains(a)) {
writer.write(a);
continue;
}
if (directions.contains(c) || c == CHIP_RELATIVE_CLICK) {
writer.write(c);
if (directions.contains(c)) { //Keyboard input check
continue;
}
else if (c == CHIP_RELATIVE_CLICK) {
i = j;
writer.write(quarterMoves[++j]);
writer.write(quarterMoves[++j]);
++i; //Puts the reader right into the first direction so that the i += 2 at the start jumps to
//the next pair of quarter moves
continue;
}
}
if (a == CHIP_RELATIVE_CLICK) {
writer.write(a);
writer.write(quarterMoves[++i]);
writer.write(quarterMoves[++i]);
continue;
}
}
}
writer.write(WAIT);
//Sometimes solutions end on slides into the exit which TW somehow handles magically even when no waits
//occur at solution end, so sticking an extra wait onto the end here should be enough to fix that
// System.out.println(Arrays.toString(writer.toCharArray()));
return writer.toCharArray();
}
private static char[] quarterMovesToQuarterBasicMoves(char[] quarterMoves) {
CharArrayWriter writer = new CharArrayWriter();
for (int i=0; i < quarterMoves.length; i++) {
char c = quarterMoves[i];
if (c != CHIP_RELATIVE_CLICK)
writer.write(c == '~' ? '-' : c);
else {
writer.write(c);
writer.write(++i);
writer.write(++i);
}
}
return writer.toCharArray();
}
@Override
public String toString(){
return toJSON().toJSONString();
}
public Solution(char[] moves, int rngSeed, Step step, int format, Ruleset ruleset, Direction initialSlide){
if (format == QUARTER_MOVES) this.basicMoves = quarterToBasicMoves(moves, ruleset);
else if (format == SUCC_MOVES) this.basicMoves = succToBasicMoves(moves, ruleset);
else if (format == BASIC_MOVES) this.basicMoves = moves;
this.rngSeed = rngSeed;
this.step = step;
this.ruleset = ruleset;
this.initialSlide = initialSlide;
}
public Solution(CharList moves, int rngSeed, Step step, Ruleset ruleset, Direction initialSlide){
this.basicMoves = succToBasicMoves(moves, ruleset);
this.rngSeed = rngSeed;
this.step = step;
this.ruleset = ruleset;
this.initialSlide = initialSlide;
//for (int move = 0; move < basicMoves.length; move++) System.out.println(basicMoves[move]);
}
public Solution(Solution solution) { //copy constructor
this.basicMoves = Arrays.copyOf(solution.basicMoves, solution.basicMoves.length);
this.rngSeed = solution.rngSeed;
this.step = solution.step;
this.ruleset = solution.ruleset;
this.initialSlide = solution.initialSlide;
}
}
| 9,940 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
ArgumentParser.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/emulator/ArgumentParser.java | package emulator;
import game.Direction;
import game.Ruleset;
import game.Step;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
final class ArgumentParser {
private final static String helpLong = "--help", helpShort = "-h", helpQuestion = "-?", twsLong = "--testtws",
levelLong = "--level", levelShort = "-l", stepLong = "--step", stepShort = "-s", rffLong = "-rff",
rffShort = "-f", rngLong = "--rng", rngShort = "-r", rulesLong = "--rules", rulesShort = "-m";
static void parseArguments(SuperCC emulator, String[] args) throws IllegalArgumentException {
if (args.length != 0) {
Set<String> arguments = new HashSet<>(Arrays.asList(helpLong, helpShort, helpQuestion, twsLong, levelLong,
levelShort, stepLong, stepShort, rngLong, rngShort, rulesLong, rulesShort));
Ruleset rules = Ruleset.CURRENT;
boolean testTWS = false;
Path levelsetPath = null;
Path twsPath = null;
int levelNum = 1;
Step step = Step.EVEN;
Direction rffDir = Direction.UP;
int rng = 0;
for (int i=0; i < args.length; i++) {
String s = args[i];
if (arguments.contains(s.toLowerCase())) {
switch (s.toLowerCase()) {
case helpLong:
case helpShort:
case helpQuestion:
help();
continue;
case twsLong:
testTWS = true;
continue;
case levelLong:
case levelShort:
String levelString = args[++i];
try {
levelNum = Integer.parseInt(levelString);
continue;
}
catch (NumberFormatException e) {
numberError(levelLong+"/"+levelShort, s +" "+ levelString);
}
continue;
case stepLong:
case stepShort:
String stepString = args[++i];
try {
step = Step.valueOf(stepString.toUpperCase());
continue;
}
catch (IllegalArgumentException e) {
enumError(Arrays.toString(Step.values()), stepLong+"/"+stepShort, s +" "+ stepString);
}
continue;
case rffLong:
case rffShort:
String rffString = args[++i];
try {
rffDir = Direction.valueOf(rffString.toUpperCase());
continue;
}
catch (IllegalArgumentException e) {
enumError(Arrays.toString(Direction.CARDINALS), rffLong+"/"+rffShort, s +" "+ rffString);
}
continue;
case rulesLong:
case rulesShort:
String rulesString = args[++i];
try {
rules = Ruleset.valueOf(rulesString.toUpperCase());
continue;
}
catch (IllegalArgumentException e) {
enumError(Arrays.toString(Ruleset.PLAYABLES), rulesLong+"/"+rulesShort, s +" "+ rulesString);
}
continue;
case rngLong:
case rngShort:
String rngString = args[++i];
try {
rng = Integer.parseInt(rngString);
continue;
}
catch (NumberFormatException e) {
numberError(rngLong+"/"+rngShort, s +" "+ rngString);
}
}
}
Path p = Paths.get(s);
if (p.toString().toLowerCase().endsWith(".dat") || p.toString().toLowerCase().endsWith(".ccl")) {
levelsetPath = p;
continue;
}
if (p.toString().toLowerCase().endsWith(".tws")) {
twsPath = p;
continue;
}
}
if (levelsetPath != null) {
emulator.openLevelset(levelsetPath.toFile());
emulator.loadLevel(levelNum, rng, step, false, rules, rffDir);
if (twsPath != null) {
emulator.setTWSFile(twsPath.toFile());
if (testTWS)
emulator.testTWS();
}
}
}
}
private static void enumError(String values, String flag, String arg) throws IllegalArgumentException {
System.err.println("The " + flag + " flag MUST be followed by one of the following: " +
values);
throw new IllegalArgumentException(arg);
}
private static void numberError(String flag, String arg) throws IllegalArgumentException {
System.err.println("The " + flag + " flag MUST be followed by an integer number");
throw new IllegalArgumentException(arg);
}
private static void help() {
//exclude CURRENT and the non cardinal directions
System.out.println(
"usage: SuperCC.jar [-h] [LEVELSET [-lr N] [-s STEP] [-f DIR] [-m RULE] [TWS [--testtws]]]\n"+
"-h Display this help and exit.\n"+
"-l Load level number N.\n" +
"-r Load level with starting RNG seed N.\n" +
"-s Load level with a step parity of STEP.\n" +
"-f Load level with an initial random force floor direction of DIR.\n" +
"-m Load level with a ruleset of RULE.\n" +
"LEVELSET Open the levelset given by this path.\n" +
"TWS Set the TWS file to the one given by this path.\n" +
"--testtws Perform a unit test on the given TWS file with the given levelset.\n\n" +
"STEP must be one of: " + Arrays.toString(Step.values()) + ".\n" +
"DIR must be one of: " + Arrays.toString(Direction.CARDINALS) + ".\n" +
"RULE must be one of: " + Arrays.toString(Ruleset.PLAYABLES) + ".\n\n" +
"Each flag has an alternate form of: [-h/--help/-?], [-l/--level], [-r/--rng],\n" +
"[-s/--step], [-f/--rff], [-m/--rules].");
System.exit(0);
}
private ArgumentParser(){} //static class only, hide the default constructor
}
| 7,414 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
TickFlags.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/emulator/TickFlags.java | package emulator;
public enum TickFlags {
GAME_PLAY(true, true, true),
REPLAY(true, false, false),
LIGHT(false, false, true),
PRELOADING(false, true, true);
public final boolean repaint;
public final boolean save;
public final boolean multiTick;
TickFlags(boolean repaint, boolean save, boolean multiTick) {
this.repaint = repaint;
this.save = save;
this.multiTick = multiTick;
}
}
| 463 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
TWSWriter.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/io/TWSWriter.java | package io;
import emulator.SavestateManager;
import emulator.Solution;
import emulator.SuperCC;
import game.Direction;
import game.Level;
import game.Position;
import game.Ruleset;
import util.CharList;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.ListIterator;
import java.util.Set;
public class TWSWriter{
public static byte[] write(Level level, Solution solution, SavestateManager savestates) {
//Goes over the level and transforms all mouse moves into a form TW can handle
CharList mouseMoves = new CharList();
if (level.supportsClick()) {
savestates.addSavestate(-1); //shouldn't be possible for a user to save a savestate to this key
savestates.restart();
ListIterator<Character> itr = savestates.getMoveList().listIterator(false);
while (itr.hasNext()) {
char c = itr.next();
if (SuperCC.isClick(c)) { //Use to math out the relative click position for TWS writing with mouse moves
Position screenPosition = Position.screenPosition(level.getChip().getPosition());
Position clickedPosition = Position.clickPosition(screenPosition, c);
int relativeClickX = clickedPosition.getX() - level.getChip().getPosition().getX(); //down and to the right of Chip are positive, this just quickly gets the relative position following that
int relativeClickY = clickedPosition.getY() - level.getChip().getPosition().getY();
mouseMoves.add(relativeClickX);
mouseMoves.add(relativeClickY);
}
savestates.replay();
}
savestates.load(-1, level);
}
try(TWSOutputStream writer = new TWSOutputStream()) {
final int ticksPerMove = level.getRuleset().ticksPerMove;
writer.writeTWSHeader(level, solution);
writer.writeInt(writer.solutionLength(solution));
writer.writeLevelHeader(level, solution);
int timeBetween = 0;
boolean firstMove = true;
int i = 0;
for (char c : solution.basicMoves) {
if (c == SuperCC.WAIT) {
if (ticksPerMove == 2)
timeBetween += 2;
else
timeBetween += 1;
}
else {
int relativeClickX;
int relativeClickY;
int twsRelativeClick = 0;
if (SuperCC.isClick(c) && level.supportsClick()) {
relativeClickX = mouseMoves.get(i++);
relativeClickY = mouseMoves.get(i++);
twsRelativeClick = 16 + ((relativeClickY + 9) * 19) + (relativeClickX + 9);
}
writer.writeMove(c, timeBetween, firstMove, twsRelativeClick);
if (ticksPerMove == 2)
timeBetween = 2;
else
timeBetween = 1;
firstMove = false;
}
}
return writer.toByteArray();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static class TWSOutputStream extends ByteArrayOutputStream{
private final byte NORTH = 0, WEST = 1, SOUTH = 2, EAST = 3,
NORTHWEST = -3, SOUTHWEST = -6, NORTHEAST = -9, SOUTHEAST = -12,
MOUSE = -1;
private final Set<Byte> CARDINALS = Set.of(NORTH, WEST, SOUTH, EAST);
//all cardinal directions (u, l, d, r) use format 2 on this page http://www.muppetlabs.com/~breadbox/software/tworld/tworldff.html#3
void writeMove(char c, int time, boolean firstMove, int relativeClick) throws IOException {
if (!firstMove)
time -= 1;
byte twsMoveByte = switch (c) {
case SuperCC.UP -> NORTH;
case SuperCC.LEFT -> WEST;
case SuperCC.DOWN -> SOUTH;
case SuperCC.RIGHT -> EAST;
case SuperCC.UP_LEFT -> NORTHWEST;
case SuperCC.DOWN_LEFT -> SOUTHWEST;
case SuperCC.UP_RIGHT -> NORTHEAST;
case SuperCC.DOWN_RIGHT -> SOUTHEAST;
default -> MOUSE;
};
if (CARDINALS.contains(twsMoveByte))
writeFormat2(twsMoveByte, time);
else {
if (twsMoveByte == MOUSE) { //mouse moves
writeFormat4(relativeClick, time);
}
else
writeFormat4(-twsMoveByte, time);
/* for some reason format 4 doesn't use the move type mentioned in the docs, it uses the moves as they
appear in TW's source, which overlap with the ones given in the docs, so we resolve that by assigning
them negative values and then inverting it here */
}
}
void writeTWSHeader(Level level, Solution solution) throws IOException {
writeInt(0x999B3335); // Signature
if (level.getRuleset() == Ruleset.MS) write(2);
else write(1); //Lynx Ruleset
writeShort(level.getLevelNumber());
write(5);
writeInt(Arrays.hashCode(solution.basicMoves)); //sig
write(0); //in case of further extensions
}
void writeLevelHeader(Level level, Solution solution) throws IOException {
writeShort(level.getLevelNumber());
byte[] password = level.getPassword().getBytes("Windows-1252");
for (int i = 0; i < 4; i++)
write(password[i]);
write(0x83); // Other flags
write(solution.step.toTWS() | solution.initialSlide.turn(Direction.LEFT).toTWS()); //Compensation for TW's turning of the RFF on load
writeInt(solution.rngSeed);
if (level.getRuleset().ticksPerMove == 2)
writeInt(2 * solution.basicMoves.length - 2);
/* minus 2 because the time value is always 2 extra for unknown reasons
(likely tick counting differences between TW and SuCC).
there's actually an issue here in that if Chip slides into the exit in MS Mode
SuCC writes a time value one higher than it should be,
this however can't be helped without introducing potential side effects */
else if (level.getRuleset().ticksPerMove == 4)
writeInt(solution.basicMoves.length);
}
private static final int LEVEL_HEADER_SIZE = 16;
void writeShort(int i) throws IOException{
write(i);
write(i >> 8);
}
void writeInt(int i) throws IOException{
write(i);
write(i >> 8);
write(i >> 16);
write(i >> 24);
}
public int solutionLength(Solution s) {
int length = LEVEL_HEADER_SIZE;
for (char c : s.basicMoves) {
if (c != SuperCC.WAIT)
length += 4;
}
return length;
}
void writeFormat2(byte twsMoveByte, int time) throws IOException {
write(twsMoveByte << 2 | 0b11 | (time & 0b111) << 5);
write((time >> 3) & 0xFF);
write((time >> 11) & 0xFF);
write(((time >> 19) & 0b00001111) | 011 << 01104);
}
void writeFormat4(int direction, int time) throws IOException {
// First byte DDD1NN11
//int numBytes = measureTime(time);
write(0b11011 | (direction & 0b111) << 5); //(2 << 2), the first 2 used to be the result of measureTime however as all bytes have to be 4 long its forced to being 2 now
// Second byte TTDDDDDD
write(((time & 0b11) << 6) | ((direction & 0b11_1111_000) >> 3));
// Third byte TTTTTTTT
//if (numBytes > 0) {
write((time & 0b1111_1111_00) >> 2);
//}
// Fourth byte TTTTTTTT
//if (numBytes > 1) {
write((time & 0b1111_1111_0000_0000_00) >> 10);
//}
// Fifth byte 000TTTTT
// if (numBytes > 2) {
// write((time & 0b1_1111_0000_0000_0000_0000_00) >> 18);
// }
}
// int measureTime(int time) {
// if ((time & 0b11) == time) {
// return 0;
// }
// else if ((time & 0b11_1111_1111) == time) {
// return 1;
// }
// else if ((time & 0b11_1111_1111_1111_1111) == time) {
// return 2;
// }
// else {
// return 3;
// }
// }
}
}
| 8,984 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
TWSReader.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/io/TWSReader.java | package io;
import emulator.Solution;
import game.Direction;
import game.Level;
import game.Ruleset;
import game.Step;
import java.io.*;
import java.util.Set;
import static emulator.SuperCC.*;
public class TWSReader{
private int headerLength;
private Ruleset ruleset;
private final File twsFile;
public void verifyAndInit() throws IOException {
twsInputStream reader = new twsInputStream(twsFile);
try{
if (reader.readInt() != -1717882059)
throw new IOException("Invalid signature");
if (reader.readByte() == 2)
ruleset = Ruleset.MS;
else
ruleset = Ruleset.LYNX;
reader.skip(2);
int len = reader.readByte();
headerLength = 8 + len;
reader.skip(len);
reader.close();
}
catch (IOException e){
reader.close();
throw e;
}
}
public Solution readSolution(Level level) throws IOException{
verifyAndInit();
twsInputStream reader = new twsInputStream(twsFile);
reader.skip(headerLength);
long offset = headerLength;
int recordLength = 0;
while (offset < twsFile.length()){
recordLength = reader.readInt();
int levelNumber = reader.readShort();
int twsPassword = reader.readInt();
byte[] levelPass = level.getPassword().getBytes("Windows-1252");
long pass = Integer.toUnsignedLong(levelPass[0] + (levelPass[1] << 8) + (levelPass[2] << 16) + (levelPass[3] << 24));
if (levelNumber == level.getLevelNumber() && twsPassword == pass)
break;
offset += recordLength + 4; //4: length of recordLength
reader.skip(recordLength - 6); //6: bytes read since recordLength
}
if (offset >= twsFile.length())
throw new IOException("Level not found in tws");
if (recordLength == 6)
throw new IOException("No solution recorded"); //If the offset is equal to 6 it means that the only thing the TWS file stores for that level is its level number, and its password
reader.bytesRead = 6; //cancel out earlier readings and add len of level number and pass
reader.readByte(); //Other Flags
int stepSlideValue = reader.readByte();
Step step = Step.fromTWS(stepSlideValue);
Direction initialSlide = Direction.fromTWS(stepSlideValue);
int rngSeed = reader.readInt();
int solutionTime = reader.readInt();
reader.counter = 0;
CharArrayWriter writer = new CharArrayWriter();
while (reader.bytesRead < recordLength){
int b = reader.readByte();
try {
switch (b & 0b11) {
case 0:
reader.readFormat3(b, writer);
break;
case 1:
case 2:
reader.readFormat1(b, writer);
break;
case 3:
if ((b & 0b10000) == 0) reader.readFormat2(b, writer);
else reader.readFormat4(b, writer);
break;
}
}
catch (Exception e){ // Some solution files are too long - seems to be caused by long slides at the end of a level
e.printStackTrace();
//System.out.println("TWS file too long on level: "+level.getLevelNumber()+" "+Arrays.toString(level.getTitle()));
break;
}
}
for (int i = writer.size() + reader.solutionLengthOffset; i <= solutionTime; i++)
writer.write('~');
Solution s = new Solution(writer.toCharArray(), rngSeed, step, Solution.QUARTER_MOVES, ruleset, initialSlide);
s.efficiency = 1 - (double) reader.ineffiencies / solutionTime;
s.melindaRouterGenerated = reader.melindaRouter;
return s;
}
public TWSReader (File twsFile) throws IOException{
this.twsFile = twsFile;
verifyAndInit();
}
private static class twsInputStream extends FileInputStream{
private final char[] DIRECTIONS = new char[] {UP, LEFT, DOWN, RIGHT, UP_LEFT, DOWN_LEFT, UP_RIGHT, DOWN_RIGHT};
private final Set<Character> cardinalSet = Set.of(UP, LEFT, DOWN, RIGHT);
public int solutionLengthOffset = 0;
public int ineffiencies = 0;
public int numCardinals = 0; //These are used for MR detection, counting if 3 ortho moves are in a row with 3 tick between
public int num3TickTime = 0;
public boolean melindaRouter = false;
public int bytesRead = 0;
public int counter;
public void readFormat1(int b, Writer writer) throws IOException{
int length = b & 0b11;
counter += length;
int time;
char direction = DIRECTIONS[(b & 0b11100) >>> 2];
if (length == 1){
time = (b & 0b11100000) >>> 5;
}
else{
time = ((b & 0b11100000) >>> 5 | readByte() << 3);
if (time < 8)
ineffiencies++;
}
for (int i = 0; i < time; i++)
writer.write('~');
writer.write(direction);
if (cardinalSet.contains(direction) && time == 3) {
numCardinals++;
num3TickTime++;
}
else {
numCardinals = 0;
num3TickTime = 0;
}
if (numCardinals == 3 && num3TickTime == 3)
melindaRouter = true;
}
public void readFormat2(int b, Writer writer) throws IOException{
counter += 4;
char direction = DIRECTIONS[(b & 0b1100) >>> 2];
int time = ((b & 0b11100000) >> 5) | readByte() << 3 | readByte() << 11 | (readByte() & 0xf) << 19;
if (time < 2047)
ineffiencies++;
for (int i = 0; i < time; i++) writer.write('~');
writer.write(direction);
}
public void readFormat3(int b, Writer writer) throws IOException{
counter += 1;
char[] waits = new char[] {'~', '~', '~'};
writer.write(waits);
writer.write(DIRECTIONS[(b >>> 2) & 0b11]);
writer.write(waits);
writer.write(DIRECTIONS[(b >>> 4) & 0b11]);
writer.write(waits);
writer.write(DIRECTIONS[(b >>> 6) & 0b11]);
}
public void readFormat4(int b, Writer writer) throws IOException { //format 4 DOES NOT use the format given in the docs
final int NORTH = 1, WEST = 2, SOUTH = 4, EAST = 8,
NORTHWEST = NORTH | WEST, SOUTHWEST = SOUTH | WEST, SOUTHEAST = SOUTH | EAST,
NORTHEAST = NORTH | EAST;
int length = ((b >>> 2) & 0b11) + 2;
counter += length;
int b2 = readByte();
int d = (b >>> 5) | ((b2 & 0b00111111) << 3);
int time = (b2 & 0b11000000) >> 6;
for (int i = 0; i < length - 2; i++)
time |= ((readByte() & (i == 2 ? 0x1f : 0xff)) << (2 + 8*i));
for (int i = 0; i < time; i++)
writer.write('~');
if (length >= 4) {
if (length == 4 && time < 0x400) //2^10
ineffiencies++;
else if (time < 0x40000) //len 5 and 2^18
ineffiencies++;
}
char direction = switch (d) {
case NORTH -> UP;
case WEST -> LEFT;
case SOUTH -> DOWN;
case EAST -> RIGHT;
case NORTHWEST -> UP_LEFT;
case SOUTHWEST -> DOWN_LEFT;
case SOUTHEAST -> DOWN_RIGHT;
case NORTHEAST -> UP_RIGHT;
default -> Character.MAX_VALUE; //mouse moves
};
if (direction != Character.MAX_VALUE)
writer.write(direction);
else { //mouse moves
d -= 16;
int x9 = d % 19;
int y9 = (d - x9) / 19;
writer.write(CHIP_RELATIVE_CLICK);
writer.write(x9);
writer.write(y9);
solutionLengthOffset -= 2;
}
}
public twsInputStream (File file) throws FileNotFoundException{
super(file);
}
int readByte() throws IOException{
bytesRead++;
return read();
}
int readShort() throws IOException{
bytesRead += 2;
return read() + (read() << 8);
}
int readInt() throws IOException{
bytesRead += 4;
return read() + (read() << 8) + (read() << 16) + (read() << 24);
}
byte[] readAscii(int length) throws IOException{
bytesRead += length;
byte[] asciiBytes = new byte[length];
read(asciiBytes);
return asciiBytes;
}
byte[] readEncodedAscii(int length) throws IOException{
bytesRead += length;
byte[] asciiBytes = new byte[length];
read(asciiBytes);
for (int i = 0; i < length; i++) asciiBytes[i] = (byte) ((int) asciiBytes[i] ^ 0x99b);
return asciiBytes;
}
}
}
| 9,505 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
DatParser.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/io/DatParser.java | package io;
import game.Direction;
import game.Level;
import game.Ruleset;
import game.Step;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* A class for reading the .dat format.
* For documentation on the dat format itself please read http://www.seasip.info/ccfile.html
*/
public class DatParser{
private final static int MSCC_SIGNATURE = 0x0002AAAC;
private final static int MSCC_PG_SIGNATURE = 0x0003AAAC;
private final static int TWORLD_LYNX_SIGNATURE = 0x0102AAAC;
private final static Set<Integer> SIGNATURES = Set.of(MSCC_SIGNATURE, MSCC_PG_SIGNATURE, TWORLD_LYNX_SIGNATURE);
private final File file;
private long[] levelStart;
private Ruleset rules;
public int lastLevel() {
return levelStart.length;
}
public String getLevelsetName() {
return file.getName().replaceFirst("[.][^.]+$", "");
}
public String getLevelsetPath() {
return file.getPath();
}
public Ruleset getRuleset() {
return rules;
}
/**
* Reads either layer 1 or layer 2 of the .dat file. Only call this if the
* FileInputStream stream is pointing at the layer data, so that the next
* word is the "Number of bytes in X layer".
*
* @return A 1028 element byte array containing the layer, row by row.
*/
private byte[] readLayer(DatReader reader) throws IOException{
byte[] layer = new byte[32*32];
int bytesInLayer = reader.readWord();
int i = 0;
while (i < 1024){
int b = reader.readUnsignedByte();
if (b == 0xFF){
int copies = reader.readUnsignedByte();
int objectCode = reader.read();
for (int k = 0; k < copies; k++){
layer[i] = (byte) objectCode;
i++;
}
}
else{
layer[i] = (byte) b;
i++;
}
}
return layer;
}
/**
* Reads a set of button connections from the .dat file. Only call this if
* the FileInputStream stream is pointing at the connection data, so that
* the next word is the "Button X position".
*
* @param length Length of this field
* @param trapConnections if true, handles trap connections; else, handles
* clone machine connections
* @return an nx2 array where each row is {buttonPosition, targetPosition},
* where a position is 32*y+x
*/
private int[][] readConnections(DatReader reader, int length, boolean trapConnections) throws IOException{
int[][] connections = new int[length][2];
for (int j = 0; j < length; j++){
int buttonX = reader.readWord();
int buttonY = reader.readWord();
int targetX = reader.readWord();
int targetY = reader.readWord();
connections[j][0] = 32*buttonY+buttonX;
connections[j][1] = 32*targetY+targetX;
if (trapConnections) reader.readWord();
}
return connections;
}
/**
* Load a level from the .dat file.
* @param level The level number
* @param rngSeed The starting rng seed
* @param step The starting step of the level. Either Step.ODD or Step.EVEN
* @param rules The ruleset to use, a value of CURRENT means to keep the currently selected ruleset (defaulting to file signature)
* @return a Level object
*/
public Level parseLevel(int level, int rngSeed, Step step, Ruleset rules, Direction initialSlide) throws IOException{
DatReader reader = new DatReader(file);
if (rules != Ruleset.CURRENT)
this.rules = rules;
try {
reader.skip(levelStart[level]);
final int levelNumber = reader.readWord();
int timeLimit = reader.readWord();
int chips = reader.readWord();
final int mapDetail = reader.readWord();
final byte[] layerFG = readLayer(reader);
final byte[] layerBG = readLayer(reader);
String title = null;
int[][] trapConnections = new int[][] {};
int[][] cloneConnections = new int[][] {};
String password = null;
String hint = null;
String author = null;
int[][] monsterPositions = null;
int optionalFieldsLength = reader.readWord();
while (optionalFieldsLength > 0) {
final int fieldType = reader.readUnsignedByte();
optionalFieldsLength--;
final int fieldLength = reader.readUnsignedByte();
optionalFieldsLength--;
switch (fieldType) {
case 1:
timeLimit = reader.readWord();
break;
case 2:
chips = reader.readWord();
break;
case 3:
title = reader.readText(fieldLength);
break;
case 4:
trapConnections = readConnections(reader, fieldLength / 10, true);
break;
case 5:
cloneConnections = readConnections(reader, fieldLength / 8, false);
break;
case 6:
password = reader.readEncodedText(fieldLength);
break;
case 7:
hint = reader.readText(fieldLength);
break;
case 8:
password = reader.readText(fieldLength);
break;
case 9:
author = reader.readText(fieldLength);
break;
case 10:
int numMonsters = fieldLength / 2;
monsterPositions = new int[numMonsters][2];
for (int j = 0; j < numMonsters; j++) {
monsterPositions[j][0] = reader.readUnsignedByte();
monsterPositions[j][1] = reader.readUnsignedByte();
}
break;
}
optionalFieldsLength -= fieldLength;
}
reader.close();
return LevelFactory.makeLevel(levelNumber, timeLimit, chips, layerFG, layerBG, title, trapConnections,
cloneConnections, password, hint, author, monsterPositions, rngSeed, step, lastLevel(), this.rules, initialSlide);
}
catch (IOException e){
reader.close();
throw(e);
}
}
/**
* DatParser constructor. The .dat file is skimmed in order to create an
* array of pointers to each individual level. No levels get loaded in
* this constructor.
* @param file The .dat file
*/
public DatParser(File file) throws IOException {
this.file = file;
DatReader reader = new DatReader(file);
try {
int signature = reader.readInt32();
if (!SIGNATURES.contains(signature)) {
throw new IOException("Invalid signature");
}
if (signature == MSCC_SIGNATURE || signature == MSCC_PG_SIGNATURE)
rules = Ruleset.MS;
else
rules = Ruleset.LYNX;
final int levels = reader.readWord();
long byteN = 4+2;
levelStart = new long[levels+1]; // +1 because we skip level #0
for (int i = 1; i <= levels; i++) {
long bytesInLevel = reader.readWord();
byteN += 2;
levelStart[i] = byteN;
byteN += bytesInLevel;
reader.skip(bytesInLevel);
}
reader.close();
}
catch (IOException e){
reader.close();
throw e;
}
}
private static class DatReader extends FileInputStream{
private int readUnsignedByte() throws IOException{
return read() & 0xFF;
}
private int readWord() throws IOException{
return readUnsignedByte() + 256*readUnsignedByte();
}
private int readInt32() throws IOException{
return readUnsignedByte() + 256*readUnsignedByte() + 65536*readUnsignedByte() + 16777216*readUnsignedByte();
}
private String readText(int length) throws IOException{
byte[] textBytes = new byte[length-1];
read(textBytes, 0, length-1);
read(); // trailing '\0'
return new String(textBytes, "Windows-1252");
}
private String readEncodedText(int length) throws IOException{
byte[] textBytes = new byte[length-1];
read(textBytes, 0, length-1);
read(); // trailing '\0'
for (int i = 0; i < length - 1; i++)
textBytes[i] = (byte) (textBytes[i] ^ 0x99);
return new String(textBytes, "Windows-1252");
}
DatReader (File datFile) throws IOException{
super(datFile);
}
}
}
| 9,450 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
SuccPaths.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/io/SuccPaths.java | package io;
import java.awt.event.KeyEvent;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SuccPaths {
private final File settingsFile;
private Map<String, String> settingsMap;
private void updateSettingsFile() {
try (PrintWriter writer = new PrintWriter(settingsFile, StandardCharsets.UTF_8)) {
writer.println("[Paths]");
writer.printf("%s = %s\n", "Levelset", settingsMap.get("Paths:Levelset"));
writer.printf("%s = %s\n", "TWS", settingsMap.get("Paths:TWS"));
writer.printf("%s = %s\n\n", "succ", settingsMap.get("Paths:succ"));
writer.println("[Controls]");
writer.printf("%s = %s\n", "Up", settingsMap.get("Controls:Up"));
writer.printf("%s = %s\n", "Left", settingsMap.get("Controls:Left"));
writer.printf("%s = %s\n", "Down", settingsMap.get("Controls:Down"));
writer.printf("%s = %s\n", "Right", settingsMap.get("Controls:Right"));
writer.printf("%s = %s\n", "HalfWait", settingsMap.get("Controls:HalfWait"));
writer.printf("%s = %s\n", "FullWait", settingsMap.get("Controls:FullWait"));
writer.printf("%s = %s\n", "UpLeft", settingsMap.get("Controls:UpLeft"));
writer.printf("%s = %s\n", "DownLeft", settingsMap.get("Controls:DownLeft"));
writer.printf("%s = %s\n", "DownRight", settingsMap.get("Controls:DownRight"));
writer.printf("%s = %s\n", "UpRight", settingsMap.get("Controls:UpRight"));
writer.printf("%s = %s\n", "AutoDiagonals", settingsMap.get("Controls:AutoDiagonals"));
writer.printf("%s = %s\n", "Rewind", settingsMap.get("Controls:Rewind"));
writer.printf("%s = %s\n\n", "Play", settingsMap.get("Controls:Play"));
writer.println("[Graphics]");
writer.printf("%s = %s\n", "TilesheetNum", settingsMap.get("Graphics:TilesheetNum"));
writer.printf("%s = %s\n", "LynxTilesheetNum", settingsMap.get("Graphics:LynxTilesheetNum"));
writer.printf("%s = %s\n", "TileWidth", settingsMap.get("Graphics:TileWidth"));
writer.printf("%s = %s\n", "TileHeight", settingsMap.get("Graphics:TileHeight"));
writer.printf("%s = %s", "TWSNotate", settingsMap.get("Graphics:TWSNotate"));
}
catch (IOException e) {
e.printStackTrace();
}
}
public String getLevelsetFolderPath() {
String levelsetFolder = settingsMap.get("Paths:Levelset");
if (levelsetFolder != null) return levelsetFolder;
else {
setLevelsetFolderPath("");
return "";
}
}
public String getTWSPath() {
String tws = settingsMap.get("Paths:TWS");
if (tws != null) return tws;
else {
setTWSPath("");
return "";
}
}
public String getSuccPath() {
String succ = settingsMap.get("Paths:succ");
if (succ != null) return succ;
else {
setSuccPath("succsave");
return "";
}
}
public static class Controls {
public static String[] keyNames = new String[] {"Controls:Up", "Controls:Left", "Controls:Down", "Controls:Right",
"Controls:UpLeft", "Controls:DownLeft", "Controls:DownRight", "Controls:UpRight",
"Controls:HalfWait", "Controls:FullWait", "Controls:Rewind", "Controls:Play"};
public int[] keys = new int[] {KeyEvent.VK_UP, KeyEvent.VK_LEFT, KeyEvent.VK_DOWN, KeyEvent.VK_RIGHT,
KeyEvent.VK_U, KeyEvent.VK_J, KeyEvent.VK_K, KeyEvent.VK_I, KeyEvent.VK_SPACE, KeyEvent.VK_ESCAPE,
KeyEvent.VK_BACK_SPACE, KeyEvent.VK_ENTER};
public boolean autoDiagonals = false;
}
public Controls getControls() {
Controls controls = new Controls();
boolean error = false;
for (int i=0; i < controls.keyNames.length; i++) {
try {
controls.keys[i] = Integer.parseInt(settingsMap.get(controls.keyNames[i]));
}
catch (NumberFormatException e) {
error = true;
}
}
controls.autoDiagonals = Boolean.parseBoolean(settingsMap.get("Controls:AutoDiagonals"));
if (error)
setControls(controls);
return controls;
}
public int getMSTilesetNum() {
try {
return Integer.parseInt(settingsMap.get("Graphics:TilesheetNum"));
}
catch (NumberFormatException e) {
setMSTilesetNum(0);
return 0;
}
}
public int getLynxTilesetNum() {
try {
return Integer.parseInt(settingsMap.get("Graphics:LynxTilesheetNum"));
}
catch (NumberFormatException e) {
setLynxTilesetNum(0);
return 0;
}
}
public int[] getTileSizes() {
try {
return new int[]{Integer.parseInt(settingsMap.get("Graphics:TileWidth")),
Integer.parseInt(settingsMap.get("Graphics:TileHeight"))};
}
catch (NumberFormatException e) {
int[] tileSizes = new int[] {20, 20};
setTileSizes(tileSizes);
return tileSizes;
}
}
public boolean getTWSNotation() {
if (settingsMap.get("Graphics:TWSNotate") != null) return Boolean.parseBoolean(settingsMap.get("Graphics:TWSNotate"));
else {
setTWSNotation(false);
return false;
}
}
public String getJSONPath(String levelsetName, int levelNumber, String levelName, String ruleset) {
String json = getSuccPath();
new File(Paths.get(json, levelsetName).toString()).mkdirs();
return Paths.get(json, levelsetName, levelNumber +"_"+levelName+"-"+ruleset+".json").toString();
}
public String getSccPath(String levelsetName, int levelNumber, String levelName) {
return Paths.get(getSuccPath(), levelsetName, Integer.toString(levelNumber), levelName+".scc").toString();
}
public void setLevelsetFolderPath(String levelsetFolderPath) {
settingsMap.put("Paths:Levelset", levelsetFolderPath);
updateSettingsFile();
}
public void setTWSPath(String twsPath) {
settingsMap.put("Paths:TWS", twsPath);
updateSettingsFile();
}
public void setSuccPath(String succPath) {
settingsMap.put("Paths:succ", succPath);
updateSettingsFile();
}
public void setControls(Controls controls) {
for(int i = 0;i < controls.keyNames.length;i++) {
settingsMap.put(controls.keyNames[i], String.valueOf(controls.keys[i]));
}
settingsMap.put("Controls:AutoDiagonals", String.valueOf(controls.autoDiagonals));
updateSettingsFile();
}
public void setMSTilesetNum(int tilesetNum) {
settingsMap.put("Graphics:TilesheetNum", String.valueOf(tilesetNum));
updateSettingsFile();
}
public void setLynxTilesetNum(int tilesetNum) {
settingsMap.put("Graphics:LynxTilesheetNum", String.valueOf(tilesetNum));
updateSettingsFile();
}
public void setTileSizes(int[] tileSizes) {
settingsMap.put("Graphics:TileWidth", String.valueOf(tileSizes[0]));
settingsMap.put("Graphics:TileHeight", String.valueOf(tileSizes[1]));
updateSettingsFile();
}
public void setTWSNotation(boolean twsNotation) {
settingsMap.put("Graphics:TWSNotate", String.valueOf(twsNotation));
updateSettingsFile();
}
public SuccPaths(File settingsFile) throws IOException {
this.settingsFile = settingsFile;
settingsMap = new HashMap<>();
parseSettings(settingsMap, new BufferedReader(new FileReader(settingsFile)));
}
private static void parseSettings(Map<String, String> settingsMap, Reader source)
throws IOException
{
BufferedReader reader = new BufferedReader(source);
String
section = "",
line = null;
Pattern headerPattern = null;
while ((line = reader.readLine()) != null)
{
line = line.trim();
if (line.isEmpty() || line.charAt(0) == ';')
{
continue;
}
else if (line.charAt(0) == '[')
{
if (headerPattern == null)
headerPattern = Pattern.compile("\\[\\W*(\\w*)\\W*\\]?");
Matcher matcher = headerPattern.matcher(line);
if (matcher.find()) section = matcher.group(1);
}
else
{
int pivot = line.indexOf('=');
if (pivot > 0)
{
String name = line.substring(0, pivot - 1).trim(),
value = line.substring(pivot + 1).trim();
if (!name.isEmpty())
settingsMap.put(section + ':' + name, value);
/*`[View]
Zoom = 1.0000`
would get put into the map as:
["View:Zoom": "1.0000"]
*/
}
}
}
}
public static void createSettingsFile() {
try {
FileWriter fw = new FileWriter("settings.ini");
fw.write("[Paths]\n" +
"Levelset = \n" +
"TWS = \n" +
"succ = succsave\n" +
"\n" +
"[Controls]\n" +
"Up = 38\n" +
"Left = 37\n" +
"Down = 40\n" +
"Right = 39\n" +
"HalfWait = 32\n" +
"FullWait = 27\n" +
"Rewind = 8\n" +
"Play = 10\n" +
"\n" +
"[Graphics]\n" +
"TilesheetNum = 0\n" +
"TileWidth = 20\n" +
"TileHeight = 20");
fw.close();
}
catch(Exception g) {
g.printStackTrace();
}
}
}
| 10,440 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
LevelFactory.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/io/LevelFactory.java | package io;
import game.*;
import game.Lynx.LynxCreature;
import game.Lynx.LynxCreatureList;
import game.Lynx.LynxLevel;
import game.MS.*;
import game.button.BlueButton;
import game.button.BrownButton;
import game.button.GreenButton;
import game.button.RedButton;
import util.MultiHashMap;
import java.util.*;
/**
* A class for turning creating a Level object using only the data from the
* .dat file.
*/
public class LevelFactory {
// Various helper functions for processing parts of the .dat file.
private static Position[] getToggleDoors(Layer layerFG, Layer layerBG){
List<Position> toggleDoors = new ArrayList<>();
for (short i = 0; i < 32*32; i++){
Tile tileFG = layerFG.get(i);
if (tileFG == Tile.TOGGLE_CLOSED || tileFG == Tile.TOGGLE_OPEN){
toggleDoors.add(new Position(i));
}
Tile tileBG = layerBG.get(i);
if ((tileBG == Tile.TOGGLE_CLOSED || tileBG == Tile.TOGGLE_OPEN) && tileFG.isMonster()){
toggleDoors.add(new Position(i));
}
}
return toggleDoors.toArray(new Position[0]);
}
private static Position[] getTeleports(Layer layerFG, Layer layerBG){
int l = 0;
for (int i = 0; i < 32*32; i++){
if (layerFG.get(i) == Tile.TELEPORT || (layerFG.get(i).isMonster() && layerBG.get(i) == Tile.TELEPORT)) l++;
}
Position[] teleports = new Position[l];
l = 0;
for (short i = 0; i < 32*32; i++){
if (layerFG.get(i) == Tile.TELEPORT || (layerFG.get(i).isMonster() && layerBG.get(i) == Tile.TELEPORT)){
teleports[l++] = new Position(i);
}
}
return teleports;
}
private static MSCreatureList getMSMonsterList(int[][] monsterPositions, Layer layerFG, Layer layerBG){ //Probably not the best solution for this, but it does work
if (monsterPositions == null) return new MSCreatureList(new MSCreature[] {}, layerFG, layerBG);
int l = 0;
for (int i = 0; i < monsterPositions.length; i++){
int x = monsterPositions[i][0];
int y = monsterPositions[i][1];
int position = 32*y+x;
if (layerFG.get(position).isMonster() && (layerBG.get(position) != Tile.CLONE_MACHINE)) {
l++;
}
}
MSCreature[] monsterList = new MSCreature[l];
l = 0;
for (int[] monsterPosition : monsterPositions) {
int x = monsterPosition[0];
int y = monsterPosition[1];
Position position = new Position(x, y);
if (!position.isValid())
continue;
if (layerFG.get(position).isMonster() && (layerBG.get(position) != Tile.CLONE_MACHINE)) {
monsterList[l++] = new MSCreature(position, layerFG.get(position));
}
}
return new MSCreatureList(monsterList, layerFG, layerBG);
}
private static LynxCreatureList getLynxMonsterList(Layer layerFG, Layer layerBG){ //Probably not the best solution for this, but it does work
List<LynxCreature> creatures = new ArrayList<>();
int numChips = 0;
int index = 0;
for (Tile tile : layerFG) {
if (tile.isCreature() || tile == Tile.BLOCK || (tile.isChip() && numChips == 0) || tile.isSwimmingChip()) {
creatures.add(new LynxCreature(new Position(index), tile));
if (tile.isChip())
numChips++;
layerFG.set(index, layerBG.get(index)); //Lynx doesn't have a lower layer, so every creature's tile needs to be popped
layerBG.set(index, Tile.FLOOR);
}
index++;
}
if (numChips == 0)
creatures.add(new LynxCreature(new Position(0, 0), Tile.CHIP_DOWN));
//the idea is that instead of making levels invalid we instead "legalize" them
for (int i=0; i < creatures.size(); i++) {
LynxCreature c = creatures.get(i);
if (c.getCreatureType() == CreatureID.CHIP) {
Collections.swap(creatures, 0, i);
break;
}
}
for (int i = 0; i < 1024; i++) {
Tile tileFG = layerBG.get(i);
if (tileFG.isChip() || tileFG.isCreature() || tileFG == Tile.BLOCK)
layerFG.set(i, Tile.FLOOR); //clear out illegal tiles
}
return new LynxCreatureList(creatures.toArray(new LynxCreature[0]));
}
private static MSCreature findMSPlayer(Layer layerFG){
for (int i = 32*32-1; i >= 0; i--){
Tile tile = layerFG.get(i);
if (Tile.CHIP_UP.ordinal() <= tile.ordinal()) return new MSCreature(new Position(i), tile);
}
return new MSCreature(new Position(0), Tile.CHIP_DOWN);
}
private static int getTimer(int timeLimit, int startingDecimalTimesTen){
if (timeLimit == 0) return -2;
return (timeLimit*100 + startingDecimalTimesTen);
}
private static int getSliplistCapacity(Layer layerFG, Layer layerBG){
int counter = 0;
for (Tile t : layerBG) if (t.isSliding()) counter++;
for (Tile t : layerFG) if (t.isSliding()) counter++;
return counter;
}
private static MultiHashMap<Position, GreenButton> getGreenButtons(Layer layerFG, Layer layerBG) {
MultiHashMap<Position, GreenButton> buttons = new MultiHashMap<>();
for (short i = 0; i < 32*32; i++){
if (layerFG.get(i) == Tile.BUTTON_GREEN || layerBG.get(i) == Tile.BUTTON_GREEN){
Position p = new Position(i);
buttons.put(p, new GreenButton(p));
}
}
return buttons;
}
private static MultiHashMap<Position, BlueButton> getBlueButtons(Layer layerFG, Layer layerBG) {
MultiHashMap<Position, BlueButton> buttons = new MultiHashMap<>();
for (short i = 0; i < 32*32; i++){
if (layerFG.get(i) == Tile.BUTTON_BLUE || layerBG.get(i) == Tile.BUTTON_BLUE){
Position p = new Position(i);
buttons.put(p, new BlueButton(p));
}
}
return buttons;
}
private static MultiHashMap<Position, BrownButton> getBrownButtons(int[][] trapConnections) {
MultiHashMap<Position, BrownButton> buttons = new MultiHashMap<>(trapConnections.length);
for (int[] trapConnection : trapConnections) {
Position buttonPos = new Position(trapConnection[0]);
buttons.put(buttonPos, new BrownButton(buttonPos, new Position(trapConnection[1])));
}
return buttons;
}
private static MultiHashMap<Position, RedButton> getRedButtons(int[][] cloneConnections) {
MultiHashMap<Position, RedButton> buttons = new MultiHashMap<>(cloneConnections.length);
for (int[] cloneConnection : cloneConnections) {
Position buttonPos = new Position(cloneConnection[0]);
buttons.put(buttonPos, new RedButton(buttonPos, new Position(cloneConnection[1])));
}
return buttons;
}
/**
* Convert the raw data of the .dat file into a level
* @param levelNumber The level number
* @param timeLimit The time limit of the level - this does not include the
* decimal.
* @param chips The number of chips to collect in the level before the
* socket opens
* @param byteLayerFG The foreground layer, as a 32*32 byte[] in C order
* @param byteLayerBG The background layer, as a 32*32 byte[] in C order
* @param title The level title, as a byte[] representing ASCII characters
* @param trapConnections Trap connections, such that trapConnections[i][0]
* is a button connected to trapConnections[i][1]
* @param cloneConnections Clone machine connections, such that
* cloneConnections[i][0] is a button connected to
* cloneConnections[i][1]
* @param password The level password, as a byte[] representing ASCII
* characters, not encoded
* @param hint The level hint, as a byte[] representing ASCII characters
* @param monsterPositions The x and y coordinates of all monsters that
* will be in the initial monster list. Buried
* monsters and monsters on clone machines may
* be included. They will be ignored.
* @param lastLevel The last level number in the set.
* @param rngSeed The starting RNG seed to use.
* @param step The starting step to use.
* @param rules The ruleset to use.
* @return A Level
*/
static Level makeLevel(int levelNumber, int timeLimit, int chips, byte[] byteLayerFG, byte[] byteLayerBG,
String title, int[][] trapConnections, int[][] cloneConnections, String password,
String hint, String author, int[][] monsterPositions, int rngSeed, Step step,
int lastLevel, Ruleset rules, Direction initialSlide) {
Layer layerBG = new ByteLayer(byteLayerBG);
Layer layerFG = new ByteLayer(byteLayerFG);
if (rules == Ruleset.MS) {
return new MSLevel(
levelNumber,
title,
password,
hint,
author,
getToggleDoors(layerFG, layerBG),
getTeleports(layerFG, layerBG),
getGreenButtons(layerFG, layerBG),
getRedButtons(cloneConnections),
getBrownButtons(trapConnections),
getBlueButtons(layerFG, layerBG),
new BitSet(trapConnections.length),
layerBG,
layerFG,
getMSMonsterList(monsterPositions, layerFG, layerBG),
new SlipList(),
findMSPlayer(layerFG),
getTimer(timeLimit, 90),
chips,
new RNG(rngSeed, 0, 0),
rngSeed,
step,
lastLevel
);
}
else {
LynxCreatureList creatures;
creatures = getLynxMonsterList(layerFG, layerBG);
return new LynxLevel(
levelNumber,
title,
password,
hint,
author,
getToggleDoors(layerFG, layerBG),
getTeleports(layerFG, layerBG),
getGreenButtons(layerFG, layerBG),
getRedButtons(cloneConnections),
getBrownButtons(trapConnections),
getBlueButtons(layerFG, layerBG),
layerFG,
creatures,
creatures.get(0),
getTimer(timeLimit, 95),
chips,
new RNG(rngSeed, 0, 0),
rngSeed,
step,
lastLevel,
initialSlide
);
}
}
} | 11,187 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
GifSequenceWriter.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/tools/GifSequenceWriter.java | //
// GifSequenceWriter.java
//
// Created by Elliot Kroo on 2009-04-25.
//
// This work is licensed under the Creative Commons Attribution 3.0 Unported
// License. To view a copy of this license, visit
// http://creativecommons.org/licenses/by/3.0/ or send a letter to Creative
// Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA.
package tools;
import javax.imageio.*;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.metadata.IIOMetadataNode;
import javax.imageio.stream.FileImageOutputStream;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
public class GifSequenceWriter {
protected ImageWriter gifWriter;
protected ImageWriteParam imageWriteParam;
protected IIOMetadata imageMetaData;
/**
* Creates a new GifSequenceWriter
*
* @param outputStream the ImageOutputStream to be written to
* @param imageType one of the imageTypes specified in BufferedImage
* @param timeBetweenFramesMS the time between frames in miliseconds
* @param loopContinuously wether the gif should loop repeatedly
* @throws IIOException if no gif ImageWriters are found
*
* @author Elliot Kroo (elliot[at]kroo[dot]net)
*/
public GifSequenceWriter(
ImageOutputStream outputStream,
int imageType,
int timeBetweenFramesMS,
boolean loopContinuously) throws IIOException, IOException {
// my method to create a writer
gifWriter = getWriter();
imageWriteParam = gifWriter.getDefaultWriteParam();
ImageTypeSpecifier imageTypeSpecifier =
ImageTypeSpecifier.createFromBufferedImageType(imageType);
imageMetaData =
gifWriter.getDefaultImageMetadata(imageTypeSpecifier,
imageWriteParam);
String metaFormatName = imageMetaData.getNativeMetadataFormatName();
IIOMetadataNode root = (IIOMetadataNode)
imageMetaData.getAsTree(metaFormatName);
IIOMetadataNode graphicsControlExtensionNode = getNode(
root,
"GraphicControlExtension");
graphicsControlExtensionNode.setAttribute("disposalMethod", "none");
graphicsControlExtensionNode.setAttribute("userInputFlag", "FALSE");
graphicsControlExtensionNode.setAttribute(
"transparentColorFlag",
"FALSE");
graphicsControlExtensionNode.setAttribute(
"delayTime",
Integer.toString(timeBetweenFramesMS / 10));
graphicsControlExtensionNode.setAttribute(
"transparentColorIndex",
"0");
IIOMetadataNode commentsNode = getNode(root, "CommentExtensions");
commentsNode.setAttribute("CommentExtension", "Created by MAH");
IIOMetadataNode appEntensionsNode = getNode(
root,
"ApplicationExtensions");
IIOMetadataNode child = new IIOMetadataNode("ApplicationExtension");
child.setAttribute("applicationID", "NETSCAPE");
child.setAttribute("authenticationCode", "2.0");
int loop = loopContinuously ? 0 : 1;
child.setUserObject(new byte[]{ 0x1, (byte) (loop & 0xFF), (byte)
((loop >> 8) & 0xFF)});
appEntensionsNode.appendChild(child);
imageMetaData.setFromTree(metaFormatName, root);
gifWriter.setOutput(outputStream);
gifWriter.prepareWriteSequence(null);
}
public void writeToSequence(RenderedImage img) throws IOException {
gifWriter.writeToSequence(
new IIOImage(
img,
null,
imageMetaData),
imageWriteParam);
}
/**
* Close this GifSequenceWriter object. This does not close the underlying
* stream, just finishes off the GIF.
*/
public void close() throws IOException {
gifWriter.endWriteSequence();
}
/**
* Returns the first available GIF ImageWriter using
* ImageIO.getImageWritersBySuffix("gif").
*
* @return a GIF ImageWriter object
* @throws IIOException if no GIF image writers are returned
*/
private static ImageWriter getWriter() throws IIOException {
Iterator<ImageWriter> iter = ImageIO.getImageWritersBySuffix("gif");
if(!iter.hasNext()) {
throw new IIOException("No GIF Image Writers Exist");
} else {
return iter.next();
}
}
/**
* Returns an existing child node, or creates and returns a new child node (if
* the requested node does not exist).
*
* @param rootNode the <tt>IIOMetadataNode</tt> to search for the child node.
* @param nodeName the name of the child node.
*
* @return the child node, if found or a new node created with the given name.
*/
private static IIOMetadataNode getNode(
IIOMetadataNode rootNode,
String nodeName) {
int nNodes = rootNode.getLength();
for (int i = 0; i < nNodes; i++) {
if (rootNode.item(i).getNodeName().compareToIgnoreCase(nodeName)
== 0) {
return((IIOMetadataNode) rootNode.item(i));
}
}
IIOMetadataNode node = new IIOMetadataNode(nodeName);
rootNode.appendChild(node);
return(node);
}
/*
public GifSequenceWriter(
BufferedOutputStream outputStream,
int imageType,
int timeBetweenFramesMS,
boolean loopContinuously) {
*/
public static void main(String[] args) throws Exception {
if (args.length > 1) {
// grab the output image type from the first image in the sequence
BufferedImage firstImage = ImageIO.read(new File(args[0]));
// create a new BufferedOutputStream with the last argument
ImageOutputStream output =
new FileImageOutputStream(new File(args[args.length - 1]));
// create a gif sequence with the type of the first image, 1 second
// between frames, which loops continuously
GifSequenceWriter writer =
new GifSequenceWriter(output, firstImage.getType(), 1, false);
// write out the first image to our sequence...
writer.writeToSequence(firstImage);
for(int i=1; i<args.length-1; i++) {
BufferedImage nextImage = ImageIO.read(new File(args[i]));
writer.writeToSequence(nextImage);
}
writer.close();
output.close();
} else {
System.out.println(
"Usage: java GifSequenceWriter [list of gif files] [output file]");
}
}
} | 7,026 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
VariationResult.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/tools/VariationResult.java | package tools;
import emulator.Solution;
import emulator.SuperCC;
import emulator.TickFlags;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.util.ArrayList;
public class VariationResult {
private JPanel mainPanel;
private JLabel labelVariations;
private JScrollPane scroll;
private JPanel solutionsPanel;
private JLabel labelSolutions;
private JButton buttonFastest;
VariationResult(SuperCC emulator, long count, ArrayList<Solution> solutions, int bestSolutionIndex) {
labelVariations.setText("Variations tested: " + String.format("%,d", count));
labelSolutions.setText("Solutions found: " + String.format("%,d", solutions.size()));
solutionsPanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
GridBagConstraints labelC = new GridBagConstraints();
labelC.anchor = GridBagConstraints.EAST;
for(int i = 0; i < solutions.size(); i++) {
int index = i;
JPanel container = new JPanel();
container.setLayout(new GridBagLayout());
JLabel labelNumber = new JLabel();
labelNumber.setText(Integer.toString(i + 1));
labelNumber.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 12));
labelNumber.setHorizontalAlignment(SwingConstants.RIGHT);
labelNumber.setPreferredSize(new Dimension(30, 25));
JButton loadButton = new JButton();
loadButton.setText("Load");
loadButton.addActionListener(e -> {
solutions.get(index).load(emulator);
});
JButton copyButton = new JButton();
copyButton.setText("Copy");
copyButton.addActionListener(e -> {
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(solutions.get(index).toString()), null);
});
c.gridy = i;
container.add(labelNumber, labelC);
container.add(loadButton);
container.add(copyButton);
solutionsPanel.add(container, c);
}
buttonFastest.addActionListener(e -> {
solutions.get(bestSolutionIndex).load(emulator);
});
JFrame frame = new JFrame("Variation Results");
frame.setContentPane(mainPanel);
frame.pack();
frame.setVisible(true);
}
}
| 2,518 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
ChooseTileSize.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/tools/ChooseTileSize.java | package tools;
import emulator.SuperCC;
import graphics.Gui;
import graphics.SmallGamePanel;
import graphics.TileSheet;
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowEvent;
import java.io.IOException;
public class ChooseTileSize {
private JPanel panel1;
private JSpinner heightSpinner;
private JSpinner widthSpinner;
private JButton okButton;
public ChooseTileSize(SuperCC emulator, int defaultValue, int min, int max){
short[] keys = emulator.getLevel().getKeys();
SpinnerModel sm = new SpinnerNumberModel(defaultValue, min, max, 1);
heightSpinner.setModel(sm);
sm = new SpinnerNumberModel(defaultValue, min, max, 1);
widthSpinner.setModel(sm);
JFrame frame = new JFrame("Choose Dimensions");
frame.setContentPane(panel1);
frame.pack();
frame.setLocationRelativeTo(emulator.getMainWindow());
frame.setVisible(true);
okButton.addActionListener((e) -> {
try {
TileSheet ts;
try {
ts = emulator.getMainWindow().getGamePanel().getTileSheet();
}
catch (NullPointerException npe) {
ts = Gui.DEFAULT_TILESHEET;
}
int width = ((Number) widthSpinner.getValue()).intValue();
int height = ((Number) heightSpinner.getValue()).intValue();
Gui window = emulator.getMainWindow();
SmallGamePanel gamePanel = (SmallGamePanel) window.getGamePanel();
window.getGamePanel().initialise(emulator, ts.getTileSheets(width, height), ts, width, height);
window.getInventoryPanel().initialise(emulator);
window.getInventoryPanel().repaint();
window.setSize(200+width*gamePanel.getWindowSizeX(), 200+height*gamePanel.getWindowSizeY());
window.getGamePanel().setPreferredSize(new Dimension(width * gamePanel.getWindowSizeX(), height * gamePanel.getWindowSizeY()));
window.getGamePanel().setSize(width*gamePanel.getWindowSizeX(), height*gamePanel.getWindowSizeY());
window.pack();
window.repaint(true);
emulator.getPaths().setTileSizes(new int[]{width, height});
}
catch (IOException e1) {
emulator.throwError(e1.getMessage());
}
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
});
}
}
| 2,543 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
VerifyTWS.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/tools/VerifyTWS.java | package tools;
import emulator.Solution;
import emulator.SuperCC;
import javax.swing.*;
import javax.swing.border.BevelBorder;
import java.util.ArrayList;
public class VerifyTWS {
private JPanel mainPanel;
private JList list1;
private JList list2;
private JTable table1;
public VerifyTWS(SuperCC emulator) {
int lastLevel = emulator.lastLevelNumber();
ArrayList<String> titles = new ArrayList<>(lastLevel);
ArrayList<String> results = new ArrayList<>(lastLevel);
for (int i = 1; i < lastLevel; i++) {
emulator.loadLevel(i);
titles.add(i + " " + emulator.getLevel().getTitle());
try {
Solution s = emulator.twsReader.readSolution(emulator.getLevel());
if (s.melindaRouterGenerated)
results.add("Melinda Router");
else
results.add(s.efficiency > 0.9 ? "Tile World" : "SuCC");
}
catch (Exception e) {
results.add("Could not read tws");
}
}
list1.setListData(titles.toArray());
list2.setListData(results.toArray());
list1.setBorder(new BevelBorder(BevelBorder.LOWERED));
list2.setBorder(new BevelBorder(BevelBorder.LOWERED));
JFrame frame = new JFrame("Verification");
frame.setContentPane(mainPanel);
frame.pack();
frame.setLocationRelativeTo(emulator.getMainWindow());
frame.setVisible(true);
}
private void createUIComponents() {
list1 = new JList(new String[] {});
list2 = new JList(new String[] {});
}
}
| 1,679 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
VariationTesting.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/tools/VariationTesting.java | package tools;
import emulator.SuperCC;
import tools.variation.*;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;
public class VariationTesting {
private JTextPane codeEditor;
private JTextPane codeOutput;
private JPanel mainPanel;
private JPanel menuPanel;
private JButton runButton;
private JPanel editorPanel;
private JPanel consolePanel;
private JProgressBar progressBar;
private JLabel solutionsFoundLabel;
private JTextPane console;
private JLayeredPane editorArea;
private JScrollPane editor;
private JScrollPane output;
private ArrayList<JLabel> lineNumbers = new ArrayList<>();
private Interpreter interpreter;
public boolean killFlag = false;
public static boolean running = false;
private static final HashMap<TokenType, Color> colors;
public boolean hasGui = true;
static {
colors = new HashMap<>();
colors.put(TokenType.COMMENT, new Color(0, 204, 0));
colors.put(TokenType.NUMBER, new Color(255, 153, 255));
colors.put(TokenType.IDENTIFIER, new Color(68, 221, 255));
colors.put(TokenType.MOVE, new Color(221, 51, 221));
colors.put(TokenType.FUNCTION, new Color(221, 170, 0));
colors.put(TokenType.TILE, new Color(221, 221, 0));
colors.put(TokenType.START, new Color(68, 221, 255));
colors.put(TokenType.BEFORE_MOVE, new Color(68, 221, 255));
colors.put(TokenType.AFTER_MOVE, new Color(68, 221, 255));
colors.put(TokenType.BEFORE_STEP, new Color(68, 221, 255));
colors.put(TokenType.AFTER_STEP, new Color(68, 221, 255));
colors.put(TokenType.END, new Color(68, 221, 255));
colors.put(TokenType.IF, new Color(0, 153, 255));
colors.put(TokenType.ELSE, new Color(0, 153, 255));
colors.put(TokenType.FOR, new Color(0, 153, 255));
colors.put(TokenType.TRUE, new Color(0, 153, 255));
colors.put(TokenType.FALSE, new Color(0, 153, 255));
colors.put(TokenType.NULL, new Color(0, 153, 255));
colors.put(TokenType.VAR, new Color(0, 153, 255));
colors.put(TokenType.PRINT, new Color(0, 153, 255));
colors.put(TokenType.BREAK, new Color(0, 153, 255));
colors.put(TokenType.AND, new Color(0, 153, 255));
colors.put(TokenType.OR, new Color(0, 153, 255));
colors.put(TokenType.NOT, new Color(0, 153, 255));
colors.put(TokenType.RETURN, new Color(0, 153, 255));
colors.put(TokenType.CONTINUE, new Color(0, 153, 255));
colors.put(TokenType.TERMINATE, new Color(0, 153, 255));
colors.put(TokenType.LEXICOGRAPHIC, new Color(0, 153, 255));
colors.put(TokenType.ALL, new Color(0, 153, 255));
colors.put(TokenType.OTHER, new Color(221, 0, 0));
}
private SuperCC emulator;
public VariationTesting(SuperCC emulator) {
this.emulator = emulator;
setGUI();
}
public VariationTesting(SuperCC emulator, boolean hasGui) {
this.emulator = emulator;
this.console = new JTextPane();
this.hasGui = hasGui;
if(hasGui) {
setGUI();
}
}
private void setGUI() {
setTextPanes();
setScrollPanes();
setAdjustmentListeners();
setEditorArea();
setEditorPanel();
setConsole();
setFrame();
highlight();
runButton.addActionListener(e -> {
if(running) {
killFlag = true;
return;
}
interpreter = new Interpreter(emulator, this, console, codeEditor.getText());
this.progressBar.setMaximum(Integer.MAX_VALUE);
new VariationTestingThread().start();
Timer timer = new Timer(true);
timer.scheduleAtFixedRate(new VariationTestingProgressTask(), 0, 100);
});
}
private void setTextPanes() {
codeEditor = new JTextPane();
codeEditor.setOpaque(false);
codeEditor.setSize(new Dimension(6000, 600));
codeEditor.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 16));
codeEditor.setForeground(new Color(0, 0, 0, 0));
codeEditor.setCaretColor(new Color(255, 255, 255));
codeEditor.getStyledDocument().addDocumentListener(new EditorDocumentListener());
codeEditor.setMargin(new Insets(0, 60, 0, 0));
codeOutput = new JTextPane();
codeOutput.setEditable(false);
codeOutput.setSize(new Dimension(6000, 600));
codeOutput.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 16));
codeOutput.setBackground(new Color(50, 50, 50));
codeOutput.setForeground(new Color(255, 255, 255));
codeOutput.setMargin(new Insets(0, 60, 0, 0));
console = new JTextPane();
console.setEditable(false);
console.setSize(new Dimension(6000, 200));
console.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 16));
console.setBackground(new Color(50, 50, 50));
}
private void setScrollPanes() {
JPanel outputNoWrapPanel = new JPanel(new BorderLayout());
outputNoWrapPanel.add(codeOutput);
output = new JScrollPane(outputNoWrapPanel);
output.setSize(new Dimension(600, 600));
JPanel editorNoWrapPanel = new JPanel(new BorderLayout());
editorNoWrapPanel.setOpaque(false);
editorNoWrapPanel.add(codeEditor);
editorNoWrapPanel.setSize(new Dimension(600, 600));
editor = new JScrollPane(editorNoWrapPanel);
editor.setOpaque(false);
editor.getViewport().setOpaque(false);
editor.setSize(new Dimension(600, 600));
}
private void setAdjustmentListeners() {
editor.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
output.getVerticalScrollBar().setValue(e.getValue());
updateLineNumbers();
}
});
editor.getHorizontalScrollBar().addAdjustmentListener(new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
output.getHorizontalScrollBar().setValue(e.getValue());
updateLineNumbers();
}
});
output.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
output.getVerticalScrollBar().setValue(editor.getVerticalScrollBar().getValue());
updateLineNumbers();
}
});
output.getHorizontalScrollBar().addAdjustmentListener(new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
output.getHorizontalScrollBar().setValue(editor.getHorizontalScrollBar().getValue());
updateLineNumbers();
}
});
}
private void setEditorArea() {
editorArea = new JLayeredPane();
editorArea.add(editor, Integer.valueOf(1));
editorArea.add(output, Integer.valueOf(1));
}
private void setEditorPanel() {
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
editorPanel.add(new JScrollPane(editorArea), gbc);
}
private void setConsole() {
JPanel noWrapPanel = new JPanel(new BorderLayout());
noWrapPanel.add(console);
consolePanel.setLayout(new BorderLayout());
consolePanel.add(new JScrollPane(noWrapPanel), BorderLayout.CENTER);
}
private void setFrame() {
JFrame frame = new JFrame("Variation testing");
frame.setContentPane(mainPanel);
frame.pack();
frame.setVisible(true);
frame.addWindowListener(new WindowListener() {
@Override public void windowClosing(WindowEvent windowEvent) { killFlag = true; }
//None of these are useful but the code requires them to be here so i shoved them all into one line
@Override public void windowOpened(WindowEvent windowEvent) {}@Override public void windowClosed(WindowEvent windowEvent) {}@Override public void windowIconified(WindowEvent windowEvent) {}@Override public void windowDeiconified(WindowEvent windowEvent) {}@Override public void windowActivated(WindowEvent windowEvent) { }@Override public void windowDeactivated(WindowEvent windowEvent) { }
});
frame.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
super.componentResized(e);
editor.setSize(new Dimension(editorArea.getWidth(), editorArea.getHeight()));
output.setSize(new Dimension(editorArea.getWidth(), editorArea.getHeight()));
}
});
}
private class EditorDocumentListener implements DocumentListener {
public void insertUpdate(DocumentEvent e) {
highlight();
}
public void removeUpdate(DocumentEvent e) {
highlight();
}
public void changedUpdate(DocumentEvent e) {
}
}
private void highlight() {
codeOutput.setText("");
StyledDocument doc = codeOutput.getStyledDocument();
Style style = codeOutput.addStyle("style", null);
Tokenizer tokenizer = new Tokenizer(codeEditor.getText());
ArrayList<Token> tokens = tokenizer.getAllTokens();
int lines = 1;
for(Token token : tokens) {
Color c = colors.get(token.type);
if(c == null) {
c = new Color(255, 255, 255);
}
StyleConstants.setForeground(style, c);
if(token.type == TokenType.NEW_LINE) {
lines++;
}
try {
doc.insertString(doc.getLength(), token.lexeme, style);
} catch(BadLocationException ex) {}
}
for(int i = 0; i < lines; i++) {
if(lineNumbers.size() <= i) {
JLabel lineNumber = new JLabel();
lineNumber.setText(Integer.toString(i + 1));
lineNumber.setBounds(0, 22 * i, 40, 24);
lineNumber.setForeground(new Color(153, 153, 153));
lineNumber.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 16));
lineNumber.setHorizontalAlignment(SwingConstants.RIGHT);
lineNumbers.add(lineNumber);
editorArea.add(lineNumber, Integer.valueOf(2));
}
else {
lineNumbers.get(i).setVisible(true);
}
}
for(int i = lines; i < lineNumbers.size(); i++) {
lineNumbers.get(i).setVisible(false);
}
}
private void updateLineNumbers() {
int offsetX = editor.getHorizontalScrollBar().getValue();
int offsetY = editor.getVerticalScrollBar().getValue();
for(int i = 0; i < lineNumbers.size(); i++) {
lineNumbers.get(i).setBounds(0 - offsetX, i * 22 - offsetY, 40, 24);
}
}
public JTextPane getConsole() {
return console;
}
public void clearConsole() {
console.setText("");
}
public static boolean isRunning() {
return running;
}
private class VariationTestingThread extends Thread {
public void run() {
running = true;
killFlag = false;
runButton.setText("Stop");
interpreter.interpret();
running = false;
killFlag = false;
runButton.setText("Run");
if(hasGui && interpreter.solutions.size() > 0) {
VariationResult result = new VariationResult(emulator, interpreter.variationCount, interpreter.solutions, interpreter.bestSolutionIndex);
}
}
}
private class VariationTestingProgressTask extends TimerTask {
public void run() {
solutionsFoundLabel.setText("Solutions found: " + interpreter.solutions.size());
double normalization = Integer.MAX_VALUE/interpreter.totalPermutationCount;
double permutationIndex = interpreter.getPermutationIndex() * normalization;
progressBar.setValue((int)permutationIndex);
double percentage = permutationIndex/Integer.MAX_VALUE * 100;
progressBar.setString(String.format("%.3f", percentage) + "%");
if(killFlag || !running) {
progressBar.setValue(0);
progressBar.setString("0.000%");
cancel();
}
}
}
}
| 13,113 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
TSPHelpWindow.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/tools/TSPHelpWindow.java | package tools;
import emulator.SuperCC;
import javax.swing.*;
public class TSPHelpWindow {
private JPanel mainPanel;
private JTextPane mainText;
public TSPHelpWindow(SuperCC emulator) {
JFrame frame = new JFrame("Help");
frame.setContentPane(mainPanel);
frame.pack();
frame.setLocationRelativeTo(emulator.getMainWindow());
frame.setVisible(true);
}
}
| 411 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
MonsterlistRearrangeGUI.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/tools/MonsterlistRearrangeGUI.java | package tools;
import emulator.SuperCC;
import game.Creature;
import game.Level;
import javax.swing.*;
import java.awt.event.*;
public class MonsterlistRearrangeGUI {
private JPanel mainPanel;
private JList<Creature> guiList;
private DefaultListModel<Creature> listModel = new DefaultListModel<>();
private JScrollPane scrollPane;
private JButton upButton;
private JButton downButton;
public MonsterlistRearrangeGUI(SuperCC emulator, boolean useSliplist) {
Creature[] list;
if (useSliplist)
list = emulator.getLevel().getSlipList().toArray(new Creature[0]);
else
list = emulator.getLevel().getMonsterList().getCreatures();
for (Creature c : list) {
if (c.getCreatureType().isChip())
continue;
listModel.addElement(c);
}
guiList.setModel(listModel);
guiList.setVisibleRowCount(-1);
JFrame frame = new JFrame("Change " + (useSliplist ? "Slip" : "Monster") + " List Positions");
frame.setContentPane(mainPanel);
frame.pack();
frame.setLocationRelativeTo(emulator.getMainWindow());
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
updateChanges(emulator, useSliplist);
}
});
upButton.addActionListener(e -> {
int index = guiList.getSelectedIndex();
Creature selected = guiList.getSelectedValue();
if (index > 0) {
listModel.remove(index);
listModel.add(index-1, selected);
guiList.setSelectedIndex(index-1);
}
});
downButton.addActionListener(e -> {
int index = guiList.getSelectedIndex();
Creature selected = guiList.getSelectedValue();
if (index < listModel.size()-1) {
listModel.remove(index);
listModel.add(index+1, selected);
guiList.setSelectedIndex(index+1);
}
});
}
private void updateChanges(SuperCC emulator, boolean useSliplist) {
Level level = emulator.getLevel();
if (!useSliplist) {
int chipIndex = level.getMonsterList().getIndexOfCreature(level.getChip());
if (level.chipInMonsterList())
listModel.add(chipIndex, level.getChip());
}
Creature[] list = new Creature[listModel.size()];
listModel.copyInto(list);
if (useSliplist)
level.getSlipList().setSliplist(list);
else
level.getMonsterList().setCreatures(list);
emulator.getMainWindow().repaint(false);
}
}
| 2,773 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
ChooseWindowSize.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/tools/ChooseWindowSize.java | package tools;
import emulator.SuperCC;
import graphics.Gui;
import graphics.SmallGamePanel;
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowEvent;
public class ChooseWindowSize {
private JPanel panel1;
private JButton okButton;
private JSpinner heightSpinner;
private JSpinner widthSpinner;
private static final int MIN_WINDOW_SIZE = 1, MAX_WINDOW_SIZE = 32;
public ChooseWindowSize(SuperCC emulator){
SmallGamePanel gamePanel = (SmallGamePanel) emulator.getMainWindow().getGamePanel();
SpinnerModel sm = new SpinnerNumberModel(gamePanel.getWindowSizeY(), MIN_WINDOW_SIZE, MAX_WINDOW_SIZE, 1);
heightSpinner.setModel(sm);
sm = new SpinnerNumberModel(gamePanel.getWindowSizeY(), MIN_WINDOW_SIZE, MAX_WINDOW_SIZE, 1);
widthSpinner.setModel(sm);
JFrame frame = new JFrame("Choose Dimensions");
frame.setContentPane(panel1);
frame.pack();
frame.setLocationRelativeTo(emulator.getMainWindow());
frame.setVisible(true);
okButton.addActionListener((e) -> {
int width = ((Number) widthSpinner.getValue()).intValue();
int height = ((Number) heightSpinner.getValue()).intValue();
gamePanel.setWindowSize(width, height);
int tileWidth = gamePanel.getTileWidth(), tileHeight = gamePanel.getTileHeight();
Gui window = emulator.getMainWindow();
window.setSize(200+tileWidth*width, 200+tileHeight*height);
window.getGamePanel().setPreferredSize(new Dimension(tileWidth*width, tileHeight*height));
window.getGamePanel().setSize(tileWidth*width, tileHeight*height);
window.pack();
window.repaint(true);
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
});
}
}
| 1,863 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
SeedSearch.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/tools/SeedSearch.java | package tools;
import emulator.Solution;
import emulator.SuperCC;
import emulator.TickFlags;
import game.Position;
import game.Ruleset;
import javax.swing.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.text.DecimalFormat;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
public class SeedSearch {
private JPanel panel1;
private JButton startStopButton;
private JLabel resultsLabel;
private JLabel exampleSeedLabel;
private JLabel startLabel;
private JTextField startField;
private JRadioButton untilExitRadioButton;
private JRadioButton untilPositionRadioButton;
private JLabel searchTypeLabel;
private JTextField positionField;
private JSlider threadSlider;
private JLabel threadLabel;
private JLabel rulesetWarningLabel;
private static final int UPDATE_VALUE_RATE = 1000;
private static final int UPDATE_GUI_RATE = UPDATE_VALUE_RATE * 2;
private final byte[] startingState;
private static boolean killFlag = false;
private static boolean running = false;
private static AtomicInteger numAlive = new AtomicInteger(0);
private DecimalFormat df;
private long[] threadCurrentSeed;
private AtomicLong globalAttempts = new AtomicLong(0);
private AtomicLong globalSuccesses = new AtomicLong(0);
private AtomicLong globalLastSuccess = new AtomicLong(-1);
private boolean ranAlready = false;
private boolean untilPosition = false;
private Position endPosition = new Position(0, 0);
public SeedSearch(SuperCC emulator, Solution solution) {
int maxNumThreads = Runtime.getRuntime().availableProcessors();
threadSlider.setMaximum(maxNumThreads);
threadSlider.setValue(maxNumThreads);
if (solution.ruleset != emulator.getLevel().getRuleset()) {
rulesetWarningLabel.setVisible(true);
rulesetWarningLabel.setText("The provided solution does not match the current ruleset, the ruleset HAS been changed");
}
emulator.loadLevel(emulator.getLevel().getLevelNumber(), 0, solution.step, false,
solution.ruleset, solution.initialSlide);
startingState = emulator.getLevel().save();
resultsLabel.setText("Successes: 0/0 (0%)");
df = new DecimalFormat("##.####");
startStopButton.addActionListener((e) -> {
int numThreads = threadSlider.getValue();
int start = Integer.parseInt(startField.getText());
long numSeeds = Integer.MAX_VALUE - start;
long seedPoolSize = (numSeeds + 1) / numThreads; //avoids overflow before reducing back in range
if (running) {
startStopButton.setText("Resume");
killFlag = true;
}
else {
if (!ranAlready) {
threadCurrentSeed = new long[numThreads];
ranAlready = true;
for (int i=0; i < numThreads; i++) {
threadCurrentSeed[i] = (start + seedPoolSize * i);
}
}
if (untilPosition) {
String positionString = positionField.getText().replaceAll("\\s+",""); //Remove whitespace
String[] positionStrings = positionString.split(",");
int[] positions = {Integer.parseInt(positionStrings[0]), Integer.parseInt(positionStrings[1])};
positions[0] = Integer.max(positions[0], 0);
positions[0] = Integer.min(positions[0], 31);
positions[1] = Integer.max(positions[1], 0);
positions[1] = Integer.min(positions[1], 31);
endPosition = new Position(positions[0], positions[1]);
}
searchTypeLabel.setVisible(false);
untilExitRadioButton.setVisible(false);
untilPositionRadioButton.setVisible(false);
positionField.setVisible(false);
startLabel.setVisible(false);
startField.setVisible(false);
threadLabel.setVisible(false);
threadSlider.setVisible(false);
rulesetWarningLabel.setVisible(false);
startStopButton.setText("Pause");
for (int i = 0; i < numThreads; i++) {
long end;
if (i != numThreads - 1) {
end = start + seedPoolSize * (i + 1) - 1;
}
else
end = Integer.MAX_VALUE;
SuperCC threadEmulator = new SuperCC(false);
threadEmulator.openLevelset(new File(emulator.getLevelsetPath()));
threadEmulator.loadLevel(emulator.getLevel().getLevelNumber(), solution.rngSeed, solution.step, false, solution.ruleset, solution.initialSlide);
new SeedSearchThread(i, end, threadEmulator, new Solution(solution)).start();
}
}
});
untilPositionRadioButton.addActionListener(e -> {
positionField.setEnabled(true);
untilPosition = true;
});
untilExitRadioButton.addActionListener(e -> {
positionField.setEnabled(false);
untilPosition = false;
});
JFrame frame = new JFrame("Seed Search");
frame.setContentPane(panel1);
frame.pack();
frame.setLocationRelativeTo(emulator.getMainWindow());
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
@Override public void windowClosing(WindowEvent windowEvent) { killFlag = true; }
});
}
private void createUIComponents() {
resultsLabel = new JLabel();
exampleSeedLabel = new JLabel("Example seed:");
}
private void updateValues(int attempsSinceUpdate, int successes, long exampleSuccess, long currentSeed) {
globalAttempts.addAndGet(attempsSinceUpdate);
globalSuccesses.addAndGet(successes);
if (exampleSuccess >= 0)
globalLastSuccess.set(exampleSuccess);
if (currentSeed % UPDATE_GUI_RATE == 0)
updateText();
}
private void updateText() {
long lastSuccessNA = globalLastSuccess.get();
long globalSuccessesNA = globalSuccesses.get();
long globalAttemptsNA = globalAttempts.get();
resultsLabel.setText("Successes: "+ globalSuccessesNA +"/"+globalAttemptsNA+" ("+df.format(100.0 * globalSuccessesNA / globalAttemptsNA)+"%)");
resultsLabel.repaint();
if (lastSuccessNA >= 0)
exampleSeedLabel.setText("Example seed: " + lastSuccessNA);
exampleSeedLabel.repaint();
}
private boolean verifySeed(long seed, Solution solution, SuperCC emulator) {
solution.rngSeed = (int) seed;
emulator.getLevel().load(startingState);
emulator.getLevel().getCheats().setRng((int) seed);
solution.loadMoves(emulator, TickFlags.LIGHT, false);
if (!untilPosition)
return emulator.getLevel().isCompleted();
else
return emulator.getLevel().getChip().getPosition().equals(endPosition) && !emulator.getLevel().getChip().isDead();
}
public static boolean isRunning() {
return running;
}
private class SeedSearchThread extends Thread {
int threadNum, attemptsSinceUpdate, successesSinceUpdate;
long currentSeed, endSeed, lastSuccess;
SuperCC emulator;
Solution solution;
public void run(){
running = true;
killFlag = false;
while (!killFlag && currentSeed <= endSeed) {
if (verifySeed(currentSeed, solution, emulator)) {
successesSinceUpdate++;
lastSuccess = currentSeed;
}
attemptsSinceUpdate++;
currentSeed++;
if (currentSeed % UPDATE_VALUE_RATE == 0) {
updateValues(attemptsSinceUpdate, successesSinceUpdate, lastSuccess, currentSeed);
attemptsSinceUpdate = 0;
successesSinceUpdate = 0;
}
}
updateValues(attemptsSinceUpdate, successesSinceUpdate, lastSuccess, currentSeed); //just have it update with the last result, in case a success is found before an update and it gets canceled
threadCurrentSeed[threadNum] = currentSeed;
if (numAlive.decrementAndGet() == 0) { //last one cleans up
updateText();
running = false;
killFlag = false;
}
}
SeedSearchThread(int threadNum, long endSeed, SuperCC emulator, Solution solution) {
this.threadNum = threadNum;
this.currentSeed = threadCurrentSeed[threadNum];
this.endSeed = endSeed;
this.lastSuccess = -1;
this.emulator = emulator;
this.solution = solution;
numAlive.incrementAndGet();
}
}
}
| 9,182 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
ControlGUI.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/tools/ControlGUI.java | package tools;
import emulator.EmulatorKeyListener;
import emulator.SuperCC;
import io.SuccPaths;
import javax.swing.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class ControlGUI {
private JPanel mainPanel;
private JPanel MovementPanel;
private JButton upButton;
private JButton downButton;
private JButton leftButton;
private JButton rightButton;
private JButton halfWaitButton;
private JButton fullWaitButton;
private JTabbedPane tabbedPane1;
private JButton rewindButton;
private JButton forwardButton;
private JPanel toolPanel;
private JButton upLeftButton;
private JButton downLeftButton;
private JButton downRightButton;
private JButton upRightButton;
private JCheckBox autoDiagonals;
private SuperCC emulator;
public ControlGUI(SuperCC emulator) {
this.emulator = emulator;
JButton[] buttons = new JButton[] {upButton, leftButton, downButton, rightButton, upLeftButton, downLeftButton,
downRightButton, upRightButton, halfWaitButton, fullWaitButton, rewindButton, forwardButton};
for (JButton button : buttons) {
KeyRemapButton krb = (KeyRemapButton) button;
krb.setText(KeyEvent.getKeyText(krb.key.getKeyCode()));
if (krb.key.getKeyCode() == KeyEvent.VK_ESCAPE) {
krb.setText("Disabled");
}
else {
krb.setText(KeyEvent.getKeyText(krb.key.getKeyCode()));
}
}
autoDiagonals.setSelected(emulator.getPaths().getControls().autoDiagonals);
updateDiagonalButtons();
JFrame frame = new JFrame("Controls");
frame.setContentPane(mainPanel);
frame.pack();
frame.setLocationRelativeTo(emulator.getMainWindow());
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
SuccPaths.Controls controls = new SuccPaths.Controls();
for (int i = 0; i < buttons.length; i++) {
controls.keys[i] = ((KeyRemapButton) buttons[i]).key.getKeyCode();
}
controls.autoDiagonals = autoDiagonals.isSelected();
emulator.getPaths().setControls(controls);
}
});
autoDiagonals.addChangeListener((e) -> {
updateDiagonalButtons();
});
}
private void updateDiagonalButtons() {
boolean diagonalsEnabled = !autoDiagonals.isSelected();
upRightButton.setEnabled(diagonalsEnabled);
upLeftButton.setEnabled(diagonalsEnabled);
downRightButton.setEnabled(diagonalsEnabled);
downLeftButton.setEnabled(diagonalsEnabled);
}
private void createUIComponents() {
upButton = new KeyRemapButton(EmulatorKeyListener.Key.UP);
leftButton = new KeyRemapButton(EmulatorKeyListener.Key.LEFT);
downButton = new KeyRemapButton(EmulatorKeyListener.Key.DOWN);
rightButton = new KeyRemapButton(EmulatorKeyListener.Key.RIGHT);
upLeftButton = new KeyRemapButton(EmulatorKeyListener.Key.UP_LEFT);
downLeftButton = new KeyRemapButton(EmulatorKeyListener.Key.DOWN_LEFT);
downRightButton = new KeyRemapButton(EmulatorKeyListener.Key.DOWN_RIGHT);
upRightButton = new KeyRemapButton(EmulatorKeyListener.Key.UP_RIGHT);
halfWaitButton = new KeyRemapButton(EmulatorKeyListener.Key.HALF_WAIT);
fullWaitButton = new KeyRemapButton(EmulatorKeyListener.Key.FULL_WAIT);
rewindButton = new KeyRemapButton(EmulatorKeyListener.Key.REWIND);
forwardButton = new KeyRemapButton(EmulatorKeyListener.Key.FORWARD);
}
private class KeyRemapButton extends JButton {
private EmulatorKeyListener.Key key;
KeyRemapButton(EmulatorKeyListener.Key key) {
this.key = key;
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
KeyRemapButton.super.setText("Disabled");
}
else {
KeyRemapButton.super.setText(KeyEvent.getKeyText(e.getKeyCode()));
}
emulator.getControls().setKeyCode(key, e.getKeyCode());
}
});
}
}
}
| 4,604 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
HelpWindow.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/tools/HelpWindow.java | package tools;
import emulator.SuperCC;
import javax.swing.*;
public class HelpWindow {
private JPanel mainPanel;
private JTextPane mainText;
public HelpWindow(SuperCC emulator) {
JFrame frame = new JFrame("Help/About");
frame.setContentPane(mainPanel);
frame.pack();
frame.setLocationRelativeTo(emulator.getMainWindow());
frame.setVisible(true);
}
}
| 411 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
GameGifRecorder.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/tools/GameGifRecorder.java | package tools;
import emulator.SavestateManager;
import emulator.SuperCC;
import graphics.Gui;
import javax.imageio.stream.FileImageOutputStream;
import javax.imageio.stream.ImageOutputStream;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;
public class GameGifRecorder {
private JRadioButton a5FpsRadioButton;
private JRadioButton a10FpsRadioButton;
private JButton okButton;
private JPanel mainPanel;
private JSpinner spinner;
private JProgressBar progressBar;
private static final int GIF_RECORDING_STATE = -1;
public GameGifRecorder(SuperCC emulator) {
ButtonGroup bg = new ButtonGroup();
bg.add(a5FpsRadioButton);
bg.add(a10FpsRadioButton);
a5FpsRadioButton.setSelected(true);
okButton.addActionListener((e) -> {
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws Exception {
try {
SavestateManager savestates = emulator.getSavestates();
int numTicks = (int) (((Number) spinner.getValue()).doubleValue() * (emulator.getLevel().ticksPerMove() * 5));
savestates.addSavestate(GIF_RECORDING_STATE);
emulator.showAction("Recording gif, please wait");
List<BufferedImage> images = savestates.play(emulator, numTicks);
int i = 1;
File outFile = new File("out.gif");
while (outFile.exists()) outFile = new File("out" + (i++) + ".gif");
ImageOutputStream output = new FileImageOutputStream(outFile);
int imageSkip = 1;
if (a5FpsRadioButton.isSelected()) imageSkip = 2;
int timePerFrame = 100 * imageSkip;
GifSequenceWriter writer = new GifSequenceWriter(output, images.get(0).getType(), timePerFrame, true);
progressBar.setMinimum(0);
progressBar.setMaximum(images.size());
for (i = 0; i < numTicks && i < images.size(); i += imageSkip) {
writer.writeToSequence(images.get(i));
progressBar.setValue(i);
progressBar.repaint();
}
writer.close();
output.close();
emulator.getSavestates().load(GIF_RECORDING_STATE, emulator.getLevel());
emulator.showAction("Recorded " + outFile.getName());
}
catch (IOException exc) {
exc.printStackTrace();
}
SwingUtilities.getWindowAncestor(mainPanel).dispose();
emulator.repaint(false);
return null;
}
};
worker.execute();
});
JFrame frame = new JFrame("Gif Recorder");
frame.setContentPane(mainPanel);
frame.pack();
frame.setLocationRelativeTo(emulator.getMainWindow());
frame.setVisible(true);
}
private void createUIComponents() {
SpinnerModel model = new SpinnerNumberModel(2.5, 0.2, Integer.MAX_VALUE, 0.1);
spinner = new JSpinner(model);
progressBar = new JProgressBar();
}
}
| 3,460 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
ChangeInventory.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/tools/ChangeInventory.java | package tools;
import emulator.SuperCC;
import javax.swing.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
public class ChangeInventory extends JPanel {
private JPanel mainPanel;
private JPanel boots2;
private JPanel keys;
private JTextField textBlue;
private JTextField textRed;
private JTextField textGreen;
private JTextField textYellow;
private JPanel boots;
private JPanel chips;
private JTextField textChips;
private JCheckBox checkFlippers;
private JCheckBox checkFire;
private JCheckBox checkIce;
private JCheckBox checkSuction;
private final JTextField[] allKeyTextFields = new JTextField[] {textBlue, textRed, textGreen, textYellow};
private final JCheckBox[] allBootCheckboxes = new JCheckBox[] {checkFlippers, checkFire, checkIce, checkSuction};
public static final int KEYS_MAX_VALUE = 2 * 32 * 32 - 1;
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setContentPane(new ChangeInventory().mainPanel);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
private ChangeInventory(){}
public void updateChanges(SuperCC emulator){
short[] keys = emulator.getLevel().getKeys();
for (int i = 0; i < allKeyTextFields.length; i++) keys[i] = (short) (KEYS_MAX_VALUE & Integer.parseInt(allKeyTextFields[i].getText()));
byte[] boots = emulator.getLevel().getBoots();
for (int i = 0; i < allBootCheckboxes.length; i++) {
if (!allBootCheckboxes[i].isSelected()) boots[i] = 0;
else boots[i] = 1;
}
emulator.getLevel().getCheats().setChipsLeft(Integer.parseInt(textChips.getText()));
emulator.getMainWindow().repaint(false);
}
public ChangeInventory(SuperCC emulator){
short[] keys = emulator.getLevel().getKeys();
for (int i = 0; i < allKeyTextFields.length; i++) allKeyTextFields[i].setText(String.valueOf(keys[i]));
byte[] boots = emulator.getLevel().getBoots();
for (int i = 0; i < allBootCheckboxes.length; i++) allBootCheckboxes[i].setSelected(boots[i] == 1);
textChips.setText(String.valueOf(emulator.getLevel().getChipsLeft()));
JFrame frame = new JFrame("Inventory");
frame.setContentPane(mainPanel);
frame.pack();
frame.setLocationRelativeTo(emulator.getMainWindow());
frame.setVisible(true);
frame.addWindowListener(new WindowListener() {
@Override
public void windowOpened(WindowEvent e) {}
@Override
public void windowClosing(WindowEvent e) {
updateChanges(emulator);
}
@Override
public void windowClosed(WindowEvent e) {}
@Override
public void windowIconified(WindowEvent e) {}
@Override
public void windowDeiconified(WindowEvent e) {}
@Override
public void windowActivated(WindowEvent e) {}
@Override
public void windowDeactivated(WindowEvent e) {}
});
}
}
| 3,246 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
TSPGUI.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/tools/TSPGUI.java | package tools;
import emulator.SuperCC;
import game.Position;
import game.Tile;
import tools.tsp.ActingWallParameters;
import tools.tsp.SimulatedAnnealingParameters;
import tools.tsp.TSPSolver;
import javax.swing.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class TSPGUI {
private JPanel mainPanel;
private JList<ListNode> nodesList;
private JList<ListNode> exitsList;
private JList<RestrictionNode> restrictionsList;
private JTextField nodesInput;
private JButton addNodeButton;
private JTextField exitsInput;
private JButton addExitButton;
private JTextField restrictionsInput;
private JButton addRestrictionButton;
private JTextField startTempInput;
private JTextField endTempInput;
private JTextField coolingInput;
private JButton quickButton;
private JButton normalButton;
private JButton longButton;
private JButton thoroughButton;
private JButton runButton;
private JTextField iterationsInput;
private JButton allChipsButton;
private JButton allExitsButton;
private JTextPane output;
private JButton removeNodeButton;
private JButton removeExitButton;
private JButton removeRestrictionButton;
private JCheckBox waterCheckBox;
private JCheckBox fireCheckBox;
private JCheckBox bombsCheckBox;
private JCheckBox thievesCheckBox;
private JCheckBox trapsCheckBox;
private DefaultListModel<ListNode> nodes = new DefaultListModel<>();
private DefaultListModel<ListNode> exitNodes = new DefaultListModel<>();
private DefaultListModel<RestrictionNode> restrictionNodes = new DefaultListModel<>();
private SuperCC emulator;
private boolean hasGui = true;
public boolean killFlag = false;
public static boolean running = false;
public TSPGUI(SuperCC emulator) {
this.emulator = emulator;
setup();
}
public TSPGUI(SuperCC emulator, boolean hasGui) {
this.emulator = emulator;
this.hasGui = hasGui;
setup();
}
public ArrayList<ListNode> getAllChips() {
addAllTilesToContainer(nodes, Tile.CHIP);
return listModelToArrayList(nodes);
}
public ArrayList<ListNode> getAllExits() {
addAllTilesToContainer(exitNodes, Tile.EXIT);
return listModelToArrayList(exitNodes);
}
private void setup() {
if (nodesList == null || exitsList == null || restrictionsList == null) {
nodesList = new JList<>(); //yes yes its overriden by the IntelliJ forms generator, but maven doesn't
exitsList = new JList<>(); //have that so this prevents errors from building it with maven
restrictionsList = new JList<>();
}
this.nodesList.setModel(nodes);
this.exitsList.setModel(exitNodes);
this.restrictionsList.setModel(restrictionNodes);
if(hasGui) {
JFrame frame = new JFrame("TSP Solver");
frame.setContentPane(mainPanel);
frame.pack();
frame.setVisible(true);
frame.addWindowListener(new WindowListener() {
@Override
public void windowClosing(WindowEvent windowEvent) {
killFlag = true;
}
//Unused, but part of interface
@Override
public void windowOpened(WindowEvent windowEvent) {
}
@Override
public void windowClosed(WindowEvent windowEvent) {
}
@Override
public void windowIconified(WindowEvent windowEvent) {
}
@Override
public void windowDeiconified(WindowEvent windowEvent) {
}
@Override
public void windowActivated(WindowEvent windowEvent) {
}
@Override
public void windowDeactivated(WindowEvent windowEvent) {
}
});
runButton.addActionListener(e -> {
if (running) {
killFlag = true;
return;
}
new TSPSolverThread(this).start();
});
addNodeButton.addActionListener(e -> {
try {
String[] coords = nodesInput.getText().split(" ");
if (coords.length != 2)
throw new Exception("Please enter two numbers between 0 and 31 separated by a space.");
int x = Integer.parseInt(coords[0]);
int y = Integer.parseInt(coords[1]);
if (x < 0 || x > 31 || y < 0 || y > 31)
throw new Exception("Numbers must be between 0 and 31 inclusive.");
ListNode node = new ListNode(x, y, emulator.getLevel().getLayerFG().get(new Position(x, y)));
if (checkDuplicate(nodes, node))
throw new Exception("No duplicates allowed");
nodes.addElement(node);
nodesInput.setText("");
} catch (Exception ex) {
emulator.throwError(ex.getMessage());
}
});
removeNodeButton.addActionListener(e -> {
int index = nodesList.getSelectedIndex();
if (index != -1) {
removeRelatedRestrictions(nodes.getElementAt(index));
nodes.remove(index);
}
});
allChipsButton.addActionListener(e -> {
nodes.clear();
restrictionNodes.clear();
addAllTilesToContainer(nodes, Tile.CHIP);
});
addExitButton.addActionListener(e -> {
try {
String[] coords = exitsInput.getText().split(" ");
if (coords.length != 2)
throw new Exception("Please enter two numbers between 0 and 31 separated by a space.");
int x = Integer.parseInt(coords[0]);
int y = Integer.parseInt(coords[1]);
if (x < 0 || x > 31 || y < 0 || y > 31)
throw new Exception("Numbers must be between 0 and 31 inclusive.");
ListNode node = new ListNode(x, y, emulator.getLevel().getLayerFG().get(new Position(x, y)));
if (checkDuplicate(exitNodes, node))
throw new Exception("No duplicates allowed.");
exitNodes.addElement(node);
exitsInput.setText("");
} catch (Exception ex) {
emulator.throwError(ex.getMessage());
}
});
removeExitButton.addActionListener(e -> {
int index = exitsList.getSelectedIndex();
if (index != -1) {
exitNodes.remove(index);
}
});
allExitsButton.addActionListener(e -> {
exitNodes.clear();
addAllTilesToContainer(exitNodes, Tile.EXIT);
});
addRestrictionButton.addActionListener(e -> {
try {
String[] coords = restrictionsInput.getText().split(" ");
if (coords.length != 4)
throw new Exception("Please enter four numbers between 0 and 31 separated by a space.");
int x1 = Integer.parseInt(coords[0]);
int y1 = Integer.parseInt(coords[1]);
int x2 = Integer.parseInt(coords[2]);
int y2 = Integer.parseInt(coords[3]);
if (x1 < 0 || x1 > 31 || y1 < 0 || y1 > 31 || x2 < 0 || x2 > 31 || y2 < 0 || y2 > 31)
throw new Exception("Numbers must be between 0 and 31 inclusive.");
if (x1 == x2 && y1 == y2)
throw new Exception("Both coordinates cannot be equal.");
ListNode n1 = new ListNode(x1, y1, emulator.getLevel().getLayerFG().get(new Position(x1, y1)));
ListNode n2 = new ListNode(x2, y2, emulator.getLevel().getLayerFG().get(new Position(x2, y2)));
if (!nodesExist(n1, n2))
throw new Exception("Coordinates must refer to nodes.");
RestrictionNode node = new RestrictionNode(n1, n2);
if (checkDuplicate(restrictionNodes, node))
throw new Exception("No duplicates allowed.");
restrictionNodes.addElement(node);
restrictionsInput.setText("");
} catch (Exception ex) {
emulator.throwError(ex.getMessage());
}
});
removeRestrictionButton.addActionListener(e -> {
int index = restrictionsList.getSelectedIndex();
if (index != -1) {
restrictionNodes.remove(index);
}
});
setParameters(100, 0.1, 0.995, 20000);
quickButton.addActionListener(e -> {
setParameters(100, 0.1, 0.98, 10000);
});
normalButton.addActionListener(e -> {
setParameters(100, 0.1, 0.995, 20000);
});
longButton.addActionListener(e -> {
setParameters(100, 0.05, 0.998, 50000);
});
thoroughButton.addActionListener(e -> {
setParameters(100, 0.05, 0.999, 100000);
});
}
}
private void removeRelatedRestrictions(ListNode node) {
for(int i = restrictionNodes.getSize() - 1; i >= 0; i--) {
RestrictionNode rn = restrictionNodes.getElementAt(i);
if(rn.before.equals(node) || rn.after.equals(node)) {
restrictionNodes.remove(i);
}
}
}
private boolean nodesExist(ListNode n1, ListNode n2) {
boolean n1Found = false;
boolean n2Found = false;
for(int i = 0; i < nodes.getSize(); i++) {
ListNode n = nodes.getElementAt(i);
if(n1.equals(n)) {
n1Found = true;
}
if(n2.equals(n)) {
n2Found = true;
}
}
return n1Found && n2Found;
}
private boolean checkDuplicate(ListModel list, Object node) {
for(int i = 0; i < list.getSize(); i++) {
Object n = list.getElementAt(i);
if(n.equals(node)) {
return true;
}
}
return false;
}
private void addAllTilesToContainer(DefaultListModel<ListNode> container, Tile tile) {
for(int i = 0; i < 1024; i++) {
Tile foregroundTile = emulator.getLevel().getLayerFG().get(i);
if(foregroundTile == tile) {
container.addElement(new ListNode(i, foregroundTile));
}
Tile backgroundTile = emulator.getLevel().getLayerBG().get(i);
if(backgroundTile == tile) {
container.addElement(new ListNode(i, backgroundTile));
}
}
}
private void setParameters(double startTemp, double endTemp, double cooling, int iterations) {
startTempInput.setText(startTemp + "");
endTempInput.setText(endTemp + "");
coolingInput.setText(cooling + "");
iterationsInput.setText(iterations + "");
}
private <T> ArrayList<T> listModelToArrayList(DefaultListModel<T> listModel) {
ArrayList<T> nodeList = new ArrayList<>();
for(int i = 0; i < listModel.getSize(); i++) {
nodeList.add(listModel.getElementAt(i));
}
return nodeList;
}
public static boolean isRunning() {
return running;
}
public static class ListNode {
public int index;
public Tile t;
public ListNode(int x, int y, Tile t) {
this.index = y * 32 + x;
this.t = t;
}
public ListNode(int i, Tile t) {
this.index = i;
this.t = t;
}
@Override
public String toString() {
return "(" + (index % 32) + ", " + (index / 32) + ") - " + t.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ListNode listNode = (ListNode) o;
return index == listNode.index &&
t == listNode.t;
}
@Override
public int hashCode() {
return Objects.hash(index, t);
}
}
public static class RestrictionNode {
public ListNode before;
public ListNode after;
public int beforeIndex;
public int afterIndex;
public RestrictionNode(ListNode before, ListNode after) {
this.before = before;
this.after = after;
}
@Override
public String toString() {
return before.toString() + " BEFORE " + after.toString();
}
@Override
public boolean equals(Object o) {
if(this == o) {
return true;
}
if(!(o instanceof RestrictionNode)) {
return false;
}
RestrictionNode node = (RestrictionNode) o;
return node.before.equals(this.before) && node.after.equals(this.after);
}
}
private class TSPSolverThread extends Thread {
private TSPGUI gui;
TSPSolverThread(TSPGUI gui) {
this.gui = gui;
}
public void run() {
ArrayList<ListNode> nodesArray = listModelToArrayList(nodes);
ArrayList<ListNode> exitNodesArray = listModelToArrayList(exitNodes);
ArrayList<RestrictionNode> restrictionNodesArray = listModelToArrayList(restrictionNodes);
SimulatedAnnealingParameters simulatedAnnealingParameters;
try {
double startTemp = Double.parseDouble(startTempInput.getText());
double endTemp = Double.parseDouble(endTempInput.getText());
double cooling = Double.parseDouble(coolingInput.getText());
int iterations = Integer.parseInt(iterationsInput.getText());
simulatedAnnealingParameters = new SimulatedAnnealingParameters(startTemp, endTemp, cooling, iterations);
if (startTemp <= 0 || endTemp <= 0 || cooling <= 0 || iterations <= 0) throw new Exception("Parameters must be greater than 0.");
if (startTemp <= endTemp) throw new Exception("Starting temperature must be greater than ending temperature.");
if (cooling >= 1) throw new Exception("Cooling factor must be less than 1.");
if(exitNodesArray.size() == 0) throw new Exception("There must be at least one exit tile.");
} catch(Exception e) {
emulator.throwError(e.getMessage());
return;
}
ActingWallParameters actingWallParameters = new ActingWallParameters(
waterCheckBox.isSelected(),
fireCheckBox.isSelected(),
bombsCheckBox.isSelected(),
thievesCheckBox.isSelected(),
trapsCheckBox.isSelected()
);
running = true;
runButton.setText("Stop");
TSPSolver solver = new TSPSolver(emulator, gui, nodesArray, exitNodesArray, restrictionNodesArray,
simulatedAnnealingParameters, actingWallParameters, output);
try {
solver.solve();
} catch(Exception e) {
output.setText("An error occured:\n" + e.getMessage());
} finally {
runButton.setText("Run");
killFlag = false;
running = false;
}
}
}
}
| 16,225 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
ChangeTimer.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/tools/ChangeTimer.java | package tools;
import emulator.SuperCC;
import javax.swing.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
public class ChangeTimer {
private JPanel mainPanel;
private JSpinner spinner;
public ChangeTimer(SuperCC emulator){
short[] keys = emulator.getLevel().getKeys();
SpinnerModel sm = new SpinnerNumberModel(((double) emulator.getLevel().getTimer()) / 100, 0.1, Short.MAX_VALUE, 0.1);
spinner.setModel(sm);
JFrame frame = new JFrame("Timer");
frame.setContentPane(mainPanel);
frame.pack();
frame.setLocationRelativeTo(emulator.getMainWindow());
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
emulator.getLevel().getCheats().setTimer((int) Math.round(10 * ((java.lang.Number) spinner.getValue()).doubleValue()));
emulator.getMainWindow().getLevelPanel().repaint();
}
});
}
}
| 1,090 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
SimulatedAnnealing.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/tools/tsp/SimulatedAnnealing.java | package tools.tsp;
import tools.TSPGUI;
import javax.swing.*;
import java.util.ArrayList;
import java.util.Random;
public class SimulatedAnnealing {
private TSPGUI gui;
private double temperature;
private double end;
private double cooling;
private int iterations;
private int[][] distances;
private int[][] distancesBoost;
private boolean[][] boostNodes;
private boolean[][] boostNodesBoost;
private int[] bestSolution;
private int bestDistance;
private int inputNodeSize;
private int exitNodeSize;
public int bestExit;
private int exitChosen;
private int startTime;
private ArrayList<TSPGUI.RestrictionNode> restrictionNodes;
private JTextPane output;
private Random r = new Random();
private boolean unreachable;
public SimulatedAnnealing(TSPGUI gui, int startTime, SimulatedAnnealingParameters simulatedAnnealingParameters, int[][] distances,
int[][] distancesBoost, boolean[][] boostNodes, boolean[][] boostNodesBoost,
int inputNodeSize, int exitNodeSize, ArrayList<TSPGUI.RestrictionNode> restrictionNodes, JTextPane output) {
this.gui = gui;
this.startTime = startTime <= 0 ? 9999 : startTime/10;
this.temperature = simulatedAnnealingParameters.startTemp;
this.end = simulatedAnnealingParameters.endTemp;
this.cooling = simulatedAnnealingParameters.cooling;
this.iterations = simulatedAnnealingParameters.iterations;
this.distances = distances;
this.distancesBoost = distancesBoost;
this.boostNodes = boostNodes;
this.boostNodesBoost = boostNodesBoost;
this.inputNodeSize = inputNodeSize;
this.exitNodeSize = exitNodeSize;
this.bestSolution = initialSolution();
this.bestDistance = Integer.MAX_VALUE;
this.restrictionNodes = restrictionNodes;
this.output = output;
this.unreachable = false;
}
public int[] start() {
bestExit = exitChosen;
if(inputNodeSize == 0) {
return new int[]{};
}
if(inputNodeSize == 1) {
return new int[]{1};
}
int[] solution = bestSolution.clone();
int distance = bestDistance;
double totalSteps = Math.ceil(Math.log(end/temperature)/Math.log(cooling));
double steps = 0;
while(temperature > end && !gui.killFlag) {
temperature *= cooling;
output.setText("Calculating shortest path..." +
"\nProgress: " + (steps/totalSteps*100) + "%" +
"\nTemperature: " + temperature +
"\nCurrent best: " + ((double)(startTime - bestDistance + 2)/10) +
(unreachable ? "\n\nCould not find path that goes through all nodes!" : ""));
int startDistance = distance;
for(int i = 0; i < iterations; i++) {
int[] newSolution = solution.clone();
mutate(newSolution);
handleRestrictions(newSolution);
int newDistance = calculateDistance(newSolution);
if(newDistance < distance) {
distance = newDistance;
solution = newSolution.clone();
}
else if(shouldAccept(distance, newDistance)) {
distance = newDistance;
solution = newSolution.clone();
}
if(newDistance < bestDistance) {
bestDistance = newDistance;
bestSolution = newSolution.clone();
bestExit = exitChosen;
}
}
if(distance < startDistance) {
temperature /= cooling;
} else {
steps++;
}
}
return bestSolution;
}
public boolean isUnreachable() {
return unreachable;
}
private int[] initialSolution() {
int[] solution = new int[inputNodeSize];
for(int i = 0; i < inputNodeSize; i++) {
solution[i] = i + 1;
}
for(int i = solution.length - 1; i > 0; i--) {
int index = r.nextInt(i + 1);
swap(solution, i, index);
}
return solution;
}
private int calculateDistance(int[] solution) {
int distance = distances[0][solution[0]];
boolean boosted = false;
unreachable = false;
for(int i = 0; i < solution.length - 1; i++) {
int segmentDistance = boosted ?
distancesBoost[solution[i]][solution[i + 1]] : distances[solution[i]][solution[i + 1]];
distance += segmentDistance;
if(segmentDistance == TSPSolver.INFINITE_DISTANCE) {
unreachable = true;
}
boosted = boosted ?
boostNodesBoost[solution[i]][solution[i + 1]] : boostNodes[solution[i]][solution[i + 1]];
}
exitChosen = 0;
int bestExitDistance = distances[solution[solution.length - 1]][solution.length + 1];
for(int i = 1; i < exitNodeSize; i++) {
if(distances[solution[solution.length - 1]][solution.length + 1 + i] < bestExitDistance) {
exitChosen = i;
if(boosted) {
bestExitDistance = distancesBoost[solution[solution.length - 1]][solution.length + 1 + i];
}
else {
bestExitDistance = distances[solution[solution.length - 1]][solution.length + 1 + i];
}
}
}
distance += bestExitDistance;
if(distance < 0) return TSPSolver.INFINITE_DISTANCE;
return distance;
}
private void mutate(int[] solution) {
int index1 = r.nextInt(solution.length);
int index2 = index1;
int temp;
while(index1 == index2) {
index2 = r.nextInt(solution.length);
}
if(index1 > index2) {
temp = index1;
index1 = index2;
index2 = temp;
}
int type = r.nextInt(3);
switch(type) {
case 0: // Inserts index1 right after index2, shifting the subarray to the left
temp = solution[index1];
for(int i = index1 + 1; i <= index2; i++) {
solution[i - 1] = solution[i];
}
solution[index2] = temp;
break;
case 1: // Performs 2-opt
opt2(solution, index1, index2);
break;
case 2: // Performs 3-opt (excluding 2-opt equivalents)
int index3 = index2; // index1 < index2 < index3
while(index3 == index1 || index3 == index2) {
index3 = r.nextInt(solution.length + 1);
}
if(index3 < index1) {
temp = index3;
index3 = index2;
index2 = index1;
index1 = temp;
}
else if(index3 < index2) {
temp = index3;
index3 = index2;
index2 = temp;
}
int opt3Type = r.nextInt(4);
opt3(solution, index1, index2, index3, opt3Type);
}
}
private void opt2(int[] solution, int index1, int index2) {
for(int i = index1; i <= (index1 + index2)/2; i++) {
swap(solution, i, index1 + index2 - i);
}
}
private void opt3(int[] solution, int index1, int index2, int index3, int type) {
switch(type) {
case 0: // [12][34] -> [34][12]
for(int i = index1; i < (index1+index2)/2; i++) swap(solution, i, index1 + index2 - i - 1);
for(int i = index2; i < (index2+index3)/2; i++) swap(solution, i, index2 + index3 - i - 1);
for(int i = index1; i < (index1+index3)/2; i++) swap(solution, i, index1 + index3 - i - 1);
break;
case 1: // [12][34] -> [34][21]
for(int i = index2; i < (index2+index3)/2; i++) swap(solution, i, index2 + index3 - i - 1);
for(int i = index1; i < (index1+index3)/2; i++) swap(solution, i, index1 + index3 - i - 1);
break;
case 2: // [12][34] -> [43][12]
for(int i = index1; i < (index1+index2)/2; i++) swap(solution, i, index1 + index2 - i - 1);
for(int i = index1; i < (index1+index3)/2; i++) swap(solution, i, index1 + index3 - i - 1);
break;
case 3: // [12][34] -> [21][43]
for(int i = index1; i < (index1+index2)/2; i++) swap(solution, i, index1 + index2 - i - 1);
for(int i = index2; i < (index2+index3)/2; i++) swap(solution, i, index2 + index3 - i - 1);
}
}
private void handleRestrictions(int[] solution) {
int[] indexes = new int[inputNodeSize];
for(int i = 0; i < solution.length; i++) {
indexes[solution[i] - 1] = i;
}
for(int i = 0; i < restrictionNodes.size(); i++) {
TSPGUI.RestrictionNode node = restrictionNodes.get(i);
if(indexes[node.beforeIndex] > indexes[node.afterIndex]) {
swap(solution, indexes[node.beforeIndex], indexes[node.afterIndex]);
}
}
}
private boolean shouldAccept(int distance, int newDistance) {
return Math.exp(((double)distance - newDistance)/ temperature) > r.nextDouble();
}
private void swap(int[] solution, int i, int j) {
int temp = solution[i];
solution[i] = solution[j];
solution[j] = temp;
}
}
| 9,769 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
ActingWallParameters.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/tools/tsp/ActingWallParameters.java | package tools.tsp;
public class ActingWallParameters {
public boolean isWaterWall;
public boolean isFireWall;
public boolean isBombWall;
public boolean isThiefWall;
public boolean isTrapWall;
public ActingWallParameters(boolean isWaterWall, boolean isFireWall, boolean isBombWall, boolean isThiefWall, boolean isTrapWall) {
this.isWaterWall = isWaterWall;
this.isFireWall = isFireWall;
this.isBombWall = isBombWall;
this.isThiefWall = isThiefWall;
this.isTrapWall = isTrapWall;
}
}
| 552 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
SimulatedAnnealingParameters.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/tools/tsp/SimulatedAnnealingParameters.java | package tools.tsp;
public class SimulatedAnnealingParameters {
public double startTemp;
public double endTemp;
public double cooling;
public int iterations;
public SimulatedAnnealingParameters(double startTemp, double endTemp, double cooling, int iterations) {
this.startTemp = startTemp;
this.endTemp = endTemp;
this.cooling = cooling;
this.iterations = iterations;
}
}
| 429 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
TSPSolver.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/tools/tsp/TSPSolver.java | package tools.tsp;
import emulator.Solution;
import emulator.SuperCC;
import emulator.TickFlags;
import game.*;
import tools.TSPGUI;
import util.CharList;
import javax.swing.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.PriorityQueue;
public class TSPSolver {
public static final int INFINITE_DISTANCE = 9999;
private SuperCC emulator;
private TSPGUI gui;
private Level level;
private byte[] startState;
private char[] directions = { SuperCC.UP, SuperCC.RIGHT, SuperCC.DOWN, SuperCC.LEFT };
private byte[] initialState;
private ArrayList<Integer> nodes = new ArrayList<>();
private boolean[][] boostNodes;
private boolean[][] boostNodesBoost;
private int[][] distances;
private int[][] distancesBoost;
private PathNode[][] paths;
private PathNode[][] pathsBoost;
private int startTime;
ActingWallParameters actingWallParameters;
private int inputNodeSize;
private int exitNodeSize;
private ArrayList<TSPGUI.RestrictionNode> restrictionNodes;
private SimulatedAnnealingParameters simulatedAnnealingParameters;
private int chosenExit;
private JTextPane output;
private Creature[] monsterList;
private int[][] currentDistances;
private PathNode[][] currentPaths;
private boolean[][] currentBoostNodes;
private int deltaTime;
private final int LIMIT = 500000; // Upper bound of exploration
public TSPSolver(SuperCC emulator, TSPGUI gui, ArrayList<TSPGUI.ListNode> inputNodes, ArrayList<TSPGUI.ListNode> exitNodes,
ArrayList<TSPGUI.RestrictionNode> restrictionNodes, SimulatedAnnealingParameters simulatedAnnealingParameters,
ActingWallParameters actingWallParameters, JTextPane output) {
this.emulator = emulator;
this.gui = gui;
this.level = emulator.getLevel();
setupState();
this.actingWallParameters = actingWallParameters;
this.initialState = normalizeState();
setupNodes(inputNodes, exitNodes);
this.boostNodes = new boolean[nodes.size()][nodes.size()];
this.boostNodesBoost = new boolean[nodes.size()][nodes.size()];
this.distances = new int[nodes.size()][nodes.size()];
this.distancesBoost = new int[nodes.size()][nodes.size()];
this.inputNodeSize = inputNodes.size();
this.exitNodeSize = exitNodes.size();
setupDistances();
this.paths = new PathNode[nodes.size()][nodes.size()];
this.pathsBoost = new PathNode[nodes.size()][nodes.size()];
this.startTime = level.getTChipTime() / 10;
this.restrictionNodes = restrictionNodes;
setupRestrictionNodes();
this.simulatedAnnealingParameters = simulatedAnnealingParameters;
this.output = output;
}
private void setupState() {
emulator.getSavestates().restart();
level.load(emulator.getSavestates().getSavestate());
this.monsterList = level.getMonsterList().getCreatures().clone();
level.getMonsterList().setCreatures(new Creature[0]);
this.startState = level.save();
emulator.tick(SuperCC.WAIT, TickFlags.LIGHT); // Full wait
emulator.tick(SuperCC.WAIT, TickFlags.LIGHT);
}
private void setupNodes(ArrayList<TSPGUI.ListNode> inputNodes, ArrayList<TSPGUI.ListNode> exitNodes) {
for(TSPGUI.ListNode node : inputNodes) {
this.nodes.add(node.index);
}
for(TSPGUI.ListNode node : exitNodes) {
this.nodes.add(node.index);
}
}
private void setupDistances() {
for(int i = 0 ; i < nodes.size(); i++) {
Arrays.fill(distances[i], INFINITE_DISTANCE);
Arrays.fill(distancesBoost[i], INFINITE_DISTANCE);
}
}
private void setupRestrictionNodes() {
for(TSPGUI.RestrictionNode node : restrictionNodes) {
node.beforeIndex = nodes.indexOf(node.before.index) - 1;
node.afterIndex = nodes.indexOf(node.after.index) - 1;
}
}
public void solve() throws Exception {
gatherNormal();
gatherBoost();
level.load(startState);
validate();
if(!gui.killFlag) {
solveWithSA();
} else {
output.setText("Stopped");
}
}
public void gatherNormal() {
currentDistances = distances;
currentPaths = paths;
currentBoostNodes = boostNodes;
deltaTime = 0;
search();
}
public void gatherBoost() {
currentDistances = distancesBoost;
currentPaths = pathsBoost;
currentBoostNodes = boostNodesBoost;
deltaTime = -1;
search();
}
private void search() {
boolean isBoost = deltaTime == -1;
for(int from = 0; from < inputNodeSize + 1; from++) {
if(isBoost && !canBoost(nodes.get(from))) {
continue;
}
outputDistanceProgress(from, isBoost);
level.load(initialState);
level.getCheats().moveChip(new Position(nodes.get(from)));
if(isBoost) {
emulator.tick(SuperCC.WAIT, TickFlags.LIGHT); // Half wait
}
searchBFS(from);
}
}
private void outputDistanceProgress(int from, boolean isBoost) {
int current = from + 1;
if(isBoost) current += inputNodeSize + 1;
int total = (inputNodeSize + 1) * 2;
output.setText("Finding distances... " + current + "/" + total);
}
private boolean canBoost(int position) {
for(Direction dir : new Direction[] {Direction.UP, Direction.RIGHT, Direction.DOWN, Direction.LEFT}) {
int delta = getDelta(dir);
int newPosition = position + delta;
if(newPosition >= 0 && newPosition < 1024 && level.getLayerFG().get(newPosition).isSliding()) {
return true;
}
}
return false;
}
private void validate() throws Exception {
String errorString = validateInputNodeAccessibility() + validateExitAccessibility();
if(!errorString.equals("")) {
throw new Exception(errorString);
}
}
private String validateInputNodeAccessibility() {
String errorString = "";
for(int i = 1; i < inputNodeSize + 1; i++) {
if(distances[0][i] == INFINITE_DISTANCE) {
errorString += " " +
emulator.getLevel().getLayerFG().get(nodes.get(i)).toString() +
" at " +
new Position(nodes.get(i)).toString() +
" inaccessible!\n";
}
}
return errorString;
}
private String validateExitAccessibility() {
boolean isExitAccessible = false;
for(int i = inputNodeSize + 1; i < nodes.size(); i++) {
if(distances[0][i] != INFINITE_DISTANCE) {
isExitAccessible = true;
break;
}
}
if(!isExitAccessible) {
return " No exit accessible!";
}
return "";
}
private void solveWithSA() throws Exception {
level.getMonsterList().setCreatures(monsterList);
SimulatedAnnealing sa = new SimulatedAnnealing(gui, level.getStartTime(), simulatedAnnealingParameters, distances, distancesBoost,
boostNodes, boostNodesBoost, inputNodeSize, exitNodeSize, restrictionNodes, output);
int[] solution = sa.start();
chosenExit = sa.bestExit;
if(!sa.isUnreachable()) {
createSolution(solution);
output.setText("Finished!");
}
else {
throw new Exception(" Could not find path that goes through all nodes!");
}
}
private void searchBFS(int from) {
currentDistances[from][from] = 0;
PriorityQueue<PathNode> states = new PriorityQueue<>(100, (a, b) -> b.time - a.time);
states.add(new PathNode(level.save(), new CharList(), startTime, 'u'));
int[] visitedAt = new int[1024 * 4];
int[] visitedCount = new int[1024 * 4];
int statesExplored = 0;
while (!states.isEmpty() && statesExplored < LIMIT && !gui.killFlag) {
statesExplored++;
PathNode node = states.poll();
byte[] state = node.state;
level.load(state);
int index = level.getChip().getPosition().getIndex() + 1024 * getDirectionIndex(node.lastMove);
Tile onTile = level.getLayerBG().get(index % 1024);
if(!onTile.isSliding()) {
index %= 1024;
}
if(statesExplored > 1) {
if (visitedAt[index] < level.getTChipTime()) {
visitedAt[index] = level.getTChipTime();
visitedCount[index] = 0;
}
if (visitedCount[index] > 0) {
continue;
}
visitedCount[index]++;
getToNode(from, index, node, false);
}
for (int direction = 0; direction < directions.length; direction++) {
if (direction > 0) {
level.load(state);
}
boolean can = true;
if (level.getChip().isSliding()) {
can = handleSliding(directions[direction], index, visitedAt, visitedCount, from, onTile, node);
}
if (can) {
emulator.tick(directions[direction], TickFlags.LIGHT);
int newIndex = level.getChip().getPosition().index;
if(index == newIndex) {
continue;
}
CharList newMoves = node.moves.clone();
newMoves.add(directions[direction]);
states.add(new PathNode(level.save(), newMoves, level.getTChipTime(), directions[direction]));
}
}
}
}
private boolean getToNode(int from, int index, PathNode node, boolean isBoost) {
if (nodes.contains(index % 1024)) {
ArrayList<Integer> indices = getNodeIndices(index % 1024);
for(int to : indices) {
int distance = startTime - level.getTChipTime() / 10 + deltaTime;
if (currentDistances[from][to] > distance) {
currentDistances[from][to] = distance;
currentPaths[from][to] = node;
currentBoostNodes[from][to] = isBoost;
}
}
return true;
}
return false;
}
private ArrayList<Integer> getNodeIndices(int index) {
ArrayList<Integer> indices = new ArrayList<>();
for(int i = 0; i < nodes.size(); i++) {
if(nodes.get(i) == index) {
indices.add(i);
}
}
return indices;
}
private int getDirectionIndex(char d) {
if(d == SuperCC.UP) return 0;
if(d == SuperCC.RIGHT) return 1;
if(d == SuperCC.DOWN) return 2;
if(d == SuperCC.LEFT) return 3;
return 0;
}
private byte[] normalizeState() {
int start = 0;
for(int i = 0; i < 1024; i++) {
Tile t = level.getLayerFG().get(i);
if(t.isChip()) {
start = i;
}
if(!isTSPTile(t)) {
level.getLayerFG().set(i, Tile.FLOOR);
}
if(isActingWall(t)) {
level.getLayerFG().set(i, Tile.BOMB);
}
if(t == Tile.BLOCK || t.isTransparent()) {
Tile bgT = level.getLayerBG().get(i);
if(isActingWall(bgT)) {
level.getLayerFG().set(i, Tile.WALL);
}
}
level.getLayerBG().set(i, Tile.FLOOR);
}
nodes.add(start);
return level.save();
}
private boolean isActingWall(Tile t) {
if(t == Tile.WATER && actingWallParameters.isWaterWall) {
return true;
}
if(t == Tile.FIRE && actingWallParameters.isFireWall) {
return true;
}
if(t == Tile.BOMB && actingWallParameters.isBombWall) {
return true;
}
if(t == Tile.THIEF && actingWallParameters.isThiefWall) {
return true;
}
return t == Tile.TRAP && actingWallParameters.isTrapWall;
}
private boolean isTSPTile(Tile t) {
return (t == Tile.FLOOR || t == Tile.WALL || t.isChip() ||
t.isIce() || t.isFF() || t == Tile.TELEPORT || t == Tile.BLUEWALL_REAL ||
t == Tile.HIDDENWALL_TEMP || t == Tile.INVISIBLE_WALL || t == Tile.CLONE_MACHINE ||
t == Tile.THIN_WALL_LEFT || t == Tile.THIN_WALL_RIGHT || t == Tile.THIN_WALL_DOWN_RIGHT ||
t == Tile.THIN_WALL_DOWN || t == Tile.THIN_WALL_UP);
}
private boolean handleSliding(char direction, int position, int[] visitedAt, int[] visitedCount, int from, Tile onTile, PathNode node) {
Direction dir = level.getChip().getDirection();
int delta = getDelta(dir);
if(position % 1024 + delta >= 1024) {
return false;
}
int newPosition = ((position % 1024) + delta) + 1024 * getDirectionIndex(direction);
Tile newTile = level.getLayerFG().get(newPosition % 1024);
if(!canEnter(direction, newPosition) && !isThinWall(newTile)) {
return false;
}
if(!canEnter(dirToChar(dir), newPosition)) {
return !onTile.isIce();
}
if(!newTile.isSliding()) {
boolean isBoost = level.getTChipTime() % 2 == 1;
boolean gotTo = getToNode(from, newPosition, node, isBoost);
if(!gotTo && visitedCount[newPosition] >= 1) {
return false;
}
return true;
}
return canOverride(direction, newTile);
}
private int getDelta(Direction dir) {
if(dir == Direction.UP) return -32;
if(dir == Direction.RIGHT) return 1;
if(dir == Direction.DOWN) return 32;
return -1;
}
private char dirToChar(Direction dir) {
switch(dir) {
case UP: return SuperCC.UP;
case RIGHT: return SuperCC.RIGHT;
case DOWN: return SuperCC.DOWN;
case LEFT: return SuperCC.LEFT;
default: return SuperCC.WAIT;
}
}
private boolean isThinWall(Tile tile) {
switch(tile) {
case THIN_WALL_DOWN:
case THIN_WALL_DOWN_RIGHT:
case THIN_WALL_LEFT:
case THIN_WALL_RIGHT:
case THIN_WALL_UP:
return true;
default: return false;
}
}
private boolean directionEquals(Direction dir, char d) {
if(dir == Direction.UP && d == SuperCC.UP) return true;
if(dir == Direction.RIGHT && d == SuperCC.RIGHT) return true;
if(dir == Direction.DOWN && d == SuperCC.DOWN) return true;
if(dir == Direction.LEFT && d == SuperCC.LEFT) return true;
return false;
}
private boolean canEnter(char d, int position) {
Tile t = level.getLayerFG().get(position % 1024);
switch(t) {
case WALL:
case HIDDENWALL_TEMP:
case INVISIBLE_WALL:
case BLUEWALL_REAL:
case CLONE_MACHINE:
return false;
case THIN_WALL_DOWN: return d != SuperCC.UP;
case THIN_WALL_DOWN_RIGHT: return (d == SuperCC.DOWN || d == SuperCC.RIGHT);
case THIN_WALL_LEFT: return d != SuperCC.RIGHT;
case THIN_WALL_RIGHT: return d != SuperCC.LEFT;
case THIN_WALL_UP: return d != SuperCC.DOWN;
case ICE_SLIDE_NORTHEAST: return (d == SuperCC.DOWN || d == SuperCC.LEFT);
case ICE_SLIDE_SOUTHEAST: return (d == SuperCC.UP || d == SuperCC.LEFT);
case ICE_SLIDE_NORTHWEST: return (d == SuperCC.DOWN || d == SuperCC.RIGHT);
case ICE_SLIDE_SOUTHWEST: return (d == SuperCC.UP || d == SuperCC.RIGHT);
default: return true;
}
}
private boolean canOverride(char d, Tile t) {
return directionEquals(level.getChip().getDirection(), d) || t.isFF();
}
private void createSolution(int[] solution) {
output.setText("Reconstructing solution...");
level.load(startState);
ArrayList<CharList> partialSolutions = new ArrayList<>();
if(solution.length > 0) {
partialSolutions.add(paths[0][solution[0]].moves);
boolean boosted = boostNodes[0][solution[0]];
for (int i = 0; i < solution.length - 1; i++) {
if(boosted) {
partialSolutions.add(pathsBoost[solution[i]][solution[i + 1]].moves);
}
else {
partialSolutions.add(paths[solution[i]][solution[i + 1]].moves);
}
boosted = boosted ?
boostNodesBoost[solution[i]][solution[i + 1]] : boostNodes[solution[i]][solution[i + 1]];
}
if(boosted) {
partialSolutions.add(pathsBoost[solution[solution.length - 1]][1 + inputNodeSize + chosenExit].moves);
}
else {
partialSolutions.add(paths[solution[solution.length - 1]][1 + inputNodeSize + chosenExit].moves);
}
}
else {
partialSolutions.add(paths[0][1].moves);
}
emulator.getSavestates().restart();
level.load(emulator.getSavestates().getSavestate());
for(CharList partialSolution : partialSolutions) {
for(Character c : partialSolution) {
emulator.tick(c, TickFlags.PRELOADING);
}
}
Solution tspSolution = new Solution(emulator.getSavestates().getMoveList(), level.getRngSeed(), level.getStep(), level.getRuleset(), level.getInitialRFFDirection());
tspSolution.load(emulator);
}
public int[][] getDistances() {
return distances;
}
public int[][] getDistancesBoost() {
return distancesBoost;
}
private class PathNode {
public byte[] state;
public CharList moves;
public int time;
char lastMove;
public PathNode(byte[] state, CharList moves, int time, char lastMove) {
this.state = state;
this.moves = moves;
this.time = time;
this.lastMove = lastMove;
}
}
}
| 18,642 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
Expr.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/tools/variation/Expr.java | package tools.variation;
import java.util.ArrayList;
import java.util.Objects;
public abstract class Expr {
interface Evaluator {
Object evaluateBinary(Binary expr);
Object evaluateLiteral(Literal expr);
Object evaluateGroup(Group expr);
Object evaluateLogical(Logical expr);
Object evaluateUnary(Unary expr);
Object evaluateVariable(Variable expr);
Object evaluateAssign(Assign expr);
Object evaluateFunction(Function expr);
}
abstract public Object evaluate(Evaluator evaluator);
static public class Binary extends Expr {
public final Expr left;
public final Token operator;
public final Expr right;
public Binary(Expr left, Token operator, Expr right) {
this.left = left;
this.operator = operator;
this.right = right;
}
@Override
public Object evaluate(Evaluator evaluator) {
return evaluator.evaluateBinary(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Binary binary = (Binary) o;
return Objects.equals(left, binary.left) &&
Objects.equals(operator, binary.operator) &&
Objects.equals(right, binary.right);
}
@Override
public int hashCode() {
return Objects.hash(left, operator, right);
}
}
static public class Literal extends Expr {
public final Object value;
public Literal(Object value) {
this.value = value;
}
@Override
public Object evaluate(Evaluator evaluator) {
return evaluator.evaluateLiteral(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Literal literal = (Literal) o;
return Objects.equals(value, literal.value);
}
@Override
public int hashCode() {
return Objects.hash(value);
}
}
static public class Group extends Expr {
public final Expr expr;
public Group(Expr expr) {
this.expr = expr;
}
@Override
public Object evaluate(Evaluator evaluator) {
return evaluator.evaluateGroup(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Group group = (Group) o;
return Objects.equals(expr, group.expr);
}
@Override
public int hashCode() {
return Objects.hash(expr);
}
}
static public class Logical extends Expr {
public final Expr left;
public final Token operator;
public final Expr right;
public Logical(Expr left, Token operator, Expr right) {
this.left = left;
this.operator = operator;
this.right = right;
}
@Override
public Object evaluate(Evaluator evaluator) {
return evaluator.evaluateLogical(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Logical logical = (Logical) o;
return Objects.equals(left, logical.left) &&
Objects.equals(operator, logical.operator) &&
Objects.equals(right, logical.right);
}
@Override
public int hashCode() {
return Objects.hash(left, operator, right);
}
}
static public class Unary extends Expr {
public final Token operator;
public final Expr right;
public Unary(Token operator, Expr right) {
this.operator = operator;
this.right = right;
}
@Override
public Object evaluate(Evaluator evaluator) {
return evaluator.evaluateUnary(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Unary unary = (Unary) o;
return Objects.equals(operator, unary.operator) &&
Objects.equals(right, unary.right);
}
@Override
public int hashCode() {
return Objects.hash(operator, right);
}
}
static public class Variable extends Expr {
public final Token var;
public Variable(Token var) {
this.var = var;
}
@Override
public Object evaluate(Evaluator evaluator) {
return evaluator.evaluateVariable(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Variable variable = (Variable) o;
return Objects.equals(var, variable.var);
}
@Override
public int hashCode() {
return Objects.hash(var);
}
}
static public class Assign extends Expr {
public final Token var;
public final Token operator;
public final Expr value;
public Assign(Token var, Token operator, Expr value) {
this.var = var;
this.operator = operator;
this.value = value;
}
@Override
public Object evaluate(Evaluator evaluator) {
return evaluator.evaluateAssign(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Assign assign = (Assign) o;
return Objects.equals(var, assign.var) &&
Objects.equals(operator, assign.operator) &&
Objects.equals(value, assign.value);
}
@Override
public int hashCode() {
return Objects.hash(var, operator, value);
}
}
static public class Function extends Expr {
public final String name;
public final ArrayList<Expr> arguments;
public final Token token;
public Function(String name, ArrayList<Expr> arguments, Token token) {
this.name = name;
this.arguments = arguments;
this.token = token;
}
@Override
public Object evaluate(Evaluator evaluator) {
return evaluator.evaluateFunction(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Function function = (Function) o;
return Objects.equals(name, function.name) &&
Objects.equals(arguments, function.arguments) &&
Objects.equals(token, function.token);
}
@Override
public int hashCode() {
return Objects.hash(name, arguments, token);
}
}
}
| 7,407 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
Stmt.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/tools/variation/Stmt.java | package tools.variation;
import java.util.ArrayList;
import java.util.Objects;
public abstract class Stmt {
interface Executor {
void executeExpression(Expression stmt);
void executeBlock(Block stmt);
void executeIf(If stmt);
void executeFor(For stmt);
void executePrint(Print stmt);
void executeEmpty(Empty stmt);
void executeBreak(Break stmt);
void executeSequence(Sequence stmt);
void executeReturn(Return stmt);
void executeTerminate(Terminate stmt);
void executeContinue(Continue stmt);
void executeAll(All stmt);
}
abstract public void execute(Executor executor);
public static class Expression extends Stmt {
public final Expr expr;
public Expression(Expr expr) {
this.expr = expr;
}
@Override
public void execute(Executor executor) {
executor.executeExpression(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Expression that = (Expression) o;
return Objects.equals(expr, that.expr);
}
@Override
public int hashCode() {
return Objects.hash(expr);
}
}
public static class Block extends Stmt {
public final ArrayList<Stmt> statements;
public Block(ArrayList<Stmt> statements) {
this.statements = statements;
}
@Override
public void execute(Executor executor) {
executor.executeBlock(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Block block = (Block) o;
return Objects.equals(statements, block.statements);
}
@Override
public int hashCode() {
return Objects.hash(statements);
}
}
public static class If extends Stmt {
public final Expr condition;
public final Stmt thenBranch;
public final Stmt elseBranch;
public If(Expr condition, Stmt thenBranch, Stmt elseBranch) {
this.condition = condition;
this.thenBranch = thenBranch;
this.elseBranch = elseBranch;
}
@Override
public void execute(Executor executor) {
executor.executeIf(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
If anIf = (If) o;
return Objects.equals(condition, anIf.condition) &&
Objects.equals(thenBranch, anIf.thenBranch) &&
Objects.equals(elseBranch, anIf.elseBranch);
}
@Override
public int hashCode() {
return Objects.hash(condition, thenBranch, elseBranch);
}
}
public static class For extends Stmt {
public final Stmt init;
public final Expr condition;
public final Stmt post;
public final Stmt body;
public For(Stmt init, Expr condition, Stmt post, Stmt body) {
this.init = init;
this.condition = condition;
this.post = post;
this.body = body;
}
@Override
public void execute(Executor executor) {
executor.executeFor(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
For aFor = (For) o;
return Objects.equals(init, aFor.init) &&
Objects.equals(condition, aFor.condition) &&
Objects.equals(post, aFor.post) &&
Objects.equals(body, aFor.body);
}
@Override
public int hashCode() {
return Objects.hash(init, condition, post, body);
}
}
public static class Print extends Stmt {
public final Expr expr;
public Print(Expr expr) {
this.expr = expr;
}
@Override
public void execute(Executor executor) {
executor.executePrint(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Print print = (Print) o;
return Objects.equals(expr, print.expr);
}
@Override
public int hashCode() {
return Objects.hash(expr);
}
}
public static class Empty extends Stmt {
@Override
public void execute(Executor executor) {
executor.executeEmpty(this);
}
@Override
public boolean equals(Object o) {
return getClass() == o.getClass();
}
}
public static class Break extends Stmt {
@Override
public void execute(Executor executor) {
executor.executeBreak(this);
}
@Override
public boolean equals(Object o) {
return getClass() == o.getClass();
}
}
public static class Sequence extends Stmt {
public final MovePoolContainer movePools;
public final BoundLimit limits;
public final String lexicographic;
public final SequenceLifecycle lifecycle;
public final Permutation permutation;
Sequence(MovePoolContainer movePools, BoundLimit limits, String lexicographic, SequenceLifecycle lifecycle) {
this.movePools = movePools;
this.limits = limits;
this.lexicographic = (lexicographic.equals("")) ? "urdlwh" : lexicographic;
this.lifecycle = lifecycle;
this.permutation = new Permutation(movePools, limits, this.lexicographic);
}
@Override
public void execute(Executor executor) {
executor.executeSequence(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Sequence sequence = (Sequence) o;
return movePools.equals(sequence.movePools) &&
limits.equals(sequence.limits) &&
lexicographic.equals(sequence.lexicographic) &&
lifecycle.equals(sequence.lifecycle);
}
@Override
public int hashCode() {
return Objects.hash(movePools, limits, lexicographic, lifecycle);
}
}
public static class Return extends Stmt {
@Override
public void execute(Executor executor) {
executor.executeReturn(this);
}
@Override
public boolean equals(Object o) {
return getClass() == o.getClass();
}
}
public static class Terminate extends Stmt {
public final Expr index;
Terminate(Expr index) {
this.index = index;
}
@Override
public void execute(Executor executor) {
executor.executeTerminate(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Terminate terminate = (Terminate) o;
return Objects.equals(index, terminate.index);
}
@Override
public int hashCode() {
return Objects.hash(index);
}
}
public static class Continue extends Stmt {
@Override
public void execute(Executor executor) {
executor.executeContinue(this);
}
@Override
public boolean equals(Object o) {
return getClass() == o.getClass();
}
}
public static class All extends Stmt {
public final Expr amount;
All(Expr amount) {
this.amount = amount;
}
@Override
public void execute(Executor executor) {
executor.executeAll(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
All all = (All) o;
return Objects.equals(amount, all.amount);
}
@Override
public int hashCode() {
return Objects.hash(amount);
}
}
}
| 8,726 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
BoundLimit.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/tools/variation/BoundLimit.java | package tools.variation;
import java.util.Objects;
public class BoundLimit {
public Integer lower = null;
public Integer upper = null;
public BoundLimit() {
}
public BoundLimit(Integer limit) {
this.lower = limit;
this.upper = limit;
}
public BoundLimit(Integer lower, Integer upper) {
this.lower = lower;
this.upper = upper;
}
public void setBounds(MovePoolContainer movePools) {
int size = movePools.optional.size + movePools.forced.size;
if(lower == null && upper == null) {
lower = size;
upper = size;
}
else if(upper == null) {
upper = lower;
}
if(upper < lower) {
int temp = upper;
upper = lower;
lower = temp;
}
upper = Math.min(upper, size);
lower = Math.min(lower, size);
upper = Math.max(upper, movePools.forced.size);
lower = Math.max(lower, movePools.forced.size);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BoundLimit that = (BoundLimit) o;
return Objects.equals(lower, that.lower) &&
Objects.equals(upper, that.upper);
}
@Override
public int hashCode() {
return Objects.hash(lower, upper);
}
}
| 1,419 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
Interpreter.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/tools/variation/Interpreter.java | package tools.variation;
import emulator.Solution;
import emulator.SuperCC;
import emulator.TickFlags;
import game.Level;
import tools.VariationTesting;
import util.CharList;
import javax.swing.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import java.awt.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Objects;
import java.util.function.DoubleBinaryOperator;
public class Interpreter implements Expr.Evaluator, Stmt.Executor {
private Parser parser;
private final SuperCC emulator;
private final ArrayList<Stmt> statements;
private final JTextPane console;
private final HashMap<String, Object> variables;
private Level level;
public int atSequence = 0;
public int atMove = 0;
public boolean inSequence = false;
public VariationManager manager;
private int[] sequenceIndex;
private FunctionEvaluator evaluator;
public CharList moveList;
private int amount = 1;
public ArrayList<Solution> solutions = new ArrayList<>();
public int bestSolutionIndex = 0;
private int bestSolutionTime = 0;
private boolean hadError = false;
private VariationTesting vt;
private int fromStatement = 0;
public long variationCount = 0;
public double totalPermutationCount;
public double totalValidPermutationCount;
public Interpreter(SuperCC emulator, VariationTesting vt, JTextPane console, String code) {
this.parser = new Parser(console);
this.statements = parser.parseCode(code);
this.variables = parser.getVariables(code);
this.emulator = emulator;
this.console = console;
this.level = emulator.getLevel();
this.manager = new VariationManager(emulator, statements, variables, this.level, this);
this.sequenceIndex = manager.sequenceIndex;
this.evaluator = new FunctionEvaluator(emulator, this, this.manager);
this.vt = vt;
this.totalPermutationCount = manager.getTotalPermutationCount();
this.totalValidPermutationCount = manager.getTotalValidPermutationCount();
}
public void interpret() {
if(parser.hadError) {
return;
}
begin();
long timeStart = System.currentTimeMillis();
while(!vt.killFlag && !isFinished()) {
variationCount++;
try {
level.load(manager.savestates[atSequence][manager.getStartingMove()]);
moveList = manager.moveLists[atSequence][manager.getStartingMove()].clone();
for (int i = fromStatement; i < statements.size(); i++) {
Stmt stmt = statements.get(i);
stmt.execute(this);
}
}
catch(TerminateException te) {
getNextPermutation();
continue;
}
catch(ReturnException re) {
if(solutions.size() >= amount) {
break;
}
}
catch(RuntimeError err) {
String str = "[Line " + err.token.line + " near '" + err.token.lexeme + "'] " + err.getMessage() + "\n";
print(str, new Color(255, 68, 68));
hadError = true;
}
catch(Exception e) {
String str = "Unknown runtime error.\n " + e.toString();
print(str, new Color(255, 68, 68));
hadError = true;
e.printStackTrace();
}
getNextPermutation();
}
long timeEnd = System.currentTimeMillis();
double totalTime = (double)(timeEnd - timeStart)/1000;
long varsPerSecond = Math.round(variationCount/totalTime);
finish(totalTime, varsPerSecond);
}
private void begin() {
console.setText("");
displayPermutationCount();
if(!manager.validate()) {
hadError = true;
}
}
private void getNextPermutation() {
atSequence = manager.nextPermutation();
if(atSequence == -1) {
return;
}
fromStatement = sequenceIndex[atSequence];
}
private boolean isFinished() {
return hadError || atSequence == -1;
}
private void finish(double totalTime, long varsPerSecond) {
if(vt.killFlag) {
print("Search stopped!\n", new Color(255, 68, 68));
}
if(!hadError) {
String str = "Successfully tested " + String.format("%,d", variationCount) + " variations.\n" +
"Found " + String.format("%,d", solutions.size()) + " solutions.\n" +
"Ran for " + totalTime + "s at " + String.format("%,d", varsPerSecond) + " vars/s.";
print(str, new Color(0, 153, 0));
}
emulator.getSavestates().restart();
level.load(emulator.getSavestates().getSavestate());
if(manager.getSequenceCount() > 0) {
if(manager.moveLists != null) {
for (char move : manager.moveLists[0][0]) {
emulator.tick(move, TickFlags.PRELOADING);
}
}
}
if(vt.hasGui) {
emulator.repaint(true);
}
}
@Override
public void executeExpression(Stmt.Expression stmt) {
stmt.expr.evaluate(this);
}
@Override
public void executeBlock(Stmt.Block stmt) {
for(Stmt statement : stmt.statements) {
statement.execute(this);
}
}
@Override
public void executeIf(Stmt.If stmt) {
if(isTruthy(stmt.condition.evaluate(this))) {
stmt.thenBranch.execute(this);
}
else {
stmt.elseBranch.execute(this);
}
}
@Override
public void executeFor(Stmt.For stmt) {
stmt.init.execute(this);
while(isTruthy(stmt.condition.evaluate(this))) {
try {
stmt.body.execute(this);
} catch(BreakException b) {
break;
}
stmt.post.execute(this);
}
}
@Override
public void executePrint(Stmt.Print stmt) {
Object obj = stmt.expr.evaluate(this);
String str = (obj == null) ? "null\n" : obj.toString() + '\n';
if(str.endsWith(".0\n")) {
str = str.substring(0, str.length() - 3) + '\n';
}
print(str, Color.white);
}
@Override
public void executeEmpty(Stmt.Empty stmt) {
}
@Override
public void executeBreak(Stmt.Break stmt) {
throw new BreakException();
}
@Override
public void executeSequence(Stmt.Sequence stmt) {
inSequence = true;
CharList[] permutation = manager.getPermutation(atSequence);
int start = manager.getStartingMove(atSequence);
if(start == 0) {
manager.setVariables(atSequence, 0);
stmt.lifecycle.start.execute(this);
}
for(atMove = start; atMove < permutation.length;) {
if(atMove > 0 && atMove < permutation.length - 1) {
manager.setVariables(atSequence, atMove);
}
stmt.lifecycle.beforeMove.execute(this);
for(int i = 0; i < permutation[atMove].size(); i++) {
stmt.lifecycle.beforeStep.execute(this);
doMove(permutation[atMove].get(i));
stmt.lifecycle.afterStep.execute(this);
}
atMove++;
stmt.lifecycle.afterMove.execute(this);
}
stmt.lifecycle.end.execute(this);
atSequence++;
inSequence = false;
}
@Override
public void executeReturn(Stmt.Return stmt) {
emulator.getSavestates().restart();
level.load(emulator.getSavestates().getSavestate());
for(char move : moveList) {
emulator.tick(move, TickFlags.PRELOADING);
}
solutions.add(new Solution(emulator.getSavestates().getMoveList(), level.getRngSeed(), level.getStep(), level.getRuleset(), level.getInitialRFFDirection()));
if(emulator.getLevel().getTChipTime() > bestSolutionTime) {
bestSolutionTime = emulator.getLevel().getTChipTime();
bestSolutionIndex = solutions.size() - 1;
}
throw new ReturnException();
}
@Override
public void executeTerminate(Stmt.Terminate stmt) {
if(!inSequence && manager.getPermutation(atSequence - 1).length == 0) {
manager.terminateZero(atSequence - 1);
throw new TerminateException();
}
int index;
if(stmt.index != null) {
index = ((Double) stmt.index.evaluate(this)).intValue();
}
else {
index = inSequence ? atMove : -1;
for(int i = 0; i < atSequence; i++) {
index += manager.getPermutation(i).length;
}
}
manager.terminate(index);
throw new TerminateException();
}
@Override
public void executeContinue(Stmt.Continue stmt) {
throw new TerminateException();
}
@Override
public void executeAll(Stmt.All stmt) {
if(stmt.amount != null) {
this.amount = ((Double) stmt.amount.evaluate(this)).intValue();
}
}
@Override
public Object evaluateBinary(Expr.Binary expr) {
Object left = expr.left.evaluate(this);
Object right = expr.right.evaluate(this);
switch(expr.operator.type) {
case PLUS:
checkIfNumber(expr.operator, left, right);
return (double)left + (double)right;
case MINUS:
checkIfNumber(expr.operator, left, right);
return (double)left - (double)right;
case STAR:
checkIfNumber(expr.operator, left, right);
return (double)left * (double)right;
case SLASH:
checkIfNumber(expr.operator, left, right);
return (double)left / (double)right;
case MODULO:
checkIfNumber(expr.operator, left, right);
return (double)left % (double)right;
case EQUAL_EQUAL:
return isEqual(left, right);
case BANG_EQUAL:
return !isEqual(left, right);
case LESS:
checkIfNumber(expr.operator, left, right);
return (double)left < (double)right;
case LESS_EQUAL:
checkIfNumber(expr.operator, left, right);
return (double)left <= (double)right;
case GREATER:
checkIfNumber(expr.operator, left, right);
return (double)left > (double)right;
case GREATER_EQUAL:
checkIfNumber(expr.operator, left, right);
return (double)left >= (double)right;
}
return null;
}
@Override
public Object evaluateLiteral(Expr.Literal expr) {
return expr.value;
}
@Override
public Object evaluateGroup(Expr.Group expr) {
return expr.expr.evaluate(this);
}
@Override
public Object evaluateLogical(Expr.Logical expr) {
Object left = expr.left.evaluate(this);
switch(expr.operator.type) {
case OR:
case OR_OR:
if(isTruthy(left)) {
return left;
}
break;
case AND:
case AND_AND:
if(!isTruthy(left)) {
return left;
}
break;
default:
throw new RuntimeError(expr.operator, "Unknown logical expression");
}
return expr.right.evaluate(this);
}
@Override
public Object evaluateUnary(Expr.Unary expr) {
Object right = expr.right.evaluate(this);
switch(expr.operator.type) {
case BANG:
case NOT:
return !isTruthy(right);
case MINUS:
return -(double)right;
}
return null;
}
@Override
public Object evaluateVariable(Expr.Variable expr) {
return variables.get(expr.var.lexeme);
}
@Override
public Object evaluateAssign(Expr.Assign expr) {
Object value = variables.get(expr.var.value);
if(value == null && expr.operator.type != TokenType.EQUAL) {
throw new RuntimeError(expr.var, "Variable undefined");
}
Object exprValue = expr.value.evaluate(this);
switch(expr.operator.type) {
case EQUAL:
variables.put(expr.var.lexeme, exprValue);
return exprValue;
case PLUS_EQUAL:
return applyAssignment((a, b) -> a + b, value, exprValue, expr);
case MINUS_EQUAL:
return applyAssignment((a, b) -> a - b, value, exprValue, expr);
case STAR_EQUAL:
return applyAssignment((a, b) -> a * b, value, exprValue, expr);
case SLASH_EQUAL:
return applyAssignment((a, b) -> a / b, value, exprValue, expr);
case MODULO_EQUAL:
return applyAssignment((a, b) -> a % b, value, exprValue, expr);
}
return null;
}
@Override
public Object evaluateFunction(Expr.Function expr) {
return evaluator.evaluate(expr);
}
private void checkIfNumber(Token operator, Object left, Object right) {
if(left instanceof Double && right instanceof Double) {
return;
}
throw new RuntimeError(operator, "Operand must be a number");
}
public void doMove(char move) {
if (move == 'w') {
tick(SuperCC.WAIT);
tick(SuperCC.WAIT);
} else {
tick(move);
}
}
private void tick(char move) {
emulator.tick(move, TickFlags.LIGHT);
moveList.add(move);
checkMove();
}
private void checkMove() {
if(level.isCompleted()) {
executeReturn(null);
}
if(level.getChip().isDead()) {
executeTerminate(new Stmt.Terminate(null));
throw new TerminateException();
}
}
private double applyAssignment(DoubleBinaryOperator op, Object value, Object exprValue, Expr.Assign expr) {
checkIfNumber(expr.operator, exprValue, value);
double newValue = op.applyAsDouble((double)value, (double)exprValue);
variables.put(expr.var.lexeme, newValue);
return newValue;
}
private boolean isTruthy(Object value) {
if(value == null) {
return false;
}
if(value instanceof Boolean) {
return (boolean)value;
}
if(value instanceof Double) {
return (double)value != 0;
}
return true;
}
private boolean isEqual(Object left, Object right) {
return Objects.equals(left, right);
}
private class BreakException extends RuntimeException {
BreakException() {
super(null, null, false, false);
}
}
private class TerminateException extends RuntimeException {
TerminateException() {
super(null, null, false, false);
}
}
private class ReturnException extends RuntimeException {
ReturnException() { super(null, null, false, false); }
}
public static class RuntimeError extends RuntimeException {
final Token token;
RuntimeError(Token token, String message) {
super(message);
this.token = token;
}
}
public void print(String message, Color color) {
StyledDocument doc = console.getStyledDocument();
Style style = console.addStyle("style", null);
StyleConstants.setForeground(style, color);
try {
doc.insertString(doc.getLength(), message, style);
} catch (BadLocationException e) {}
}
public void displayPermutationCount() {
String type = (totalValidPermutationCount > Permutation.LIMIT) ? "more than " : "up to ";
String str = "Upper bound: " + type + String.format("%,.0f", totalValidPermutationCount) + " variations\n";
print(str, Color.white);
}
public double getPermutationIndex() {
return manager.getPermutationIndex();
}
}
| 16,450 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
VariationManager.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/tools/variation/VariationManager.java | package tools.variation;
import emulator.SuperCC;
import game.Level;
import util.CharList;
import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
public class VariationManager {
private ArrayList<Stmt.Sequence> sequences = new ArrayList<>();
private HashMap<String, Object> variables;
private HashMap<String, Object>[][] variableStates;
private Level level;
private Interpreter interpreter;
public int[] sequenceIndex;
public byte[][][] savestates;
public CharList[][] moveLists;
private ArrayList<Double> cumulativeTotalPermutations = new ArrayList<>();
private double totalValidPermutationCount = 1;
public int startingMove = 0;
private int lastIndex = 0;
private int lastStartingMove = 0;
VariationManager(SuperCC emulator, ArrayList<Stmt> statements, HashMap<String, Object> variables,
Level level, Interpreter interpreter) {
setSequences(statements);
this.interpreter = interpreter;
for(Stmt.Sequence seq : sequences) {
if(seq.permutation.limits.upper == 0) {
return;
}
}
this.variables = variables;
this.level = level;
calculatePermutationCount();
if(sequences.size() == 0) {
return;
}
this.sequenceIndex = new int[sequences.size()];
this.variableStates = new HashMap[sequences.size()][];
this.savestates = new byte[sequences.size()][][];
this.moveLists = new CharList[sequences.size()][];
for(int i = 0; i < sequences.size(); i++) {
int limit = sequences.get(i).permutation.getUpperLimit();
this.savestates[i] = new byte[limit][];
this.variableStates[i] = new HashMap[limit];
this.moveLists[i] = new CharList[limit];
}
byte[] initialState = level.save();
this.savestates[0][0] = Arrays.copyOf(initialState, initialState.length);
this.moveLists[0][0] = new CharList();
char[] moves = emulator.getSavestates().getMoves();
int index = emulator.getSavestates().getPlaybackIndex();
if(emulator.getSavestates().getMoveList().size() == 0) {
index = 0;
}
for(int i = 0; i < index; i++) {
char move = lowercase(moves[i]);
moveLists[0][0].add(move);
}
setSequenceIndex(statements);
}
public CharList[] getPermutation(int index) {
return sequences.get(index).permutation.getPermutation();
}
public int nextPermutation() {
for(int i = sequences.size() - 1; i >= 0; i--) {
Stmt.Sequence seq = sequences.get(i);
seq.permutation.nextPermutation();
if(seq.permutation.finished) {
seq.permutation.reset();
}
else {
startingMove = seq.permutation.startingMove;
if(lastIndex < i) {
i = lastIndex;
}
else if(i == lastIndex && startingMove > lastStartingMove) {
startingMove = lastStartingMove;
}
loadVariables(i, getStartingMove());
return i;
}
}
return -1;
}
public void setVariables(int index, int move) {
HashMap<String, Object> newVariables = new HashMap<>();
for (String var : variables.keySet()) {
Object newVal = variables.get(var);
if (newVal instanceof Move) {
newVal = new Move(((Move) newVal).value);
}
newVariables.put(var, newVal);
}
variableStates[index][move] = newVariables;
byte[] newSavestate = level.save();
savestates[index][move] = Arrays.copyOf(newSavestate, newSavestate.length);
moveLists[index][move] = interpreter.moveList.clone();
lastIndex = index;
lastStartingMove = move;
}
public void terminate(int index) {
int sum = 0;
int prevSum = 0;
for(int i = 0; i < getSequenceCount(); i++) {
sum += getPermutation(i).length;
if(index < sum) {
sequences.get(i).permutation.terminate(index - prevSum);
endSequences(i + 1);
return;
}
prevSum = sum;
}
}
public void terminateZero(int index) {
sequences.get(index).permutation.reset();
endSequences(index + 1);
}
public int getStartingMove() {
return (startingMove < 0) ? 0 : startingMove;
}
public int getStartingMove(int atSequence) {
if(atSequence > lastIndex) {
return 0;
}
return (startingMove < 0) ? 0 : startingMove;
}
private void endSequences(int from) {
for(int i = from; i < getSequenceCount(); i++) {
sequences.get(i).permutation.end();
}
}
private void setSequences(ArrayList<Stmt> statements) {
for(Stmt stmt : statements) {
if(stmt instanceof Stmt.Sequence) {
sequences.add((Stmt.Sequence)stmt);
}
}
}
private void setSequenceIndex(ArrayList<Stmt> statements) {
int j = 0;
for(int i = 0; i < statements.size(); i++) {
Stmt stmt = statements.get(i);
if(stmt instanceof Stmt.Sequence) {
sequenceIndex[j++] = i;
}
}
}
private void loadVariables(int index, int move) {
HashMap<String, Object> newVars = variableStates[index][move];
for (String var : newVars.keySet()) {
Object val = newVars.get(var);
if (val instanceof Move) {
val = new Move(((Move) val).value);
}
variables.put(var, val);
}
}
public int getSequenceCount() {
return sequences.size();
}
public void calculatePermutationCount() {
double total = 1;
cumulativeTotalPermutations.add(total);
for(int i = sequences.size() - 1; i >= 0; i--) {
total *= sequences.get(i).permutation.permutationCount;
cumulativeTotalPermutations.add(total);
totalValidPermutationCount *= sequences.get(i).permutation.permutationValidCount;
}
Collections.reverse(cumulativeTotalPermutations);
}
public double getPermutationIndex() {
int index = 0;
for(int i = 0; i < sequences.size(); i++) {
index += sequences.get(i).permutation.getPermutationIndex() * cumulativeTotalPermutations.get(i + 1);
}
return index;
}
public double getTotalPermutationCount() {
if(cumulativeTotalPermutations.size() == 0) {
return 0;
}
return cumulativeTotalPermutations.get(0);
}
public double getTotalValidPermutationCount() {
return totalValidPermutationCount;
}
public boolean validate() {
if(getSequenceCount() == 0) {
interpreter.print("Script must contain at least 1 sequence\n", new Color(255, 68, 68));
return false;
}
for(Stmt.Sequence sequence : sequences) {
if(sequence.permutation.limits.upper == 0) {
interpreter.print("Sequence upper bound must be at least 1\n", new Color(255, 68, 68));
return false;
}
}
return true;
}
private char lowercase(char b) {
switch(b) {
case 'U':
return SuperCC.UP;
case 'R':
return SuperCC.RIGHT;
case 'D':
return SuperCC.DOWN;
case 'L':
return SuperCC.LEFT;
default:
return b;
}
}
}
| 7,922 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
Multiset.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/tools/variation/Multiset.java | package tools.variation;
import emulator.SuperCC;
import util.CharList;
import java.util.ArrayList;
import java.util.HashMap;
public class Multiset {
private MovePool movePoolForced;
private int[] movePool;
private BoundLimit limits;
public int currentSize;
private int[] subset;
public boolean finished = false;
public ArrayList<String> moves;
public CharList[] movesList;
private HashMap<String, Integer> moveIndex = new HashMap<>();
public ArrayList<Double> cumulativePermutationCounts = new ArrayList<>();
private int setIndex = 0;
private double totalValidPermutations = 0;
public static double LIMIT = 1e18;
public Multiset(MovePoolContainer movePools, BoundLimit limits, String lexicographic) {
MovePool movePoolTotal = getMovePoolTotal(movePools);
this.movePoolForced = movePools.forced;
this.limits = limits;
this.currentSize = limits.lower;
int size = movePoolTotal.moves.size();
this.movePool = new int[size];
this.subset = new int[size];
this.moves = new ArrayList<>(movePoolTotal.moves.keySet());
this.moves.sort((s1, s2) -> compareLexicographic(s1, s2, lexicographic));
this.movesList = new CharList[this.moves.size()];
for(int i = 0; i < this.moves.size(); i++) {
this.moveIndex.put(this.moves.get(i), i);
CharList moveList = new CharList();
String str = this.moves.get(i);
for(int j = 0; j < str.length(); j++) {
moveList.add((str.charAt(j) == 'h') ? SuperCC.WAIT : str.charAt(j));
}
this.movesList[i] = moveList;
}
for(int i = 0; i < size; i++) {
this.movePool[i] = movePoolTotal.moves.get(moves.get(i));
}
initialSubset();
calculatePermutationCount();
}
/**
* This algorithm represents subsets as arrays where each index represents a move in specified order.
* The value at each index is the amount of these moves.
* If each value is interpreted as a digit, the next subset is the next possible smaller number.
* E.g. in default order (urdlwh), if the move pool consists of [2u, r, 3d, l] and the size of subset is 4,
* the first subset is [2, 1, 1, 0], and the next one is [2, 1, 0, 1] then [2, 0, 2, 0] then [2, 0, 1, 1] etc.
* 2110 -> 2101 -> 2020 -> 2011, where each digit has a limit
*/
public void nextSubset() {
while(!finished) {
setIndex++;
int i = getDistributionIndex();
if (i == 0) {
endOfCurrentSize();
return;
}
subset[i - 1]--;
distribute(i, gatherDistribution(i));
if(isSubsetValid()) {
return;
}
}
}
public int[] getSubset() {
return subset;
}
public void reset() {
finished = false;
currentSize = limits.lower;
setIndex = 0;
initialSubset();
}
public double getTotalPermutationCount() {
return cumulativePermutationCounts.get(cumulativePermutationCounts.size() - 1);
}
public double getTotalValidPermutationCount() {
return totalValidPermutations;
}
public double getCumulativePermutationCount() {
return cumulativePermutationCounts.get(setIndex);
}
private int getDistributionIndex() {
for (int i = subset.length - 1; i >= 1; i--) {
if (subset[i] != movePool[i] && subset[i - 1] > 0) {
return i;
}
}
return 0;
}
private void distribute(int from, int toDistribute) {
for(int i = from; i < subset.length; i++) {
int distributed = Math.min(toDistribute, movePool[i]);
toDistribute -= distributed;
subset[i] = distributed;
}
}
private int gatherDistribution(int from) {
int toDistribute = 1;
for (int j = from; j < subset.length; j++) {
toDistribute += subset[j];
subset[j] = 0;
}
return toDistribute;
}
private void endOfCurrentSize() {
if (currentSize < limits.upper) {
currentSize++;
initialSubset();
return;
}
finished = true;
}
private void initialSubset() {
distribute(0, currentSize);
if(!isSubsetValid()) {
nextSubset();
}
}
private int compareLexicographic(String s1, String s2, String lexicographic) {
int size = Math.min(s1.length(), s2.length());
for(int i = 0; i < size; i++) {
int index1 = lexicographic.indexOf(s1.charAt(i));
int index2 = lexicographic.indexOf(s2.charAt(i));
if(index1 != index2) {
return index1 - index2;
}
}
return s1.length() - s2.length();
}
private MovePool getMovePoolTotal(MovePoolContainer movePools) {
MovePool movePoolTotal = new MovePool();
movePoolTotal.add(movePools);
return movePoolTotal;
}
private boolean isSubsetValid() {
for(String move : movePoolForced.moves.keySet()) {
if(subset[moveIndex.get(move)] < movePoolForced.moves.get(move)) {
return false;
}
}
return true;
}
private void calculatePermutationCount() {
double count = 0;
cumulativePermutationCounts.add(count);
MovePool forcedBackup = movePoolForced;
movePoolForced = new MovePool();
reset();
do {
double permutations = uniquePermutations(currentSize, subset);
count += permutations;
if(shouldCountPermutations(forcedBackup)) {
totalValidPermutations += permutations;
}
cumulativePermutationCounts.add(count);
nextSubset();
} while(!finished && count < LIMIT);
movePoolForced = forcedBackup;
reset();
}
private boolean shouldCountPermutations(MovePool forcedBackup) {
movePoolForced = forcedBackup;
boolean ret = isSubsetValid();
movePoolForced = new MovePool();
return ret;
}
private double factorial(int n) {
if(n == 0 || n == 1) {
return 1;
}
return (double)n * factorial(n - 1);
}
private double uniquePermutations(int n, int[] moves) {
double denominator = 1;
for (int move : moves) {
denominator *= factorial(move);
}
return factorial(n)/denominator;
}
}
| 6,658 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
MovePoolContainer.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/tools/variation/MovePoolContainer.java | package tools.variation;
import java.util.Objects;
public class MovePoolContainer {
public MovePool optional = new MovePool();
public MovePool forced = new MovePool();
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MovePoolContainer that = (MovePoolContainer) o;
return optional.equals(that.optional) &&
forced.equals(that.forced);
}
@Override
public int hashCode() {
return Objects.hash(optional, forced);
}
}
| 587 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
Parser.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/tools/variation/Parser.java | package tools.variation;
import game.Tile;
import javax.swing.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import java.awt.*;
import java.util.ArrayList;
import java.util.HashMap;
public class Parser {
private final char[] LEXICOGRAPHIC_CHARS = "urdlwh".toCharArray();
private ArrayList<Token> tokens;
private JTextPane console;
private int current = 0;
public boolean hadError = false;
public Parser() {
}
public Parser(JTextPane console) {
this.console = console;
console.setText("");
}
/**
* Uses the recursive descent parsing technique.
* @return Array of statements for the interpreter to execute.
*/
public ArrayList<Stmt> parseCode(String code) {
Tokenizer tokenizer = new Tokenizer(code);
ArrayList<Token> tokens = tokenizer.getParsableTokens();
this.tokens = tokens;
return parse();
}
public HashMap<String, Object> getVariables(String code) {
Tokenizer tokenizer = new Tokenizer(code);
return tokenizer.getVariables();
}
public ArrayList<Stmt> parse() {
ArrayList<Stmt> statements = new ArrayList<>();
while(!isEnd()) {
try {
statements.add(statement(true));
} catch(Exception e) {
print(getToken(), "Unknown parsing error.\n " + e.toString());
synchronize();
hadError = true;
e.printStackTrace();
}
}
return statements;
}
private Stmt statement() {
return statement(false);
}
private Stmt statement(boolean isGlobal) {
Token token = getNextToken();
try {
switch(token.type) {
case LEFT_BRACE: return new Stmt.Block(block());
case IF: return ifStatement();
case FOR: return forStatement();
case PRINT: return printStatement();
case LEFT_BRACKET: return sequenceStatement(isGlobal);
case SEMICOLON: return new Stmt.Empty();
case BREAK: return breakStatement();
case RETURN: return returnStatement();
case TERMINATE: return terminateStatement();
case CONTINUE: return continueStatement();
case ALL: return allStatement();
default: current--; return expressionStatement();
}
} catch(SyntaxError err) {
synchronize();
hadError = true;
return null;
}
}
private ArrayList<Stmt> block() {
ArrayList<Stmt> statements = new ArrayList<>();
while(!(getToken().type == TokenType.RIGHT_BRACE) && !isEnd()) {
statements.add(statement());
}
expect(TokenType.RIGHT_BRACE, "Expected '}'");
return statements;
}
private Stmt ifStatement() {
expect(TokenType.LEFT_PAREN, "Expected '('");
Expr condition = expression();
expect(TokenType.RIGHT_PAREN, "Expected ')'");
Stmt thenBranch = statement();
Stmt elseBranch = isNextToken(TokenType.ELSE) ? statement() : new Stmt.Empty();
return new Stmt.If(condition, thenBranch, elseBranch);
}
private Stmt forStatement() {
Stmt init = new Stmt.Empty();
Expr condition = null;
Stmt post = new Stmt.Empty();
expect(TokenType.LEFT_PAREN, "Expected '('");
if(getToken().type != TokenType.SEMICOLON) {
init = expressionStatement();
} else {
expect(TokenType.SEMICOLON, "Expected ';'");
}
if(getToken().type != TokenType.SEMICOLON) {
condition = expression();
}
expect(TokenType.SEMICOLON, "Expected ';'");
if(getToken().type != TokenType.RIGHT_PAREN) {
post = new Stmt.Expression(expression());
}
expect(TokenType.RIGHT_PAREN, "Expected ')'");
Stmt body = statement();
return new Stmt.For(init, condition, post, body);
}
private Stmt printStatement() {
Expr expr = expression();
expect(TokenType.SEMICOLON, "Expected ';'");
return new Stmt.Print(expr);
}
private Stmt sequenceStatement(boolean isGlobal) {
if(!isGlobal) {
throw error(getPreviousToken(), "Sequence must be outside conditions and loops");
}
return sequence();
}
private Stmt sequence() {
MovePoolContainer movePools = new MovePoolContainer();
parseSequenceMovePools(movePools);
BoundLimit limits = new BoundLimit();
parseSequenceLimits(limits);
expect(TokenType.LEFT_BRACE, "Expected '{'");
String lexicographic = parseSequenceLexicographic();
SequenceLifecycle lifecycle = new SequenceLifecycle();
parseSequenceLifecycle(lifecycle);
expect(TokenType.RIGHT_BRACE, "Expected '}'");
return new Stmt.Sequence(movePools, limits, lexicographic, lifecycle);
}
private void parseSequenceMovePools(MovePoolContainer movePools) {
MovePool movePoolOptional = movePools.optional;
MovePool movePoolForced = movePools.forced;
collectMoves(movePoolOptional);
if(movePoolOptional.size == 0) {
throw error(getPreviousToken(), "Moves must be provided in brackets");
}
expect(TokenType.RIGHT_BRACKET, "Expected ']'");
if(getToken().type == TokenType.LEFT_BRACKET && !isEnd()) {
movePoolForced.replace(movePoolOptional);
movePoolOptional.clear();
expect(TokenType.LEFT_BRACKET, "Expected '['");
collectMoves(movePoolOptional);
if(movePoolOptional.size == 0 || movePoolForced.size == 0) {
throw error(getPreviousToken(), "Moves must be provided in brackets");
}
expect(TokenType.RIGHT_BRACKET, "Expected ']'");
}
}
private void collectMoves(MovePool movePool) {
while(getToken().type != TokenType.RIGHT_BRACKET && !isEnd()) {
movePool.add(parseMove());
consume(TokenType.COMMA);
}
}
private void parseSequenceLimits(BoundLimit limits) {
expect(TokenType.LEFT_PAREN, "Expected '('");
if(getToken().type != TokenType.RIGHT_PAREN) {
limits.lower = parseInteger();
consume(TokenType.COMMA);
}
if(getToken().type != TokenType.RIGHT_PAREN) {
limits.upper = parseInteger();
}
expect(TokenType.RIGHT_PAREN, "Expected ')'");
}
private Move parseMove() {
try {
return new Move((String)(getNextToken().value));
} catch(Exception e) {
throw error(getPreviousToken(), "Expected move");
}
}
private int parseInteger() {
try {
return Integer.parseInt(getNextToken().lexeme);
} catch(Exception e) {
throw error(getPreviousToken(), "Expected integer");
}
}
private String parseSequenceLexicographic() {
String lexicographic = "";
if(isNextToken(TokenType.LEXICOGRAPHIC)) {
lexicographic += getNextToken().lexeme.toLowerCase();
expect(TokenType.SEMICOLON, "Expected ';'");
if(!checkLexicographic(lexicographic)) {
throw error(getPreviousToken(), "All 6 move types required for order");
}
}
return lexicographic;
}
private void parseSequenceLifecycle(SequenceLifecycle lifecycle) {
while(isNextToken(TokenType.START, TokenType.BEFORE_MOVE, TokenType.AFTER_MOVE,
TokenType.BEFORE_STEP, TokenType.AFTER_STEP, TokenType.END)) {
Token lifecycleToken = getPreviousToken();
expect(TokenType.COLON, "Expected ':'");
Stmt stmt = statement();
switch(lifecycleToken.type) {
case START: lifecycle.start = stmt; break;
case BEFORE_MOVE: lifecycle.beforeMove = stmt; break;
case AFTER_MOVE: lifecycle.afterMove = stmt; break;
case BEFORE_STEP: lifecycle.beforeStep = stmt; break;
case AFTER_STEP: lifecycle.afterStep = stmt; break;
case END: lifecycle.end = stmt; break;
}
}
}
private Stmt breakStatement() {
expect(TokenType.SEMICOLON, "Expected ';'");
return new Stmt.Break();
}
private Stmt returnStatement() {
expect(TokenType.SEMICOLON, "Expected ';'");
return new Stmt.Return();
}
private Stmt terminateStatement() {
Expr index = null;
if(!isNextToken(TokenType.SEMICOLON)) {
index = expression();
expect(TokenType.SEMICOLON, "Expected ';'");
}
return new Stmt.Terminate(index);
}
private Stmt continueStatement() {
expect(TokenType.SEMICOLON, "Expected ';'");
return new Stmt.Continue();
}
private Stmt allStatement() {
Expr amount = new Expr.Literal(1000.0);
if(!isNextToken(TokenType.SEMICOLON)) {
amount = expression();
expect(TokenType.SEMICOLON, "Expected ';'");
}
return new Stmt.All(amount);
}
private Stmt expressionStatement() {
Expr expr = expression();
expect(TokenType.SEMICOLON, "Expected ';'");
return new Stmt.Expression(expr);
}
private Expr expression() {
return assignment();
}
private Expr assignment() {
Expr expr = or();
if(isNextToken(TokenType.EQUAL, TokenType.PLUS_EQUAL, TokenType.MINUS_EQUAL, TokenType.STAR_EQUAL,
TokenType.SLASH_EQUAL, TokenType.MODULO_EQUAL)) {
Token operator = getPreviousToken();
Expr value = assignment();
if(expr instanceof Expr.Variable) {
Token var = ((Expr.Variable)expr).var;
return new Expr.Assign(var, operator, value);
}
throw error(getToken(), "You can only assign to a variable");
}
return expr;
}
private Expr or() {
Expr expr = and();
while(isNextToken(TokenType.OR, TokenType.OR_OR)) {
Token operator = getPreviousToken();
Expr right = and();
expr = new Expr.Logical(expr, operator, right);
}
return expr;
}
private Expr and() {
Expr expr = equality();
while(isNextToken(TokenType.AND, TokenType.AND_AND)) {
Token operator = getPreviousToken();
Expr right = equality();
expr = new Expr.Logical(expr, operator, right);
}
return expr;
}
private Expr equality() {
Expr expr = comparison();
while(isNextToken(TokenType.EQUAL_EQUAL, TokenType.BANG_EQUAL)) {
Token operator = getPreviousToken();
Expr right = comparison();
expr = new Expr.Binary(expr, operator, right);
}
return expr;
}
private Expr comparison() {
Expr expr = addition();
while(isNextToken(TokenType.LESS, TokenType.LESS_EQUAL, TokenType.GREATER, TokenType.GREATER_EQUAL)) {
Token operator = getPreviousToken();
Expr right = addition();
expr = new Expr.Binary(expr, operator, right);
}
return expr;
}
private Expr addition() {
Expr expr = multiplication();
while(isNextToken(TokenType.PLUS, TokenType.MINUS)) {
Token operator = getPreviousToken();
Expr right = multiplication();
expr = new Expr.Binary(expr, operator, right);
}
return expr;
}
private Expr multiplication() {
Expr expr = unary();
while(isNextToken(TokenType.STAR, TokenType.SLASH, TokenType.MODULO)) {
Token operator = getPreviousToken();
Expr right = unary();
expr = new Expr.Binary(expr, operator, right);
}
return expr;
}
private Expr unary() {
if(isNextToken(TokenType.MINUS, TokenType.BANG, TokenType.NOT)) {
Token operator = getPreviousToken();
Expr right = unary();
return new Expr.Unary(operator, right);
}
return function();
}
private Expr function() {
if(isNextToken(TokenType.FUNCTION)) {
Token token = getPreviousToken();
String name = getPreviousToken().lexeme.toLowerCase();
ArrayList<Expr> arguments = parseFunctionArguments();
return new Expr.Function(name, arguments, token);
}
return primary();
}
private ArrayList<Expr> parseFunctionArguments() {
ArrayList<Expr> arguments = new ArrayList<>();
expect(TokenType.LEFT_PAREN, "Expected '('");
while(!isNextToken(TokenType.RIGHT_PAREN)) {
Expr expr = expression();
arguments.add(expr);
consume(TokenType.COMMA);
}
return arguments;
}
private Expr primary() {
Token token = getNextToken();
switch(token.type) {
case NULL: return new Expr.Literal(null);
case TRUE: return new Expr.Literal(true);
case FALSE: return new Expr.Literal(false);
case NUMBER: return new Expr.Literal(token.value);
case MOVE: return new Expr.Literal(new Move((String)token.value));
case IDENTIFIER: return new Expr.Variable(token);
case TILE: return new Expr.Literal(Tile.valueOf((String)token.value));
case LEFT_PAREN: return groupExpression();
case OTHER: throw error(token, "Unexpected symbol");
default: throw error(token, "Expected expression");
}
}
private Expr groupExpression() {
Expr expr = expression();
expect(TokenType.RIGHT_PAREN, "Expected ')'");
return new Expr.Group(expr);
}
private Token getNextToken() {
if(!isEnd()) current++;
return getPreviousToken();
}
private Token getPreviousToken() {
return tokens.get(current - 1);
}
private boolean isNextToken(TokenType... types) {
for(TokenType type : types) {
if(isTokenType(type)) {
getNextToken();
return true;
}
}
return false;
}
private boolean isTokenType(TokenType type) {
if(isEnd()) {
return false;
}
return getToken().type == type;
}
private Token getToken() {
return tokens.get(current);
}
private boolean isEnd() {
return getToken().type == TokenType.EOF;
}
private void expect(TokenType type, String message) {
if(isTokenType(type)) {
getNextToken();
return;
}
throw error(getPreviousToken(), message);
}
private void consume(TokenType type) {
if(getToken().type == type) {
getNextToken();
}
}
private SyntaxError error(Token token, String message) {
print(token, message);
return new SyntaxError();
}
private void print(Token token, String message) {
if(console != null) {
StyledDocument doc = console.getStyledDocument();
Style style = console.addStyle("style", null);
StyleConstants.setForeground(style, new Color(255, 68, 68));
String str = "[Line " + token.line + " near '" + token.lexeme + "'] " + message + "\n";
try {
doc.insertString(doc.getLength(), str, style);
} catch (BadLocationException e) {
}
}
}
private void synchronize() {
while(!isEnd()) {
switch(getToken().type) {
case SEMICOLON:
getNextToken();
case FOR:
case IF:
case PRINT:
case RETURN:
case CONTINUE:
case TERMINATE:
case LEXICOGRAPHIC:
case ALL:
return;
}
getNextToken();
}
}
private boolean checkLexicographic(String lexicographic) {
if(lexicographic.length() != 6) {
return false;
}
for(char moveType : LEXICOGRAPHIC_CHARS) {
if(lexicographic.indexOf(moveType) < 0) {
return false;
}
}
return true;
}
private class SyntaxError extends RuntimeException { }
}
| 16,754 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
Token.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/tools/variation/Token.java | package tools.variation;
import java.awt.*;
import java.util.HashMap;
import java.util.Objects;
public class Token {
public final TokenType type;
public final String lexeme;
public final Object value;
public final int line;
public Token(TokenType type, String lexeme, Object value, int line) {
this.type = type;
this.lexeme = (type == TokenType.EOF) ? "" : lexeme;
this.value = value;
this.line = line;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Token token = (Token) o;
return line == token.line &&
type == token.type &&
lexeme.equals(token.lexeme) &&
Objects.equals(value, token.value);
}
@Override
public int hashCode() {
return Objects.hash(type, lexeme, value, line);
}
}
| 940 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
Tokenizer.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/tools/variation/Tokenizer.java | package tools.variation;
import game.Tile;
import java.util.ArrayList;
import java.util.HashMap;
public class Tokenizer {
private String code;
private ArrayList<Token> tokens;
private int start = 0;
private int current = 0;
private int line = 1;
private static final String moves = "urdlwhURDLWH";
private static final HashMap<String, TokenType> keywords;
static {
keywords = new HashMap<>();
keywords.put("start", TokenType.START);
keywords.put("beforemove", TokenType.BEFORE_MOVE);
keywords.put("aftermove", TokenType.AFTER_MOVE);
keywords.put("beforestep", TokenType.BEFORE_STEP);
keywords.put("afterstep", TokenType.AFTER_STEP);
keywords.put("end", TokenType.END);
keywords.put("if", TokenType.IF);
keywords.put("else", TokenType.ELSE);
keywords.put("for", TokenType.FOR);
keywords.put("true", TokenType.TRUE);
keywords.put("false", TokenType.FALSE);
keywords.put("null", TokenType.NULL);
keywords.put("var", TokenType.VAR);
keywords.put("print", TokenType.PRINT);
keywords.put("break", TokenType.BREAK);
keywords.put("and", TokenType.AND);
keywords.put("or", TokenType.OR);
keywords.put("not", TokenType.NOT);
keywords.put("return", TokenType.RETURN);
keywords.put("continue", TokenType.CONTINUE);
keywords.put("terminate", TokenType.TERMINATE);
keywords.put("order", TokenType.LEXICOGRAPHIC);
keywords.put("all", TokenType.ALL);
keywords.put("previousmove", TokenType.FUNCTION);
keywords.put("nextmove", TokenType.FUNCTION);
keywords.put("getmove", TokenType.FUNCTION);
keywords.put("getoppositemove", TokenType.FUNCTION);
keywords.put("movesexecuted", TokenType.FUNCTION);
keywords.put("movecount", TokenType.FUNCTION);
keywords.put("seqlength", TokenType.FUNCTION);
keywords.put("getchipsleft", TokenType.FUNCTION);
keywords.put("getredkeycount", TokenType.FUNCTION);
keywords.put("getyellowkeycount", TokenType.FUNCTION);
keywords.put("getgreenkeycount", TokenType.FUNCTION);
keywords.put("getbluekeycount", TokenType.FUNCTION);
keywords.put("hasflippers", TokenType.FUNCTION);
keywords.put("hasfireboots", TokenType.FUNCTION);
keywords.put("hassuctionboots", TokenType.FUNCTION);
keywords.put("hasiceskates", TokenType.FUNCTION);
keywords.put("getforegroundtile", TokenType.FUNCTION);
keywords.put("getbackgroundtile", TokenType.FUNCTION);
keywords.put("getplayerx", TokenType.FUNCTION);
keywords.put("getplayery", TokenType.FUNCTION);
keywords.put("move", TokenType.FUNCTION);
keywords.put("distanceto", TokenType.FUNCTION);
keywords.put("gettimeleft", TokenType.FUNCTION);
keywords.put("printe", TokenType.FUNCTION);
for (Tile t : Tile.values()) {
keywords.put(t.name().toLowerCase(), TokenType.TILE);
}
}
public Tokenizer(String code) {
this.code = code;
this.tokens = new ArrayList<>();
tokenize();
}
public ArrayList<Token> getAllTokens() {
return tokens;
}
public ArrayList<Token> getParsableTokens() {
return getFilteredTokens(TokenType.SPACE, TokenType.TAB, TokenType.CARRIAGE_RETURN,
TokenType.NEW_LINE, TokenType.COMMENT, TokenType.VAR);
}
public HashMap<String, Object> getVariables() {
HashMap<String, Object> variables = new HashMap<>();
ArrayList<Token> filteredTokens = getFilteredTokens(TokenType.SPACE, TokenType.TAB, TokenType.CARRIAGE_RETURN,
TokenType.NEW_LINE, TokenType.COMMENT);
for (int i = 0; i < filteredTokens.size(); i++) {
Token token = filteredTokens.get(i);
if (token.type == TokenType.VAR) {
variables.put(filteredTokens.get(i + 1).lexeme, null);
}
}
return variables;
}
private ArrayList<Token> getFilteredTokens(TokenType... types) {
ArrayList<Token> newTokens = new ArrayList<>();
for (Token token : tokens) {
if (!isTokenType(token, types)) {
newTokens.add(token);
}
}
return newTokens;
}
private boolean isTokenType(Token token, TokenType... types) {
for (TokenType type : types) {
if (token.type == type) {
return true;
}
}
return false;
}
private void tokenize() {
while (!isEnd()) {
start = current;
getNextToken();
}
addToken(TokenType.EOF);
}
private void getNextToken() {
char c = getNextChar();
switch (c) {
case '[': addToken(TokenType.LEFT_BRACKET); break;
case ']': addToken(TokenType.RIGHT_BRACKET); break;
case '(': addToken(TokenType.LEFT_PAREN); break;
case ')': addToken(TokenType.RIGHT_PAREN); break;
case '{': addToken(TokenType.LEFT_BRACE); break;
case '}': addToken(TokenType.RIGHT_BRACE); break;
case ',': addToken(TokenType.COMMA); break;
case ';': addToken(TokenType.SEMICOLON);break;
case ':': addToken(TokenType.COLON); break;
case '+': processPlus(); break;
case '-': processMinus(); break;
case '/': processSlash(); break;
case '*': processStar(); break;
case '%': processModulo(); break;
case '=': processEqual(); break;
case '&': processAnd(); break;
case '|': processOr(); break;
case '!': processBang(); break;
case '<': processLess(); break;
case '>': processGreater(); break;
case ' ': addToken(TokenType.SPACE); break;
case '\t': addToken(TokenType.TAB); break;
case '\r': addToken(TokenType.CARRIAGE_RETURN); break;
case '\n': line++; addToken(TokenType.NEW_LINE); break;
default: processOther(c);
}
}
private void processPlus() {
char c = getNextChar();
switch(c) {
case '+': addToken(TokenType.PLUS_PLUS); break;
case '=': addToken(TokenType.PLUS_EQUAL); break;
default: getPrevChar(); addToken(TokenType.PLUS);
}
}
private void processMinus() {
char c = getNextChar();
switch(c) {
case '-': addToken(TokenType.MINUS_MINUS); break;
case '=': addToken(TokenType.MINUS_EQUAL); break;
default: getPrevChar(); addToken(TokenType.MINUS);
}
}
private void processSlash() {
char c = getNextChar();
switch(c) {
case '/': processComment(); break;
case '=': addToken(TokenType.SLASH_EQUAL); break;
default: getPrevChar(); addToken(TokenType.SLASH);
}
}
private void processComment() {
while (getChar() != '\n' && !isEnd()) {
getNextChar();
}
addToken(TokenType.COMMENT);
}
private void processStar() {
char c = getNextChar();
switch(c) {
case '=': addToken(TokenType.STAR_EQUAL); break;
default: getPrevChar(); addToken(TokenType.STAR);
}
}
private void processModulo() {
char c = getNextChar();
switch(c) {
case '=': addToken(TokenType.MODULO_EQUAL); break;
default: getPrevChar(); addToken(TokenType.MODULO);
}
}
private void processEqual() {
char c = getNextChar();
switch(c) {
case '=': addToken(TokenType.EQUAL_EQUAL); break;
default: getPrevChar(); addToken(TokenType.EQUAL);
}
}
private void processAnd() {
char c = getNextChar();
switch(c) {
case '&': addToken(TokenType.AND_AND); break;
default: getPrevChar(); addToken(TokenType.OTHER);
}
}
private void processOr() {
char c = getNextChar();
switch(c) {
case '|': addToken(TokenType.OR_OR); break;
default: getPrevChar(); addToken(TokenType.OTHER);
}
}
private void processBang() {
char c = getNextChar();
switch(c) {
case '=': addToken(TokenType.BANG_EQUAL); break;
default: getPrevChar(); addToken(TokenType.BANG);
}
}
private void processLess() {
char c = getNextChar();
switch(c) {
case '=': addToken(TokenType.LESS_EQUAL); break;
default: getPrevChar(); addToken(TokenType.LESS);
}
}
private void processGreater() {
char c = getNextChar();
switch(c) {
case '=': addToken(TokenType.GREATER_EQUAL); break;
default: getPrevChar(); addToken(TokenType.GREATER);
}
}
private void processOther(char c) {
if (isDigit(c)) {
processNumber();
} else if (isAlpha(c)) {
processIdentifier();
} else {
addToken(TokenType.OTHER);
}
}
private void processNumber() {
while (isDigit(getChar())) {
getNextChar();
}
if (getChar() == '.') {
getNextChar();
while (isDigit(getChar())) {
getNextChar();
}
} else if (isMove(getChar())) {
processMultipleMoves();
return;
}
String substr = code.substring(start, current);
addToken(TokenType.NUMBER, Double.parseDouble(substr));
}
private boolean isMove(char c) {
return moves.contains(c + "");
}
private void processMultipleMoves() {
while (isMove(getChar())) {
getNextChar();
}
String substr = code.substring(start, current);
addToken(TokenType.MOVE, substr.toLowerCase());
}
private void processIdentifier() {
while (isAlphaNumeric(getChar())) {
getNextChar();
}
String substr = code.substring(start, current);
TokenType type = keywords.get(substr.toLowerCase());
if (type == null) {
type = TokenType.OTHER;
}
switch (type) {
case OTHER: processNonKeyword(substr); break;
case TILE: addToken(type, substr.toUpperCase()); break;
default: addToken(type);
}
}
private void processNonKeyword(String substr) {
if (isMoveString(substr)) {
addToken(TokenType.MOVE, substr.toLowerCase());
} else {
addToken(TokenType.IDENTIFIER, substr);
}
}
private boolean isMoveString(String substr) {
boolean move = true;
for (int i = 0; i < substr.length(); i++) {
if (!isMove(substr.charAt(i))) {
move = false;
break;
}
}
return move;
}
private char getNextChar() {
if(isEnd()) return '\0';
current++;
return code.charAt(current - 1);
}
private char getPrevChar() {
if(isEnd()) return '\0';
current--;
return code.charAt(current);
}
private boolean isDigit(char c) {
return c >= '0' && c <= '9';
}
private boolean isAlpha(char c) {
return (c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
c == '_' || c == '@' || c == '#' || c == '$';
}
private boolean isAlphaNumeric(char c) {
return isDigit(c) || isAlpha(c);
}
private char getChar() {
if (isEnd()) {
return '\0';
}
return code.charAt(current);
}
private boolean isEnd() {
return this.current >= this.code.length();
}
private void addToken(TokenType type) {
addToken(type, null);
}
private void addToken(TokenType type, Object value) {
String lexeme = code.substring(start, current);
tokens.add(new Token(type, lexeme, value, line));
}
}
| 12,182 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
TokenType.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/tools/variation/TokenType.java | package tools.variation;
public enum TokenType {
// Structural
LEFT_BRACKET, RIGHT_BRACKET, LEFT_PAREN, RIGHT_PAREN,
LEFT_BRACE, RIGHT_BRACE, COMMA, SEMICOLON, COLON,
// Operations
PLUS, MINUS, PLUS_PLUS, MINUS_MINUS, SLASH, STAR, MODULO,
EQUAL, PLUS_EQUAL, MINUS_EQUAL, SLASH_EQUAL, STAR_EQUAL, MODULO_EQUAL,
AND_AND, OR_OR, BANG,
// Comparison
EQUAL_EQUAL, BANG_EQUAL,
LESS, LESS_EQUAL, GREATER, GREATER_EQUAL,
// Values
IDENTIFIER, NUMBER, MOVE, FUNCTION, TILE,
// Keywords
START, BEFORE_MOVE, AFTER_MOVE, BEFORE_STEP, AFTER_STEP, END,
IF, ELSE, FOR, TRUE, FALSE, NULL, VAR, PRINT, BREAK,
AND, OR, NOT,
// Sequence control
RETURN, CONTINUE, TERMINATE, LEXICOGRAPHIC, ALL,
// Unimportant in parsing
SPACE, TAB, CARRIAGE_RETURN, NEW_LINE, COMMENT,
// Unknown
OTHER,
// End
EOF
}
| 887 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
FunctionEvaluator.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/tools/variation/FunctionEvaluator.java | package tools.variation;
import emulator.SuperCC;
import game.Position;
import util.CharList;
import java.awt.*;
import java.util.ArrayList;
public class FunctionEvaluator {
private SuperCC emulator;
private Interpreter interpreter;
private VariationManager manager;
public FunctionEvaluator(SuperCC emulator, Interpreter interpreter, VariationManager manager) {
this.emulator = emulator;
this.interpreter = interpreter;
this.manager = manager;
}
public Object evaluate(Expr.Function function) {
switch(function.name) {
case "previousmove":
checkArgCount(function, 0);
return previousMove();
case "nextmove":
checkArgCount(function, 0);
return nextMove();
case "getmove":
checkArgCount(function, 1);
Object index = function.arguments.get(0).evaluate(interpreter);
checkIfNumber(function, index);
return getMoveAt(((Double)index).intValue());
case "getoppositemove":
checkArgCount(function, 1);
Object move = function.arguments.get(0).evaluate(interpreter);
checkIfMove(function, move);
return getOppositeMove((Move)move);
case "movesexecuted":
checkArgCount(function, 0);
return movesExecuted();
case "movecount":
checkArgCount(function, 1);
move = function.arguments.get(0).evaluate(interpreter);
checkIfMove(function, move);
return moveCount((Move)move);
case "seqlength":
checkArgCount(function, 0);
return seqLength();
case "getchipsleft":
checkArgCount(function, 0);
return (double)emulator.getLevel().getChipsLeft();
case "getredkeycount":
checkArgCount(function, 0);
return (double)emulator.getLevel().getKeys()[1];
case "getyellowkeycount":
checkArgCount(function, 0);
return (double)emulator.getLevel().getKeys()[3];
case "getgreenkeycount":
checkArgCount(function, 0);
return (double)emulator.getLevel().getKeys()[2];
case "getbluekeycount":
checkArgCount(function, 0);
return (double)emulator.getLevel().getKeys()[0];
case "hasflippers":
checkArgCount(function, 0);
return emulator.getLevel().getBoots()[0] != 0;
case "hasfireboots":
checkArgCount(function, 0);
return emulator.getLevel().getBoots()[1] != 0;
case "hassuctionboots":
checkArgCount(function, 0);
return emulator.getLevel().getBoots()[3] != 0;
case "hasiceskates":
checkArgCount(function, 0);
return emulator.getLevel().getBoots()[2] != 0;
case "getforegroundtile":
checkArgCount(function, 2);
Object x = function.arguments.get(0).evaluate(interpreter);
Object y = function.arguments.get(1).evaluate(interpreter);
checkIfNumber(function, x, y);
return emulator.getLevel().getLayerFG().get(new Position(((Double)x).intValue(), ((Double)y).intValue()));
case "getbackgroundtile":
checkArgCount(function, 2);
x = function.arguments.get(0).evaluate(interpreter);
y = function.arguments.get(1).evaluate(interpreter);
checkIfNumber(function, x, y);
return emulator.getLevel().getLayerBG().get(new Position(((Double)x).intValue(), ((Double)y).intValue()));
case "getplayerx":
checkArgCount(function, 0);
return (double)emulator.getLevel().getChip().getPosition().getX();
case "getplayery":
checkArgCount(function, 0);
return (double)emulator.getLevel().getChip().getPosition().getY();
case "move":
return move(function.arguments);
case "distanceto":
checkArgCount(function, 2);
x = function.arguments.get(0).evaluate(interpreter);
y = function.arguments.get(1).evaluate(interpreter);
checkIfNumber(function, x, y);
int playerX = emulator.getLevel().getChip().getPosition().getX();
int playerY = emulator.getLevel().getChip().getPosition().getY();
return Math.abs(playerX - ((Double)x).intValue()) + Math.abs(playerY - ((Double)y).intValue());
case "gettimeleft":
checkArgCount(function, 0);
int time = emulator.getLevel().getTimer();
if(emulator.getLevel().isUntimed()) time = emulator.getLevel().getTChipTime();
return (double)time / 100;
case "printe":
interpreter.print("e\n", Color.WHITE);
return null;
}
return null;
}
private Move previousMove() {
int atSequence = interpreter.atSequence;
int atMove = interpreter.atMove - 1;
if(!interpreter.inSequence) {
if(atSequence == 0) {
return null;
}
atSequence--;
}
else {
if(atMove < 0) {
atSequence--;
if(atSequence < 0) {
return null;
}
atMove = manager.getPermutation(atSequence).length - 1;
}
}
CharList moves = manager.getPermutation(atSequence)[atMove];
return getMove(moves.get(moves.size() - 1));
}
private Move nextMove() {
int atSequence = interpreter.atSequence;
int atMove = interpreter.atMove;
if(!interpreter.inSequence && atSequence > 0) {
if(atSequence > manager.getSequenceCount()) {
return null;
}
atMove = 0;
}
else {
if(atMove >= manager.getPermutation(atSequence).length) {
if(atSequence < manager.getSequenceCount() - 1) {
atSequence++;
atMove = 0;
}
else {
return null;
}
}
}
CharList moves = manager.getPermutation(atSequence)[atMove];
return getMove(moves.get(0));
}
private Move getMove(char move) {
switch(move) {
case SuperCC.UP:
return new Move("u");
case SuperCC.RIGHT:
return new Move("r");
case SuperCC.DOWN:
return new Move("d");
case SuperCC.LEFT:
return new Move("l");
case 'w':
return new Move("w");
case SuperCC.WAIT:
return new Move("h");
}
return null;
}
private Move getMoveAt(int index) {
int sum = 0;
int prevSum = 0;
for(int i = 0; i < manager.getSequenceCount(); i++) {
sum += manager.getPermutation(i).length;
if(index < sum) {
return getMove(manager.getPermutation(i)[index - prevSum].get(0));
}
prevSum = 0;
}
return null;
}
private Move getOppositeMove(Move move) {
switch(move.move.charAt(0)) {
case SuperCC.UP:
return new Move(String.valueOf(SuperCC.DOWN));
case SuperCC.RIGHT:
return new Move(String.valueOf(SuperCC.LEFT));
case SuperCC.LEFT:
return new Move(String.valueOf(SuperCC.RIGHT));
case SuperCC.DOWN:
return new Move(String.valueOf(SuperCC.UP));
}
return move;
}
private double movesExecuted() {
int atSequence = interpreter.atSequence;
int atMove = interpreter.atMove;
int sum = 0;
for(int i = 0; i < atSequence; i++) {
sum += manager.getPermutation(i).length;
}
if(atSequence > 0) {
if(atMove >= manager.getPermutation(atSequence - 1).length) {
atMove = 0;
}
}
return (double)sum + atMove;
}
private double moveCount(Move move) {
char moveByte = move.move.charAt(0);
double count = 0;
for(int i = 0; i < manager.getSequenceCount(); i++) {
for(CharList cl : manager.getPermutation(i)) {
for(char c : cl) {
if (c == moveByte) {
count++;
}
}
}
}
return count;
}
private double seqLength() {
double length = 0;
for(int i = 0; i < manager.getSequenceCount(); i++) {
length += manager.getPermutation(i).length;
}
return length;
}
private Object move(ArrayList<Expr> arguments) {
for(Expr arg : arguments) {
Move move = (Move)arg.evaluate(interpreter);
String str = move.move;
for(int i = 0; i < move.number; i++) {
for(int j = 0; j < str.length(); j++) {
char moveDir = str.charAt(j);
interpreter.doMove(moveDir);
}
}
}
return null;
}
// private char toByte(char c) {
// switch(c) {
// case 'u':
// return SuperCC.UP;
// case 'r':
// return SuperCC.RIGHT;
// case 'd':
// return SuperCC.DOWN;
// case 'l':
// return SuperCC.LEFT;
// case 'w':
// return 'w';
// default:
// return SuperCC.WAIT;
// }
// }
private void checkArgCount(Expr.Function function, int required) {
if(function.arguments.size() != required) {
throw new Interpreter.RuntimeError(function.token,
"Expected " + required + " arguments, got " + function.arguments.size());
}
}
private void checkIfMove(Expr.Function function, Object arg1) {
if(arg1 instanceof Move) {
return;
}
throw new Interpreter.RuntimeError(function.token, "Argument must be a move");
}
private void checkIfNumber(Expr.Function function, Object... args) {
for(Object arg : args) {
if(!(arg instanceof Double)) {
throw new Interpreter.RuntimeError(function.token, "Argument must be a number");
}
}
}
}
| 10,848 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
MovePool.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/tools/variation/MovePool.java | package tools.variation;
import java.util.HashMap;
import java.util.Objects;
public class MovePool {
public HashMap<String, Integer> moves = new HashMap<>();
public int size = 0;
public MovePool() {
}
public void add(Move move) {
if(moves.get(move.move) == null) {
moves.put(move.move, move.number);
size += move.number;
return;
}
int value = moves.get(move.move);
moves.put(move.move, value + move.number);
size += move.number;
}
public void add(MovePool movePool) {
for(String key : movePool.moves.keySet()) {
int keyValue = movePool.moves.get(key);
if(moves.get(key) == null) {
moves.put(key, keyValue);
}
else {
int value = moves.get(key);
moves.put(key, value + keyValue);
}
size += keyValue;
}
}
public void add(MovePoolContainer movePools) {
add(movePools.optional);
add(movePools.forced);
}
public void clear() {
moves.clear();
size = 0;
}
public void replace(MovePool movePool) {
clear();
add(movePool);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MovePool movePool = (MovePool) o;
return size == movePool.size &&
Objects.equals(moves, movePool.moves);
}
@Override
public int hashCode() {
return Objects.hash(moves, size);
}
}
| 1,632 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
Move.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/tools/variation/Move.java | package tools.variation;
public class Move {
public final String value;
public final int number;
public final String move;
public Move(String value) {
this.value = value;
int numIndex = 0;
while(value.charAt(numIndex) >= '0' && value.charAt(numIndex) <= '9') {
numIndex++;
}
String num = value.substring(0, numIndex);
this.number = num.equals("") ? 1 : Math.max(Integer.parseInt(num), 1);
this.move = value.substring(numIndex);
}
@Override
public String toString() {
return value;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Move) {
return this.number == ((Move) obj).number && this.move.equals(((Move) obj).move);
}
return false;
}
}
| 818 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
Permutation.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/tools/variation/Permutation.java | package tools.variation;
import util.CharList;
import java.util.Arrays;
public class Permutation {
private MovePoolContainer movePools;
public BoundLimit limits;
private int[] permutation;
public boolean finished = false;
private Multiset set;
private int[] subset;
private int currentSize;
private String lexicographic;
public double permutationCount;
public double permutationValidCount;
public int startingMove;
public static double LIMIT = 1e18;
public Permutation(MovePoolContainer movePools, BoundLimit limits, String lexicographic) {
this.movePools = movePools;
this.limits = limits;
limits.setBounds(movePools);
this.set = new Multiset(movePools, limits, lexicographic);
this.subset = this.set.getSubset();
this.currentSize = this.limits.lower;
this.lexicographic = lexicographic;
this.permutationCount = calculatePermutationCount();
this.permutationValidCount = calculatePermutationValidCount();
initialPermutation();
}
/**
* This algorithm represents permutations as arrays where each index i is the i-th move.
* The value at each index is its specified order within the permutation.
* If each value is interpreted as a digit, the next permutation is the next possible larger number.
* E.g. in default order (urdlwh), if the move pool consists of [2u, r, l],
* the first permutation is [1, 1, 2, 3], and the next one is [1, 1, 3, 2] then [1, 2, 1, 3] then [1, 2, 3, 1] etc.
* 1123 -> 1132 -> 1213 -> 1231
*/
public void nextPermutation() {
int i = getFirstDescendingIndex();
startingMove = i;
if(i == -1) {
endOfCurrentSubset();
return;
}
int j = getNextLargerIndex(i);
swap(i, j);
reverseSubarray(i + 1);
}
public CharList[] getPermutation() {
if(finished) {
return null;
}
CharList[] moves = new CharList[currentSize];
for(int i = 0; i < currentSize; i++) {
moves[i] = this.set.movesList[permutation[i]];
}
return moves;
}
public int[] getRawPermutation() {
return permutation;
}
public int getUpperLimit() {
return limits.upper;
}
// Returns double due to potentially large value
private double calculatePermutationCount() {
return set.getTotalPermutationCount();
}
private double calculatePermutationValidCount() {
return set.getTotalValidPermutationCount();
}
public void reset() {
set.reset();
finished = false;
currentSize = limits.lower;
initialPermutation();
startingMove = 0;
}
public void terminate(int index) {
Arrays.sort(permutation, index + 1, permutation.length);
for(int i = index + 1; i < (index + 2 + permutation.length)/2; i++) {
int temp = permutation[i];
permutation[i] = permutation[permutation.length - i + index];
permutation[permutation.length - i + index] = temp;
}
}
public void end() {
terminate(-1);
finished = true;
}
public double getPermutationIndex() {
double index = 0;
double potential = uniquePermutations(currentSize, subset);
int[] currentSubset = subset.clone();
for(int position = 0, currentLength = currentSize; position < currentSize - 1 && potential > 1; position++, currentLength--) {
int offset = 0;
for(int i = 0; i < permutation[position]; i++) {
offset += currentSubset[i];
}
index += (potential * offset) / currentLength;
potential *= currentSubset[permutation[position]];
potential /= currentLength;
currentSubset[permutation[position]]--;
}
// System.out.println(index + set.getCumulativePermutationCount() + " " + set.setIndex + " " + index + " " +
// set.cumulativePermutationCounts.get(set.setIndex));
return index + set.getCumulativePermutationCount();
}
private int getFirstDescendingIndex() {
for(int i = currentSize - 2; i >= 0; i--) {
if(permutation[i] < permutation[i + 1]) {
return i;
}
}
return -1;
}
private void endOfCurrentSubset() {
set.nextSubset();
if(!set.finished) {
currentSize = set.currentSize;
initialPermutation();
return;
}
finished = true;
}
private int getNextLargerIndex(int to) {
for(int i = currentSize - 1; i > to; i--) {
if(permutation[to] < permutation[i]) {
return i;
}
}
return to;
}
private void swap(int i, int j) {
int temp = permutation[i];
permutation[i] = permutation[j];
permutation[j] = temp;
}
private void reverseSubarray(int from) {
for(int i = 0; i < (currentSize - from)/2; i++) {
swap(from + i, currentSize - 1 - i);
}
}
private void initialPermutation() {
permutation = new int[currentSize];
int i = 0;
for(int j = 0; j < subset.length; j++) {
for(int k = 0; k < subset[j]; k++) {
permutation[i++] = j;
}
}
}
private double factorial(int n) {
if(n == 0 || n == 1) {
return 1;
}
return (double)n * factorial(n - 1);
}
private double uniquePermutations(int n, int[] moves) {
double denominator = 1;
for (int move : moves) {
denominator *= factorial(move);
}
return factorial(n)/denominator;
}
}
| 5,832 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
SequenceLifecycle.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/tools/variation/SequenceLifecycle.java | package tools.variation;
import java.util.Objects;
public class SequenceLifecycle {
public Stmt start = new Stmt.Empty();
public Stmt beforeMove = new Stmt.Empty();
public Stmt afterMove = new Stmt.Empty();
public Stmt beforeStep = new Stmt.Empty();
public Stmt afterStep = new Stmt.Empty();
public Stmt end = new Stmt.Empty();
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SequenceLifecycle lifecycle = (SequenceLifecycle) o;
return Objects.equals(start, lifecycle.start) &&
Objects.equals(beforeMove, lifecycle.beforeMove) &&
Objects.equals(afterMove, lifecycle.afterMove) &&
Objects.equals(beforeStep, lifecycle.beforeStep) &&
Objects.equals(afterStep, lifecycle.afterStep) &&
Objects.equals(end, lifecycle.end);
}
@Override
public int hashCode() {
return Objects.hash(start, beforeMove, afterMove, beforeStep, afterStep, end);
}
}
| 1,092 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
GamePanel.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/graphics/GamePanel.java | package graphics;
import emulator.SuperCC;
import emulator.TickFlags;
import game.*;
import game.MS.*;
import game.button.ConnectionButton;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.util.Collection;
import java.util.List;
import static game.Position.UNCLICKABLE;
public abstract class GamePanel extends JPanel
implements MouseMotionListener, MouseListener {
static final int CHANNELS = 4, SMALL_NUMERAL_WIDTH = 3, SMALL_NUMERAL_HEIGHT = 5;
protected int tileHeight, tileWidth;
protected double hBetweenTiles, vBetweenTiles;
private TileSheet tileSheet;
protected Position screenTopLeft = new Position(0, 0);
protected static final int[][]
blackDigits = new int[10][(SMALL_NUMERAL_WIDTH+2)*(SMALL_NUMERAL_HEIGHT+2)*CHANNELS],
blueDigits = new int[10][(SMALL_NUMERAL_WIDTH+2)*(SMALL_NUMERAL_HEIGHT+2)*CHANNELS];
static int[][] tileImage, overlayTileImage;
static Image[][] creatureImages;
protected boolean showMonsterListNumbers = true, showSlipListNumbers = true; //Makes sure that the BG layer, the slip list, and the monster list show by default
protected boolean showTrapConnections, showCloneConnections, showHistory;
// The background image
protected BufferedImage lowerImage;
// The foreground image
protected BufferedImage upperImage;
// The image behind the background (32*32 floor tiles)
protected BufferedImage backingImage;
//Where extras are drawn (slip/monster list #s, move history, etc.)
protected BufferedImage overlayImage;
protected SuperCC emulator;
protected ConnectionButton hoveredButton;
public void setEmulator(SuperCC emulator){
this.emulator = emulator;
}
public void setTileSheet(TileSheet ts) {
this.tileSheet = ts;
}
public TileSheet getTileSheet() {
return tileSheet;
}
public int getTileWidth() {
return tileWidth;
}
public int getTileHeight() {
return tileHeight;
}
@Override
public void paintComponent(Graphics g){
g.drawImage(backingImage, 0, 0, null);
g.drawImage(lowerImage, 0, 0, null);
g.drawImage(upperImage, 0, 0, null);
g.drawImage(overlayImage, 0, 0, null);
}
public static void drawNumber(int n, int[][] digitRaster, int x, int y, WritableRaster raster){
char[] chars = (String.valueOf(n)).toCharArray();
for (int j = 0; j < chars.length; j++){
int digit = Character.digit(chars[j], 10);
raster.setPixels(x+4*j, y, SMALL_NUMERAL_WIDTH+2, SMALL_NUMERAL_HEIGHT+2, digitRaster[digit]);
}
}
protected abstract void drawLevel(Level level, boolean fromScratch);
protected abstract void drawMonsterListNumbers(Level level, CreatureList monsterList, BufferedImage overlay);
protected abstract void drawSlipListNumbers(SlipList monsterList, BufferedImage overlay);
protected abstract void drawButtonConnections(Collection<? extends ConnectionButton> connections, BufferedImage overlay, Color color);
public abstract void drawPositionList(List<Position> positionList, Graphics2D g);
protected abstract void drawChipHistory(Position currentPosition, BufferedImage overlay);
void updateGraphics(boolean fromScratch) {
Level level = emulator.getLevel();
drawLevel(level, fromScratch);
overlayImage = new BufferedImage(32 * tileWidth, 32 * tileHeight, BufferedImage.TYPE_4BYTE_ABGR);
if (showMonsterListNumbers) drawMonsterListNumbers(level, level.getMonsterList(), overlayImage);
if (showSlipListNumbers && level.supportsSliplist()) drawSlipListNumbers(level.getSlipList(), overlayImage);
if (showCloneConnections) drawButtonConnections(level.getRedButtons().allValues(), overlayImage, Color.BLACK);
if (showTrapConnections) drawButtonConnections(level.getBrownButtons().allValues(), overlayImage, Color.BLACK);
if (hoveredButton != null) drawButtonConnections(List.of(hoveredButton), overlayImage, Color.RED);
if (showHistory) drawChipHistory(level.getChip().getPosition(), overlayImage);
}
public void setMonsterListVisible(boolean visible){
showMonsterListNumbers = visible;
}
public void setSlipListVisible(boolean visible){
showSlipListNumbers = visible;
}
public void setTrapsVisible(boolean visible){
showTrapConnections = visible;
}
public void setClonesVisible(boolean visible){
showCloneConnections = visible;
}
public void setHistoryVisible(boolean visible){
showHistory = visible;
}
protected static BufferedImage drawDigit(int n, Color colorBG, Color colorFG){
int[] smallNumeralBitmap = new int[] {
0b111_010_111_111_101_111_111_111_111_111_00,
0b101_010_001_001_101_100_100_001_101_101_00,
0b101_010_111_111_111_111_111_001_111_111_00,
0b101_010_100_001_001_001_101_001_101_001_00,
0b111_010_111_111_001_111_111_001_111_111_00
};
BufferedImage digit = new BufferedImage(SMALL_NUMERAL_WIDTH+2, SMALL_NUMERAL_HEIGHT+2, BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D graphics = digit.createGraphics();
graphics.setPaint(colorBG);
graphics.fillRect(0, 0, digit.getWidth(), digit.getHeight());
int rgb = colorFG.getRGB();
for (int y = 0; y < SMALL_NUMERAL_HEIGHT; y++){
for (int x = 0; x < SMALL_NUMERAL_WIDTH; x++) {
if (((smallNumeralBitmap[y] << (x + 3*n)) & 0x80000000) == 0x80000000){
digit.setRGB(x+1, y+1, rgb);
}
}
}
return digit;
}
protected void initialiseDigits(){
for (int n = 0; n <= 9; n++){
BufferedImage digitBlue = drawDigit(n, Color.BLUE, Color.WHITE);
digitBlue.getRaster().getPixels(0, 0, digitBlue.getWidth(), digitBlue.getHeight(), blueDigits[n]);
BufferedImage digitBlack = drawDigit(n, Color.BLACK, Color.WHITE);
digitBlack.getRaster().getPixels(0, 0, digitBlue.getWidth(), digitBlue.getHeight(), blackDigits[n]);
}
}
protected abstract void initialiseTileGraphics(BufferedImage tilespng);
protected abstract void initialiseOverlayGraphics(BufferedImage tilespng);
protected abstract void initialiseCreatureGraphics(BufferedImage overlayImage, BufferedImage tilesImage);
protected abstract void initialiseLayers();
public void initialise(SuperCC emulator, BufferedImage[] tilespng, TileSheet tileSheet, int tileWidth, int tileHeight) {
this.emulator = emulator;
this.tileWidth = tileWidth;
this.tileHeight = tileHeight;
this.hBetweenTiles = tileWidth / 8.0;
this.vBetweenTiles = tileHeight / 8.0;
this.tileSheet = tileSheet;
initialiseDigits();
initialiseTileGraphics(tilespng[0]);
initialiseOverlayGraphics(tilespng[1]);
initialiseCreatureGraphics(tilespng[1], tilespng[0]);
initialiseLayers();
if (getMouseListeners().length == 0) { //Just so you don't add extra mouse listeners when you update tilesize or something
addMouseListener(this);
addMouseMotionListener(this); //I don't check existing motion listeners cause its always the same number of them as the normal mouse listener
}
}
class GamePopupMenu extends JPopupMenu {
GamePopupMenu(Position position) {
add(new JLabel("Cheats", SwingConstants.CENTER));
Level level = emulator.getLevel();
Cheats cheats = level.getCheats();
Tile tileFG = level.getLayerFG().get(position);
Tile[] tiles;
if(level.supportsLayerBG()) {
Tile tileBG = level.getLayerBG().get(position);
tiles = new Tile[] {tileFG, tileBG};
} else {
tiles = new Tile[] {tileFG};
}
for (Tile tile : tiles) {
if (tile.isButton()) {
JMenuItem press = new JMenuItem("Press button");
press.addActionListener((e) -> {
cheats.pressButton(position);
updateGraphics(false);
emulator.getMainWindow().repaint();
});
add(press);
}
if (tile == Tile.TRAP && !level.trapRequiresHeldButton()) {
JMenuItem open = new JMenuItem("Open Trap");
open.addActionListener((e) -> cheats.setTrap(position, true));
add(open);
JMenuItem close = new JMenuItem("Close Trap");
close.addActionListener((e) -> cheats.setTrap(position, false));
add(close);
}
Creature c = emulator.getLevel().getMonsterList().creatureAt(position, false);
if (c == null) {
if (tile.isMonster()) {
JMenuItem animate = new JMenuItem("Animate Monster");
animate.addActionListener(e -> cheats.animateMonster(position));
add(animate);
}
}
}
Creature c = emulator.getLevel().getMonsterList().creatureAt(position, level.chipInMonsterList());
if (c != null) {
JMenu setDirection = new JMenu("Change Creature's Direction");
for (Direction d : Direction.CARDINALS) {
JMenuItem menuItem = new JMenuItem(d.toString());
menuItem.addActionListener((e) -> {
cheats.setDirection(c, d);
updateGraphics(false);
emulator.getMainWindow().repaint();
});
setDirection.add(menuItem);
}
add(setDirection);
JMenuItem kill = new JMenuItem("Kill Creature");
kill.addActionListener((e) -> {
cheats.kill(c);
updateGraphics(false);
emulator.getMainWindow().repaint();
});
add(kill);
}
if (position.equals(emulator.getLevel().getChip().getPosition()) && emulator.getLevel().getChip().isDead()) {
JMenuItem revive = new JMenuItem("Revive Chip");
revive.addActionListener((e) -> {
cheats.reviveChip();
updateGraphics(false);
emulator.getMainWindow().repaint();
});
add(revive);
}
JMenuItem teleportChip = new JMenuItem("Move Chip Here");
teleportChip.addActionListener((e) -> {
cheats.moveChip(position);
updateGraphics(false);
emulator.getMainWindow().repaint();
});
add(teleportChip);
if (c == null) {
JMenuItem pop = new JMenuItem("Remove Tile: " + tileFG.toString());
pop.addActionListener((e) -> {
if(emulator.getLevel().supportsSliplist()) {
emulator.getLevel().getSlipList().removeIf(creature -> creature.getPosition().equals(position)); //In practice this only affects sliding blocks
}
cheats.popTile(position);
updateGraphics(false);
emulator.getMainWindow().repaint();
});
add(pop);
}
JMenu insertTile = new JMenu("Insert Tile");
Tile[] allTiles = Tile.values();
for (int i = 0; i < allTiles.length; i+= 0x10) {
if (!level.creaturesAreTiles() && (Tile.BUG_UP.ordinal() <= i && i <= Tile.BLOB_RIGHT.ordinal()))
continue;
JMenu tileSubsetMenu = new JMenu(String.format("0x%02X - 0x%02X", i, i+0XF));
for (int j = i; j < i + 0x10; j++) {
Tile t = allTiles[j];
if (!level.creaturesAreTiles() && (t.isCreature() || t.isChip() || t.isBlock() || t.isSwimmingChip()))
continue;
JMenuItem menuItem = new JMenuItem(String.format("0x%02X - %s", j, t.toString()));
menuItem.addActionListener((e) -> {
cheats.insertTile(position, t);
updateGraphics(false);
emulator.getMainWindow().repaint();
});
tileSubsetMenu.add(menuItem);
}
insertTile.add(tileSubsetMenu);
}
add(insertTile);
JMenuItem insertCreature = new JMenu("Insert Creature");
CreatureID[] allIDs = CreatureID.values();
for (CreatureID id : allIDs) {
//ah, the mess that is different rulesets
if (!level.hasStillTanks() && id == CreatureID.TANK_STATIONARY)
continue;
if (!level.blocksInMonsterList() && id.isBlock() || id == CreatureID.ICE_BLOCK)
continue;
if (!level.swimmingChipIsCreature() && id == CreatureID.CHIP_SWIMMING)
continue;
if (id.isChip() || id == CreatureID.DEAD)
continue;
JMenu dirSubMenu = new JMenu(id.prettyPrint());
Direction[] cardinals = Direction.CARDINALS;
for (Direction d : cardinals) {
JMenuItem menuItem = new JMenuItem(d.toString());
menuItem.addActionListener(e -> {
cheats.insertCreature(d, id, position);
emulator.getMainWindow().repaint(false);
});
dirSubMenu.add(menuItem);
}
insertCreature.add(dirSubMenu);
}
add(insertCreature);
}
}
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {
mousePressedOrReleased(e, true);
}
public void mouseReleased(MouseEvent e) {
mousePressedOrReleased(e, false);
}
private void mousePressedOrReleased(MouseEvent e, boolean checkLeft) {
if(emulator.isLevelLoaded()) {
Position clickPosition = new Position(e.getX() / tileWidth + screenTopLeft.getX(), e.getY() / tileHeight + screenTopLeft.getY());
if (e.isPopupTrigger()) //docs for this say that it should be checked on both press and release
rightClick(clickPosition, e);
else if (checkLeft && SwingUtilities.isLeftMouseButton(e))
leftClick(clickPosition);
}
}
private void leftClick(Position clickPosition) {
if(emulator.isLevelLoaded()) {
if (!emulator.getLevel().supportsClick()) return;
MSCreature chip = (MSCreature) emulator.getLevel().getChip(); //Relies on MS code, might want to refactor that
if (!emulator.getLevel().getChip().isDead() && !SuperCC.areToolsRunning()) {
char c = clickPosition.clickChar(chip.getPosition());
if (c == UNCLICKABLE) return;
emulator.showAction("Clicked " + clickPosition);
emulator.getLevel().setClick(clickPosition.getIndex());
Direction[] directions = chip.seek(clickPosition);
emulator.tick(c, directions, TickFlags.GAME_PLAY);
}
}
}
private void rightClick(Position clickPosition, MouseEvent e) {
if(emulator.isLevelLoaded()) {
GamePanel.GamePopupMenu popupMenu = new GamePopupMenu(clickPosition);
popupMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseDragged(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {
if (emulator.isLevelLoaded()) {
Level level = emulator.getLevel();
Position pos = new Position(e.getX() / tileWidth + screenTopLeft.getX(), e.getY() / tileHeight + screenTopLeft.getY());
Tile bgTile = null;
Tile fgTile;
if (level.supportsLayerBG())
bgTile = level.getLayerBG().get(pos);
fgTile = level.getLayerFG().get(pos);
String str = pos + " " + fgTile;
if (level.supportsLayerBG()) {
if (bgTile != Tile.FLOOR) str += " / " + bgTile;
}
emulator.showAction(str);
hoveredButton = null;
boolean fgButton = fgTile == Tile.BUTTON_BROWN || fgTile == Tile.BUTTON_RED;
boolean bgButton = level.supportsLayerBG() && (bgTile == Tile.BUTTON_BROWN || bgTile == Tile.BUTTON_RED);
if (fgButton || bgButton) {
hoveredButton = (ConnectionButton) emulator.getLevel().getButton(pos); //red and brown buttons SHOULD always be safe to downcast like this
}
emulator.getMainWindow().repaint(false);
}
}
}
| 17,626 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
SmallGamePanel.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/graphics/SmallGamePanel.java | package graphics;
import game.*;
import game.MS.*;
import game.button.ConnectionButton;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
public class SmallGamePanel extends GamePanel {
private Position screenBottomRight; // not included
private int windowSizeX, windowSizeY;
private byte[] previousLayerFG = new byte[32*32];
private byte[] previousLayerBG = new byte[32*32];
private Position previousScreenTopLeft = new Position(-1, -1);
private static final double[] offsets = new double[] {
(double) 7/15 + (double) 1/30,
(double) 3/15 + (double) 1/30,
(double) 11/15 + (double) 1/30,
(double) 5/15 + (double) 1/30,
(double) 9/15 + (double) 1/30,
(double) 1/15 + (double) 1/30,
(double) 13/15 + (double) 1/30,
(double) 4/15 + (double) 1/30,
(double) 10/15 + (double) 1/30,
(double) 2/15 + (double) 1/30,
(double) 12/15 + (double) 1/30,
(double) 6/15 + (double) 1/30,
(double) 8/15 + (double) 1/30,
(double) 0/15 + (double) 1/30,
(double) 14/15 + (double) 1/30
};
public void setWindowSize(int windowSizeX, int windowSizeY) {
this.windowSizeX = windowSizeX;
this.windowSizeY = windowSizeY;
try {
super.initialise(emulator, getTileSheet().getTileSheets(tileWidth, tileHeight), getTileSheet(), tileWidth, tileHeight);
}
catch (IOException e) {}
}
public int getWindowSizeX() {
return windowSizeX;
}
public int getWindowSizeY() {
return windowSizeY;
}
private boolean onScreen(Position p) {
return screenTopLeft.getX() <= p.getX() && p.getX() < screenBottomRight.getX()
&& screenTopLeft.getY() <= p.getY() && p.getY() < screenBottomRight.getY();
}
//onScreen but with one more tile per edge, useful for things like Lynx which can have monsters between tiles
private boolean onScreenExtended(Position p) {
return screenTopLeft.getX() - 1 <= p.getX() && p.getX() < screenBottomRight.getX() + 1
&& screenTopLeft.getY() - 1 <= p.getY() && p.getY() < screenBottomRight.getY() + 1;
}
@Override
void updateGraphics(boolean fromScratch) {
Position chipPosition = emulator.getLevel().getChip().getPosition();
int screenX, screenY;
int chipX = chipPosition.getX();
int chipY = chipPosition.getY();
screenX = chipX - (windowSizeX) / 2;
if (screenX < 0) screenX = 0;
if (screenX + windowSizeX > 32) screenX = 32 - windowSizeX;
screenY = chipY - (windowSizeY) / 2;
if (screenY < 0) screenY = 0;
if (screenY + windowSizeY > 32) screenY = 32 - windowSizeY;
screenTopLeft = new Position(screenX, screenY);
screenBottomRight = screenTopLeft.add(windowSizeX, windowSizeY);
super.updateGraphics(fromScratch);
}
@Override
protected void drawLevel(Level level, boolean fromScratch) {
if (level.supportsLayerBG()) drawLevelWithBGSupport(level, fromScratch);
else drawLevelWithoutBGSupport(level, fromScratch);
}
protected void drawLevelWithBGSupport(Level level, boolean fromScratch) {
byte[] layerBG;
byte[] layerFG;
WritableRaster rasterFG;
WritableRaster rasterBG;
int screenMotion = screenTopLeft.getIndex() - previousScreenTopLeft.getIndex();
rasterFG = upperImage.getRaster();
rasterBG = lowerImage.getRaster();
try{
layerFG = level.getLayerFG().getBytes();
layerBG = level.getLayerBG().getBytes();
}
catch (NullPointerException npe){
return;
}
for (int xPos = 0; xPos < windowSizeX; xPos++) {
for (int yPos = 0; yPos < windowSizeY; yPos++) {
Position p = new Position(screenTopLeft.getX() + xPos, screenTopLeft.getY() + yPos);
int i = p.getIndex();
if (fromScratch || layerFG[i] != previousLayerFG[i - screenMotion] || layerBG[i] != previousLayerBG[i - screenMotion]) {
int x = tileWidth * xPos, y = tileHeight * yPos;
rasterBG.setPixels(x, y, tileWidth, tileHeight, tileImage[layerBG[i]]);
if (layerBG[i] != Tile.FLOOR.ordinal())
rasterFG.setPixels(x, y, tileWidth, tileHeight, overlayTileImage[layerFG[i]]);
else
rasterFG.setPixels(x, y, tileWidth, tileHeight, tileImage[layerFG[i]]);
}
}
}
previousLayerFG = layerFG.clone();
previousLayerBG = layerBG.clone();
previousScreenTopLeft = screenTopLeft.clone();
}
protected void drawLevelWithoutBGSupport(Level level, boolean fromScratch) {
byte[] layerFG;
Graphics graphicsCreatures;
WritableRaster rasterTerrain;
int screenMotion = screenTopLeft.getIndex() - previousScreenTopLeft.getIndex();
upperImage = new BufferedImage(32 * tileWidth, 32 * tileHeight, BufferedImage.TYPE_4BYTE_ABGR);
graphicsCreatures = upperImage.getGraphics();
rasterTerrain = lowerImage.getRaster();
/* We create a blank/transparent image since we have to redraw the creature list every time we want a
transparent image/raster to draw overtop of, so we just create a blank image the correct size and go from there */
try{
layerFG = level.getLayerFG().getBytes();
}
catch (NullPointerException npe){
return;
}
for (int xPos = 0; xPos < windowSizeX; xPos++) {
for (int yPos = 0; yPos < windowSizeY; yPos++) {
Position p = new Position(screenTopLeft.getX() + xPos, screenTopLeft.getY() + yPos);
int i = p.getIndex();
if (fromScratch || layerFG[i] != previousLayerFG[i - screenMotion]) {
int x = tileWidth * xPos, y = tileHeight * yPos;
rasterTerrain.setPixels(x, y, tileWidth, tileHeight, tileImage[layerFG[i]]);
/* If there's no bottom layer than that means we have to draw the creature list on top of
everything else, however it would be extremely wasteful to create an entire other raster for
that and leave the BG raster and BBG raster unused and only use the FG raster and the new creature
raster so instead I draw the FG layer onto the BG raster and draw the creature list on the FG
raster to avoid creating new rasters and having unused ones */
}
}
}
for (Creature creature : emulator.getLevel().getMonsterList()) { //If we don't support BG (meaning: lynx) it means we have to draw the creature list separately
if (creature.isDead() && creature.getAnimationTimer() == 0)
continue;
if (!onScreenExtended(creature.getPosition()))
continue;
int x = (creature.getPosition().x - screenTopLeft.getX()) * tileWidth;
int y = (creature.getPosition().y - screenTopLeft.getY()) * tileHeight;
switch (creature.getDirection()) {
case UP -> y += vBetweenTiles * creature.getTimeTraveled();
case LEFT -> x += hBetweenTiles * creature.getTimeTraveled();
case DOWN -> y -= vBetweenTiles * creature.getTimeTraveled();
case RIGHT -> x -= hBetweenTiles * creature.getTimeTraveled();
}
Image creatureImage = switch (creature.getCreatureType()) { //creatureImages is laid out the same way as the creatures in the tilesheet
default -> creatureImages[creature.getCreatureType().ordinal() + 1][creature.getDirection().ordinal()];
case BLOCK -> creatureImages[11][creature.getDirection().ordinal()];
case CHIP -> creatureImages[10][creature.getDirection().ordinal()];
case CHIP_SWIMMING -> creatureImages[0][creature.getDirection().ordinal()];
case DEAD -> creatureImages[12][creature.getDirection().ordinal()];
};
graphicsCreatures.drawImage(creatureImage, x, y, tileWidth, tileHeight, null);
}
previousLayerFG = layerFG.clone();
previousScreenTopLeft = screenTopLeft.clone();
graphicsCreatures.dispose();
}
@Override
protected void drawMonsterListNumbers(Level level, CreatureList monsterList, BufferedImage overlay){
int i = 0;
for (Creature c : monsterList){
++i;
if (onScreen(c.getPosition()) && level.shouldDrawCreatureNumber(c)) {
int x = (c.getPosition().getX() - screenTopLeft.getX()) * tileWidth;
int y = (c.getPosition().getY() - screenTopLeft.getY()) * tileHeight;
drawNumber(i, blackDigits, x, y, overlay.getRaster());
}
}
}
@Override
protected void drawSlipListNumbers(SlipList slipList, BufferedImage overlay){
int yOffset = tileHeight - SMALL_NUMERAL_HEIGHT - 2;
for (int i = 0; i < slipList.size(); i++){
Creature monster = slipList.get(i);
if (onScreen(monster.getPosition())) {
int x = (monster.getPosition().getX() - screenTopLeft.getX()) * tileWidth;
int y = (monster.getPosition().getY() - screenTopLeft.getY()) * tileHeight + yOffset;
// System.out.println(x); //I have no idea why these 2 are here
// System.out.println(y);
drawNumber(i + 1, blueDigits, x, y, overlay.getRaster());
}
}
}
@Override
protected void drawButtonConnections(Collection<? extends ConnectionButton> connections, BufferedImage overlay, Color color){
Graphics2D g = overlay.createGraphics();
g.setColor(color);
for (ConnectionButton connection : connections){
if (connection == null)
continue;
int x1 = (connection.getButtonPosition().getX() - screenTopLeft.getX()) * tileWidth + tileWidth/2;
int y1 = (connection.getButtonPosition().getY() - screenTopLeft.getY()) * tileHeight + tileHeight/2;
int x2 = (connection.getTargetPosition().getX() - screenTopLeft.getX()) * tileWidth + tileWidth/2;
int y2 = (connection.getTargetPosition().getY() - screenTopLeft.getY()) * tileHeight + tileHeight/2;
g.drawLine(x1, y1, x2, y2);
}
}
@Override
public void drawPositionList(List<Position> positionList, Graphics2D g) {
Position previousPos = positionList.get(0);
boolean[][] tileEnterCount = new boolean[32*32][offsets.length];
tileEnterCount[previousPos.getIndex()][0] = true;
int oldOffset = 0, offset;
g.setColor(Color.BLACK);
for(Position pos : positionList) {
int tile = pos.getIndex();
if (tile == previousPos.getIndex()) continue;
if (tileEnterCount[tile][oldOffset]){
for (offset = 0; offset < offsets.length; offset++) if (!tileEnterCount[tile][offset]) break;
}
else offset = oldOffset;
if (offset == offsets.length) offset = 0;
int x1 = (previousPos.getX() - screenTopLeft.getX()) * tileWidth + ((int) (tileWidth * offsets[oldOffset]));
int y1 = (previousPos.getY() - screenTopLeft.getY()) * tileHeight + ((int) (tileHeight * offsets[oldOffset]));
int x2 = (pos.getX() - screenTopLeft.getX()) * tileWidth + ((int) (tileWidth * offsets[offset]));
int y2 = (pos.getY() - screenTopLeft.getY()) * tileHeight + ((int) (tileHeight * offsets[offset]));
g.drawLine(x1, y1, x2, y2);
previousPos = pos;
oldOffset = offset;
tileEnterCount[tile][offset] = true;
}
}
@Override
protected void drawChipHistory(Position currentPosition, BufferedImage overlay){
List<Position> history = emulator.getSavestates().getChipHistory();
history.add(currentPosition);
drawPositionList(history, overlay.createGraphics());
}
@Override
protected void initialiseTileGraphics(BufferedImage allTiles) {
tileImage = new int[7*16][tileWidth*tileHeight*CHANNELS];
for (int i = 0; i < 16 * 7; i++) {
int x = i / 16;
int y = i % 16;
allTiles.getRaster().getPixels(x * tileWidth, y * tileHeight, tileWidth, tileHeight, tileImage[i]);
}
}
@Override
protected void initialiseOverlayGraphics(BufferedImage allTiles) {
overlayTileImage = new int[7*16][tileWidth*tileHeight*CHANNELS];
for (int i = 0; i < 16 * 7; i++) {
int x = i / 16;
int y = i % 16;
allTiles.getRaster().getPixels(x * tileWidth, y * tileHeight, tileWidth, tileHeight, overlayTileImage[i]);
}
}
@Override
protected void initialiseCreatureGraphics(BufferedImage overlayImage, BufferedImage tilesImage) {
creatureImages = new Image[13][4]; //11 creatures (plus blocks and death effect), each has 4 direction images
for (int i = 0; i < 10; i++) {
int offset = 60 + i*4; //60 is Swimming Chip N's tile
int x = offset / 16;
for (int j = 0; j < 4; j++) {
int y = (offset + j) % 16;
creatureImages[i][j] = overlayImage.getSubimage(x * tileWidth, y * tileHeight, tileWidth, tileHeight);
}
}
for (int k=0; k<4; k++) { //Chip's graphics are separate from the rest of the creatures so we handle them here
int offset = 108; //Chip's tile
int x = offset / 16;
int y = (offset + k) % 16;
creatureImages[10][k] = overlayImage.getSubimage(x * tileWidth, y * tileHeight, tileWidth, tileHeight);
if (k < 2) offset = 14; //Clone blocks start at 14
else offset = 16; //And they're split across 2 columns for some reason
x = offset / 16;
y = (offset + (k % 2)) % 16;
creatureImages[11][k] = overlayImage.getSubimage(x * tileWidth, y * tileHeight, tileWidth, tileHeight);
int vOff = 0;
if (k > 0) { //splash image is at 51 and explode is at 54 followed by chip death explosion
offset = 54;
vOff = k-1;
}
else
offset = 51;
x = offset / 16;
y = (offset + vOff) % 16;
creatureImages[12][k] = tilesImage.getSubimage(x * tileWidth, y * tileHeight, tileWidth, tileHeight);
//we actually *don't* want the hole cut through the animations
}
}
@Override
protected void initialiseLayers() {
lowerImage = new BufferedImage(windowSizeX * tileWidth, windowSizeY * tileHeight, BufferedImage.TYPE_4BYTE_ABGR);
upperImage = new BufferedImage(windowSizeX * tileWidth, windowSizeY * tileHeight, BufferedImage.TYPE_4BYTE_ABGR);
backingImage = new BufferedImage(windowSizeX * tileWidth, windowSizeY * tileHeight, BufferedImage.TYPE_4BYTE_ABGR);
WritableRaster bbgRaster = backingImage.getRaster();
for (int i = 0; i < windowSizeX * windowSizeY; i++){
int x = tileWidth * (i % windowSizeX), y = tileHeight * (i / windowSizeX);
bbgRaster.setPixels(x, y, tileWidth, tileHeight, tileImage[Tile.FLOOR.ordinal()]);
}
}
SmallGamePanel(int windowSizeX, int windowSizeY) {
this.windowSizeX = windowSizeX;
this.windowSizeY = windowSizeY;
}
}
| 15,934 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
LevelPanel.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/graphics/LevelPanel.java | package graphics;
import game.Level;
import java.awt.*;
public class LevelPanel extends TextPanel {
private static boolean twsNotation;
private static String timerToString(Level level){
boolean untimed = level.isUntimed();
int timePerSecond = level.ticksPerMove()*5;
int twsMax = timePerSecond == 10 ? 90 : 95;
String decimalPoints = ".%0" + (timePerSecond == 10 ? 1 : 2) + "d"; //%02d in lynx so that .05 renders correctly
int time;
if (untimed)
time = level.getTChipTime();
else
time = level.getTimer();
int integerPart = time / 100;
int fractionalPart = Math.abs(time % 100);
if (twsNotation)
fractionalPart = twsMax - fractionalPart;
if (timePerSecond == 10)
fractionalPart /= 10; //correction for MS so that it won't display with a trailing 0
String formatString = decimalPoints;
if (twsNotation)
formatString = " (-" + formatString + ")";
formatString = "%d" + formatString;
if (untimed)
formatString = "[" + formatString + "]";
return String.format(formatString, integerPart, fractionalPart);
}
public void changeNotation(boolean change) {
twsNotation = change;
emulator.getPaths().setTWSNotation(change);
}
@Override
public void paintComponent(Graphics g){
if (emulator == null) return;
Level level = emulator.getLevel();
if (level == null) return;
//setSize(emulator.getMainWindow().getRightContainer().getWidth(), getHeight());
textHeight = 40;
g.setColor(Color.DARK_GRAY);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.WHITE);
g.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 16));
drawText(g, "Level "+level.getLevelNumber()+": ", 1);
drawText(g, "", 1);
g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 32));
drawText(g, level.getTitle(), 3);
g.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 16));
drawText(g, "Password: " + level.getPassword(), 1);
drawText(g, "Ruleset: " + level.getRuleset().prettyPrint(), 1);
if (level.getAuthor() != null)
drawText(g, "Author: " + level.getAuthor(), 1);
drawText(g, level.getStep().toString()+" step, seed: " + level.getRngSeed(), 1);
if (level.hasCyclicRFF())
drawText(g, "RFF Initial Direction: "+level.getInitialRFFDirection(), 1);
g.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 24));
drawText(g, "", 1);
drawText(g, "Time: "+ timerToString(level), 1);
drawText(g, "Chips left: "+level.getChipsLeft(), 1);
if (textHeight != getHeight()){
setPreferredSize(new Dimension(getWidth(), textHeight));
setSize(getPreferredSize());
emulator.getMainWindow().pack();
}
}
}
| 2,997 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
MovePanel.java | /FileExtraction/Java_unseen/SicklySilverMoon_SuperCC/src/main/java/graphics/MovePanel.java | package graphics;
import game.Level;
import java.awt.*;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
public class MovePanel extends TextPanel implements MouseWheelListener {
private static final int SCROLL_WHEEL_MULTIPLIER = 8,
MIN_SCROLL = 32;
private int heightOffset = MIN_SCROLL;
@Override
public void paintComponent(Graphics g){
if (emulator == null) return;
Level level = emulator.getLevel();
if (level == null) return;
textHeight = heightOffset;
g.setColor(Color.DARK_GRAY);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.WHITE);
g.setFont(new Font(Font.MONOSPACED, Font.BOLD, 24));
drawText(g, emulator.getSavestates().movesToString(), Integer.MAX_VALUE);
}
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
int i = e.getUnitsToScroll();
heightOffset -= i * SCROLL_WHEEL_MULTIPLIER;
if (heightOffset > MIN_SCROLL) heightOffset = MIN_SCROLL;
repaint();
}
public MovePanel(){
addMouseWheelListener(this);
}
}
| 1,210 | Java | .java | SicklySilverMoon/SuperCC | 12 | 4 | 0 | 2019-04-17T23:57:42Z | 2022-05-14T03:33:32Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.