code
stringlengths
3
1.18M
language
stringclasses
1 value
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep 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. QuiteSleep 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. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.subactivities; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import es.cesar.quitesleep.R; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class Help extends Activity implements OnClickListener{ private final String CLASS_NAME = getClass().getName(); private final int backButtonId = R.id.information_button_cancel; private Button backButton; public void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.help); backButton = (Button)findViewById(backButtonId); backButton.setOnClickListener(this); } public void onClick (View view) { int viewId = view.getId(); switch (viewId) { case backButtonId: setResult(Activity.RESULT_CANCELED); finish(); break; default: break; } } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep 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. QuiteSleep 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. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.subactivities; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.graphics.Typeface; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; import es.cesar.quitesleep.R; import es.cesar.quitesleep.ddbb.ClientDDBB; import es.cesar.quitesleep.ddbb.Contact; import es.cesar.quitesleep.ddbb.Mail; import es.cesar.quitesleep.ddbb.Phone; import es.cesar.quitesleep.operations.ContactOperations; import es.cesar.quitesleep.staticValues.ConfigAppValues; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; import es.cesar.quitesleep.utils.QSToast; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class EditContact extends Activity implements OnClickListener { final private String CLASS_NAME = getClass().getName(); //Global widgets private ScrollView scrollView; private LinearLayout linearLayout; //Phone and mail list for dynamic checkbox private List<CheckBox> phoneCheckboxList; private List<CheckBox> mailCheckboxList; /* The contact Name selected in parent and caller activity when the user * selectd clicking in it. */ private String selectContactName; //Ids for button widgets private final int removeContactButtonId = 1; private final int editContactButtonId = 2; private final int cancelButtonId = 3; //Ids for colors private final int backgroundColor = R.color.black; private final int textColor = R.color.black; @Override public void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); initDynamicLayout(); } /** * Create and initialize the dynamic layout and put some widgets on it */ private void initDynamicLayout () { try { /* Get the contactName passed from the parent activity to this, and * use for get a Contact object refferenced to this name. */ selectContactName = getIntent().getExtras().getString(ConfigAppValues.CONTACT_NAME); ClientDDBB clientDDBB = new ClientDDBB(); Contact contact = clientDDBB.getSelects().selectContactForName(selectContactName); if (contact != null && contact.isBanned()) { if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "selectContactName: " + selectContactName); createLayout(); createHeader(); createPhoneNumbersSection(clientDDBB, contact); createMailAddressesSection(clientDDBB, contact); addButtons(); setContentView(scrollView); clientDDBB.close(); }else { clientDDBB.close(); setResult(Activity.RESULT_CANCELED); finish(); } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /* * Create the scrollView and LinearLayput for put some widgets on it */ private void createLayout () { try { scrollView = new ScrollView(this); linearLayout = new LinearLayout(this); linearLayout.setOrientation(LinearLayout.VERTICAL); scrollView.setBackgroundColor(this.getResources().getColor(backgroundColor)); scrollView.addView(linearLayout); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Put the contactName and a separator view how header for the layout */ private void createHeader () { try { TextView contactName = new TextView(this); contactName.setText(selectContactName); //contactName.setTextColor(textColor); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT); contactName.setLayoutParams(params); contactName.setTypeface(Typeface.create("", Typeface.BOLD_ITALIC)); contactName.setTextSize(25); linearLayout.addView(contactName); addDividerBlack(); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Create the phone numbers section * * @param clientDDBB * @param contact */ private void createPhoneNumbersSection (ClientDDBB clientDDBB, Contact contact) { try { List<Phone> contactPhones = clientDDBB.getSelects().selectAllContactPhonesForName(selectContactName); if (contactPhones != null) { addDividerDetails(R.string.contactdetails_label_phonedetails); phoneCheckboxList = new ArrayList<CheckBox>(contactPhones.size()); for (int i=0; i<contactPhones.size(); i++) { Phone phone = contactPhones.get(i); CheckBox checkbox = new CheckBox(this); checkbox.setText(phone.getContactPhone()); checkbox.setChecked(phone.isUsedToSend()); //checkbox.setTextColor(textColor); linearLayout.addView(checkbox); phoneCheckboxList.add(checkbox); } } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Create the mail addresses section * * @param clientDDBB * @param contact */ private void createMailAddressesSection (ClientDDBB clientDDBB, Contact contact) { try { List<Mail> contactMails = clientDDBB.getSelects().selectAllContactMailsForName(selectContactName); if (contactMails != null && contactMails.size() > 0) { addDividerDetails(R.string.contactdetails_label_maildetails); mailCheckboxList = new ArrayList<CheckBox>(contactMails.size()); for (int i=0; i<contactMails.size(); i++) { Mail mail = contactMails.get(i); CheckBox checkbox = new CheckBox(this); checkbox.setText(mail.getContactMail()); checkbox.setChecked(mail.isUsedToSend()); //checkbox.setTextColor(textColor); linearLayout.addView(checkbox); mailCheckboxList.add(checkbox); } } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Put one black dividerDetails view in the layout. * Pass the resId with the string that we like it. * @param resId */ private void addDividerDetails (int resId) { TextView details = new TextView(this); details.setBackgroundResource(R.drawable.solid_black); details.setTypeface(Typeface.create("", Typeface.BOLD)); details.setTextSize(15); details.setText(resId); details.setPadding(0, 10, 0, 0); linearLayout.addView(details); } /** * Put one black divider view in the layout as separator for other views */ private void addDividerBlack () { TextView dividerBlack = new TextView(this); dividerBlack.setBackgroundResource(R.drawable.gradient_black); dividerBlack.setTextSize(3); linearLayout.addView(dividerBlack); } /** * Put one blue divider view in the layout as separator for other views */ private void addDividerBlue () { TextView dividerBlue = new TextView(this); dividerBlue.setBackgroundResource(R.drawable.gradient_blue); dividerBlue.setTextSize(2); linearLayout.addView(dividerBlue); } /** * Put two buttons, one for addContact to the banned list and other for * cancel and go back to the parent activity. */ private void addButtons () { try { addDividerBlack(); Button editButton = new Button(this); editButton.setText(R.string.editcontact_button_edit); editButton.setId(editContactButtonId); editButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.edit, 0, 0, 0); editButton.setId(editContactButtonId); editButton.setOnClickListener(this); linearLayout.addView(editButton); addDividerBlue(); Button removeContactButton = new Button(this); removeContactButton.setText(R.string.editcontact_button_remove); removeContactButton.setId(removeContactButtonId); removeContactButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.delete, 0, 0, 0); removeContactButton.setId(removeContactButtonId); removeContactButton.setOnClickListener(this); linearLayout.addView(removeContactButton); addDividerBlue(); Button cancelButton = new Button(this); cancelButton.setText(R.string.contactdetails_button_cancel); cancelButton.setId(cancelButtonId); cancelButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.back, 0, 0, 0); cancelButton.setId(cancelButtonId); cancelButton.setOnClickListener(this); linearLayout.addView(cancelButton); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } @Override public void onClick (View view) { try { int viewId = view.getId(); boolean result; switch (viewId) { case editContactButtonId: result = ContactOperations.editContact( selectContactName, phoneCheckboxList, mailCheckboxList); showEditToast(result); break; case removeContactButtonId: result = ContactOperations.removeContact(selectContactName); showRemoveToast(result); setResult(Activity.RESULT_OK); finish(); break; case cancelButtonId: setResult(Activity.RESULT_CANCELED); finish(); break; default: break; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Show toast notification for information to user * * @param result */ private void showEditToast (boolean result) { try { if (result) if (QSToast.RELEASE) QSToast.r( this, this.getString( R.string.editcontact_toast_edit), Toast.LENGTH_SHORT); else if (QSToast.RELEASE) QSToast.r( this, this.getString( R.string.editcontact_toast_edit_fail), Toast.LENGTH_SHORT); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Show notification toast to the user for information. * * @param result */ private void showRemoveToast (boolean result) { try { if (result) if (QSToast.RELEASE) QSToast.r( this, this.getString( R.string.editcontact_toast_remove), Toast.LENGTH_SHORT); else if (QSToast.RELEASE) QSToast.r( this, this.getString( R.string.editcontact_toast_remove_fail), Toast.LENGTH_SHORT); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep 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. QuiteSleep 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. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.subactivities; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.app.Dialog; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import es.cesar.quitesleep.R; import es.cesar.quitesleep.ddbb.Banned; import es.cesar.quitesleep.ddbb.ClientDDBB; import es.cesar.quitesleep.dialogs.WarningDialog; import es.cesar.quitesleep.staticValues.ConfigAppValues; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; import es.cesar.quitesleep.utils.QSToast; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class DeleteBanned extends ListActivity { //Constants final private String CLASS_NAME = this.getClass().getName(); final private int WARNING_DIALOG = 0; //Widgets Ids private final int removeAllMenuId = R.id.menu_removeall; //Widgets private WarningDialog warningDialog; private ArrayAdapter<String> arrayAdapter; //Attributes private String selectContactName; @Override public void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); warningDialog = new WarningDialog( this, ConfigAppValues.WARNING_REMOVE_ALL_CONTACTS); getAllContactList(); } /** * Get all banned contact list from the database */ private void getAllContactList () { try { ClientDDBB clientDDBB = new ClientDDBB(); List<Banned> contactList = clientDDBB.getSelects().selectAllBannedContacts(); List<String> contactListString = convertContactList(contactList); if (contactListString != null) { arrayAdapter = new ArrayAdapter<String>( this, R.layout.deletebanned, R.id.deleteBanned_textview_name, contactListString); setListAdapter(arrayAdapter); } clientDDBB.close(); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Function that convert all banned contact list in Contact objects to * one List<String> with only the contact name attribute. * * @param contactList * @return The contactList but only the list with the name contacts * @see List<String> */ private List<String> convertContactList (List<Banned> bannedList) throws Exception { try { if (bannedList != null && bannedList.size()>0) { List<String> bannedListString = new ArrayList<String>(bannedList.size()); for (int i=0; i<bannedList.size(); i++) { Banned banned = bannedList.get(i); String contactName = banned.getContact().getContactName(); if (contactName == null) contactName = ""; bannedListString.add(contactName); } return bannedListString; } return null; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); throw new Exception(); } } @Override protected void onListItemClick ( ListView listView, View view, int position, long id){ try { if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "OnListItemClick"); super.onListItemClick(listView, view, position, id); selectContactName = (String) this.getListAdapter().getItem(position); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Name: " + selectContactName); /* If we like to use one subactivity for show better contact details * and edit what phone number and/or mail addresses are used for * send busy response, and remove contact from banned list. */ Intent intentEditContact = new Intent(this, EditContact.class); intentEditContact.putExtra(ConfigAppValues.CONTACT_NAME, selectContactName); startActivityForResult(intentEditContact, ConfigAppValues.REQCODE_EDIT_CONTACT); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } @Override public void onActivityResult (int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch(requestCode) { case ConfigAppValues.REQCODE_EDIT_CONTACT: if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Valor retornado: " + resultCode); if (resultCode == Activity.RESULT_OK) arrayAdapter.remove(selectContactName); break; default: break; } } /** * Create the activity dialogs used for it * * @param id * @return the dialog for the option specified * @see Dialog */ @Override protected Dialog onCreateDialog (int id) { Dialog dialog; switch (id) { case WARNING_DIALOG: if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Create the AlertDialog for 1st time"); dialog = warningDialog.getAlertDialog(); break; default: dialog = null; } return dialog; } /** * This function prepare the dalogs every time to call for some of this * * @param int * @param dialog */ @Override protected void onPrepareDialog (int idDialog, Dialog dialog) { try { switch (idDialog) { case WARNING_DIALOG: warningDialog.setContext(this); warningDialog.setArrayAdapter(arrayAdapter); warningDialog.setHandler(handler); break; default: break; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } @Override public boolean onCreateOptionsMenu (Menu menu) { try { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.removeallmenu, menu); return true; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } /** * @param item * @return boolean */ @Override public boolean onOptionsItemSelected (MenuItem item) { try { switch (item.getItemId()) { case removeAllMenuId: showDialog(WARNING_DIALOG); break; default: break; } return false; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } /** * Handler for clear the listView and the array adapter once we have been * add all contacts to the banned list */ public final Handler handler = new Handler() { public void handleMessage(Message message) { if (arrayAdapter != null && arrayAdapter.getCount()>0) { //int count = arrayAdapter.getCount(); int numRemoveContacts = message.getData().getInt( ConfigAppValues.NUM_REMOVE_CONTACTS); //clear the arrayAdapter arrayAdapter.clear(); //Show the toast message if (QSToast.RELEASE) QSToast.r( ConfigAppValues.getContext(), numRemoveContacts + " " + ConfigAppValues.getContext().getString( R.string.menu_removeall_toast_removecount), Toast.LENGTH_SHORT); } } }; }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep 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. QuiteSleep 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. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.menus; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.widget.ArrayAdapter; import es.cesar.quitesleep.ddbb.Banned; import es.cesar.quitesleep.ddbb.ClientDDBB; import es.cesar.quitesleep.ddbb.Contact; import es.cesar.quitesleep.ddbb.Schedule; import es.cesar.quitesleep.dialogs.AddAllDialog; import es.cesar.quitesleep.staticValues.ConfigAppValues; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class AddAllMenu extends Thread { private final String CLASS_NAME = getClass().getName(); private ArrayAdapter<String> arrayAdapter = null; private AddAllDialog addAllDialog; private Handler handler; //------------- Getters & Setters ------------------------------// public ArrayAdapter<String> getArrayAdapter() { return arrayAdapter; } public void setArrayAdapter(ArrayAdapter<String> arrayAdapter) { this.arrayAdapter = arrayAdapter; } //------------------------------------------------------------------------// /** * Constructor with the basic parameter * * @param arrayAdapter * @param addAllDialog * @param handler */ public AddAllMenu ( ArrayAdapter<String> arrayAdapter, AddAllDialog addAllDialog, Handler handler) { this.arrayAdapter = arrayAdapter; this.addAllDialog = addAllDialog; this.handler = handler; } public void run () { addAll(); } /** * Add to the banned list all contacts of the listview (arrayadapter) * */ private void addAll () { final String NUM_BANNED = "NUM_BANNED"; int numBanend = 0; try { ClientDDBB clientDDBB = new ClientDDBB(); Schedule schedule = clientDDBB.getSelects().selectSchedule(); if (schedule != null) { if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "size list: " + arrayAdapter.getCount()); //while (arrayAdapter.getCount()>0) { for (int i=0; i<arrayAdapter.getCount(); i++) { /* all time we get the first element (0) of the list * because when we remove the actual element at the final code * the next element put to the first position, and so with all. */ String contactName = arrayAdapter.getItem(i); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "añadiendo: " + contactName); if (contactName != null && !contactName.equals("")) { Contact contact = clientDDBB.getSelects().selectContactForName(contactName); if (contact != null) { Banned banned = new Banned(contact, schedule); contact.setBanned(true); clientDDBB.getUpdates().insertContact(contact); clientDDBB.getInserts().insertBanned(banned); numBanend ++; } } } clientDDBB.commit(); } clientDDBB.close(); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); }finally { //Hide and dismiss de synchronization dialog addAllDialog.stopDialog(ConfigAppValues.getContext()); //Create and send the numBanned message to the handler in gui main thread Message message = handler.obtainMessage(); Bundle bundle = new Bundle(); bundle.putInt(NUM_BANNED, numBanend); message.setData(bundle); handler.sendMessage(message); } } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep 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. QuiteSleep 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. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.menus; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.widget.ArrayAdapter; import es.cesar.quitesleep.ddbb.ClientDDBB; import es.cesar.quitesleep.dialogs.CallLogDialog; import es.cesar.quitesleep.staticValues.ConfigAppValues; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class RemoveCallLogMenu extends Thread { private final String CLASS_NAME = getClass().getName(); private ArrayAdapter<String> arrayAdapter = null; private CallLogDialog callLogDialog; private Handler handler; //------------- Getters & Setters ------------------------------// public ArrayAdapter<String> getArrayAdapter() { return arrayAdapter; } public void setArrayAdapter(ArrayAdapter<String> arrayAdapter) { this.arrayAdapter = arrayAdapter; } //------------------------------------------------------------------------// /** * Constructor with the basic parameter * * @param arrayAdapter * @param callLogDialog * @param handler */ public RemoveCallLogMenu ( ArrayAdapter<String> arrayAdapter, CallLogDialog callLogDialog, Handler handler) { this.arrayAdapter = arrayAdapter; this.callLogDialog = callLogDialog; this.handler = handler; } public void run () { removeAll(); } /** * Remove all callLog objects from the ddbb and the list */ private void removeAll () { int numRemoveCallLogs = 0; try { ClientDDBB clientDDBB = new ClientDDBB(); numRemoveCallLogs = clientDDBB.getDeletes().deleteAllCallLog(); clientDDBB.commit(); clientDDBB.close(); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); }finally { //Hide and dismiss de synchronization dialog callLogDialog.stopDialog(ConfigAppValues.getContext()); //Create and send the numBanned message to the handler in gui main thread Message message = handler.obtainMessage(); Bundle bundle = new Bundle(); bundle.putInt(ConfigAppValues.NUM_REMOVE_CALL_LOGS, numRemoveCallLogs); message.setData(bundle); handler.sendMessage(message); } } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep 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. QuiteSleep 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. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.menus; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.widget.ArrayAdapter; import es.cesar.quitesleep.ddbb.Banned; import es.cesar.quitesleep.ddbb.ClientDDBB; import es.cesar.quitesleep.ddbb.Contact; import es.cesar.quitesleep.dialogs.RemoveAllDialog; import es.cesar.quitesleep.staticValues.ConfigAppValues; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class RemoveAllMenu extends Thread { private final String CLASS_NAME = getClass().getName(); private ArrayAdapter<String> arrayAdapter = null; private RemoveAllDialog removeAllDialog; private Handler handler; //------------- Getters & Setters ------------------------------// public ArrayAdapter<String> getArrayAdapter() { return arrayAdapter; } public void setArrayAdapter(ArrayAdapter<String> arrayAdapter) { this.arrayAdapter = arrayAdapter; } //------------------------------------------------------------------------// /** * Constructor with the basic parameter * * @param arrayAdapter * @param removeAllDialog * @param handler */ public RemoveAllMenu ( ArrayAdapter<String> arrayAdapter, RemoveAllDialog removeAllDialog, Handler handler) { this.arrayAdapter = arrayAdapter; this.removeAllDialog = removeAllDialog; this.handler = handler; } public void run () { removeAll(); } /** * Remove all contacts from the banned list */ private void removeAll () { int numRemoveContacts = 0; try { ClientDDBB clientDDBB = new ClientDDBB(); //while (arrayAdapter.getCount() > 0) { for (int i=0; i<arrayAdapter.getCount(); i++) { String contactName = arrayAdapter.getItem(i); if (contactName != null && !contactName.equals("")) { Banned banned = clientDDBB.getSelects().selectBannedContactForName(contactName); if (banned != null) { Contact contact = banned.getContact(); contact.setBanned(false); clientDDBB.getUpdates().insertContact(contact); clientDDBB.getDeletes().deleteBanned(banned); numRemoveContacts ++; } } } clientDDBB.commit(); clientDDBB.close(); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); }finally { //Hide and dismiss de synchronization dialog removeAllDialog.stopDialog(ConfigAppValues.getContext()); //Create and send the numBanned message to the handler in gui main thread Message message = handler.obtainMessage(); Bundle bundle = new Bundle(); bundle.putInt(ConfigAppValues.NUM_REMOVE_CONTACTS, numRemoveContacts); message.setData(bundle); handler.sendMessage(message); } } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep 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. QuiteSleep 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. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.menus; import java.util.ArrayList; import java.util.List; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.widget.ArrayAdapter; import es.cesar.quitesleep.ddbb.CallLog; import es.cesar.quitesleep.ddbb.ClientDDBB; import es.cesar.quitesleep.dialogs.CallLogDialog; import es.cesar.quitesleep.staticValues.ConfigAppValues; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class RefreshCallLogMenu extends Thread { private final String CLASS_NAME = getClass().getName(); private ArrayAdapter<String> arrayAdapter = null; private CallLogDialog callLogDialog; private Handler handler; //------------- Getters & Setters ------------------------------// public ArrayAdapter<String> getArrayAdapter() { return arrayAdapter; } public void setArrayAdapter(ArrayAdapter<String> arrayAdapter) { this.arrayAdapter = arrayAdapter; } //------------------------------------------------------------------------// /** * Constructor with the basic parameter * * @param arrayAdapter * @param callLogDialog * @param handler */ public RefreshCallLogMenu ( ArrayAdapter<String> arrayAdapter, CallLogDialog callLogDialog, Handler handler) { this.arrayAdapter = arrayAdapter; this.callLogDialog = callLogDialog; this.handler = handler; } public void run () { refreshAll(); } /** * Remove all callLog objects from the ddbb and the list */ private void refreshAll () { ArrayList<String> callLogListString = null; try { ClientDDBB clientDDBB = new ClientDDBB(); List<CallLog> callLogList = clientDDBB.getSelects().selectAllCallLog(); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Call log list: " + callLogList); if (callLogList != null) { callLogListString = new ArrayList<String>(callLogList.size()); for (int i=0; i<callLogList.size(); i++) { String callLog = callLogList.get(i).toString(); callLogListString.add(callLog); } } clientDDBB.close(); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); }finally { //Hide and dismiss de synchronization dialog callLogDialog.stopDialog(ConfigAppValues.getContext()); //Create and send the numBanned message to the handler in gui main thread Message message = handler.obtainMessage(); Bundle bundle = new Bundle(); bundle.putStringArrayList(ConfigAppValues.REFRESH_CALL_LOG, callLogListString); message.setData(bundle); handler.sendMessage(message); } } }
Java
package controller; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.imageio.ImageIO; import model.Food; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import dao.FoodDAO; @Controller public class FoodController { private static final int IMG_WIDTH = 100; private static final int IMG_HEIGHT = 100; String url = ""; String rootPath = System.getProperty("user.dir"); @Autowired private FoodDAO dao; @RequestMapping(value = "/foodlist", method = RequestMethod.GET) public ModelAndView foodList() { List<Food> list = dao.getList(); Map<String, Object> model = new HashMap<String, Object>(); url = "foodlist"; model.put("list", list); model.put("url", url); return new ModelAndView("../../Homepage", model); } @RequestMapping(value = "/addfood", method = RequestMethod.POST) public ModelAndView addFood(@ModelAttribute Food food) { Map<String, Object> model = new HashMap<String, Object>(); url = "foodinfo"; if (food.getId()==0) { String name = food.getName(); File dir = new File(rootPath + File.separator + "workspace" + File.separator + "CNPM" + File.separator + "WebContent" + File.separator + "resources" + File.separator + "image"); Food.makeQR(name, dir.getAbsolutePath() + File.separator + "qr" + name + ".jpg"); String filePath = "/resources/image/qr" + name + ".jpg"; food.setQr(filePath); } dao.saveOrUpdate(food); model.put("url", url); return new ModelAndView("../../Homepage", model); } @RequestMapping(value = "/displayaddfood", method = RequestMethod.GET) public ModelAndView displayAddFood() { Map<String, Object> model = new HashMap<String, Object>(); url = "displayaddfood"; model.put("url", url); model.put("food", new Food()); return new ModelAndView("../../Homepage", model); } @RequestMapping(value = "/displayupload", method = RequestMethod.GET) public String displayUpload() { return "Upload"; } @RequestMapping(value = "/upload", method = RequestMethod.POST) public ModelAndView upload(@RequestParam("file") MultipartFile file) { Map<String, Object> model = new HashMap<String, Object>(); String message = ""; if (!file.isEmpty()) { try { byte[] bytes = file.getBytes(); File dir = new File(rootPath + File.separator + "workspace" + File.separator + "CNPM" + File.separator + "WebContent" + File.separator + "resources" + File.separator + "image"); if (!dir.exists()) dir.mkdirs(); Calendar cal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); String name = sdf.format(cal.getTime()); File serverFile = new File(dir.getAbsolutePath() + File.separator + "img" + name + ".jpg"); BufferedOutputStream stream = new BufferedOutputStream( new FileOutputStream(serverFile)); stream.write(bytes); stream.close(); resizeIMG(serverFile); String filePath = "/resources/image/img" + name + ".jpg"; model.put("filepath", filePath); message = "You successfully uploaded file"; } catch (Exception e) { message = "You failed to upload => " + e.getMessage(); } } else { message = "You failed to upload because the file was empty."; } model.put("message", message); return new ModelAndView("Upload", model); } public static void resizeIMG(File file) { try { BufferedImage originalImage = ImageIO.read(file); int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType(); BufferedImage resizeImageJpg = resizeImage(originalImage, type); ImageIO.write(resizeImageJpg, "jpg", new File(file.getAbsolutePath())); } catch (IOException e) { e.printStackTrace(); } } private static BufferedImage resizeImage(BufferedImage originalImage, int type) { BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type); Graphics2D g = resizedImage.createGraphics(); g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null); g.dispose(); return resizedImage; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.chl.tdaniel.jpa_query.nbp.core; import java.io.Serializable; import java.math.BigDecimal; import java.util.Collection; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * * @author Daniel */ @Entity @Table(name = "PRODUCT") @NamedQueries({ @NamedQuery(name = "Product.findAll", query = "SELECT p FROM Product p")}) public class Product implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Column(name = "PRODUCT_ID") private Integer productId; // @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation @Column(name = "PURCHASE_COST") private BigDecimal purchaseCost; @Column(name = "QUANTITY_ON_HAND") private Integer quantityOnHand; @Column(name = "MARKUP") private BigDecimal markup; @Size(max = 5) @Column(name = "AVAILABLE") private String available; @Size(max = 50) @Column(name = "DESCRIPTION") private String description; @JoinColumn(name = "PRODUCT_CODE", referencedColumnName = "PROD_CODE") @ManyToOne(optional = false) private ProductCode productCode; @JoinColumn(name = "MANUFACTURER_ID", referencedColumnName = "MANUFACTURER_ID") @ManyToOne(optional = false) private Manufacturer manufacturerId; @OneToMany(cascade = CascadeType.ALL, mappedBy = "productId") private Collection<PurchaseOrder> purchaseOrderCollection; public Product() { } public Product(Integer productId) { this.productId = productId; } public Integer getProductId() { return productId; } public void setProductId(Integer productId) { this.productId = productId; } public BigDecimal getPurchaseCost() { return purchaseCost; } public void setPurchaseCost(BigDecimal purchaseCost) { this.purchaseCost = purchaseCost; } public Integer getQuantityOnHand() { return quantityOnHand; } public void setQuantityOnHand(Integer quantityOnHand) { this.quantityOnHand = quantityOnHand; } public BigDecimal getMarkup() { return markup; } public void setMarkup(BigDecimal markup) { this.markup = markup; } public String getAvailable() { return available; } public void setAvailable(String available) { this.available = available; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public ProductCode getProductCode() { return productCode; } public void setProductCode(ProductCode productCode) { this.productCode = productCode; } public Manufacturer getManufacturerId() { return manufacturerId; } public void setManufacturerId(Manufacturer manufacturerId) { this.manufacturerId = manufacturerId; } public Collection<PurchaseOrder> getPurchaseOrderCollection() { return purchaseOrderCollection; } public void setPurchaseOrderCollection(Collection<PurchaseOrder> purchaseOrderCollection) { this.purchaseOrderCollection = purchaseOrderCollection; } @Override public int hashCode() { int hash = 0; hash += (productId != null ? productId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Product)) { return false; } Product other = (Product) object; if ((this.productId == null && other.productId != null) || (this.productId != null && !this.productId.equals(other.productId))) { return false; } return true; } @Override public String toString() { return "edu.chl.tdaniel.jpa_query.nbp.core.Product[ productId=" + productId + " ]"; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.chl.tdaniel.jpa_query.nbp.core; import java.io.Serializable; import java.util.Collection; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * * @author Daniel */ @Entity @Table(name = "CUSTOMER") @NamedQueries({ @NamedQuery(name = "Customer.findAll", query = "SELECT c FROM Customer c")}) public class Customer implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Column(name = "CUSTOMER_ID") private Integer customerId; @Basic(optional = false) @NotNull @Size(min = 1, max = 10) @Column(name = "ZIP") private String zip; @Size(max = 30) @Column(name = "NAME") private String name; @Size(max = 30) @Column(name = "ADDRESSLINE1") private String addressline1; @Size(max = 30) @Column(name = "ADDRESSLINE2") private String addressline2; @Size(max = 25) @Column(name = "CITY") private String city; @Size(max = 2) @Column(name = "STATE") private String state; // @Pattern(regexp="^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$", message="Invalid phone/fax format, should be as xxx-xxx-xxxx")//if the field contains phone or fax number consider using this annotation to enforce field validation @Size(max = 12) @Column(name = "PHONE") private String phone; // @Pattern(regexp="^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$", message="Invalid phone/fax format, should be as xxx-xxx-xxxx")//if the field contains phone or fax number consider using this annotation to enforce field validation @Size(max = 12) @Column(name = "FAX") private String fax; // @Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation @Size(max = 40) @Column(name = "EMAIL") private String email; @Column(name = "CREDIT_LIMIT") private Integer creditLimit; @JoinColumn(name = "DISCOUNT_CODE", referencedColumnName = "DISCOUNT_CODE") @ManyToOne(optional = false) private DiscountCode discountCode; @OneToMany(cascade = CascadeType.ALL, mappedBy = "customerId") private Collection<PurchaseOrder> purchaseOrderCollection; public Customer() { } public Customer(Integer customerId) { this.customerId = customerId; } public Customer(Integer customerId, String zip) { this.customerId = customerId; this.zip = zip; } public Integer getCustomerId() { return customerId; } public void setCustomerId(Integer customerId) { this.customerId = customerId; } public String getZip() { return zip; } public void setZip(String zip) { this.zip = zip; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddressline1() { return addressline1; } public void setAddressline1(String addressline1) { this.addressline1 = addressline1; } public String getAddressline2() { return addressline2; } public void setAddressline2(String addressline2) { this.addressline2 = addressline2; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getFax() { return fax; } public void setFax(String fax) { this.fax = fax; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Integer getCreditLimit() { return creditLimit; } public void setCreditLimit(Integer creditLimit) { this.creditLimit = creditLimit; } public DiscountCode getDiscountCode() { return discountCode; } public void setDiscountCode(DiscountCode discountCode) { this.discountCode = discountCode; } public Collection<PurchaseOrder> getPurchaseOrderCollection() { return purchaseOrderCollection; } public void setPurchaseOrderCollection(Collection<PurchaseOrder> purchaseOrderCollection) { this.purchaseOrderCollection = purchaseOrderCollection; } @Override public int hashCode() { int hash = 0; hash += (customerId != null ? customerId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Customer)) { return false; } Customer other = (Customer) object; if ((this.customerId == null && other.customerId != null) || (this.customerId != null && !this.customerId.equals(other.customerId))) { return false; } return true; } @Override public String toString() { return "edu.chl.tdaniel.jpa_query.nbp.core.Customer[ customerId=" + customerId + " ]"; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.chl.tdaniel.jpa_query.nbp.core; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * * @author Daniel */ @Entity @Table(name = "MICRO_MARKET") @NamedQueries({ @NamedQuery(name = "MicroMarket.findAll", query = "SELECT m FROM MicroMarket m")}) public class MicroMarket implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Size(min = 1, max = 10) @Column(name = "ZIP_CODE") private String zipCode; // @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation @Column(name = "RADIUS") private Double radius; @Column(name = "AREA_LENGTH") private Double areaLength; @Column(name = "AREA_WIDTH") private Double areaWidth; public MicroMarket() { } public MicroMarket(String zipCode) { this.zipCode = zipCode; } public String getZipCode() { return zipCode; } public void setZipCode(String zipCode) { this.zipCode = zipCode; } public Double getRadius() { return radius; } public void setRadius(Double radius) { this.radius = radius; } public Double getAreaLength() { return areaLength; } public void setAreaLength(Double areaLength) { this.areaLength = areaLength; } public Double getAreaWidth() { return areaWidth; } public void setAreaWidth(Double areaWidth) { this.areaWidth = areaWidth; } @Override public int hashCode() { int hash = 0; hash += (zipCode != null ? zipCode.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof MicroMarket)) { return false; } MicroMarket other = (MicroMarket) object; if ((this.zipCode == null && other.zipCode != null) || (this.zipCode != null && !this.zipCode.equals(other.zipCode))) { return false; } return true; } @Override public String toString() { return "edu.chl.tdaniel.jpa_query.nbp.core.MicroMarket[ zipCode=" + zipCode + " ]"; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.chl.tdaniel.jpa_query.nbp.core; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * * @author Daniel */ @Entity @Table(name = "PURCHASE_ORDER") @NamedQueries({ @NamedQuery(name = "PurchaseOrder.findAll", query = "SELECT p FROM PurchaseOrder p")}) public class PurchaseOrder implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Column(name = "ORDER_NUM") private Integer orderNum; @Column(name = "QUANTITY") private Short quantity; // @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation @Column(name = "SHIPPING_COST") private BigDecimal shippingCost; @Column(name = "SALES_DATE") @Temporal(TemporalType.DATE) private Date salesDate; @Column(name = "SHIPPING_DATE") @Temporal(TemporalType.DATE) private Date shippingDate; @Size(max = 30) @Column(name = "FREIGHT_COMPANY") private String freightCompany; @JoinColumn(name = "PRODUCT_ID", referencedColumnName = "PRODUCT_ID") @ManyToOne(optional = false) private Product productId; @JoinColumn(name = "CUSTOMER_ID", referencedColumnName = "CUSTOMER_ID") @ManyToOne(optional = false) private Customer customerId; public PurchaseOrder() { } public PurchaseOrder(Integer orderNum) { this.orderNum = orderNum; } public Integer getOrderNum() { return orderNum; } public void setOrderNum(Integer orderNum) { this.orderNum = orderNum; } public Short getQuantity() { return quantity; } public void setQuantity(Short quantity) { this.quantity = quantity; } public BigDecimal getShippingCost() { return shippingCost; } public void setShippingCost(BigDecimal shippingCost) { this.shippingCost = shippingCost; } public Date getSalesDate() { return salesDate; } public void setSalesDate(Date salesDate) { this.salesDate = salesDate; } public Date getShippingDate() { return shippingDate; } public void setShippingDate(Date shippingDate) { this.shippingDate = shippingDate; } public String getFreightCompany() { return freightCompany; } public void setFreightCompany(String freightCompany) { this.freightCompany = freightCompany; } public Product getProductId() { return productId; } public void setProductId(Product productId) { this.productId = productId; } public Customer getCustomerId() { return customerId; } public void setCustomerId(Customer customerId) { this.customerId = customerId; } @Override public int hashCode() { int hash = 0; hash += (orderNum != null ? orderNum.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof PurchaseOrder)) { return false; } PurchaseOrder other = (PurchaseOrder) object; if ((this.orderNum == null && other.orderNum != null) || (this.orderNum != null && !this.orderNum.equals(other.orderNum))) { return false; } return true; } @Override public String toString() { return "edu.chl.tdaniel.jpa_query.nbp.core.PurchaseOrder[ orderNum=" + orderNum + " ]"; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.chl.tdaniel.jpa_query.nbp.core; import java.io.Serializable; import java.util.Collection; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * * @author Daniel */ @Entity @Table(name = "PRODUCT_CODE") @NamedQueries({ @NamedQuery(name = "ProductCode.findAll", query = "SELECT p FROM ProductCode p")}) public class ProductCode implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Size(min = 1, max = 2) @Column(name = "PROD_CODE") private String prodCode; @Basic(optional = false) @NotNull @Column(name = "DISCOUNT_CODE") private char discountCode; @Size(max = 10) @Column(name = "DESCRIPTION") private String description; @OneToMany(cascade = CascadeType.ALL, mappedBy = "productCode") private Collection<Product> productCollection; public ProductCode() { } public ProductCode(String prodCode) { this.prodCode = prodCode; } public ProductCode(String prodCode, char discountCode) { this.prodCode = prodCode; this.discountCode = discountCode; } public String getProdCode() { return prodCode; } public void setProdCode(String prodCode) { this.prodCode = prodCode; } public char getDiscountCode() { return discountCode; } public void setDiscountCode(char discountCode) { this.discountCode = discountCode; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Collection<Product> getProductCollection() { return productCollection; } public void setProductCollection(Collection<Product> productCollection) { this.productCollection = productCollection; } @Override public int hashCode() { int hash = 0; hash += (prodCode != null ? prodCode.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof ProductCode)) { return false; } ProductCode other = (ProductCode) object; if ((this.prodCode == null && other.prodCode != null) || (this.prodCode != null && !this.prodCode.equals(other.prodCode))) { return false; } return true; } @Override public String toString() { return "edu.chl.tdaniel.jpa_query.nbp.core.ProductCode[ prodCode=" + prodCode + " ]"; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.chl.tdaniel.jpa_query.nbp.core; import java.io.Serializable; import java.util.Collection; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * * @author Daniel */ @Entity @Table(name = "MANUFACTURER") @NamedQueries({ @NamedQuery(name = "Manufacturer.findAll", query = "SELECT m FROM Manufacturer m")}) public class Manufacturer implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Column(name = "MANUFACTURER_ID") private Integer manufacturerId; @Size(max = 30) @Column(name = "NAME") private String name; @Size(max = 30) @Column(name = "ADDRESSLINE1") private String addressline1; @Size(max = 30) @Column(name = "ADDRESSLINE2") private String addressline2; @Size(max = 25) @Column(name = "CITY") private String city; @Size(max = 2) @Column(name = "STATE") private String state; @Size(max = 10) @Column(name = "ZIP") private String zip; // @Pattern(regexp="^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$", message="Invalid phone/fax format, should be as xxx-xxx-xxxx")//if the field contains phone or fax number consider using this annotation to enforce field validation @Size(max = 12) @Column(name = "PHONE") private String phone; // @Pattern(regexp="^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$", message="Invalid phone/fax format, should be as xxx-xxx-xxxx")//if the field contains phone or fax number consider using this annotation to enforce field validation @Size(max = 12) @Column(name = "FAX") private String fax; // @Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation @Size(max = 40) @Column(name = "EMAIL") private String email; @Size(max = 30) @Column(name = "REP") private String rep; @OneToMany(cascade = CascadeType.ALL, mappedBy = "manufacturerId") private Collection<Product> productCollection; public Manufacturer() { } public Manufacturer(Integer manufacturerId) { this.manufacturerId = manufacturerId; } public Integer getManufacturerId() { return manufacturerId; } public void setManufacturerId(Integer manufacturerId) { this.manufacturerId = manufacturerId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddressline1() { return addressline1; } public void setAddressline1(String addressline1) { this.addressline1 = addressline1; } public String getAddressline2() { return addressline2; } public void setAddressline2(String addressline2) { this.addressline2 = addressline2; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getZip() { return zip; } public void setZip(String zip) { this.zip = zip; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getFax() { return fax; } public void setFax(String fax) { this.fax = fax; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getRep() { return rep; } public void setRep(String rep) { this.rep = rep; } public Collection<Product> getProductCollection() { return productCollection; } public void setProductCollection(Collection<Product> productCollection) { this.productCollection = productCollection; } @Override public int hashCode() { int hash = 0; hash += (manufacturerId != null ? manufacturerId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Manufacturer)) { return false; } Manufacturer other = (Manufacturer) object; if ((this.manufacturerId == null && other.manufacturerId != null) || (this.manufacturerId != null && !this.manufacturerId.equals(other.manufacturerId))) { return false; } return true; } @Override public String toString() { return "edu.chl.tdaniel.jpa_query.nbp.core.Manufacturer[ manufacturerId=" + manufacturerId + " ]"; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.chl.tdaniel.jpa_query.nbp.core; import java.io.Serializable; import java.math.BigDecimal; import java.util.Collection; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.NotNull; /** * * @author Daniel */ @Entity @Table(name = "DISCOUNT_CODE") @NamedQueries({ @NamedQuery(name = "DiscountCode.findAll", query = "SELECT d FROM DiscountCode d")}) public class DiscountCode implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Column(name = "DISCOUNT_CODE") private Character discountCode; // @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation @Column(name = "RATE") private BigDecimal rate; @OneToMany(cascade = CascadeType.ALL, mappedBy = "discountCode") private Collection<Customer> customerCollection; public DiscountCode() { } public DiscountCode(Character discountCode) { this.discountCode = discountCode; } public Character getDiscountCode() { return discountCode; } public void setDiscountCode(Character discountCode) { this.discountCode = discountCode; } public BigDecimal getRate() { return rate; } public void setRate(BigDecimal rate) { this.rate = rate; } public Collection<Customer> getCustomerCollection() { return customerCollection; } public void setCustomerCollection(Collection<Customer> customerCollection) { this.customerCollection = customerCollection; } @Override public int hashCode() { int hash = 0; hash += (discountCode != null ? discountCode.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof DiscountCode)) { return false; } DiscountCode other = (DiscountCode) object; if ((this.discountCode == null && other.discountCode != null) || (this.discountCode != null && !this.discountCode.equals(other.discountCode))) { return false; } return true; } @Override public String toString() { return "edu.chl.tdaniel.jpa_query.nbp.core.DiscountCode[ discountCode=" + discountCode + " ]"; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.chl.tdaniel.ria; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author Daniel */ @WebServlet(name = "EncylopediaServlet", urlPatterns = {"/EncylopediaServlet"}) public class EncylopediaServlet extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); InputStream in = this.getClass().getClassLoader().getResourceAsStream(request.getParameter("what") + ".ihtml"); Scanner scan = new Scanner(in); //juhegviebviebvgi try { while (scan.hasNext()){ out.println(scan.nextLine()); } } finally { scan.close(); out.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
Java
package com.example.ayelet; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import com.example.ayelet.Imagelabels.ImageAndLabel; import com.example.ayelet.Imagelabels.ImageAndLabels; public class ChoosePhotosActivity extends Activity { private static final int RESULT_LOAD_IMAGE = 1; Uri currentImage = null; ImageView currentImageView; EditText labelEditText; ImageAndLabels.Builder imagelabelsBuilder; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.choose_photos); imagelabelsBuilder = ImageAndLabels.newBuilder(); currentImageView = (ImageView) findViewById(R.id.current_image); labelEditText = (EditText) findViewById(R.id.label); if (currentImage == null) { pickImage(); } } protected void pickImage() { Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(i, RESULT_LOAD_IMAGE); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) { Uri selectedImage = data.getData(); currentImage = selectedImage; currentImageView.setImageURI(currentImage); // String picturePath contains the path of selected Image } } public void addCurrentImage() { String label = labelEditText.getText().toString(); if (label.equals("")) { return; } ImageAndLabel imagelabel = ImageAndLabel.newBuilder().setLabel(label) .setUri(currentImage.toString()).build(); imagelabelsBuilder.addImages(imagelabel); labelEditText.setText(""); } public void nextClicked(View v) { addCurrentImage(); pickImage(); } public void doneClicked(View v) { addCurrentImage(); Intent intent = new Intent(); intent.putExtra("labels", imagelabelsBuilder.build().toByteArray()); setResult(LearnEnglish.AMIR_ACTIVITY, intent); finish(); } }
Java
package com.example.ayelet; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import android.widget.Toast; import com.example.ayelet.Imagelabels.ImageAndLabels; import com.google.protobuf.InvalidProtocolBufferException; public class LearnEnglish extends Activity { private ImageView ivImageView; private ImageAndLabels imagelabels = null; protected static final int AMIR_ACTIVITY = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_learn_english); ivImageView = (ImageView) findViewById(R.id.ivImageView); if (imagelabels == null) { Intent intent = new Intent(this, ChoosePhotosActivity.class); startActivityForResult(intent, AMIR_ACTIVITY); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // Check which request we're responding to if (requestCode == AMIR_ACTIVITY) { // Make sure the request was successful if (resultCode == RESULT_OK) { // The user picked a contact. // The Intent's data Uri identifies which contact was selected. try { imagelabels = ImageAndLabels.parseFrom(data.getByteArrayExtra("labels")); NextImage(); } catch (InvalidProtocolBufferException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Do something with the contact here (bigger example below) } } } private void NextImage() { Toast.makeText(this, "NextImage", Toast.LENGTH_LONG).show(); NextImage(null); } public void NextImage(View vSourceView) { // Getting random image //int nNextImageResource = GetResourceByUri(uNextImage); Uri uTemp = Uri.parse(imagelabels.getImages(0).getUri()); // Setting the new image ivImageView.setImageURI(uTemp); } public void Echo(View vSourceView) { } }
Java
package com.ayelet.learnenglish; import android.net.Uri; public class ImageAndLabel { private Uri ImageUri; private String Label; public Uri getImageUri() { return ImageUri; } public void setImageUri(Uri imageUri) { ImageUri = imageUri; } public String getLabel() { return Label; } public void setLabel(String label) { Label = label; } public Uri GetRandomImage() { return (ImageUri); } public Uri GetRandomImageDiff() { Uri uResult = GetRandomImage(); while (uResult == ImageUri) { uResult = GetRandomImage(); } return (uResult); } }
Java
package com.ayelet.learnenglish; import java.util.ArrayList; import android.support.v7.app.ActionBarActivity; import android.net.Uri; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; public class LearnEnglish extends ActionBarActivity { private ArrayList<ImageAndLabel> alList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_learn_english); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.learn_english, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public void NextImage(View vSourceView) { // Getting random image //int nNextImageResource = GetResourceByUri(uNextImage); ImageView ivImageView = (ImageView) findViewById(R.id.ivImageView); // Setting the new image ivImageView.setImageResource(R.drawable.a); } public void Echo(View vSourceView) { } private int GetResourceByUri(Uri uImageName) { final String PATH = "@drawable/"; String strFullPath = PATH + uImageName; int Result = getResources().getIdentifier(strFullPath, null, getPackageName()); return (Result); } }
Java
package com.example.testtts; import java.util.Locale; import android.content.Context; import android.speech.tts.TextToSpeech; import android.util.Log; public class Text2Speech implements TextToSpeech.OnInitListener { private TextToSpeech tts; public Text2Speech(Context context) { tts = new TextToSpeech(context, this); } @Override public void onInit(int status) { if (status == TextToSpeech.SUCCESS) { int result = tts.setLanguage(Locale.US); tts.setPitch(1); // set pitch level tts.setSpeechRate((float) 0.5); // set speech speed rate if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) { Log.e("TTS", "Language is not supported"); } else { // speakOut(); } } else { Log.e("TTS", "Initilization Failed"); } } public void speakOut(String text) { tts.speak(text, TextToSpeech.QUEUE_FLUSH, null); } }
Java
package com.example.testtts; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; public class MainActivity extends Activity { Text2Speech tts; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tts = new Text2Speech(this); } public void readIt(View view){ tts.speakOut("alon farted out loud. this is not nice"); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package haxemultiplayer; /** * * @author carlos */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here } }
Java
package finder; import java.awt.Color; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.HashMap; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTextField; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.border.EmptyBorder; public class MainFrame extends JFrame { private int shown; private ArrayList<ArrayList<Integer>> resList = new ArrayList<ArrayList<Integer>>(); private ArrayList<JCheckBox> boxes = new ArrayList<JCheckBox>(); private JPanel contentPane, resultPane; private JTextField tfRP; private JLabel lblRP, lblAmount, lblRes; private JButton btnRP, btnStop, btnMore; private JScrollPane spRP; private JSeparator sepV, sepH; private JCheckBox c3250, c1820, c1350, c975, c880, c790, c750, c675, c585, c520, c487, c440, c395, c390, c375, c292, c260, c250; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { MainFrame frame = new MainFrame(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public MainFrame() { setTitle("0 RP Finder"); setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException e1) { e1.printStackTrace(); } catch (InstantiationException e1) { e1.printStackTrace(); } catch (IllegalAccessException e1) { e1.printStackTrace(); } catch (UnsupportedLookAndFeelException e1) { e1.printStackTrace(); } setBounds(100, 100, 560, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setLayout(null); setContentPane(contentPane); sepV = new JSeparator(JSeparator.VERTICAL); sepV.setBounds(420, 5, 2, 225); contentPane.add(sepV); sepH = new JSeparator(JSeparator.HORIZONTAL); sepH.setBounds(420, 230, 130, 2); contentPane.add(sepH); lblRP = new JLabel("Enter your RP here"); lblRP.setForeground(Color.BLACK); lblRP.setBounds(130, 8, 130, 15); contentPane.add(lblRP); lblAmount = new JLabel("You are willing to pay"); lblAmount.setForeground(Color.BLACK); lblAmount.setBounds(437, 8, 120, 15); contentPane.add(lblAmount); lblRes = new JLabel("Results found: 55555"); lblRes.setForeground(Color.BLACK); lblRes.setBounds(100, 120, 200, 15); lblRes.setVisible(false); contentPane.add(lblRes); tfRP = new JTextField(); tfRP.setBounds(100, 25, 150, 25); contentPane.add(tfRP); btnRP = new JButton("Go!"); btnRP.setOpaque(false); btnRP.setFocusPainted(false); btnRP.addActionListener(new GoListener()); btnRP.setBounds(260, 27, 50, 21); contentPane.add(btnRP); btnStop = new JButton("Stop"); btnStop.setOpaque(false); btnStop.setFocusPainted(false); btnStop.setBounds(120, 140, 60, 20); btnStop.setVisible(false); contentPane.add(btnStop); btnMore = new JButton("More"); btnMore.setOpaque(false); btnMore.setFocusPainted(false); btnMore.setVisible(false); btnMore.addActionListener(new MoreListener()); btnMore.setBounds(420, 240, 60, 20); contentPane.add(btnMore); spRP = new JScrollPane(); spRP.getVerticalScrollBar().setPreferredSize(new Dimension(10, 10)); spRP.getVerticalScrollBar().setUnitIncrement(10); spRP.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); spRP.setBounds(5, 60, 405, 210); contentPane.add(spRP); resultPane = new JPanel(); resultPane.setLayout(null); spRP.setViewportView(resultPane); c3250 = new JCheckBox("3250 RP"); c1820 = new JCheckBox("1820 RP"); c1350 = new JCheckBox("1350 RP"); c975 = new JCheckBox("975 RP"); c880 = new JCheckBox("880 RP"); c790 = new JCheckBox("790 RP"); c750 = new JCheckBox("750 RP"); c675 = new JCheckBox("675 RP"); c585 = new JCheckBox("585 RP"); c520 = new JCheckBox("520 RP"); c487 = new JCheckBox("487 RP"); c440 = new JCheckBox("440 RP"); c395 = new JCheckBox("395 RP"); c390 = new JCheckBox("390 RP"); c375 = new JCheckBox("375 RP"); c292 = new JCheckBox("292 RP"); c260 = new JCheckBox("260 RP"); c250 = new JCheckBox("250 RP"); boxes.add(c3250); boxes.add(c1820); boxes.add(c1350); boxes.add(c975); boxes.add(c880); boxes.add(c790); boxes.add(c750); boxes.add(c675); boxes.add(c585); boxes.add(c520); boxes.add(c487); boxes.add(c440); boxes.add(c395); boxes.add(c390); boxes.add(c375); boxes.add(c292); boxes.add(c260); boxes.add(c250); c3250.setBounds(425, 30, 65, 15); c1820.setBounds(425, 47, 65, 15); c1350.setBounds(425, 64, 65, 15); c975.setBounds(425, 81, 65, 15); c880.setBounds(425, 98, 65, 15); c790.setBounds(425, 115, 65, 15); c750.setBounds(425, 132, 65, 15); c675.setBounds(425, 149, 65, 15); c585.setBounds(425, 166, 65, 15); c520.setBounds(490, 30, 65, 15); c487.setBounds(490, 47, 65, 15); c440.setBounds(490, 64, 65, 15); c395.setBounds(490, 81, 65, 15); c390.setBounds(490, 98, 65, 15); c375.setBounds(490, 115, 65, 15); c292.setBounds(490, 132, 65, 15); c260.setBounds(490, 149, 65, 15); c250.setBounds(490, 166, 65, 15); c3250.setToolTipText("Ultimate Skin"); c1820.setToolTipText("Legendary Skin"); c1350.setToolTipText("High-Tier Skin"); c975.setToolTipText("6300 Champ/Normal Skin"); c880.setToolTipText("4800 Champ"); c790.setToolTipText("3150 Champ"); c750.setToolTipText("Medium-Tier Skin"); c675.setToolTipText("High-Tier Skin on sale"); c585.setToolTipText("1350 Champ"); c520.setToolTipText("Low-Tier Skin"); c487.setToolTipText("6300 Champ/Normal Skin on sale"); c440.setToolTipText("4800 Champ on sale"); c395.setToolTipText("3150 Champ on sale"); c390.setToolTipText("Bottom-Tier Skin"); c375.setToolTipText("Medium-Tier Skin on sale"); c292.setToolTipText("1350 Champ on sale"); c260.setToolTipText("Low-Tier Skin on Sale"); c250.setToolTipText("Summoner Icon"); c1350.setSelected(true); c975.setSelected(true); c750.setSelected(true); c675.setSelected(true); c520.setSelected(true); c487.setSelected(true); c390.setSelected(true); c375.setSelected(true); c260.setSelected(true); contentPane.add(c3250); contentPane.add(c1820); contentPane.add(c1350); contentPane.add(c975); contentPane.add(c880); contentPane.add(c790); contentPane.add(c750); contentPane.add(c675); contentPane.add(c585); contentPane.add(c520); contentPane.add(c487); contentPane.add(c440); contentPane.add(c395); contentPane.add(c390); contentPane.add(c375); contentPane.add(c292); contentPane.add(c260); contentPane.add(c250); } private int[] rpValues() { int count = 0; int[] rpvals = {3250, 1820, 1350, 975, 880, 790, 750, 675, 585, 520, 487, 440, 395, 390, 375, 292, 260, 250}; for (int i = 0; i < boxes.size(); i++) { if (boxes.get(i).isSelected()) { count++; } } int[] vals = new int[count]; count = 0; for (int i = 0; i < boxes.size(); i++) { if (boxes.get(i).isSelected()) { vals[count] = rpvals[i]; count++; } } return vals; } private void findSolutions() { resList.clear(); shown = 0; resultPane.removeAll(); boolean go = false; final int[] RP = rpValues(); HashMap<Integer, Counter> counterMap = new HashMap<Integer, Counter>(); int nbrp; try { nbrp = Integer.parseInt(tfRP.getText()); go = true; } catch (Exception e) { JOptionPane.showMessageDialog(null, "Invalid RP value", "Oh no!", JOptionPane.ERROR_MESSAGE); nbrp = 0; } int cntr = 1; counterMap.put(cntr, new Counter(0)); while (!counterMap.isEmpty() && go) { int tmpRP = nbrp; while (tmpRP > 0) { tmpRP = nbrp; for (int i = 1; i <= cntr; i++) { tmpRP -= RP[counterMap.get(i).index]; } if (tmpRP > 0) { counterMap.put(cntr + 1, new Counter(counterMap.get(cntr).index)); cntr++; } } if (tmpRP == 0) { ArrayList<Integer> zero = new ArrayList<Integer>(); for (int i = 1; i <= cntr; i++) { zero.add(RP[counterMap.get(i).index]); } resList.add(zero); if (resList.size() % 5000 == 0) { int resp = JOptionPane.showConfirmDialog(null, "The amount of solutions is over " + resList.size()+ "! " + "Would you like to stop, now?", "Hey listen!", JOptionPane.YES_NO_OPTION); if (resp == JOptionPane.YES_OPTION) { go = false; } } } while (!counterMap.isEmpty() && counterMap.get(cntr).index == RP.length - 1) { counterMap.remove(cntr); cntr--; } if (counterMap.isEmpty()) { break; } else { counterMap.get(cntr).index++; } } } private void showResults(int start, int number) { int count = start; shown += number; while (count < shown && count < resList.size()) { ArrayList<Integer> list = resList.get(count); int index = 0; int value = list.get(0); int valCount = 0; StringBuilder sb = new StringBuilder(); sb.append(" "); while (index < list.size()) { if (list.get(index) != value) { sb.append(valCount + "x" + value + ", "); value = list.get(index); valCount = 1; } else { valCount++; } index++; } sb.append(valCount + "x" + value); JLabel resLbl = new JLabel(sb.toString()); resLbl.setBounds(0, count * 18, resultPane.getWidth(), 18); if (count % 2 == 0) { resLbl.setBackground(Color.decode("#DDDDDD")); resLbl.setOpaque(true); } resultPane.add(resLbl); System.out.println(sb.toString()); count++; } resultPane.setPreferredSize(new Dimension(resultPane.getWidth(), count * 18)); resultPane.revalidate(); resultPane.repaint(); if (shown >= resList.size()) { btnMore.setVisible(false); } else { btnMore.setVisible(true); } } private class GoListener implements ActionListener { public void actionPerformed(ActionEvent e) { findSolutions(); showResults(0, 10); } } private class MoreListener implements ActionListener { public void actionPerformed(ActionEvent e) { showResults(shown, 10); } } private class Counter { public int index; public Counter(int ind) { index = ind; } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * InventProducts.java * * Created on 2009-12-18, 15:54:32 */ /** * * @author Stan */ public class InventProducts extends javax.swing.JFrame { /** Creates new form InventProducts */ public InventProducts() { initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jButton1 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setFont(new java.awt.Font("宋体", 1, 18)); // NOI18N jLabel1.setText("InvenProducts"); jTextArea1.setColumns(20); jTextArea1.setRows(5); jTextArea1.setText("No:1 Name:Chery-S16 Inventories:No:1 Name:Valve No:2 Name:Over Head Camshaft No:3 Name:Cylinder Block \nNo:2 Name:Chery-A5 Inventories: No:1 Name:Valve No:2 Name:Over Head Camshaft No:3 Name:Cylinder Block \nNo:3 Name:Chery-QQ6 Inventories: No:1 Name:Valve No:2 Name:Over Head Camshaft No:3 Name:Cylinder Block "); jScrollPane1.setViewportView(jTextArea1); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 457, Short.MAX_VALUE))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel1) .addGap(10, 10, 10) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 248, Short.MAX_VALUE)) ); jButton1.setText("Back"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jButton1) .addContainerGap(410, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton1)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed this.setVisible(false); }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new InventProducts().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea jTextArea1; // End of variables declaration//GEN-END:variables }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * NewJFrame.java * * Created on 2009-12-17, 16:20:22 */ /** * * @author Stan */ public class NewJFrame extends javax.swing.JFrame { /** Creates new form NewJFrame */ public NewJFrame() { initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jButton1.setText("Products"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("Inventories"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jButton3.setText("InventProduct"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jButton4.setText("Exit"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(36, 36, 36) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jButton4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jButton1) .addGap(18, 18, 18) .addComponent(jButton2) .addGap(18, 18, 18) .addComponent(jButton3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton4) .addContainerGap(24, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(24, 24, 24) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(49, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(73, 73, 73)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed new Products().setVisible(true); }//GEN-LAST:event_jButton1ActionPerformed private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed this.setVisible(false); }//GEN-LAST:event_jButton4ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed new Inventories().setVisible(true); }//GEN-LAST:event_jButton2ActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed new InventProducts().setVisible(true); }//GEN-LAST:event_jButton3ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new NewJFrame().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JPanel jPanel1; // End of variables declaration//GEN-END:variables }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * Inventories.java * * Created on 2009-12-18, 15:45:12 */ /** * * @author Stan */ public class Inventories extends javax.swing.JFrame { /** Creates new form Inventories */ public Inventories() { initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jButton1 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setFont(new java.awt.Font("宋体", 1, 18)); // NOI18N jLabel1.setText("Inventories"); jTextArea1.setColumns(20); jTextArea1.setRows(5); jTextArea1.setText("No:1 Name:Valve Num:10600 Describe:a Item of car\nNo:2 Name:Over Head Camshaft Num:20100 Describe:a Item of car\nNo:3 Name:Cylinder Block Num:14590 Describe:a Item of car\nNo:4 Name:Crank Shaft Num:7500 Describe:a Item of car\nNo:5 Name:Intake Valve Num:9800 Describe:a Item of car\nNo:6 Name:Camshaft Num:28900 Describe:a Item of car\nNo:7 Name:Fuel Pump Num:34200 Describe:a Item of car"); jScrollPane1.setViewportView(jTextArea1); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel1) .addContainerGap(406, Short.MAX_VALUE)) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 516, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel1) .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 237, Short.MAX_VALUE)) ); jButton1.setText("Back"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(jButton1) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton1)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed this.setVisible(false); }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Inventories().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea jTextArea1; // End of variables declaration//GEN-END:variables }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * Products.java * * Created on 2009-12-18, 15:29:09 */ /** * * @author Stan */ public class Products extends javax.swing.JFrame { /** Creates new form Products */ public Products() { initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jLabel1 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jTextArea1.setColumns(20); jTextArea1.setRows(5); jTextArea1.setText("No:1 Name:Chery-S16 Describe:Chery Auto plans to start produce this new mini car in April or May 2009\nNo:2 Name:Chery-A5 Describe:Chinese carmaker Chery Automobile announced that chery's two car\nNo:3 Name:Chery-QQ6 Describe:Chery Auto car new mini car"); jScrollPane1.setViewportView(jTextArea1); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(22, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 515, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(105, 105, 105)) ); jLabel1.setText("Products"); jButton1.setText("Back"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGap(25, 25, 25) .addComponent(jButton1) .addContainerGap(475, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jButton1) .addGap(64, 64, 64)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed this.setVisible(false); }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Products().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea jTextArea1; // End of variables declaration//GEN-END:variables }
Java
package lobster.games.studios; import levels.Level1; import lobster.games.studios.R; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class Main extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button play = (Button)findViewById(R.id.PlayButton); Button levelSelect = (Button)findViewById(R.id.LevelSelectButton); play.setOnClickListener(new OnClickListener() { //@Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(), Level1.class); startActivity(intent); } }); levelSelect.setOnClickListener(new OnClickListener() { //@Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(), LevelSelect.class); startActivity(intent); } }); } }
Java
package lobster.games.studios; import lobster.games.studios.ImageAdapter; import android.app.Activity; import android.content.res.Resources; import android.os.Bundle; import android.widget.GridView; public class LevelSelect extends Activity{ GridView gridView; static int[] levels; @Override public void onCreate(Bundle savedInstanceState) { Resources res = getResources(); levels = new int[res.getInteger(R.integer.numberoflevels)]; for(int i = 0; i < levels.length; i++){ levels[i] = i + 1; } super.onCreate(savedInstanceState); setContentView(R.layout.levelselect); gridView = (GridView) findViewById(R.id.gridview); gridView.setAdapter(new ImageAdapter(this, levels)); } }
Java
package lobster.games.studios; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.Toast; import lobster.games.studios.R; public class ImageAdapter extends BaseAdapter { /*int mGalleryItemBackground; private Context mContext; private final int[] values;*/ private Context context; private final int[] values; public ImageAdapter(Context context, int[] values) { this.context = context; this.values = values; } public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View gridView; final Button button; if (convertView == null) { gridView = new View(context); // get layout from mobile.xml gridView = inflater.inflate(R.layout.mobile, null); } else { gridView = (View) convertView; } button = (Button) gridView.findViewById(R.id.grid_item_image); button.setText("" + values[position]); button.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { String aux = "levels.Level" + button.getText().toString(); Class<?> clazz; try { clazz = Class.forName(aux); Intent intent = new Intent(context, clazz); ((Activity)context).startActivity(intent); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } }); button.setOnClickListener(new OnClickListener() { public void onClick(View v) { String aux = "Level" + button.getText().toString(); Toast.makeText(context, "ola", 5); Class<?> clazz; try { clazz = Class.forName(aux); Intent intent = new Intent(context, clazz); ((Activity)context).startActivity(intent); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); return gridView; } public int getCount() { return values.length; } public Object getItem(int position) { return null; } public long getItemId(int position) { return 0; } /*public ImageAdapter(Context c, int[] values) { mContext = c; this.values = values; mGalleryItemBackground = R.drawable.windowssssicon; /*TypedArray a = c.obtainStyledAttributes(R.styleable.HelloGallery); mGalleryItemBackground = a.getResourceId(R.drawable.windowssssicon, 0); a.recycle(); } public int getCount() { //return mImageIds.length; return values.length; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { final Button button = new Button(mContext); final int pos = position; button.setLayoutParams(new Gallery.LayoutParams(100,100)); button.setBackgroundResource(mGalleryItemBackground); button.setText("" + values[position]); button.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { String aux = "levels.Level" + button.getText().toString(); Toast.makeText(mContext, "ola" + values[pos], Toast.LENGTH_SHORT).show(); Class<?> clazz = null; if(aux != null){ try { clazz = Class.forName(aux); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } Intent intent = new Intent(mContext, clazz); ((Activity)mContext).startActivity(intent); } return false; } }); return button; }*/ }
Java
package lobster.games.studios; import lobster.games.studios.R; import android.app.Activity; import android.content.Intent; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.view.MotionEvent; public class Splash extends Activity { //how long until we go to the next activity protected int _splashTime = 1500; protected int ACTIVITY_MAIN = 100; private Thread splashTread; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.splash); this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); final Splash sPlashScreen = this; // thread for displaying the SplashScreen splashTread = new Thread() { @Override public void run() { try { synchronized(this){ //wait 1,5 sec wait(_splashTime); } } catch(InterruptedException e) {} finally { //start a new activity Intent i = new Intent(); i.setClass(sPlashScreen, Main.class); startActivityForResult(i,ACTIVITY_MAIN); // stop(); } } }; splashTread.start(); } @Override public void onActivityResult (int requestCode, int resultCode, Intent data){ if (requestCode == ACTIVITY_MAIN) { if (resultCode == 0) { finish(); } } } //Function that will handle the touch @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { synchronized(splashTread){ splashTread.notifyAll(); } } return true; } }
Java
package levels; import lobster.games.studios.R; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.WindowManager.LayoutParams; public class Level7 extends Activity{ private View selected_item = null; private int offset_x = 0; private int offset_y = 0; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.level); getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON); /*ImageView img = (ImageView)findViewById(R.id.windowView1); img.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { switch(event.getAction()) { case MotionEvent.ACTION_DOWN: offset_x = (int)event.getX(); offset_y = (int)event.getY(); selected_item = v; break; default: break; } return false; } });*/ } }
Java
package levels; import lobster.games.studios.R; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.WindowManager.LayoutParams; public class Level10 extends Activity{ private View selected_item = null; private int offset_x = 0; private int offset_y = 0; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.level); getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON); /*ImageView img = (ImageView)findViewById(R.id.windowView1); img.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { switch(event.getAction()) { case MotionEvent.ACTION_DOWN: offset_x = (int)event.getX(); offset_y = (int)event.getY(); selected_item = v; break; default: break; } return false; } });*/ } }
Java
package levels; import lobster.games.studios.R; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.WindowManager.LayoutParams; public class Level8 extends Activity{ private View selected_item = null; private int offset_x = 0; private int offset_y = 0; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.level); getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON); /*ImageView img = (ImageView)findViewById(R.id.windowView1); img.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { switch(event.getAction()) { case MotionEvent.ACTION_DOWN: offset_x = (int)event.getX(); offset_y = (int)event.getY(); selected_item = v; break; default: break; } return false; } });*/ } }
Java
package levels; import lobster.games.studios.R; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.WindowManager.LayoutParams; public class Level9 extends Activity{ private View selected_item = null; private int offset_x = 0; private int offset_y = 0; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.level); getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON); /*ImageView img = (ImageView)findViewById(R.id.windowView1); img.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { switch(event.getAction()) { case MotionEvent.ACTION_DOWN: offset_x = (int)event.getX(); offset_y = (int)event.getY(); selected_item = v; break; default: break; } return false; } });*/ } }
Java
package levels; import lobster.games.studios.R; import android.app.Activity; import android.os.Bundle; import android.view.WindowManager.LayoutParams; public class Level4 extends Activity{ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.level); getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON); /*final ImageView img = (ImageView)findViewById(R.id.windowView1); img.setOnClickListener(new OnClickListener() { //@Override public void onClick(View v) { img.setImageResource(R.drawable.openwindow); //img.setImageDrawable(drawable) /* Intent intent = new Intent(getApplicationContext(), Level1.class); startActivity(intent); } });*/ } }
Java
package levels; import lobster.games.studios.R; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.WindowManager.LayoutParams; public class Level6 extends Activity{ private View selected_item = null; private int offset_x = 0; private int offset_y = 0; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.level); getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON); /*ImageView img = (ImageView)findViewById(R.id.windowView1); img.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { switch(event.getAction()) { case MotionEvent.ACTION_DOWN: offset_x = (int)event.getX(); offset_y = (int)event.getY(); selected_item = v; break; default: break; } return false; } });*/ } }
Java
package levels; import lobster.games.studios.R; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.WindowManager.LayoutParams; public class Level3 extends Activity{ private View selected_item = null; private int offset_x = 0; private int offset_y = 0; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.level); getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON); /*ImageView img = (ImageView)findViewById(R.id.windowView1); img.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { switch(event.getAction()) { case MotionEvent.ACTION_DOWN: offset_x = (int)event.getX(); offset_y = (int)event.getY(); selected_item = v; break; default: break; } return false; } });*/ } }
Java
package levels; import lobster.games.studios.R; import android.app.Activity; import android.content.Intent; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.WindowManager.LayoutParams; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; public class Level2 extends Activity implements SensorEventListener{ private SensorManager sensorManager = null; private float axisX; private ImageView img; private TextView levelText; private RelativeLayout windowLayout; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); setContentView(R.layout.level); getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON); levelText = new TextView(this); levelText = (TextView)findViewById(R.id.leveltext); levelText.setText("Level 2"); windowLayout = (RelativeLayout)findViewById(R.id.windowlayout); img = new ImageView(this); img.setImageResource(R.drawable.window); windowLayout.addView(img); img.setOnClickListener(new OnClickListener() { //@Override public void onClick(View v) { if(img.getId() == R.drawable.openwindow){ Intent intent = new Intent(getApplicationContext(), Level3.class); startActivity(intent); } } }); } @Override protected void onResume() { super.onResume(); sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL); sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_NORMAL); } @Override protected void onStop() { super.onStop(); sensorManager.unregisterListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)); sensorManager.unregisterListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION)); } public void onSensorChanged(SensorEvent event) { // TODO Auto-generated method stub synchronized (this) { switch (event.sensor.getType()){ case Sensor.TYPE_ACCELEROMETER: axisX = event.values[0]; if(axisX < 0){ img.setImageResource(R.drawable.openwindow); } else if(axisX > 0){ img.setImageResource(R.drawable.window); } break; } } } public void onAccuracyChanged(Sensor arg0, int arg1) { // TODO Auto-generated method stub } }
Java
package levels; import lobster.games.studios.R; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.WindowManager.LayoutParams; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; public class Level1 extends Activity{ private Thread splashTread; private ImageView windowImage; private TextView levelText; private Button icon2; private RelativeLayout screenLayout, windowLayout; private LinearLayout itemsLayout; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.level); getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON); screenLayout = (RelativeLayout)findViewById(R.id.gamelayout); windowLayout = (RelativeLayout)findViewById(R.id.windowlayout); itemsLayout = (LinearLayout)findViewById(R.id.linearlayout); windowImage = new ImageView(this); icon2 = new Button(this); windowImage.setImageResource(R.drawable.window); windowLayout.addView(windowImage); icon2 = (Button)findViewById(R.id.button2); icon2.setBackgroundResource(R.drawable.ic_launcher); levelText = new TextView(this); levelText = (TextView)findViewById(R.id.leveltext); levelText.setText("Level 1"); windowImage.setOnClickListener(new OnClickListener() { //@Override public void onClick(View v) { windowImage.invalidate(); windowImage.setImageResource(R.drawable.openwindow); splashTread = new Thread() { @Override public void run() { try { synchronized(this){ //wait 1 sec wait(1000); } } catch(InterruptedException e) {} finally { //start a new activity Intent intent = new Intent(getApplicationContext(), Level2.class); startActivity(intent); // stop(); } } }; splashTread.start(); } }); } }
Java
package lobster.games.studios; import levels.Level1; import lobster.games.studios.R; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class Main extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button play = (Button) findViewById(R.id.PlayButton); Button levelSelect = (Button) findViewById(R.id.LevelSelectButton); play.setOnClickListener(new OnClickListener() { // @Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(), Level1.class); startActivity(intent); } }); levelSelect.setOnClickListener(new OnClickListener() { // @Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(), LevelSelect.class); startActivity(intent); } }); } }
Java
package lobster.games.studios; import lobster.games.studios.ImageAdapter; import android.app.Activity; import android.content.res.Resources; import android.os.Bundle; import android.widget.GridView; public class LevelSelect extends Activity { GridView gridView; static int[] levels; @Override public void onCreate(Bundle savedInstanceState) { Resources res = getResources(); levels = new int[res.getInteger(R.integer.numberoflevels)]; for (int i = 0; i < levels.length; i++) { levels[i] = i + 1; } super.onCreate(savedInstanceState); setContentView(R.layout.levelselect); gridView = (GridView) findViewById(R.id.gridview); gridView.setAdapter(new ImageAdapter(this, levels)); } }
Java
package lobster.games.studios; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.Toast; import lobster.games.studios.R; public class ImageAdapter extends BaseAdapter { /* * int mGalleryItemBackground; private Context mContext; private final int[] * values; */ private Context context; private final int[] values; public ImageAdapter(Context context, int[] values) { this.context = context; this.values = values; } public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View gridView; final Button button; if (convertView == null) { gridView = new View(context); // get layout from mobile.xml gridView = inflater.inflate(R.layout.mobile, null); } else { gridView = (View) convertView; } button = (Button) gridView.findViewById(R.id.grid_item_image); button.setText("" + values[position]); button.setOnClickListener(new OnClickListener() { public void onClick(View v) { String aux = "levels.Level" + button.getText().toString(); Class<?> clazz; try { clazz = Class.forName(aux); Intent intent = new Intent(context, clazz); ((Activity) context).startActivity(intent); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } //return false; } }); return gridView; } public int getCount() { return values.length; } public Object getItem(int position) { return null; } public long getItemId(int position) { return 0; } /* * public ImageAdapter(Context c, int[] values) { mContext = c; this.values * = values; mGalleryItemBackground = R.drawable.windowssssicon; * /*TypedArray a = c.obtainStyledAttributes(R.styleable.HelloGallery); * mGalleryItemBackground = a.getResourceId(R.drawable.windowssssicon, 0); * a.recycle(); } * * public int getCount() { //return mImageIds.length; return values.length; * } * * public Object getItem(int position) { return position; } * * public long getItemId(int position) { return position; } * * public View getView(int position, View convertView, ViewGroup parent) { * final Button button = new Button(mContext); final int pos = position; * * button.setLayoutParams(new Gallery.LayoutParams(100,100)); * button.setBackgroundResource(mGalleryItemBackground); button.setText("" + * values[position]); * * button.setOnTouchListener(new OnTouchListener() { * * public boolean onTouch(View v, MotionEvent event) { String aux = * "levels.Level" + button.getText().toString(); Toast.makeText(mContext, * "ola" + values[pos], Toast.LENGTH_SHORT).show(); * * Class<?> clazz = null; if(aux != null){ try { clazz = Class.forName(aux); * * } catch (ClassNotFoundException e) { // TODO Auto-generated catch block * e.printStackTrace(); } Intent intent = new Intent(mContext, clazz); * ((Activity)mContext).startActivity(intent); } return false; } }); * * return button; } */ }
Java
package lobster.games.studios; import lobster.games.studios.R; import android.app.Activity; import android.content.Intent; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.view.MotionEvent; public class Splash extends Activity { // how long until we go to the next activity protected int _splashTime = 1500; protected int ACTIVITY_MAIN = 100; private Thread splashTread; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.splash); this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); final Splash sPlashScreen = this; // thread for displaying the SplashScreen splashTread = new Thread() { @Override public void run() { try { synchronized (this) { // wait 1,5 sec wait(_splashTime); } } catch (InterruptedException e) { } finally { // start a new activity Intent i = new Intent(); i.setClass(sPlashScreen, Main.class); startActivityForResult(i, ACTIVITY_MAIN); // stop(); } } }; splashTread.start(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == ACTIVITY_MAIN) { if (resultCode == 0) { finish(); } } } // Function that will handle the touch @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { synchronized (splashTread) { splashTread.notifyAll(); } } return true; } }
Java
package levels; import java.util.ArrayList; import lobster.games.studios.R; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.WindowManager.LayoutParams; import android.widget.Button; import android.widget.ImageView; public class Level7 extends Activity { private Button buttonTop, buttonLeftMid, buttonMid, buttonRightMid, buttonRightRightMid, buttonBot; private int aux; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.level7); getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON); buttonTop = new Button(this); buttonLeftMid = new Button(this); buttonMid = new Button(this); buttonRightMid = new Button(this); buttonRightRightMid = new Button(this); buttonBot = new Button(this); buttonTop = (Button) findViewById(R.id.buttonTop); buttonLeftMid = (Button) findViewById(R.id.buttonLeftMid); buttonMid = (Button) findViewById(R.id.buttonMid); buttonRightMid = (Button) findViewById(R.id.buttonRightMid); buttonRightRightMid = (Button) findViewById(R.id.buttonRightRightMid); buttonBot = (Button) findViewById(R.id.buttonTop); buttonTop.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { changeValue((Button) v); } }); buttonLeftMid.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { changeValue((Button) v); } }); buttonMid.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { changeValue((Button) v); } }); buttonRightMid.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { changeValue((Button) v); } }); buttonRightRightMid.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { changeValue((Button) v); } }); buttonBot.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { changeValue((Button) v); } }); } public void changeValue(Button v) { aux = Integer.parseInt(v.getText().toString()); if (aux == 6) aux = 1; else aux++; v.setText(aux); } }
Java
package levels; import lobster.games.studios.R; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.WindowManager.LayoutParams; public class Level10 extends Activity { private View selected_item = null; private int offset_x = 0; private int offset_y = 0; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.level); getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON); /* * ImageView img = (ImageView)findViewById(R.id.windowView1); * img.setOnTouchListener(new View.OnTouchListener() { * * public boolean onTouch(View v, MotionEvent event) { * switch(event.getAction()) { case MotionEvent.ACTION_DOWN: offset_x = * (int)event.getX(); offset_y = (int)event.getY(); selected_item = v; * break; default: break; } return false; } }); */ } }
Java
package levels; import lobster.games.studios.R; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.WindowManager.LayoutParams; public class Level8 extends Activity { private View selected_item = null; private int offset_x = 0; private int offset_y = 0; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.level); getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON); /* * ImageView img = (ImageView)findViewById(R.id.windowView1); * img.setOnTouchListener(new View.OnTouchListener() { * * public boolean onTouch(View v, MotionEvent event) { * switch(event.getAction()) { case MotionEvent.ACTION_DOWN: offset_x = * (int)event.getX(); offset_y = (int)event.getY(); selected_item = v; * break; default: break; } return false; } }); */ } }
Java
package levels; import lobster.games.studios.R; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.WindowManager.LayoutParams; public class Level9 extends Activity { private View selected_item = null; private int offset_x = 0; private int offset_y = 0; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.level); getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON); /* * ImageView img = (ImageView)findViewById(R.id.windowView1); * img.setOnTouchListener(new View.OnTouchListener() { * * public boolean onTouch(View v, MotionEvent event) { * switch(event.getAction()) { case MotionEvent.ACTION_DOWN: offset_x = * (int)event.getX(); offset_y = (int)event.getY(); selected_item = v; * break; default: break; } return false; } }); */ } }
Java
package levels; import lobster.games.studios.R; import android.app.Activity; import android.os.Bundle; import android.view.WindowManager.LayoutParams; public class Level4 extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.level); getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON); /* * final ImageView img = (ImageView)findViewById(R.id.windowView1); * img.setOnClickListener(new OnClickListener() { * * //@Override public void onClick(View v) { * img.setImageResource(R.drawable.openwindow); * //img.setImageDrawable(drawable) * * * /* Intent intent = new Intent(getApplicationContext(), Level1.class); * startActivity(intent); } }); */ } }
Java
package levels; import java.util.ArrayList; import lobster.games.studios.R; import android.app.Activity; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.view.View; import android.view.WindowManager.LayoutParams; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; public class Level6 extends Activity { private Button[] buttonsPlus; private Button[] buttonsLess; private TextView[] textValues; private TextView[] textFlushs; private ImageView cardOne, cardTwo, cardThree; private ArrayList<String> flush = new ArrayList<String>();// = {"\u2660", // "\u2663", // "\u2666", // "\u2665"}; private ArrayList<String> value = new ArrayList<String>(); // = {"2", "3", // "4", "5", // "6", "7", // "8", "9", // "10", "J", // "Q", "K", // "A"}; private int i, aux; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.level6); getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON); cardOne = new ImageView(this); cardTwo = new ImageView(this); cardThree = new ImageView(this); cardOne = (ImageView) findViewById(R.id.cardOne); cardTwo = (ImageView) findViewById(R.id.cardTwo); cardThree = (ImageView) findViewById(R.id.cardThree); // cardOne.setImageResource(R.drawable.espadas5); flush.add("\u2660"); flush.add("\u2663"); flush.add("\u2666"); flush.add("\u2665"); value.add("2"); value.add("3"); value.add("4"); value.add("5"); value.add("6"); value.add("7"); value.add("8"); value.add("9"); value.add("10"); value.add("J"); value.add("Q"); value.add("K"); value.add("A"); buttonsPlus = findPlusButtons(); buttonsLess = findLessButtons(); textValues = findTextValueViews(); textFlushs = findTextFlushViews(); textFlushs[0].setText("\u2660"); textFlushs[0].setTextColor(Color.BLACK); textFlushs[0].setTextSize(30.0f); textFlushs[1].setText("\u2665"); textFlushs[1].setTextColor(Color.RED); textFlushs[1].setTextSize(30.0f); textFlushs[2].setText("\u2663"); textFlushs[2].setTextColor(Color.BLACK); textFlushs[2].setTextSize(30.0f); textValues[0].setText("2"); textValues[0].setTextSize(30.0f); textValues[0].setTextColor(Color.BLACK); textValues[1].setText("K"); textValues[1].setTextSize(30.0f); textValues[1].setTextColor(Color.BLACK); textValues[2].setText("7"); textValues[2].setTextSize(30.0f); textValues[2].setTextColor(Color.BLACK); for (i = 0; i < 6; i++) { buttonsPlus[i].setOnClickListener(new View.OnClickListener() { public void onClick(View v) { changeValue(((Button) v).getId()); } }); } for (i = 0; i < 6; i++) { buttonsLess[i].setOnClickListener(new View.OnClickListener() { public void onClick(View v) { changeValue(((Button) v).getId()); } }); } } public Button[] findPlusButtons() { Button[] b = new Button[6]; for (int a = 0; a < b.length; a++) { b[a] = new Button(this); } b[0] = (Button) findViewById(R.id.buttonPlus11); b[1] = (Button) findViewById(R.id.buttonPlus12); b[2] = (Button) findViewById(R.id.buttonPlus21); b[3] = (Button) findViewById(R.id.buttonPlus22); b[4] = (Button) findViewById(R.id.buttonPlus31); b[5] = (Button) findViewById(R.id.buttonPlus32); return b; } public Button[] findLessButtons() { Button[] b = new Button[6]; for (int a = 0; a < b.length; a++) { b[a] = new Button(this); } b[0] = (Button) findViewById(R.id.buttonLess11); b[1] = (Button) findViewById(R.id.buttonLess12); b[2] = (Button) findViewById(R.id.buttonLess21); b[3] = (Button) findViewById(R.id.buttonLess22); b[4] = (Button) findViewById(R.id.buttonLess31); b[5] = (Button) findViewById(R.id.buttonLess32); return b; } public TextView[] findTextFlushViews() { TextView[] b = new TextView[3]; for (int a = 0; a < b.length; a++) { b[a] = new TextView(this); } b[0] = (TextView) findViewById(R.id.text12); b[1] = (TextView) findViewById(R.id.text22); b[2] = (TextView) findViewById(R.id.text32); return b; } public TextView[] findTextValueViews() { TextView[] b = new TextView[3]; for (int a = 0; a < b.length; a++) { b[a] = new TextView(this); } b[0] = (TextView) findViewById(R.id.text11); b[1] = (TextView) findViewById(R.id.text21); b[2] = (TextView) findViewById(R.id.text31); return b; } public void changeValue(int id) { switch (id) { case (R.id.buttonPlus11): aux = value.indexOf(textValues[0].getText().toString()) + 1; if (aux == value.size()) aux = 0; textValues[0].setText(value.get(aux)); break; case (R.id.buttonPlus12): aux = flush.indexOf(textFlushs[0].getText().toString()) + 1; if (aux == flush.size()) aux = 0; if (aux > 1) { textFlushs[0].setTextColor(Color.RED); } else { textFlushs[0].setTextColor(Color.BLACK); } textFlushs[0].setText(flush.get(aux)); break; case (R.id.buttonPlus21): aux = value.indexOf(textValues[1].getText().toString()) + 1; if (aux == value.size()) aux = 0; System.out.println("" + value.get(aux)); textValues[1].setText(value.get(aux)); break; case (R.id.buttonPlus22): aux = flush.indexOf(textFlushs[1].getText().toString()) + 1; if (aux == flush.size()) aux = 0; if (aux > 1) { textFlushs[1].setTextColor(Color.RED); } else { textFlushs[1].setTextColor(Color.BLACK); } textFlushs[1].setText(flush.get(aux)); break; case (R.id.buttonPlus31): aux = value.indexOf(textValues[2].getText().toString()) + 1; if (aux == value.size()) aux = 0; textValues[2].setText(value.get(aux)); break; case (R.id.buttonPlus32): aux = flush.indexOf(textFlushs[2].getText().toString()) + 1; if (aux == flush.size()) aux = 0; if (aux > 1) { textFlushs[2].setTextColor(Color.RED); } else { textFlushs[2].setTextColor(Color.BLACK); } textFlushs[2].setText(flush.get(aux)); break; case (R.id.buttonLess11): aux = value.indexOf(textValues[0].getText().toString()) - 1; if (aux == -1) aux = value.size() - 1; textValues[0].setText(value.get(aux)); break; case (R.id.buttonLess12): aux = flush.indexOf(textFlushs[0].getText().toString()) - 1; if (aux == -1) aux = flush.size() - 1; if (aux > 1) { textFlushs[0].setTextColor(Color.RED); } else { textFlushs[0].setTextColor(Color.BLACK); } textFlushs[0].setText(flush.get(aux)); break; case (R.id.buttonLess21): aux = value.indexOf(textValues[1].getText().toString()) - 1; if (aux == -1) aux = value.size() - 1; textValues[1].setText(value.get(aux)); break; case (R.id.buttonLess22): aux = flush.indexOf(textFlushs[1].getText().toString()) - 1; if (aux == -1) aux = flush.size() - 1; if (aux > 1) { textFlushs[1].setTextColor(Color.RED); } else { textFlushs[1].setTextColor(Color.BLACK); } textFlushs[1].setText(flush.get(aux)); break; case (R.id.buttonLess31): aux = value.indexOf(textValues[2].getText().toString()) - 1; if (aux == -1) aux = value.size() - 1; textValues[2].setText(value.get(aux)); ; break; case (R.id.buttonLess32): aux = flush.indexOf(textFlushs[2].getText().toString()) - 1; if (aux == -1) aux = flush.size() - 1; if (aux > 1) { textFlushs[2].setTextColor(Color.RED); } else { textFlushs[2].setTextColor(Color.BLACK); } textFlushs[2].setText(flush.get(aux)); break; } checkValue(); } public void checkValue() { if (textValues[0].getText().toString().equals("5") && textFlushs[0].getText().toString().equals("\u2660")) { cardOne.setImageResource(R.drawable.espadas5); } if (textValues[1].getText().toString().equals("2") && textFlushs[1].getText().toString().equals("\u2660")) { cardTwo.setImageResource(R.drawable.espadas2); } if (textValues[2].getText().toString().equals("5") && textFlushs[2].getText().toString().equals("\u2663")) { cardThree.setImageResource(R.drawable.paus5); } if (cardOne.getId() == R.drawable.espadas5 && cardTwo.getId() == R.drawable.espadas2 && cardThree.getId() == R.drawable.paus5) { Intent intent = new Intent(getApplicationContext(), Level7.class); startActivity(intent); } } }
Java
package levels; import lobster.games.studios.R; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.WindowManager.LayoutParams; public class Level3 extends Activity { private View selected_item = null; private int offset_x = 0; private int offset_y = 0; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.level); getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON); /* * ImageView img = (ImageView)findViewById(R.id.windowView1); * img.setOnTouchListener(new View.OnTouchListener() { * * public boolean onTouch(View v, MotionEvent event) { * switch(event.getAction()) { case MotionEvent.ACTION_DOWN: offset_x = * (int)event.getX(); offset_y = (int)event.getY(); selected_item = v; * break; default: break; } return false; } }); */ } }
Java
package levels; import lobster.games.studios.R; import android.app.Activity; import android.content.Intent; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.WindowManager.LayoutParams; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; public class Level2 extends Activity implements SensorEventListener { private SensorManager sensorManager = null; private float axisX; private ImageView img; private TextView levelText; private RelativeLayout windowLayout; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); setContentView(R.layout.level); getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON); levelText = new TextView(this); levelText = (TextView) findViewById(R.id.leveltext); levelText.setText("Level 2"); windowLayout = (RelativeLayout) findViewById(R.id.windowlayout); img = new ImageView(this); img.setImageResource(R.drawable.window); windowLayout.addView(img); img.setOnClickListener(new OnClickListener() { // @Override public void onClick(View v) { if (img.getId() == R.drawable.openwindow) { Intent intent = new Intent(getApplicationContext(), Level3.class); startActivity(intent); } } }); } @Override protected void onResume() { super.onResume(); sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL); sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_NORMAL); } @Override protected void onStop() { super.onStop(); sensorManager.unregisterListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)); sensorManager.unregisterListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION)); } public void onSensorChanged(SensorEvent event) { // TODO Auto-generated method stub synchronized (this) { switch (event.sensor.getType()) { case Sensor.TYPE_ACCELEROMETER: axisX = event.values[0]; if (axisX < 0) { img.setImageResource(R.drawable.openwindow); } else if (axisX > 0) { img.setImageResource(R.drawable.window); } break; } } } public void onAccuracyChanged(Sensor arg0, int arg1) { // TODO Auto-generated method stub } }
Java
package levels; import lobster.games.studios.R; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.WindowManager.LayoutParams; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; public class Level1 extends Activity { private Thread splashTread; private ImageView windowImage; private TextView levelText; private Button icon2; private RelativeLayout screenLayout, windowLayout; private LinearLayout itemsLayout; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.level); getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON); screenLayout = (RelativeLayout) findViewById(R.id.gamelayout); windowLayout = (RelativeLayout) findViewById(R.id.windowlayout); itemsLayout = (LinearLayout) findViewById(R.id.linearlayout); windowImage = new ImageView(this); icon2 = new Button(this); windowImage.setImageResource(R.drawable.window); windowLayout.addView(windowImage); icon2 = (Button) findViewById(R.id.button2); icon2.setBackgroundResource(R.drawable.ic_launcher); levelText = new TextView(this); levelText = (TextView) findViewById(R.id.leveltext); levelText.setText("Level 1"); windowImage.setOnClickListener(new OnClickListener() { // @Override public void onClick(View v) { windowImage.invalidate(); windowImage.setImageResource(R.drawable.openwindow); splashTread = new Thread() { @Override public void run() { try { synchronized (this) { // wait 1 sec wait(1000); } } catch (InterruptedException e) { } finally { // start a new activity Intent intent = new Intent(getApplicationContext(), Level2.class); startActivity(intent); // stop(); } } }; splashTread.start(); } }); } }
Java
package som.util; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.cfg.Configuration; /** * fdfg * Configures and provides access to Hibernate sessions, tied to the * current thread of execution. Follows the Thread Local Session * pattern, see {@link http://hibernate.org/42.html }. */ public class HibernateSessionFactory { /** * Location of hibernate.cfg.xml file. * Location should be on the classpath as Hibernate uses * #resourceAsStream style lookup for its configuration file. * The default classpath location of the hibernate config file is * in the default package. Use #setConfigFile() to update * the location of the configuration file for the current session. */ private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml"; private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); private static Configuration configuration = new Configuration(); private static org.hibernate.SessionFactory sessionFactory; private static String configFile = CONFIG_FILE_LOCATION; static { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err .println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } private HibernateSessionFactory() { } /** * Returns the ThreadLocal Session instance. Lazy initialize * the <code>SessionFactory</code> if needed. * * @return Session * @throws HibernateException */ public static Session getSession() throws HibernateException { Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) { if (sessionFactory == null) { rebuildSessionFactory(); } session = (sessionFactory != null) ? sessionFactory.openSession() : null; threadLocal.set(session); } return session; } /** * Rebuild hibernate session factory * */ public static void rebuildSessionFactory() { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err .println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } /** * Close the single hibernate session instance. * * @throws HibernateException */ public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session != null) { session.close(); } } /** * return session factory * */ public static org.hibernate.SessionFactory getSessionFactory() { return sessionFactory; } /** * return session factory * * session factory will be rebuilded in the next call */ public static void setConfigFile(String configFile) { HibernateSessionFactory.configFile = configFile; sessionFactory = null; } /** * return hibernate configuration * */ public static Configuration getConfiguration() { return configuration; } }
Java
package com.jboa.model; import java.util.HashSet; import java.util.Set; /** * Department entity. @author MyEclipse Persistence Tools */ public class Department implements java.io.Serializable { // Fields private String id; private String name; private Set profiles = new HashSet(0); private Set tusers = new HashSet(0); // Constructors /** default constructor */ public Department() { } /** minimal constructor */ public Department(String id, String name) { this.id = id; this.name = name; } /** full constructor */ public Department(String id, String name, Set profiles, Set tusers) { this.id = id; this.name = name; this.profiles = profiles; this.tusers = tusers; } // Property accessors public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Set getProfiles() { return this.profiles; } public void setProfiles(Set profiles) { this.profiles = profiles; } public Set getTusers() { return this.tusers; } public void setTusers(Set tusers) { this.tusers = tusers; } }
Java
package com.jboa.model; import java.util.HashSet; import java.util.Set; /** * Job entity. @author MyEclipse Persistence Tools */ public class Job implements java.io.Serializable { // Fields private String id; private String name; private String tdesc; private Set profiles = new HashSet(0); private Set tusers = new HashSet(0); // Constructors /** default constructor */ public Job() { } /** minimal constructor */ public Job(String id, String name) { this.id = id; this.name = name; } /** full constructor */ public Job(String id, String name, String tdesc, Set profiles, Set tusers) { this.id = id; this.name = name; this.tdesc = tdesc; this.profiles = profiles; this.tusers = tusers; } // Property accessors public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getTdesc() { return this.tdesc; } public void setTdesc(String tdesc) { this.tdesc = tdesc; } public Set getProfiles() { return this.profiles; } public void setProfiles(Set profiles) { this.profiles = profiles; } public Set getTusers() { return this.tusers; } public void setTusers(Set tusers) { this.tusers = tusers; } }
Java
package com.jboa.model; /** * Authority entity. @author MyEclipse Persistence Tools */ public class Authority implements java.io.Serializable { // Fields private String id; private Tmenu tmenu; private Trole trole; // Constructors /** default constructor */ public Authority() { } /** minimal constructor */ public Authority(String id, Trole trole) { this.id = id; this.trole = trole; } /** full constructor */ public Authority(String id, Tmenu tmenu, Trole trole) { this.id = id; this.tmenu = tmenu; this.trole = trole; } // Property accessors public String getId() { return this.id; } public void setId(String id) { this.id = id; } public Tmenu getTmenu() { return this.tmenu; } public void setTmenu(Tmenu tmenu) { this.tmenu = tmenu; } public Trole getTrole() { return this.trole; } public void setTrole(Trole trole) { this.trole = trole; } }
Java
package com.jboa.model; import java.util.HashSet; import java.util.Set; /** * Tmenu entity. @author MyEclipse Persistence Tools */ public class Tmenu implements java.io.Serializable { // Fields private String id; private Tmenu tmenu; private String text; private String url; private String icon; private Set tmenus = new HashSet(0); private Set authorities = new HashSet(0); // Constructors /** default constructor */ public Tmenu() { } /** minimal constructor */ public Tmenu(String id, String text, String url) { this.id = id; this.text = text; this.url = url; } /** full constructor */ public Tmenu(String id, Tmenu tmenu, String text, String url, String icon, Set tmenus, Set authorities) { this.id = id; this.tmenu = tmenu; this.text = text; this.url = url; this.icon = icon; this.tmenus = tmenus; this.authorities = authorities; } // Property accessors public String getId() { return this.id; } public void setId(String id) { this.id = id; } public Tmenu getTmenu() { return this.tmenu; } public void setTmenu(Tmenu tmenu) { this.tmenu = tmenu; } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getUrl() { return this.url; } public void setUrl(String url) { this.url = url; } public String getIcon() { return this.icon; } public void setIcon(String icon) { this.icon = icon; } public Set getTmenus() { return this.tmenus; } public void setTmenus(Set tmenus) { this.tmenus = tmenus; } public Set getAuthorities() { return this.authorities; } public void setAuthorities(Set authorities) { this.authorities = authorities; } }
Java
package com.jboa.model; import java.util.HashSet; import java.util.Set; /** * Trole entity. @author MyEclipse Persistence Tools */ public class Trole implements java.io.Serializable { // Fields private String id; private String name; private String tdesc; private Set tusers = new HashSet(0); private Set authorities = new HashSet(0); // Constructors /** default constructor */ public Trole() { } /** minimal constructor */ public Trole(String id, String name) { this.id = id; this.name = name; } /** full constructor */ public Trole(String id, String name, String tdesc, Set tusers, Set authorities) { this.id = id; this.name = name; this.tdesc = tdesc; this.tusers = tusers; this.authorities = authorities; } // Property accessors public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getTdesc() { return this.tdesc; } public void setTdesc(String tdesc) { this.tdesc = tdesc; } public Set getTusers() { return this.tusers; } public void setTusers(Set tusers) { this.tusers = tusers; } public Set getAuthorities() { return this.authorities; } public void setAuthorities(Set authorities) { this.authorities = authorities; } }
Java
package com.jboa.model; import java.util.HashSet; import java.util.Set; /** * Tuser entity. @author MyEclipse Persistence Tools */ public class Tuser implements java.io.Serializable { // Fields private String id; private Trole trole; private Department department; private Job job; private String username; private String password; private String phone; private String address; private String qq; private String email; private String status; private Set profiles = new HashSet(0); // Constructors /** default constructor */ public Tuser() { } /** minimal constructor */ public Tuser(String id, String username, String password, String status) { this.id = id; this.username = username; this.password = password; this.status = status; } /** full constructor */ public Tuser(String id, Trole trole, Department department, Job job, String username, String password, String phone, String address, String qq, String email, String status, Set profiles) { this.id = id; this.trole = trole; this.department = department; this.job = job; this.username = username; this.password = password; this.phone = phone; this.address = address; this.qq = qq; this.email = email; this.status = status; this.profiles = profiles; } // Property accessors public String getId() { return this.id; } public void setId(String id) { this.id = id; } public Trole getTrole() { return this.trole; } public void setTrole(Trole trole) { this.trole = trole; } public Department getDepartment() { return this.department; } public void setDepartment(Department department) { this.department = department; } public Job getJob() { return this.job; } public void setJob(Job job) { this.job = job; } public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } public String getPhone() { return this.phone; } public void setPhone(String phone) { this.phone = phone; } public String getAddress() { return this.address; } public void setAddress(String address) { this.address = address; } public String getQq() { return this.qq; } public void setQq(String qq) { this.qq = qq; } public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } public String getStatus() { return this.status; } public void setStatus(String status) { this.status = status; } public Set getProfiles() { return this.profiles; } public void setProfiles(Set profiles) { this.profiles = profiles; } }
Java
package com.jboa.model; import java.math.BigDecimal; import java.util.Date; /** * Profile entity. @author MyEclipse Persistence Tools */ public class Profile implements java.io.Serializable { // Fields private String profileid; private Department department; private Tuser tuser; private Job job; private String fullname; private String address; private Date birthday; private String homezip; private String sex; private String marriage; private String phone; private String mobile; private String openbank; private String bankno; private String qq; private String email; private String hobby; private String religion; private String party; private String nationality; private String race; private String birthplace; private String edudegree; private String edumajor; private String educollege; private Date startworkdate; private String educase; private String awardpunishcase; private String trainingcase; private String workcase; private String idcard; private String photo; private String standardmino; private Double standardmoney; private String standardname; private Long standardid; private String creator; private Date createtime; private String checkname; private Date checktime; private BigDecimal approvalstatus; private String memo; // Constructors /** default constructor */ public Profile() { } /** minimal constructor */ public Profile(String profileid, Tuser tuser, Job job, String fullname) { this.profileid = profileid; this.tuser = tuser; this.job = job; this.fullname = fullname; } /** full constructor */ public Profile(String profileid, Department department, Tuser tuser, Job job, String fullname, String address, Date birthday, String homezip, String sex, String marriage, String phone, String mobile, String openbank, String bankno, String qq, String email, String hobby, String religion, String party, String nationality, String race, String birthplace, String edudegree, String edumajor, String educollege, Date startworkdate, String educase, String awardpunishcase, String trainingcase, String workcase, String idcard, String photo, String standardmino, Double standardmoney, String standardname, Long standardid, String creator, Date createtime, String checkname, Date checktime, BigDecimal approvalstatus, String memo) { this.profileid = profileid; this.department = department; this.tuser = tuser; this.job = job; this.fullname = fullname; this.address = address; this.birthday = birthday; this.homezip = homezip; this.sex = sex; this.marriage = marriage; this.phone = phone; this.mobile = mobile; this.openbank = openbank; this.bankno = bankno; this.qq = qq; this.email = email; this.hobby = hobby; this.religion = religion; this.party = party; this.nationality = nationality; this.race = race; this.birthplace = birthplace; this.edudegree = edudegree; this.edumajor = edumajor; this.educollege = educollege; this.startworkdate = startworkdate; this.educase = educase; this.awardpunishcase = awardpunishcase; this.trainingcase = trainingcase; this.workcase = workcase; this.idcard = idcard; this.photo = photo; this.standardmino = standardmino; this.standardmoney = standardmoney; this.standardname = standardname; this.standardid = standardid; this.creator = creator; this.createtime = createtime; this.checkname = checkname; this.checktime = checktime; this.approvalstatus = approvalstatus; this.memo = memo; } // Property accessors public String getProfileid() { return this.profileid; } public void setProfileid(String profileid) { this.profileid = profileid; } public Department getDepartment() { return this.department; } public void setDepartment(Department department) { this.department = department; } public Tuser getTuser() { return this.tuser; } public void setTuser(Tuser tuser) { this.tuser = tuser; } public Job getJob() { return this.job; } public void setJob(Job job) { this.job = job; } public String getFullname() { return this.fullname; } public void setFullname(String fullname) { this.fullname = fullname; } public String getAddress() { return this.address; } public void setAddress(String address) { this.address = address; } public Date getBirthday() { return this.birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getHomezip() { return this.homezip; } public void setHomezip(String homezip) { this.homezip = homezip; } public String getSex() { return this.sex; } public void setSex(String sex) { this.sex = sex; } public String getMarriage() { return this.marriage; } public void setMarriage(String marriage) { this.marriage = marriage; } public String getPhone() { return this.phone; } public void setPhone(String phone) { this.phone = phone; } public String getMobile() { return this.mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getOpenbank() { return this.openbank; } public void setOpenbank(String openbank) { this.openbank = openbank; } public String getBankno() { return this.bankno; } public void setBankno(String bankno) { this.bankno = bankno; } public String getQq() { return this.qq; } public void setQq(String qq) { this.qq = qq; } public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } public String getHobby() { return this.hobby; } public void setHobby(String hobby) { this.hobby = hobby; } public String getReligion() { return this.religion; } public void setReligion(String religion) { this.religion = religion; } public String getParty() { return this.party; } public void setParty(String party) { this.party = party; } public String getNationality() { return this.nationality; } public void setNationality(String nationality) { this.nationality = nationality; } public String getRace() { return this.race; } public void setRace(String race) { this.race = race; } public String getBirthplace() { return this.birthplace; } public void setBirthplace(String birthplace) { this.birthplace = birthplace; } public String getEdudegree() { return this.edudegree; } public void setEdudegree(String edudegree) { this.edudegree = edudegree; } public String getEdumajor() { return this.edumajor; } public void setEdumajor(String edumajor) { this.edumajor = edumajor; } public String getEducollege() { return this.educollege; } public void setEducollege(String educollege) { this.educollege = educollege; } public Date getStartworkdate() { return this.startworkdate; } public void setStartworkdate(Date startworkdate) { this.startworkdate = startworkdate; } public String getEducase() { return this.educase; } public void setEducase(String educase) { this.educase = educase; } public String getAwardpunishcase() { return this.awardpunishcase; } public void setAwardpunishcase(String awardpunishcase) { this.awardpunishcase = awardpunishcase; } public String getTrainingcase() { return this.trainingcase; } public void setTrainingcase(String trainingcase) { this.trainingcase = trainingcase; } public String getWorkcase() { return this.workcase; } public void setWorkcase(String workcase) { this.workcase = workcase; } public String getIdcard() { return this.idcard; } public void setIdcard(String idcard) { this.idcard = idcard; } public String getPhoto() { return this.photo; } public void setPhoto(String photo) { this.photo = photo; } public String getStandardmino() { return this.standardmino; } public void setStandardmino(String standardmino) { this.standardmino = standardmino; } public Double getStandardmoney() { return this.standardmoney; } public void setStandardmoney(Double standardmoney) { this.standardmoney = standardmoney; } public String getStandardname() { return this.standardname; } public void setStandardname(String standardname) { this.standardname = standardname; } public Long getStandardid() { return this.standardid; } public void setStandardid(Long standardid) { this.standardid = standardid; } public String getCreator() { return this.creator; } public void setCreator(String creator) { this.creator = creator; } public Date getCreatetime() { return this.createtime; } public void setCreatetime(Date createtime) { this.createtime = createtime; } public String getCheckname() { return this.checkname; } public void setCheckname(String checkname) { this.checkname = checkname; } public Date getChecktime() { return this.checktime; } public void setChecktime(Date checktime) { this.checktime = checktime; } public BigDecimal getApprovalstatus() { return this.approvalstatus; } public void setApprovalstatus(BigDecimal approvalstatus) { this.approvalstatus = approvalstatus; } public String getMemo() { return this.memo; } public void setMemo(String memo) { this.memo = memo; } }
Java
package constants; import client.Command; public class Constants { public static enum Color{ blue, red, green, cyan, magenta, orange, pink, yellow } // Order of enum important for determining opposites public static enum dir { N, W, E, S }; public static dir oppositeDir(dir d){ if(d== dir.N) return dir.S; else if(d == dir.E) return dir.W; else if(d == dir.W) return dir.E; else return dir.N; } public static Command NOOP = new Command("NoOp"); public static String NOOP_str = "NoOp"; public static String MOVE_str = "Move"; public static String PUSH_str = "Push"; public static String PULL_str = "Pull"; }
Java
package client; import java.util.LinkedList; import constants.Constants.*; public class Command { static { LinkedList< Command > cmds = new LinkedList< Command >(); for ( dir d : dir.values() ) { cmds.add( new Command( d ) ); } for ( dir d1 : dir.values() ) { for ( dir d2 : dir.values() ) { if ( !Command.isOpposite( d1, d2 ) ) { cmds.add( new Command( "Push", d1, d2 ) ); } } } for ( dir d1 : dir.values() ) { for ( dir d2 : dir.values() ) { if ( d1 != d2 ) { cmds.add( new Command( "Pull", d1, d2 ) ); } } } every = cmds.toArray( new Command[0] ); } public final static Command[] every; private static boolean isOpposite( dir d1, dir d2 ) { return d1.ordinal() + d2.ordinal() == 3; } public String cmd; public dir dir1; public dir dir2; public Command( dir d ) { cmd = "Move"; dir1 = d; } public Command(String s) { if (s.toLowerCase().equals("noop")) cmd = "NoOp"; cmd = "NoOp"; // Are there others? } public Command( String s, dir d1, dir d2 ) { cmd = s; dir1 = d1; dir2 = d2; } public String toString() { if ( dir1 == null ) return cmd; else if ( dir2 == null) return cmd + "(" + dir1 + ")"; return cmd + "(" + dir1 + "," + dir2 + ")"; } }
Java
package client; public enum Action { MoveEast, MoveWest, MoveNorth, MoveSouth, PushNW, PushW, PushSW, PushS, PushSE, PushE, PushNE, PushN, PullNW, PullW, PullSW, PullS, PullSE, PullE, PullNE, PullN, NoOp }
Java
package client.planners; import java.util.ArrayList; import java.util.Collection; import java.util.Random; import agent.objectives.DockABox; import agent.objectives.GoalABox; import agent.objectives.Objective; import agent.planners.AgentPlanner; import agent.planners.AgentProgressionPlanner; import utils.GoalPriority; import utils.Utils; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Goal; import LevelObjects.Level; public class ClientPlanner implements Planner { Level level; Random rand; public boolean firstRun = true; private static final String name = "ClientPlanner"; @Override public String getName() { return name; } public ClientPlanner(Level l) { this.level = l; rand = new Random(); } public void makePlan() { // System.err.println("Make plan!"); AgentPlanner planner = new AgentProgressionPlanner(level); int agentsNeedsPlans = 0; for (Agent agent : level.agents) { if(agent.objectives.isEmpty()) agentsNeedsPlans++; } if(agentsNeedsPlans == level.agents.size() && !Utils.allGoalsHasBoxes(level)) firstRun = true; if (firstRun) { GoalPriority.createGoalPrioritization(level, true); for (Agent a : level.agents) { a.priority = 99; a.planner = planner; a.possibleBoxesToGoals = Utils.findPossibleBoxes(level, a); } // Find goals in order and find an agent to goal it ArrayList<Goal> goals_assigned = new ArrayList<Goal>(); for (Goal g : level.goals) { for (Agent a : level.agents) { for (Box b : a.possibleBoxesToGoals.keySet()) { Goal goal = null; if (a.possibleBoxesToGoals.containsKey(b) && Utils.boxFitsGoal(b, g)){ //add goal with lowest priority goal = GoalPriority.FindGoalWithHighestPriority(a, b, level, goals_assigned); goals_assigned.add(goal); if(goal == null) continue; if(a.objectives == null || a.objectives.isEmpty()) a.objectives.addFirst(new GoalABox(b, goal)); else{ Objective o = a.objectives.peek(); if(o instanceof GoalABox && ((GoalABox) o).goal.getPriority() > goal.getPriority()){ a.objectives.addFirst(new GoalABox(b, goal)); } else{ a.objectives.addLast(new GoalABox(b, goal)); } } if(a.priority > goal.priority) a.priority = goal.priority; } } } } firstRun = false; } for (Agent a : level.agents) { if(a.objectives.isEmpty()){ Goal goal_highest_priority = Utils.allOfAgentGoalsHasBoxes(a, level); if(goal_highest_priority != null){ //Find route to goal Collection<Field> blockedFields = null; ArrayList<Box> boxesInTheWay = null; boxesInTheWay = Utils.findRouteCountBoxesInTheWay(level, a, a.getAtField(), new Field(goal_highest_priority.x, goal_highest_priority.y), blockedFields); //remove boxes in the way boxesInTheWayLoop : for (Box box : boxesInTheWay) { if(box.getId() == a.getId()){ //make DockABox thing Objective o = new DockABox(box.getAtField(), box, 15); a.objectives.addFirst(o); break boxesInTheWayLoop; } } } } a.planAndExecute(level); } } }
Java
package client.planners; public interface Planner { public String getName(); public void makePlan(); }
Java
package client; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Goal; public class Desire { public Agent agent; public Box box; public Goal goal; boolean completed; public Desire(Agent a, Box b) { this.agent = a; this.box = b; } public Desire(Agent a, Box b, Goal g) { this.agent = a; this.box = b; this.goal = g; } }
Java
package client; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map.Entry; import java.util.concurrent.LinkedBlockingQueue; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.UIManager; public class GuiClient extends JFrame { private static ActionListener listener = new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { CommandButton c = ( (CommandButton) e.getSource() ); buttonSend( c.t, c.cmd ); } }; // Receiver and Transmitter are not needed for most planners, but may lead to (negligible) speed up as you do not synchronize each // action with the server private class ServerReceiver extends Thread { private GuiClient gui; public ServerReceiver( GuiClient g ) { gui = g; } public void run() { try { BufferedReader reader = new BufferedReader( new InputStreamReader( System.in ) ); while ( true ) { String msg = reader.readLine(); if ( msg == null ) throw new IOException( "End of server messages" ); gui.AddCommunication( "<IN> " + msg ); } } catch ( IOException e ) { gui.AddInformation( e.toString() ); } } } private class ServerTransmitter extends Thread { private GuiClient gui; private LinkedBlockingQueue< String > outbound = new LinkedBlockingQueue< String >(); public ServerTransmitter( GuiClient g ) { gui = g; } public void run() { try { while ( true ) { String msg = outbound.take(); System.out.println( msg ); gui.AddCommunication( "<OUT> " + msg ); } } catch ( InterruptedException e ) { gui.AddInformation( e.toString() ); } } } private class CommandButton extends JButton { public final String cmd; public final ServerTransmitter t; public CommandButton( ServerTransmitter t, String label, String cmd ) { super( label ); this.t = t; this.cmd = cmd; this.addActionListener( listener ); } } public static void buttonSend( ServerTransmitter st, String cmd ) { st.outbound.add( cmd ); } private final String nl = System.getProperty( "line.separator" ); private JTextArea communication = new JTextArea(); private JTextArea information = new JTextArea(); private JPanel fixed = new JPanel(); private JPanel custom = new JPanel(); private JPanel comm = new JPanel(); private JPanel info = new JPanel(); private int msgNo; private int agents; private ServerReceiver receiver; private ServerTransmitter transmitter; private class GBC extends GridBagConstraints { public GBC( int x, int y ) { this( x, y, 1 ); } public GBC( int x, int y, int spanx ) { this.insets = new Insets( 0, 3, 0, 3 ); this.gridx = x; this.gridy = y; this.gridwidth = spanx; this.fill = GridBagConstraints.NONE; } public GBC( int x, int y, int spanx, int sep ) { this.insets = new Insets( sep, 3, sep, 3 ); this.gridx = x; this.gridy = y; this.gridwidth = spanx; this.fill = GridBagConstraints.HORIZONTAL; this.weightx = 0; } } public GuiClient( String[] customs ) throws IOException { super( "02285 Toy Client" ); System.err.println("Hello from GuiClient"); readMap(); // Get agent count receiver = new ServerReceiver( this ); transmitter = new ServerTransmitter( this ); communication.setEditable( false ); communication.setFont( new Font( "Monospaced", Font.PLAIN, 11 ) ); information.setEditable( false ); information.setFont( new Font( "Monospaced", Font.PLAIN, 11 ) ); // Fixed Buttons panel JSeparator sep1 = new JSeparator( JSeparator.HORIZONTAL ); JSeparator sep2 = new JSeparator( JSeparator.HORIZONTAL ); HashMap< String, GBC > buts = new HashMap< String, GBC >(); fixed.setLayout( new GridBagLayout() ); buts.put( "Move(N)", new GBC( 3, 0 ) ); buts.put( "Move(W)", new GBC( 2, 1 ) ); buts.put( "Move(E)", new GBC( 4, 1 ) ); buts.put( "Move(S)", new GBC( 3, 2 ) ); fixed.add( new JLabel( "Navigation" ), new GBC( 2, 1, 3 ) ); fixed.add( sep1, new GBC( 0, 3, 7, 10 ) ); int yoff = 4; buts.put( "Push(N,N)", new GBC( 3, yoff + 1 ) ); buts.put( "Push(N,W)", new GBC( 2, yoff + 1 ) ); buts.put( "Push(W,N)", new GBC( 1, yoff + 2 ) ); buts.put( "Push(W,W)", new GBC( 1, yoff + 3 ) ); buts.put( "Push(W,S)", new GBC( 1, yoff + 4 ) ); buts.put( "Push(S,W)", new GBC( 2, yoff + 5 ) ); buts.put( "Push(N,E)", new GBC( 4, yoff + 1 ) ); buts.put( "Push(E,N)", new GBC( 5, yoff + 2 ) ); buts.put( "Push(E,E)", new GBC( 5, yoff + 3 ) ); buts.put( "Push(E,S)", new GBC( 5, yoff + 4 ) ); buts.put( "Push(S,E)", new GBC( 4, yoff + 5 ) ); buts.put( "Push(S,S)", new GBC( 3, yoff + 5 ) ); fixed.add( new JLabel( "Push" ), new GBC( 2, yoff + 3, 3 ) ); fixed.add( sep2, new GBC( 0, yoff + 7, 7, 10 ) ); yoff = 12; buts.put( "Pull(N,S)", new GBC( 3, yoff + 1 ) ); buts.put( "Pull(N,W)", new GBC( 2, yoff + 1 ) ); buts.put( "Pull(W,N)", new GBC( 1, yoff + 2 ) ); buts.put( "Pull(W,E)", new GBC( 1, yoff + 3 ) ); buts.put( "Pull(W,S)", new GBC( 1, yoff + 4 ) ); buts.put( "Pull(S,W)", new GBC( 2, yoff + 5 ) ); buts.put( "Pull(S,N)", new GBC( 3, yoff + 5 ) ); buts.put( "Pull(N,E)", new GBC( 4, yoff + 1 ) ); buts.put( "Pull(E,N)", new GBC( 5, yoff + 2 ) ); buts.put( "Pull(E,W)", new GBC( 5, yoff + 3 ) ); buts.put( "Pull(E,S)", new GBC( 5, yoff + 4 ) ); buts.put( "Pull(S,E)", new GBC( 4, yoff + 5 ) ); fixed.add( new JLabel( "Pull" ), new GBC( 2, yoff + 3, 3 ) ); for ( Entry< String, GBC > e : buts.entrySet() ) { fixed.add( new CommandButton( transmitter, e.getKey(), "[" + Multify( e.getKey() ) + "]" ), e.getValue() ); } // Custom Panel GridBagConstraints c = new GridBagConstraints(); c.gridy++; custom.setLayout( new GridBagLayout() ); if ( customs.length == 0 ) customs = new String[] { "", "" }; for ( int i = 0; i < customs.length; i++ ) { JButton but = new JButton( "Command " + i ); final JTextField input = new JTextField( customs[i] ); but.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { buttonSend( transmitter, input.getText() ); } } ); c = new GridBagConstraints(); c.gridy = i; c.fill = GridBagConstraints.HORIZONTAL; custom.add( but, c ); c.weightx = 0.80; c.gridx = 1; custom.add( input, c ); } // Communication panel comm.setLayout( new GridBagLayout() ); comm.setMinimumSize(new Dimension(200, 250)); c = new GridBagConstraints(); c.ipadx = 5; comm.add( new JLabel( "Communication Done" ), c ); c.gridy = 1; c.weightx = 1; c.weighty = 1; c.fill = GridBagConstraints.BOTH; comm.add( new JScrollPane( communication, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED ), c ); // Information panel info.setLayout( new GridBagLayout() ); comm.setMinimumSize(new Dimension(200, 100)); c = new GridBagConstraints(); c.ipadx = 5; info.add( new JLabel( "Client Information (e.g. Exceptions)" ), c ); c.gridy = 1; c.weightx = 1; c.weighty = 1; c.fill = GridBagConstraints.BOTH; info.add( new JScrollPane( information, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED ), c ); // Add components to main frame setLayout( new GridBagLayout() ); c = new GridBagConstraints(); c.weightx = 1; c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets( 3, 3, 3, 3 ); add( fixed, c ); c.gridy = 1; add( custom, c ); c.gridy = 2; c.weighty = 0.8; c.fill = GridBagConstraints.BOTH; add( comm, c ); c.gridy = 3; c.weighty = 0.2; add( info, c ); setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); setMinimumSize( new Dimension( 525, 820 ) ); setLocation( 800, 120 ); receiver.start(); transmitter.start(); this.pack(); setVisible( true ); } public void AddCommunication( String m ) { // Append is thread safe.. communication.append( msgNo + ":\t" + m + nl ); synchronized ( this ) { communication.setCaretPosition( communication.getText().length() ); msgNo++; } } public void AddInformation( String m ) { // Append is thread safe.. information.append( m + nl ); synchronized ( this ) { information.setCaretPosition( information.getText().length() ); } } /** * Turns Cmd into Cmd,Cmd,Cmd (..) based on number of agents * * @param cmd * @return Multified cmd */ private String Multify( String cmd ) { String s = ""; for ( int i = 0; i < agents - 1; i++ ) { s += cmd + ","; } return s + cmd; } private void readMap() throws IOException { BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) ); agents = 0; String line; // Read lines specifying colors while ( ( line = in.readLine() ).matches( "^[a-z]+:\\s*[0-9A-Z](,\\s*[0-9A-Z])*\\s*$" ) ) { // Skip } // Read lines specifying level layout // By convention levels are ended with an empty newline while ( !line.equals( "" ) ) { for ( int i = 0; i < line.length(); i++ ) { char id = line.charAt( i ); if ( '0' <= id && id <= '9' ) agents++; } line = in.readLine(); if ( line == null ) break; } } public static void main( String[] args ) { try { UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() ); new GuiClient( args ); } catch ( Exception e ) { e.printStackTrace(); } } }
Java
package client; import java.util.Arrays; import java.util.Scanner; public class Output { private static Scanner scan = new Scanner(System.in); /*public Output() { scan = new Scanner(System.in); }*/ public static boolean[] Send(Command[] commands) { // System.err.println("Sending: [" + Arrays.toString(commands) + "]"); String sendString = Arrays.toString(commands); sendString = sendString.replaceAll("null", "NoOp"); System.out.println(sendString); System.out.flush(); String feedback = scan.nextLine(); // [false, false] String[] elements = feedback.substring(1, feedback.length()-1).split(", "); boolean[] result = new boolean[elements.length]; int i = 0; for (String s : elements) result[i++] = Boolean.parseBoolean(s); return result; } }
Java
package client; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import constants.Constants.Color; import constants.Constants.dir; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Goal; import LevelObjects.Level; public class Parser { // Flaws in current implementation: // - fields outside walls are created. A simple search could easily remove them, but they don't seem to be in the way, yet. public static Level readLevel() throws IOException { Level l = new Level(); //FileReader fR = new FileReader("src/levels/FOMAbispebjerg.lvl"); //BufferedReader in = new BufferedReader(fR); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // Read lines specifying colors Map<Character,Color> colors = new HashMap<Character,Color>(); String line; Color color; while ((line = in.readLine()).matches("^[a-z]+:\\s*[0-9A-Z](,\\s*[0-9A-Z])*\\s*$")) { line = line.replaceAll("\\s", ""); color = Color.valueOf(line.split(":")[0]); for (String id : line.split(":")[1].split(",")) colors.put(id.charAt(0), color); } // Read level layout ArrayList<String> rawLevel = new ArrayList<String>(); while (!line.equals("")) { rawLevel.add(line); line = in.readLine(); } // Set size of field map int maxWidth = 0; for (int y=1; y<rawLevel.size()-1; y++) { if (rawLevel.get(y).length() > maxWidth) { maxWidth = rawLevel.get(y).length(); } } l.setFieldMap(new Field[maxWidth][rawLevel.size()]); // Read lines specifying level layout (skipping the border) for (int y=0; y<rawLevel.size(); y++) { for (int x=0; x<rawLevel.get(y).length(); x++) { char id = rawLevel.get(y).charAt(x); if ('+' == id) continue; // skip if wall Field f; if ('0' <= id && id <= '9') { f = new Field(x,y); Agent a = new Agent(id, colors.get(id), f); l.agents.add(a); f.setObject(a); } else if ('A' <= id && id <= 'Z') { f = new Field(x,y); Box b = new Box(id, colors.get(id), f); l.boxes.add(b); f.setObject(b); } else if ('a' <= id && id <= 'z') { f = new Goal(id,x,y); l.goals.add((Goal)f); } else { f = new Field(x,y); } l.fields.add(f); l.fieldMap[x][y] = f; // Field links if(x!=0 && l.fieldMap[x-1][y] != null){ if (rawLevel.get(y).charAt(x-1) != '+') LinkFieldsHorizontal(f, l.fieldMap[x-1][y]); // link left } if(y!=0 && l.fieldMap[x][y-1] != null){ if (rawLevel.get(y-1).charAt(x) != '+') LinkFieldsVertical(f, l.fieldMap[x][y-1]); // link up (negative y) } } } //THE AGENTS NEED TO BE SORTED Collections.sort(l.agents, new Comparator<Agent>() { @Override public int compare(Agent a1, Agent a2) { int a1Id = Integer.parseInt(""+a1.getId()); int a2Id = Integer.parseInt(""+a2.getId()); return a1Id-a2Id; } }); return l; } private static void LinkFieldsHorizontal(Field east, Field west) { east.neighbours[dir.W.ordinal()] = west; west.neighbours[dir.E.ordinal()] = east; } private static void LinkFieldsVertical(Field south, Field north) { south.neighbours[dir.N.ordinal()] = north; north.neighbours[dir.S.ordinal()] = south; } }
Java
package client.clients; import java.io.IOException; import constants.Constants; import constants.Constants.dir; import utils.Communication; import utils.Timer; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Level; import client.Command; import client.Output; import client.Parser; import client.planners.ClientPlanner; import client.planners.Planner; public class Client { private static Level level; private static Planner planner; private static boolean timer; public static int stepCount = 0; public static boolean[] agentsFailed; public Client(String plannerName) throws IOException { level = Parser.readLevel(); planner = getPlanner(plannerName, level); } public static void main(String[] args) { try { String plannerName = "simple"; // DEFAULT timer = true; if (args.length==1) plannerName = args[0]; else if (args.length==2 && args[1].toLowerCase().equals("notimer")) timer = false; Timer t1 = new Timer(); t1.takeTime(); Client client = new Client(plannerName); agentsFailed = new boolean[level.agents.size()]; t1.stop(); // System.err.println("Level parsed. Time taken: " + t1.toString()); System.err.println( "Hello from " + planner.getName()); while (client.update()) ; } catch (Exception e) { e.printStackTrace(); } } private static Planner getPlanner(String name, Level l) { return new ClientPlanner(l); } public boolean update() throws IOException { Command[] commands = new Command[level.agents.size()]; // Get commands from agents' commandQueue loadCommands(commands); // Check if all agents have no commands left. If true, plan new commands. boolean noOps = true; for (int i = 0; i < commands.length; i++) { if (commands[i] != null) noOps = false; } if (noOps) { // System.err.println("No ops !"); Timer t = new Timer(); planner.makePlan(); t.stop(); // System.err.println("Plan calculated. Time taken: " + t.toString()); loadCommands(commands); } // Send commands to server, receive results boolean[] result = Output.Send(commands); // Let all commands accepted by the server update the level state boolean failed = false; boolean conflictFound = false; Agent conflictingAgent = null; for (int i = 0; i < result.length; i++) { if(conflictingAgent != null){ if(conflictingAgent.getId() == level.agents.get(i).getId()){ //if the other agent wins, do what he says.. Command c = commands[i]; flushAgentCommands(level.agents.get(i), c); } } if (result[i]){ completeCommand(commands[i], level.agents.get(i)); } else { // System.err.println("Conflict!!!!! " + i); Agent a = level.agents.get(i); Command c = commands[i]; //if (c.cmd.toLowerCase().equals("move")) if (c.cmd.toLowerCase().equals("move") || c.cmd.toLowerCase().equals("pull"))// agent moves { Object o = a.getAtField().neighbours[c.dir1.ordinal()].object; if (o == null) { a.commandQueue.add(Constants.NOOP); } else if(o instanceof Box) { //A box is in the way. find which box Box otherBox = (Box)o; // System.err.println("Agent" + i + " at: [" + a.getAtField() + "]. Move box at: [" + otherBox.getAtField() +"]"); //Find an agent to move the box conflictingAgent = Communication.FindAgentToMoveBox(otherBox, level); a.obstacle = o; } else if(o instanceof Agent){ a.obstacle = o; } } else { //We are pushing and should look at the next field.. Object o = a.getAtField().neighbours[c.dir1.ordinal()].neighbours[c.dir1.ordinal()].object; if (o == null) { // Field agents_desired_field = a.getAtField().neighbours[c.dir2.ordinal()]; // if(!Utils.CheckIfAnAgentWasOnThisFieldLastTurn(level, agents_desired_field)){ // System.err.println("Blocked field! Field [" + agents_desired_field.x + "." + agents_desired_field.y + "]"); // removeField(agents_desired_field); a.commandQueue.clear(); // } } else if(o instanceof Agent || o instanceof Box) { a.obstacle = o; } } flushAgentCommands(level.agents.get(i), c); //TODO: if there is no box or agent on the desired place it is a hidden obstacle -> remove it from graph updateBeliefs(commands[i], level.agents.get(i)); failed = true; } } agentsFailed = result; stepCount++; return true; } /** * Removes a field from the graph * @param field the field to be dereferenced. */ private void removeField(Field field) { for (dir direction : dir.values()) { Field neighbour = field.neighbours[direction.ordinal()]; neighbour.neighbours[Constants.oppositeDir(direction).ordinal()] = null; } } /** * Restores the agents objective from last iteration and the command queue from the error * @param agent * @param failedCommand The command on which the program failed */ private void flushAgentCommands(Agent agent, Command failedCommand) { agent.commandsNotCompleted.add(Constants.NOOP); agent.commandsNotCompleted.add(Constants.NOOP); agent.commandsNotCompleted.add(failedCommand); Command c; while ((c = agent.commandQueue.poll()) != null) agent.commandsNotCompleted.add(c); agent.objectives.addFirst(agent.tempObjective); agent.tempObjective = null; } private static void loadCommands(Command[] commands) { for (int i = 0; i < level.agents.size(); i++) { level.agents.get(i).lastLocation = level.agents.get(i).getAtField(); commands[i] = level.agents.get(i).commandQueue.poll(); } } private static void updateBeliefs(Command c, Agent a) { // TODO } // updates level by completing an agent command private static void completeCommand(Command c, Agent a) { if (c != null && a != null) { if (c.cmd.equals("Move")) completeMove(c, a); else if (c.cmd.equals("Pull")) completePull(c,a, (Box) a.getAtField().neighbours[c.dir2.ordinal()].object); else if (c.cmd.equals("Push")) completePush(c,a, (Box) a.getAtField().neighbours[c.dir1.ordinal()].object); } } private static void completeMove(Command c, Agent a) { a.getAtField().object = null; a.getAtField().neighbours[c.dir1.ordinal()].object = a; a.setAtField(a.getAtField().neighbours[c.dir1.ordinal()]); } private static void completePull(Command c, Agent a, Box o) { // Box moves to Agents' previous field o.getAtField().setObject(null); o.setAtField(a.getAtField()); a.setAtField(a.getAtField().neighbours[c.dir1.ordinal()]); o.getAtField().setObject(o); a.getAtField().setObject(a); } private static void completePush(Command c, Agent a, Box o) { // Agent moves to Box's previous field a.getAtField().setObject(null); a.setAtField(o.getAtField()); o.setAtField(o.getAtField().neighbours[c.dir2.ordinal()]); o.getAtField().setObject(o); a.getAtField().setObject(a); } }
Java
package client.clients; import java.io.*; import java.util.*; import client.Command; public class RandomWalkClient { private static Random rand = new Random(); public class Agent { // We don't actually use these for Randomly Walking Around private char id; private String color; Agent( char id, String color ) { this.id = id; this.color = color; } public String act() { return Command.every[rand.nextInt( Command.every.length )].toString(); } } private BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) ); private List< Agent > agents = new ArrayList< Agent >(); public RandomWalkClient() throws IOException { readMap(); } private void readMap() throws IOException { Map< Character, String > colors = new HashMap< Character, String >(); String line, color; // Read lines specifying colors while ( ( line = in.readLine() ).matches( "^[a-z]+:\\s*[0-9A-Z](,\\s*[0-9A-Z])*\\s*$" ) ) { line = line.replaceAll( "\\s", "" ); color = line.split( ":" )[0]; for ( String id : line.split( ":" )[1].split( "," ) ) colors.put( id.charAt( 0 ), color ); } // Read lines specifying level layout while ( !line.equals( "" ) ) { for ( int i = 0; i < line.length(); i++ ) { char id = line.charAt( i ); if ( '0' <= id && id <= '9' ) agents.add( new Agent( id, colors.get( id ) ) ); } line = in.readLine(); } } public boolean update() throws IOException { String jointAction = "["; for ( int i = 0; i < agents.size() - 1; i++ ) jointAction += agents.get( i ).act() + ","; System.out.println( jointAction + agents.get( agents.size() - 1 ).act() + "]" ); System.out.flush(); // Disregard these for now, but read or the server stalls when outputbuffer gets filled! String percepts = in.readLine(); if ( percepts == null ) return false; return true; } public static void main( String[] args ) { // Use stderr to print to console System.err.println( "Hello from RandomWalkClient. I am sending this using the error outputstream" ); try { RandomWalkClient client = new RandomWalkClient(); while ( client.update() ) ; } catch ( IOException e ) { // Got nowhere to write to probably } } }
Java
package datastructures; import java.util.ArrayList; import java.util.List; import client.Command; import LevelObjects.Box; import LevelObjects.Field; public class MoveActionSequence extends ActionSequence { private Field startField; private Field endField; public List<Box> boxesInTheWay; public MoveActionSequence(Field from, Field to, ArrayList<Command> commands) { startField = from; endField = to; super.commands = commands; } public Field getStartField() { return startField; } public void setStartField(Field startField) { this.startField = startField; } public Field getEndField() { return endField; } public void setEndField(Field endField) { this.endField = endField; } }
Java
package datastructures; import LevelObjects.Field; public class MoveBoxActionSequence extends ActionSequence { private Field agentLocation; private Field boxLocation; private Field targetLocation; public Field getAgentLocation() { return agentLocation; } public void setAgentLocation(Field agentLocation) { this.agentLocation = agentLocation; } public Field getBoxLocation() { return boxLocation; } public void setBoxLocation(Field boxLocation) { this.boxLocation = boxLocation; } public Field getTargetLocation() { return targetLocation; } public void setTargetLocation(Field targetLocation) { this.targetLocation = targetLocation; } }
Java
package datastructures; import LevelObjects.Field; public class GoalActionSequence extends ActionSequence { private Field agentStartLocation; private Field agentEndField; private Field boxStartLocation; private Field boxEndLocation; public Field getBoxStartLocation() { return boxStartLocation; } public void setBoxStartLocation(Field boxStartLocation) { this.boxStartLocation = boxStartLocation; } public Field getBoxEndLocation() { return boxEndLocation; } public void setBoxEndLocation(Field boxEndLocation) { this.boxEndLocation = boxEndLocation; } public Field getAgentEndField() { return agentEndField; } public void setAgentEndField(Field agentEndField) { this.agentEndField = agentEndField; } public Field getAgentStartLocation() { return agentStartLocation; } public void setAgentStartLocation(Field agentStartLocation) { this.agentStartLocation = agentStartLocation; } }
Java
package datastructures; public class FieldBlockedChange { public int time; public boolean changeToBlocked; public FieldBlockedChange(int time, boolean c){ this.time = time; this.changeToBlocked = c; } }
Java
package datastructures; import java.util.ArrayList; import LevelObjects.Field; public class FieldInState extends ObjectInState { public ArrayList<FieldBlockedChange> blockedTimeChangeIndexes; public FieldInState(Field f) { super(); this.f = f; blockedTimeChangeIndexes = new ArrayList<FieldBlockedChange>(); } public FieldInState(Field f, ArrayList<FieldBlockedChange> blockedTimeIndexes) { super(); this.f = f; this.blockedTimeChangeIndexes = blockedTimeIndexes; } public boolean changesStatusInFuture(int timeStep){ for (FieldBlockedChange blockedTime : blockedTimeChangeIndexes) { if (blockedTime.time >= timeStep && blockedTime.changeToBlocked == true) { return true; } } return false; } public boolean freeInInterval(int start, int end){ // System.err.println("Checking " + this.f.toString() + " intervals: " + start + "-" +end); // for (FieldBlockedChange fb : blockedTimeChangeIndexes) { // System.err.print(fb.time+ " "); // } boolean previous = false; for (FieldBlockedChange blockedTime : blockedTimeChangeIndexes) { if (blockedTime.time > start && blockedTime.time <= end) { // System.err.println("HEEER"); return false; } previous = blockedTime.changeToBlocked; if(blockedTime.time > end){ return !previous; } } return !previous; } }
Java
package datastructures; import java.util.ArrayList; import LevelObjects.Field; import client.Command; public abstract class ActionSequence { private ActionSequence parent; public ArrayList<Field> fields; public ActionSequence getParent() { return parent; } public void setParent(ActionSequence parent) { this.parent = parent; } protected ArrayList<Command> commands; public ArrayList<Command> getCommands() { return commands; } public void setCommands(ArrayList<Command> commands) { this.commands = commands; } }
Java
package datastructures; import LevelObjects.Agent; import LevelObjects.Field; public class AgentInState extends ObjectInState { public Agent a; public AgentInState(Agent a, Field f) { super(); this.a = a; this.f = f; } }
Java
package datastructures; import java.util.ArrayList; import client.Command; public class State implements Comparable<State> { public int g; public int f; public ArrayList<AgentInState> agents; public ArrayList<BoxInState> boxes; public ArrayList<FieldInState> fields; public State parent; public ArrayList<Command> commandFromParent; public int heuristicValue; public StateGoal goal; //Used for merging states. We know which step we are in, and all commands from this step should be used for merging. public int indexOfCommands; //Should be FOMA compatible public ArrayList<ActionSequence> actionSequencesFromParent; public State() { agents = new ArrayList<AgentInState>(); boxes = new ArrayList<BoxInState>(); fields = new ArrayList<FieldInState>(); commandFromParent = new ArrayList<Command>(); actionSequencesFromParent = new ArrayList<ActionSequence>(); } @Override public int compareTo(State o) { return this.heuristicValue - o.heuristicValue; } // public void printFieldChanges(){ // // for (FieldInState f : fields) { // System.err.print(f.f.toString()); // for (FieldBlockedChange fb : f.blockedTimeChangeIndexes) { // System.err.print(" " + fb.time + " " + fb.changeToBlocked); // } // System.err.println(); // } // // } }
Java
package datastructures; import LevelObjects.Box; import LevelObjects.Field; public class BoxInState extends ObjectInState { public Box b; public BoxInState(Box b, Field f) { super(); this.b = b; this.f = f; } }
Java
package datastructures; import LevelObjects.Field; public abstract class ObjectInState implements Comparable<ObjectInState> { public Field f; @Override public int compareTo(ObjectInState o) { if (this.f.x != o.f.y) { return this.f.x-o.f.x; } else{ return this.f.y-o.f.y; } } }
Java
package datastructures; import java.util.ArrayList; import LevelObjects.*; public class BoxCost { public Box box; public int cost; public ArrayList<GoalCost> goalCosts; public BoxCost() { goalCosts = new ArrayList<GoalCost>(); } }
Java
package datastructures; import LevelObjects.Field; public class StateGoal { public Field agentToPos; public Field boxToPos; public BoxInState box; public AgentInState agent; public boolean isMoveToBoxGoal; public boolean isClearPathGoal; public int nextGoalIndex; }
Java
package datastructures; import LevelObjects.Field; import client.Command; public class GoalSequenceNode implements Comparable<GoalSequenceNode> { public GoalSequenceNode parent; public Field boxLocation; public Field agentLocation; public Command action; public int timeStep; public int f; public int g; public GoalSequenceNode(Field boxLocation, Field agentLocation, Command action) { super(); this.boxLocation = boxLocation; this.agentLocation = agentLocation; this.action = action; } @Override public int compareTo(GoalSequenceNode arg0) { return this.f - arg0.f; } }
Java
package datastructures; import LevelObjects.*; public class GoalCost { public GoalCost(Goal goal, int cost) { this.cost = cost; this.goal = goal; } public Goal goal; public int cost; }
Java
package utils; public class Timer { private long _time; public volatile long time; public Timer() { time = 0; _time = System.currentTimeMillis(); } public void takeTime() { time = 0; _time = System.currentTimeMillis(); } public long stop() { time = System.currentTimeMillis() - _time; return time; } public int getElapsedTime() { return (int)(System.currentTimeMillis() - _time); } public void reset() { _time = System.currentTimeMillis(); time = 0; } public String toString() { int elapsed = getElapsedTime(); if (elapsed < 1000) return Integer.toString(elapsed) + " miliseconds"; else if (elapsed < 60000) { int seconds = elapsed/1000; int milis = (int)(elapsed % ((int)(elapsed/1000)*1000)); return Integer.toString(seconds) + "." + Integer.toString(milis) + " seconds"; } else { int minutes = elapsed/60000; int seconds = (int)((((double)elapsed)/60000.0f) % (int)(elapsed/60000)); return Integer.toString(minutes) + " minutes " + Integer.toString(seconds) + " seconds"; } } }
Java
package utils; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Queue; import LevelObjects.Field; public class BFS { public enum NodeColour { WHITE, GRAY, BLACK } private static class Node { int data; int distance; Field field; public Node(int data) { this.data = data; } public String toString() { return "(" + data + ",d=" + distance + ")"; } } Map<Node, List<Node>> nodes; private BFS() { nodes = new HashMap<Node, List<Node>>(); } public static int bfs(Field start_field, Field end_field) { ArrayList<String> fieldList = new ArrayList<String>(); Node start = new Node(0); start.distance = 0; start.field = start_field; fieldList.add(start.field.toString()); Queue<Node> q = new ArrayDeque<Node>(); q.add(start); while (!q.isEmpty()) { Node u = q.remove(); List<Node> adjacent_u = new ArrayList<Node>(); adjacent_u = getNeighbours(u, fieldList); if (adjacent_u != null) { for (Node v : adjacent_u) { if(v.field.x == end_field.x && v.field.y == end_field.y){ return u.distance + 1; } v.distance = u.distance + 1; q.add(v); // System.err.println("Field " + v.field + " added to path"); fieldList.add(v.field.toString()); } } } return -1; } public static int bfs(Field start_field, Field end_field, Field blocked_field) { ArrayList<String> fieldList = new ArrayList<String>(); Node start = new Node(0); Node blocked = new Node(0); start.distance = 0; start.field = start_field; blocked.field = blocked_field; fieldList.add(start.field.toString()); fieldList.add(blocked.field.toString()); Queue<Node> q = new ArrayDeque<Node>(); q.add(start); while (!q.isEmpty()) { Node u = q.remove(); List<Node> adjacent_u = new ArrayList<Node>(); adjacent_u = getNeighbours(u, fieldList); if (adjacent_u != null) { for (Node v : adjacent_u) { if(v.field.x == end_field.x && v.field.y == end_field.y){ return u.distance + 1; } v.distance = u.distance + 1; q.add(v); // System.err.println("Path found. Field " + v.field + " added to path"); fieldList.add(v.field.toString()); } } } return -1; } private static List<Node> getNeighbours(Node u, ArrayList<String> fieldList){ List<Node> adjacent_u = new ArrayList<Node>(); Node n = null; for (int i = 0; i < 4; i++) { if(u.field.neighbours[i] != null){ Field f = u.field.neighbours[i]; if(!fieldList.contains(f.toString())){ n = new Node(i); n.field = u.field.neighbours[i]; adjacent_u.add(n); } } } return adjacent_u; } }
Java
package utils; import java.util.ArrayList; import java.util.List; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Goal; import LevelObjects.Level; public class GoalPriority { /** * Goal prioritization. Checks to see for every goal, how many boxes and goals are disconnected, by placing this goal. * This function can be used at any time. * @param level * @param ignore_goals_completed, if you want to ignore completed goals. * @return a Goal array with the prioritized number in goal.getPriority() */ public static ArrayList<Goal> createGoalPrioritization(Level level, boolean ignore_goals_completed){ // tester(level); Timer t1 = new Timer(); t1.takeTime(); for (Goal goal : level.goals) { //ignore completed goals.. boolean ignore_goal = false; //only enter if completed goals should be ignored if(ignore_goals_completed){ ignore_goal = checkToSeeIfGoalIsOnBox(goal, level); } Timer t2 = new Timer(); t2.takeTime(); if(!(ignore_goal && ignore_goals_completed)){ //first look at fields north and south || east and west are walls or other blocking elements? goals? goals later //If so level has been disconnected //look and see if the disconnect is a problem. int count_free_neighbours = countAdjacentFields(goal); // System.err.println("Goal " + goal.getId() + " has adjacent free fields: " + count_free_neighbours); if(count_free_neighbours == 1){ //Goal only has one Neighbour and should have a low value in goal priority //Know further tests. This is highest priority! } else { List<Field> free_neighbours = getFreeNeighbours(goal); int disconnected_goals = 0; switch(count_free_neighbours){ case 2: goal.setPriority(goal.getPriority() + 1); //Goal only has two Neighbours and has a high posibility of breaking the map into to areas when box on goal //See if path it is possible to get from one neighbour to the other disconnected_goals = getDisconnectedGoalsFromBoxes(free_neighbours.get(0).getClone(), free_neighbours.get(1).getClone(), level, goal); goal.setPriority(goal.getPriority() + disconnected_goals); break; case 3: goal.setPriority(goal.getPriority() + 2); //See if path it is possible to get from one neighbour to the other. There are now 3 neighbours. 0,1,2 disconnected_goals = getDisconnectedGoalsFromBoxes(free_neighbours.get(0).getClone(), free_neighbours.get(1).getClone(), level, goal); disconnected_goals += getDisconnectedGoalsFromBoxes(free_neighbours.get(1).getClone(), free_neighbours.get(2).getClone(), level, goal); disconnected_goals += getDisconnectedGoalsFromBoxes(free_neighbours.get(0).getClone(), free_neighbours.get(2).getClone(), level, goal); goal.setPriority(goal.getPriority() + disconnected_goals); break; case 4: goal.setPriority(goal.getPriority() + 3); //See if path it is possible to get from one neighbour to the other. There are now 4 neighbours. 0,1,2,3 disconnected_goals = getDisconnectedGoalsFromBoxes(free_neighbours.get(0).getClone(), free_neighbours.get(1).getClone(), level, goal); disconnected_goals += getDisconnectedGoalsFromBoxes(free_neighbours.get(0).getClone(), free_neighbours.get(2).getClone(), level, goal); disconnected_goals += getDisconnectedGoalsFromBoxes(free_neighbours.get(0).getClone(), free_neighbours.get(3).getClone(), level, goal); disconnected_goals += getDisconnectedGoalsFromBoxes(free_neighbours.get(1).getClone(), free_neighbours.get(0).getClone(), level, goal); disconnected_goals += getDisconnectedGoalsFromBoxes(free_neighbours.get(1).getClone(), free_neighbours.get(2).getClone(), level, goal); disconnected_goals += getDisconnectedGoalsFromBoxes(free_neighbours.get(1).getClone(), free_neighbours.get(3).getClone(), level, goal); disconnected_goals += getDisconnectedGoalsFromBoxes(free_neighbours.get(2).getClone(), free_neighbours.get(0).getClone(), level, goal); disconnected_goals += getDisconnectedGoalsFromBoxes(free_neighbours.get(2).getClone(), free_neighbours.get(1).getClone(), level, goal); disconnected_goals += getDisconnectedGoalsFromBoxes(free_neighbours.get(2).getClone(), free_neighbours.get(3).getClone(), level, goal); goal.setPriority(goal.getPriority() + disconnected_goals); break; } } } t2.stop(); // System.err.println("Goal " + goal.getId() +" prioritized.. Time taken: " + t2.toString()); } t1.stop(); // System.err.println("Goals prioritized. Time taken: " + t1.toString()); return level.goals; } private static void tester(Level level){ System.err.println("----------TESTER-----------"); Agent agent = level.agents.get(0); System.err.println("----------testing distance-----------"); for (Goal goal : level.goals) { System.err.println("Agent " + agent.getId() + " is " + BFS.bfs(agent.getAtField(), goal.getClone()) + " from goal " + goal.getId()); } System.err.println("----------TESTER-----------"); Field f = new Field(6,3); for (Goal goal : level.goals) { System.err.println("Agent " + agent.getId() + " at " + agent.getAtField() + " is " + BFS.bfs(agent.getAtField(), goal.getClone(), f) + " from goal " + goal.getId() + " at " + goal.getClone() + ". Field " + f + " is blocked"); } System.err.println("---------------------"); } private static int countGoalDisconnectedFromBox(List<Box> boxes, List<Goal> goals, Goal current_goal){ int goals_disconnecting = 0; boolean box_found = false; for (Goal goal : goals) { if(goal != current_goal){ box_found = false; for (Box box : boxes) { if(box.getId() == goal.getId()){ if(BFS.bfs(box.getAtField(), goal.getClone(), current_goal.getClone()) != -1){ box_found = true; } } } if(!box_found){ goals_disconnecting++; } } } return goals_disconnecting; } // private static Goal isAgentDisconnectedFromGoal(Agent agent, List<Goal> goals, Goal current_goal){ // for (Goal goal : goals) { // if(goal != current_goal){ // if(BFS.bfs(agent.getAtField(), goal.getClone(), current_goal.getClone()) == -1){ // return goal; // } // } // } // return null; // } private static List<Field> getFreeNeighbours(Goal goal){ List<Field> free_neighbours = new ArrayList<Field>(); for (int i = 0; i < 4; i++) { if(goal.neighbours[i] != null) free_neighbours.add(goal.neighbours[i]); } return free_neighbours; } private static int countAdjacentFields(Goal goal){ int counter = 0; for (int i = 0; i < 4; i++) { if(goal.neighbours[i] != null) counter++; } return counter; } private static boolean checkToSeeIfGoalIsOnBox(Goal goal, Level level){ boolean ignoreGoal =false; for (Box box : level.boxes) { if(goal.getId() == box.getId()){ if(goal.x == box.getAtField().x && goal.y == box.getAtField().y){ ignoreGoal = true; } } } return ignoreGoal; } private static int getDisconnectedGoalsFromBoxes(Field free_neighbours1, Field free_neighbours2, Level level, Goal goal){ int disconnected_goals = 0; //See if the two neighbours 1 and 2 are disconnected with the middle field blocked. if(BFS.bfs(free_neighbours1, free_neighbours2, goal.getClone()) == -1){ //Okay, there is a disconnect.Now count goals disconnected from boxes with the same id. disconnected_goals = countGoalDisconnectedFromBox(level.boxes, level.goals, goal); goal.setPriority(goal.getPriority() + disconnected_goals); } return disconnected_goals; } /** * Finds the goal with the highest priority for the given agent * @param agent: we want to find best goal for * @param level: containing level.goals to search through * @returns Goal goal with the highest priority */ public static Goal FindGoalWithHighestPriority(Agent agent, Box box, Level level, ArrayList<Goal> goals_assigned) { char id = box.getId(); Goal candidate = null; for (Goal goal : level.goals) { if(!goals_assigned.contains(goal)){ if(goal.getId() == id){ if(candidate != null){ if(candidate.getPriority() > goal.getPriority()) candidate = goal; } else{ candidate = goal; } } } } return candidate; } // public static Goal FindGoalWithHighestPriority(Agent agent, Level level) { // //// for (Box box : level.boxes) { //// if (agent.possibleBoxesToGoals.containsKey(box) && Utils.boxFitsGoal(box, g)){ //// } // // // // char id = box.getId(); // Utils.findPossibleBoxes(level, agent); // // Goal candidate = null; // // for (Goal goal : level.goals) { // if(goal.getId() == id){ // if(candidate != null){ // if(candidate.getPriority() > goal.getPriority()) // candidate = goal; // } // else{ // candidate = goal; // } // } // } // // // // return candidate; // } }
Java
package utils; import constants.Constants.dir; import LevelObjects.Field; import client.Command; public class AStarField implements Comparable<AStarField> { public Field field; public int g; public int f; public int h; public Command c; public int timeStep; public AStarField(Field field) { this.field = field; } @Override public int compareTo(AStarField o) { return this.f - o.f; } public Field neighborTo(dir d) { return field.neighbours[d.ordinal()]; } }
Java
package utils; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.PriorityQueue; import java.util.Set; import constants.Constants; import constants.Constants.Color; import constants.Constants.dir; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Goal; import LevelObjects.Level; import client.Command; import datastructures.BoxCost; import datastructures.BoxInState; import datastructures.GoalActionSequence; import datastructures.GoalCost; import datastructures.GoalSequenceNode; import datastructures.MoveActionSequence; import datastructures.MoveBoxActionSequence; import datastructures.State; public class Utils { /** * * @param f The field * @param d The direction * @return true if the neighboring field in the direction is free */ public static boolean isNeighborFree(Field f, dir d){ return (f.neighbours[d.ordinal()] != null && f.neighbours[d.ordinal()].object == null); } /** * * @param l The level * @param from The field to travel from * @param to The field to travel to * @param blockedFields A list of fields inaccessible to the agent * @return a list of commands taking the agent from the from-field to the to-field */ public static MoveActionSequence findRoute(Level l, Field from, Field to, Collection<Field> blockedFields) { HashMap<AStarField, AStarField> cameFrom = new HashMap<AStarField, AStarField>(); PriorityQueue<AStarField> openSet = new PriorityQueue<AStarField>(); Set<Field> closedSet = new HashSet<Field>(); AStarField start = new AStarField(from); start.g = 0; start.f = start.g + heuristicEstimate(start.field, to, HeuristicType.MANHATTAN); openSet.add(start); AStarField curField = openSet.poll(); while (curField != null) { if (curField.field.equals(to)) break; closedSet.add(curField.field); int tentativeGScore = curField.g + 1; for (dir d : dir.values()) { Field neighbor = curField.neighborTo(d); if(blockedFields != null){ if ( neighbor == null || blockedFields.contains(neighbor) || closedSet.contains(neighbor)) continue; } else{ if ( neighbor == null || closedSet.contains(neighbor)) continue; } AStarField neighbourInOpenSet = null; for (AStarField aOpen : openSet) { if (aOpen.field == neighbor) neighbourInOpenSet = aOpen; } if (neighbourInOpenSet != null && tentativeGScore > neighbourInOpenSet.g) { continue; } else if (neighbourInOpenSet == null ){ neighbourInOpenSet = new AStarField(curField.neighborTo(d)); neighbourInOpenSet.g = tentativeGScore; neighbourInOpenSet.f = neighbourInOpenSet.g + heuristicEstimate(neighbourInOpenSet.field, to, HeuristicType.MANHATTAN); neighbourInOpenSet.c = new Command(d); cameFrom.put(neighbourInOpenSet, curField); openSet.add(neighbourInOpenSet); } } curField = openSet.poll(); } //If currentField is null, we didn't find a path. if (curField == null) return null; ArrayList<Command> commands = new ArrayList<Command>(); ArrayList<Field> fields = new ArrayList<Field>(); while (cameFrom.get(curField) != null) { fields.add(curField.field); commands.add(curField.c); curField = cameFrom.get(curField); } Collections.reverse(commands); Collections.reverse(fields); MoveActionSequence mas = new MoveActionSequence(from, to, commands); mas.fields = fields; return mas; } /** * * @param l The level * @param from The field to travel from * @param to The field to travel to * @param blockedFields A list of fields inaccessible to the agent * @return a list of commands taking the agent from the from-field to the to-field */ public static MoveActionSequence findRouteIgnoreObstacles(Level l, Agent agent, Field from, Field to, Collection<Field> blockedFields) { HashMap<AStarField, AStarField> cameFrom = new HashMap<AStarField, AStarField>(); HashSet<Field> ownBoxFields = new HashSet<Field>(); HashSet<Field> othersBoxFields = new HashSet<Field>(); for (Box b : l.boxes) { if (agent.getColor().equals(b.getColor())) ownBoxFields.add(b.getAtField()); else othersBoxFields.add(b.getAtField()); } PriorityQueue<AStarField> openSet = new PriorityQueue<AStarField>(); Set<Field> closedSet = new HashSet<Field>(); AStarField start = new AStarField(from); start.g = 0; start.f = start.g + heuristicEstimate(start.field, to, HeuristicType.MANHATTAN); openSet.add(start); AStarField curField = openSet.poll(); while (curField != null) { if (curField.field.equals(to)) break; closedSet.add(curField.field); int tentativeGScore = curField.g + 1; for (dir d : dir.values()) { Field neighbor = curField.neighborTo(d); if ( neighbor == null || (blockedFields != null && blockedFields.contains(neighbor)) || closedSet.contains(neighbor)) continue; AStarField neighbourInOpenSet = null; for (AStarField aOpen : openSet) { if (aOpen.field == neighbor) neighbourInOpenSet = aOpen; } if (neighbourInOpenSet != null) continue; neighbourInOpenSet = new AStarField(curField.neighborTo(d)); neighbourInOpenSet.g = tentativeGScore; if (ownBoxFields.contains(curField.field)) neighbourInOpenSet.g = tentativeGScore+50; else if (othersBoxFields.contains(curField.field)) neighbourInOpenSet.g = tentativeGScore+200; neighbourInOpenSet.f = neighbourInOpenSet.g + heuristicEstimate(neighbourInOpenSet.field, to, HeuristicType.MANHATTAN); neighbourInOpenSet.c = new Command(d); cameFrom.put(neighbourInOpenSet, curField); openSet.add(neighbourInOpenSet); } curField = openSet.poll(); } //If currentField is null, we didn't find a path. if (curField == null) return null; ArrayList<Command> commands = new ArrayList<Command>(); ArrayList<Field> fields = new ArrayList<Field>(); while (cameFrom.get(curField) != null) { fields.add(curField.field); commands.add(curField.c); //if (ownBoxFields.contains(curField.f)) curField = cameFrom.get(curField); } Collections.reverse(commands); Collections.reverse(fields); MoveActionSequence mas = new MoveActionSequence(from, to, commands); mas.fields = fields; return mas; } /** * * @param l The level * @param from The field to start from * @param to The field to get to * @return */ public static MoveActionSequence findRoute(Level l, Field from, Field to) { return findRoute(l, from, to, null); } public enum HeuristicType { EUCLID, MANHATTAN } public static int heuristicEstimate(Field a, Field goal, HeuristicType h) { switch (h) { case EUCLID: return heuristicEstimateEuclid(a, goal); case MANHATTAN: return heuristicEstimateManhattan(a, goal); default: return heuristicEstimateManhattan(a, goal); } } public static int heuristicEstimateEuclid(Field a, Field goal) { int h = (int) Math.sqrt(Math.pow(Math.abs(a.x - goal.x), 2) + Math.pow(Math.abs(a.y - goal.y), 2)); return h; } // Manhattan distance public static int heuristicEstimateManhattan(Field a, Field goal) { return Math.abs(a.x - goal.x) + Math.abs(a.y - goal.y); } public static boolean allGoalsHasBoxes(Level level) { int goalsFulfilled = 0; int totalGoals = level.goals.size(); for (Goal goal : level.goals) { for (Box box : level.boxes) { if (box.getAtField() == new Field(goal.x,goal.y) && Character.toLowerCase(box.getId()) == goal.getId()) { goalsFulfilled++; } } } if(goalsFulfilled == totalGoals) return true; else return false; } /** * checks if all goals has been fulfilled for the given agent * @param agent * @param level * @returns null if all goals are fulfilled, otherwise the goal with the highest priority */ public static Goal allOfAgentGoalsHasBoxes(Agent agent, Level level) { // Box current_box_color = a.possibleBoxesToGoals.keySet() int goalsFulfilled = 0; int totalBoxes = 0; Goal highestPriority = null; for (Goal goal : level.goals) { for (Box box : level.boxes) { if (agent.possibleBoxesToGoals.containsKey(box) && Utils.boxFitsGoal(box, goal)){ totalBoxes++; if (box.getAtField() == new Field(goal.x,goal.y) && Character.toLowerCase(box.getId()) == goal.getId()) { goalsFulfilled++; } else { if(highestPriority != null){ if(highestPriority.getPriority() > goal.getPriority()) highestPriority = goal; } else{ highestPriority = goal; } } } } } if(goalsFulfilled <= totalBoxes) return null; return highestPriority; } public static boolean GoalHasBox(Goal goal, Level level){ for (Box box : level.boxes) { if(boxFitsGoal(box, goal) && box.getAtField() == new Field(goal.x,goal.y)){ return true; } } return false; } public static MoveBoxActionSequence findEmptyFieldRoute(Level l, Agent a, Box b, Field freeField, Field agentFromField, Field agentToField, Field boxFromField, Collection<Field> blockedFields) { GoalActionSequence ga = findGoalRoute(l, a, b, agentFromField, agentToField, boxFromField, freeField, blockedFields); if (ga == null) return null; MoveBoxActionSequence mb = new MoveBoxActionSequence(); mb.setAgentLocation(ga.getAgentStartLocation()); mb.setBoxLocation(ga.getBoxStartLocation()); mb.setCommands(ga.getCommands()); mb.setTargetLocation(ga.getBoxEndLocation()); return mb; } public static Field getFreeField(Level l, Agent a, Box b, Field agentFromField, Field boxFromField, Collection<Field> blockedFields, int maxDepth, boolean includeGoalFields) { LinkedList<Field> openSet = new LinkedList<Field>(); HashSet<Field> closedSet = new HashSet<Field>(); Field current = boxFromField; Field candidate = current; int depth = 0; while (current != null && depth <= maxDepth) { candidate = current; closedSet.add(current); for (dir d : dir.values()) { Field neighbor = current.neighborTo(d); if ( neighbor != null && !blockedFields.contains(neighbor) && !closedSet.contains(neighbor) && (neighbor instanceof Goal && includeGoalFields)) openSet.add(neighbor); } current = openSet.poll(); } return candidate; } public static List<Field> getFreeFields(Field boxFromField, Collection<Field> blockedFields, int maxDepth, int maxReturnedFields, boolean includeGoalFields) { List<Field> l = getFreeFields(boxFromField, blockedFields, maxDepth, includeGoalFields); if (l.size()>maxReturnedFields) return l.subList(0, maxReturnedFields-1); return l; } public static ArrayList<Field> getFreeFields(Field boxFromField, Collection<Field> blockedFields, int maxDepth, boolean includeGoalFields) { LinkedList<Field> openSet = new LinkedList<Field>(); HashSet<Field> closedSet = new HashSet<Field>(); Field current = boxFromField; ArrayList<Field> candidates = new ArrayList<Field>(); candidates.add(current); int depth = 0; while (current != null && depth <= maxDepth) { closedSet.add(current); int count = 0; for (dir d : dir.values()) { Field neighbor = current.neighborTo(d); if ( neighbor != null && !blockedFields.contains(neighbor) && !closedSet.contains(neighbor) && (neighbor instanceof Goal && includeGoalFields)) { count++; openSet.add(neighbor); } } if (count==0) // a dead end is good! candidates.add(current); current = openSet.poll(); } return candidates; } public static Field getFirstFreeField(Field fromField, Collection<Field> escapeFromFields, Collection<Field> blockedFields, int maxDepth, boolean includeGoalFields) { LinkedList<Field> openSet = new LinkedList<Field>(); HashSet<Field> closedSet = new HashSet<Field>(); if (!escapeFromFields.contains(fromField)) escapeFromFields.add(fromField); Field current = fromField; int depth = 0; whileloop: while (current != null && depth <= maxDepth) { closedSet.add(current); for (dir d : dir.values()) { Field neighbor = current.neighborTo(d); if (neighbor == null) continue; if (!escapeFromFields.contains(neighbor)) { current = neighbor; break whileloop; } if ( escapeFromFields.contains(neighbor) && !closedSet.contains(neighbor) && !blockedFields.contains(neighbor) && (!(neighbor instanceof Goal) || includeGoalFields)) { openSet.add(neighbor); } } current = openSet.poll(); } return current; } public static Field getNthFreeField(Field fromField, Collection<Field> escapeFromFields, Collection<Field> blockedFields, int minDepth, int maxDepth, boolean includeGoalFields) { LinkedList<Field> openSet = new LinkedList<Field>(); HashSet<Field> closedSet = new HashSet<Field>(); if (!escapeFromFields.contains(fromField)) escapeFromFields.add(fromField); Field current = fromField; int depth = 0; whileloop: while (current != null && depth <= maxDepth) { closedSet.add(current); for (dir d : dir.values()) { Field neighbor = current.neighborTo(d); if (neighbor == null) continue; if(minDepth == 0 && !escapeFromFields.contains(current)){ break whileloop; } if (!escapeFromFields.contains(neighbor) && !closedSet.contains(neighbor) && !blockedFields.contains(neighbor)) { minDepth--; // current = neighbor; openSet.add(neighbor); } if ( escapeFromFields.contains(neighbor) && !closedSet.contains(neighbor) && !blockedFields.contains(neighbor) && (!(neighbor instanceof Goal) || includeGoalFields)) { openSet.add(neighbor); } } current = openSet.poll(); } return current; } // We know that the agent a has a box. Now we want to move the box to the // goal. public static GoalActionSequence findGoalRoute(Level l, Agent a, Box b, Field agentFromField, Field agentToField, Field boxFromField, Field boxToField, Collection<Field> blockedFields) { dir boxDir = null; GoalSequenceNode root = new GoalSequenceNode(boxFromField, agentFromField, null); PriorityQueue<GoalSequenceNode> queue = new PriorityQueue<GoalSequenceNode>(); // prune looped states (if agent and box ends up in a state already explored) HashMap<Field, ArrayList<Field>> closedSet = new HashMap<Field, ArrayList<Field>>(); //adding initial state to list set of explored states: ArrayList<Field> tempList = new ArrayList<Field>(); tempList.add(boxFromField); closedSet.put(agentFromField, tempList); int g = 0; root.g = g; root.f = root.g + heuristicEstimateManhattan(boxFromField, boxToField); //Add a closed set. queue.add(root); GoalSequenceNode currentNode = queue.poll(); while (currentNode != null && (currentNode.boxLocation != boxToField || currentNode.agentLocation != agentToField)) { boxDir = Agent.getBoxDirection(currentNode.agentLocation,currentNode.boxLocation); ArrayList<Command> foundCommands = addPossibleBoxCommandsForDirection(boxDir, currentNode.agentLocation, currentNode.boxLocation, blockedFields); for (Command command : foundCommands) { Field boxLocation = null; Field agentLocation = null; if (command.cmd.equals("Push")) { agentLocation = currentNode.boxLocation; boxLocation = currentNode.boxLocation.neighbours[command.dir2 .ordinal()]; } else { boxLocation = currentNode.agentLocation; agentLocation = currentNode.agentLocation.neighbours[command.dir1 .ordinal()]; } // Do we already have a way to get to this state? if (closedSet.containsKey(agentLocation)) { if (closedSet.get(agentLocation).contains(boxLocation)) continue; else // the agent has been here before but without the box in same location closedSet.get(agentLocation).add(boxLocation); } else { // neither the agent or the box has been here before. Update DS and create node in BTtree: ArrayList<Field> tempListe = new ArrayList<Field>(); tempListe.add(boxLocation); closedSet.put(agentLocation, tempListe); } GoalSequenceNode node = new GoalSequenceNode(boxLocation,agentLocation, command); node.parent = currentNode; node.g = node.parent.g+1; node.f = node.g + heuristicEstimateManhattan(boxLocation, boxToField); queue.add(node); } if (queue.isEmpty()) { //TODO: we have searched to the end without finding a solution. Move boxes to get access to goals return null; } currentNode = queue.poll(); } GoalActionSequence returnSequence = new GoalActionSequence(); returnSequence.setAgentStartLocation(currentNode.agentLocation); returnSequence.setBoxStartLocation(currentNode.boxLocation); ArrayList<Command> commands = new ArrayList<Command>(); while (currentNode.parent != null) { commands.add(currentNode.action); currentNode = currentNode.parent; } Collections.reverse(commands); returnSequence.setCommands(commands); return returnSequence; } public static ArrayList<Command> addPossibleBoxCommandsForDirection(dir direction, Field agentLocationInPlan, Field boxLocationInPlan, Collection<Field> blockedFields) { ArrayList<Command> possibleCommands = new ArrayList<Command>(); // Find possible pull commands for (dir d : dir.values()) { // we cannot pull a box forward in the box's direction if (d != direction && agentLocationInPlan.neighbours[d.ordinal()] != null && !blockedFields.contains(agentLocationInPlan.neighbours[d.ordinal()])) { possibleCommands.add(new Command("Pull", d, direction)); } } // Find possible push commands for (dir d : dir.values()) { // We cannot push a box backwards in the agents direction if (d != Constants.oppositeDir(direction) && boxLocationInPlan.neighbours[d.ordinal()] != null && !blockedFields.contains(boxLocationInPlan.neighbours[d.ordinal()])) { possibleCommands.add(new Command("Push", direction, d)); } } return possibleCommands; } public static boolean boxFitsGoal(Box b, Goal g){ return (g.getId() == Character.toLowerCase(b.getId())); } public static ArrayList<Box> getBoxesWithId(ArrayList<Box> boxes, char id) { ArrayList<Box> boxesWithId = new ArrayList<Box>(); for (Box b : boxes) if (b.getId() == id) boxesWithId.add(b); return boxesWithId; } public static ArrayList<Agent> getAgents( ArrayList<Agent> agents, Color color) { ArrayList<Agent> returnAgents = new ArrayList<Agent>(); for (Agent agent : agents) { if (agent.getColor() == color) { returnAgents.add(agent); } } return returnAgents; } public static boolean isFieldAvailable(Field f, ArrayList<Field> blockedFields) { for (Field field : blockedFields) { if (field == f) return false; } return true; } public static ArrayList<Box> getBoxesInLevel(ArrayList<Box> boxes, char id) { ArrayList<Box> boxesWithId = new ArrayList<Box>(); for (Box b : boxes) if (b.getId() == id) boxesWithId.add(b); return boxesWithId; } public static ArrayList<Field> findFreeField(Level level, ArrayList<Field> fields) { ArrayList<Field> returnFields = new ArrayList<Field>(); for (Field field : level.fields) { if(!fields.contains(field)) returnFields.add(field); } return returnFields; } public static ArrayList<Box> getBoxesWithColor(ArrayList<Box> boxes, Color color) { ArrayList<Box> returnBoxes = new ArrayList<Box>(); for (Box box : boxes) { if (box.getColor() == color) { returnBoxes.add(box); } } return returnBoxes; } public static ArrayList<Goal> getGoalsWithId(ArrayList<Goal> goals, char id) { ArrayList<Goal> returnGoals = new ArrayList<Goal>(); for (Goal goal : goals) { if (goal.getId() == id) { returnGoals.add(goal); } } return returnGoals; } /** * Calculates an a* like heuristic considering the traveled distance and the goal count * @param state * @param level * @return */ public static int CalculateStateHeuristic(State state, Level level) { int goalCountWeight = 5; int gScoreWeight = 1; int numberOfFulfilledGoals = 0; for (Goal g : level.goals) { for (BoxInState bPos : state.boxes) { if ( bPos.f == g && Character.toLowerCase(bPos.b.getId()) == g.getId()) { numberOfFulfilledGoals++; } } } int gScore = 0; // the g score is the cost of travelling here in terms of actionSequences (NOT actions) State parent = state; while(parent != null) { parent = parent.parent; gScore++; } return 1000 - (goalCountWeight*numberOfFulfilledGoals - gScoreWeight * gScore); } // public static BoxInState findBoxInCompletedState(State currentState, Box box) { // // BoxInState boxInState = currentState.goal.box; // // for (BoxInState b : currentState.boxes) { // if (b.b == boxInState.b && box == b.b) { // return new BoxInState(box, currentState.goal.boxToPos); // } else if (b.b == box) { // return b; // } // } // // return null; // } /** * Testing to if an agent can reach its boxes * @param level * @param agent * @param boxes * @return BoxInState it can reach */ public static HashMap<Box, BoxCost> findPossibleBoxes(Level level, Agent agent){ HashMap<Box, BoxCost> possibleBoxes = new HashMap<Box, BoxCost>(); for (Box box : level.boxes) { if(agent.getColor() == box.getColor()) { int cost = Utils.findRouteCostIgnoreBoxes(level, agent, agent.getAtField(), box.getAtField(), null); if (cost==-1) continue; if (possibleBoxes.containsKey(box)) { BoxCost bc = possibleBoxes.get(box); bc.box = box; bc.cost = cost; } else { BoxCost bc = new BoxCost(); bc.box = box; bc.cost = cost; possibleBoxes.put(box, bc); } } } if(possibleBoxes.isEmpty()) return possibleBoxes; for (Box box : possibleBoxes.keySet()) { for (Goal goal : level.goals) { if(!boxFitsGoal(box, goal)) continue; int cost = findRouteCostIgnoreBoxes(level, agent, box.getAtField(), (Field)goal, null)-50; //the box itself costs 50 if (cost==-1) continue; possibleBoxes.get(box).goalCosts.add(new GoalCost(goal, cost)); } } return possibleBoxes; } /** * * @param l The level * @param from The field to travel from * @param to The field to travel to * @param blockedFields A list of fields inaccessible to the agent * @return The cost of getting to the field. -1 if no route */ public static int findRouteCostIgnoreBoxes(Level l, Agent a, Field from, Field to, Collection<Field> blockedFields) { int cost = -1; HashMap<AStarField, AStarField> cameFrom = new HashMap<AStarField, AStarField>(); PriorityQueue<AStarField> openSet = new PriorityQueue<AStarField>(); HashSet<AStarField> openSetCopy = new HashSet<AStarField>(); Set<Field> closedSet = new HashSet<Field>(); HashSet<Field> ownBoxFields = new HashSet<Field>(); HashSet<Field> othersBoxFields = new HashSet<Field>(); for (Box b : l.boxes) { if (a.getColor().equals(b.getColor())) ownBoxFields.add(b.getAtField()); else othersBoxFields.add(b.getAtField()); } AStarField start = new AStarField(from); start.g = 0; start.f = start.g + heuristicEstimate(start.field, to, HeuristicType.MANHATTAN); openSet.add(start); openSetCopy.add(start); AStarField curField; while (true) { curField = openSet.poll(); // Are we there yet? if (curField.field.equals(to) || curField == null) break; openSetCopy.remove(curField); closedSet.add(curField.field); int gScore = curField.g + 1; for (dir d : dir.values()) { Field neighbor = curField.neighborTo(d); if (neighbor == null || (blockedFields != null && blockedFields.contains(neighbor)) || closedSet.contains(neighbor)) continue; // Is the neighbor already in the open set? As of uniform cost it can not be possible to find a faster route to it if (openSetCopy.contains(neighbor)) continue; // AStarField neighbourInOpenSet = null; // At some point test if it is faster to use this approach in stead of double openSet. // for (AStarField aOpen : openSet) { // if (aOpen.field == neighbor) continue; // } AStarField neighbourField = new AStarField(curField.neighborTo(d)); neighbourField.g = gScore; if (ownBoxFields.contains(curField.field)) neighbourField.g = gScore+50; else if (othersBoxFields.contains(curField.field)) neighbourField.g = gScore+200; neighbourField.f = neighbourField.g + heuristicEstimate(neighbourField.field, to, HeuristicType.MANHATTAN); neighbourField.c = new Command(d); cameFrom.put(neighbourField, curField); openSet.add(neighbourField); openSetCopy.add(neighbourField); } } if (curField != null) { cost = curField.f; } return cost; } public static ArrayList<Box> findRouteCountBoxesInTheWay(Level l, Agent a, Field from, Field to, Collection<Field> blockedFields) { ArrayList<Box> boxesInTheWay = null; HashMap<AStarField, AStarField> cameFrom = new HashMap<AStarField, AStarField>(); PriorityQueue<AStarField> openSet = new PriorityQueue<AStarField>(); HashSet<AStarField> openSetCopy = new HashSet<AStarField>(); Set<Field> closedSet = new HashSet<Field>(); HashSet<Field> ownBoxFields = new HashSet<Field>(); HashSet<Field> othersBoxFields = new HashSet<Field>(); for (Box b : l.boxes) { if (a.getColor().equals(b.getColor())) ownBoxFields.add(b.getAtField()); else othersBoxFields.add(b.getAtField()); } AStarField start = new AStarField(from); start.g = 0; start.f = start.g + heuristicEstimate(start.field, to, HeuristicType.MANHATTAN); openSet.add(start); openSetCopy.add(start); AStarField curField; boxesInTheWay = new ArrayList<Box>(); while (true) { curField = openSet.poll(); // Are we there yet? if (curField == null || curField.field.equals(to)) break; openSetCopy.remove(curField); closedSet.add(curField.field); int gScore = curField.g + 1; for (dir d : dir.values()) { Field neighbor = curField.neighborTo(d); if (neighbor == null || (blockedFields != null && blockedFields.contains(neighbor)) || closedSet.contains(neighbor)) continue; // Is the neighbor already in the open set? As of uniform cost it can not be possible to find a faster route to it if (openSetCopy.contains(neighbor)) continue; AStarField neighbourField = new AStarField(curField.neighborTo(d)); neighbourField.g = gScore; if (ownBoxFields.contains(curField.field)){ for (Box box : l.boxes) { if(box.getAtField() == curField.field) boxesInTheWay.add(box); } } else if (othersBoxFields.contains(curField.field)){ for (Box box : l.boxes) { if(box.getAtField() == curField.field) boxesInTheWay.add(box); } } neighbourField.f = neighbourField.g + heuristicEstimate(neighbourField.field, to, HeuristicType.MANHATTAN); neighbourField.c = new Command(d); cameFrom.put(neighbourField, curField); openSet.add(neighbourField); openSetCopy.add(neighbourField); } } return boxesInTheWay; } public static List<Field> getEscapeFieldsFromCommands(Agent a, Collection<Command> commandsNotCompleted) { ArrayList<Field> escapeFields = new ArrayList<Field>(); Field current = a.getAtField(); escapeFields.add(current); for (Command c : commandsNotCompleted) { if (c.cmd.equals("Move") || c.cmd.equals("Pull")) { current = current.neighbours[c.dir1.ordinal()]; } else if (c.cmd.equals("Push")) { current = current.neighbours[c.dir1.ordinal()]; } else if(c.cmd.equals("NoOp")){ continue; } if (current == null) continue; escapeFields.add(current); } return escapeFields; } /** * Checks if an agent was at this location last turn. this can happen on FOMA since actions are synchronous * @param level * @param field * @return */ public static boolean CheckIfAnAgentWasOnThisFieldLastTurn(Level level, Field field){ for (Agent agent : level.agents) { if(agent.lastLocation == field) return true; } return false; } public static Box FindBoxForAgent(Agent agent, Level level) { for (Box box : level.boxes) { if(box.getId() == agent.getId()){ return box; } } return null; } public static ArrayList<Box> OwnBoxesInTheWay(Agent agent, ArrayList<Box> boxes) { ArrayList<Box> ownBoxesInTheWay = new ArrayList<Box>(); ArrayList<Box> ownBoxesInTheWayChangeOrder = new ArrayList<Box>(); for (Box box : boxes) { if(box.getColor().equals(agent.getColor())) ownBoxesInTheWay.add(box); else break; } while(!ownBoxesInTheWay.isEmpty()){ ownBoxesInTheWayChangeOrder.add(ownBoxesInTheWay.remove(ownBoxesInTheWay.size()-1)); } return ownBoxesInTheWayChangeOrder; } public static boolean isNeighbor(Field atField, Field atField2) { for (Field nabo : atField.neighbours) { if(nabo != null && nabo.equals(atField2)) return true; } return false; } public static ArrayList<Box> changeOrderInTheArrayList(ArrayList<Box> ownBoxesInTheWay) { ArrayList<Box> tempOwnBoxesInTheWay = new ArrayList<Box>(); while(!ownBoxesInTheWay.isEmpty()){ tempOwnBoxesInTheWay.add(ownBoxesInTheWay.remove(ownBoxesInTheWay.size()-1)); } return tempOwnBoxesInTheWay; } public static Box getClosedBoxForGoal(Goal goal, Level level, HashMap<Box, BoxCost> keySet, ArrayList<Box> ignore_boxes) { Box candidate = null; int cost = 0; BoxCost boxCost; Iterator<Box> keySetIterator = keySet.keySet().iterator(); while(keySetIterator.hasNext()){ Box key = keySetIterator.next(); if(key == null || ignore_boxes.contains(key)) continue; boxCost = keySet.get(key); if(boxCost != null){ if(cost == 0) cost = boxCost.cost; if(boxCost.cost <= cost){ cost = boxCost.cost; candidate = boxCost.box; } } } return candidate; } }
Java
package utils; import java.util.ArrayList; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Level; public class Communication { /** * find agent to move a given box that might be in the way for another agent * @param box * @param level * @return */ public static Agent FindAgentToMoveBox(Box box, Level level){ for (Agent candidate_agent : level.agents) { if(box.getColor() == candidate_agent.getColor()) return candidate_agent; } return null; } public static boolean isObsticalStillInTheWay(Agent agent, Object obstacle, ArrayList<Field> avoidFields){ if(obstacle instanceof Agent){ Agent agent_obstical = (Agent) obstacle; for (Field field : avoidFields) { if(agent_obstical.getAtField().equals(field)) return true; } } else if(obstacle instanceof Box){ Box box_obstical = (Box) obstacle; for (Field field : avoidFields) { if(box_obstical.getAtField().equals(field)) return true; } } return false; } }
Java
package utils; import java.util.ArrayList; import java.util.Collection; import java.util.List; import constants.Constants.dir; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Level; import client.Command; import datastructures.ActionSequence; import datastructures.GoalActionSequence; import datastructures.MoveActionSequence; import datastructures.State; public class Moves { public static List<Field> getEscapeFieldsFromCommands(Agent a, Collection<Command> commandsNotCompleted) { ArrayList<Field> escapeFields = new ArrayList<Field>(); Field current = a.getAtField(); escapeFields.add(current); for (Command c : commandsNotCompleted) { if (c.cmd.equals("Move") || c.cmd.equals("Pull")) { current = current.neighbours[c.dir1.ordinal()]; } else if (c.cmd.equals("Push")) { current = current.neighbours[c.dir2.ordinal()]; } if (current == null) break; escapeFields.add(current); } return escapeFields; } public static void MoveABoxToLocation(Agent agent, Box box, Field newLocation, Level level){ GoalActionSequence routeToGoal; // if this is not possible due to box in the way call: //reinsert the objective ArrayList<Field> blockedFields = new ArrayList<Field>(); blockedFields.add(box.getAtField()); for (Agent tempAgent : level.agents) { if(agent != tempAgent && agent.isNooping) blockedFields.add(agent.getAtField()); } for (Box tempBox : level.boxes) { if(!tempBox.equals(box)) blockedFields.add(tempBox.getAtField()); } State newState = null; boxLoop: for (dir d : dir.values()) { Field neighbor = box.getAtField().neighborTo(d); if(neighbor == null) continue; MoveActionSequence moveAction = Utils.findRouteIgnoreObstacles(level, agent, agent.getAtField(), neighbor, blockedFields); if (moveAction == null) continue; //Here we have decided that we can get to a box. Now we must check if the box can get to a goal. //Because we are now moving the box, it's field is free. blockedFields.remove(box.getAtField()); for (dir goalNeighbourDir : dir.values()) { Field goalNeighbor = newLocation.neighbours[goalNeighbourDir.ordinal()]; if (goalNeighbor == null) continue; routeToGoal = Utils.findGoalRoute(level, agent, box, box.getAtField().neighbours[d.ordinal()], goalNeighbor, box.getAtField(), newLocation, blockedFields); if (routeToGoal != null) { newState = new State(); newState.actionSequencesFromParent.add(moveAction); newState.actionSequencesFromParent.add(routeToGoal); break boxLoop; } } blockedFields.add(box.getAtField()); } for (ActionSequence actionSequence : newState.actionSequencesFromParent) { for (Command command : actionSequence.getCommands()) { agent.commandQueue.add(command); } } } }
Java
package LevelObjects; import constants.Constants.Color; public class Box implements Comparable<Box> { private char id; // stored as lowercase so we can easily compare with goals private Color color; private Field atField; public Box(char id, Color color, Field atField) { this.id = Character.toLowerCase(id); this.color = color==null ? Color.blue : color; this.atField = atField; } // Getter / Setters public Field getAtField() { return atField; } public void setAtField(Field atField) { this.atField = atField; } public char getId() { return id; } public Color getColor() { return color; } @Override public int compareTo(Box o) { if (this.atField.x != o.atField.y) { return this.atField.x-o.atField.x; } else{ return this.atField.y-o.atField.y; } } }
Java
package LevelObjects; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.Queue; import java.util.Random; import agent.objectives.*; import agent.planners.AgentPlanner; import utils.Communication; import utils.Moves; import utils.Utils; import constants.Constants; import constants.Constants.Color; import constants.Constants.dir; import client.Command; import client.Desire; import datastructures.*; public class Agent { private static Random rand = new Random(); // del? private char id; public int number; private Color color; private Field atField; public HashMap<Box, BoxCost> possibleBoxesToGoals = new HashMap<Box, BoxCost>(); public Queue<ActionSequence> actions; public LinkedList<Objective> objectives = new LinkedList<Objective>(); public AgentPlanner planner; public boolean isNooping = false; public int priority; public Queue<Command> commandQueue; public Queue<Command> commandsNotCompleted; public Field lastLocation; public Desire desire; public Objective tempObjective; public Object obstacle; public boolean isTheCauseOfAConflict = false; private Conflict conflict; public Agent(char id, Color color, Field atField) { this.id = id; this.color = color==null ? Color.blue : color; this.atField = atField; this.commandQueue = new LinkedList<Command>(); this.commandsNotCompleted = new LinkedList<Command>(); } public Agent(char id, Color color, Field atField, AgentPlanner planner) { this(id, color, atField); this.planner = planner; } /** * Convert objective to commands and fill them in the commandqueue */ public void planAndExecute(Level level) { isNooping = false; Objective temp_o = this.objectives.peek(); if(temp_o instanceof GoalABox){ GoalABox gab = (GoalABox)temp_o; if(gab.goal.hasBox(level)){ this.objectives.remove(); } } // Check if previous action failed if (obstacle != null) { if (obstacle instanceof Agent) { Agent other = (Agent)obstacle; if (this.priority <= other.priority) { other.commandQueue.clear(); ArrayList<Field> list = new ArrayList<Field>(); list.add(this.getAtField()); other.objectives.addFirst(new Move(Utils.getEscapeFieldsFromCommands(this, commandsNotCompleted), list ,50)); other.obstacle = null; Command c; while ((c = commandsNotCompleted.poll()) != null) commandQueue.add(c); this.objectives.removeFirst(); } else this.commandsNotCompleted.clear(); } else if( obstacle instanceof Box) { //A box is in the way. find which box Box otherBox = (Box)obstacle; if(otherBox.getColor() == this.getColor()){ //Agent can move this box himself ArrayList<Field> blockedFields = new ArrayList<Field>(); ArrayList<Box> boxesInTheWay = new ArrayList<Box>(); ArrayList<Box> ownBoxesInTheWay = new ArrayList<Box>(); // getNthFreeField() java.util.List<Field> fieldsToAvoid = Utils.getEscapeFieldsFromCommands(this, commandsNotCompleted); Field field_from = null; Field field_to = null; Objective o = this.objectives.peekFirst(); if(o instanceof GoalABox){ field_from = ((GoalABox) o).box.getAtField(); field_to = new Field(((GoalABox) o).goal.x, ((GoalABox) o).goal.y); } for (Box b : level.boxes) { if(fieldsToAvoid.contains(b.getAtField())){ boxesInTheWay.add(b); } blockedFields.add(b.getAtField()); } ownBoxesInTheWay = Utils.OwnBoxesInTheWay(this, boxesInTheWay); if(Utils.isNeighbor(ownBoxesInTheWay.get(0).getAtField(), this.getAtField())){ //Change order ownBoxesInTheWay = Utils.changeOrderInTheArrayList(ownBoxesInTheWay); } if(ownBoxesInTheWay.size() > 31){ LinkedList<Objective> currentObj = new LinkedList<Objective>(); int currentBoxesInTheWay = boxesInTheWay.size(); LinkedList<Box> currentBox = new LinkedList<Box>(); currentBox.addAll(ownBoxesInTheWay); while(!currentBox.isEmpty()){ Box box = currentBox.poll(); if(box == null) continue; currentBoxesInTheWay--; Objective newObjective = new DockABox(new Field(3, 6), box, fieldsToAvoid, blockedFields, boxesInTheWay.size() - currentBoxesInTheWay, 15); currentObj.addFirst(newObjective); } while(!currentObj.isEmpty()){ Objective objective = currentObj.pollLast(); this.objectives.addFirst(objective); } // for (Box box : ownBoxesInTheWay) { // // Objective newObjective = new DockABox(new Field(3, 6), box, fieldsToAvoid, blockedFields, currentBoxesInTheWay, 15); // // currentObj.addFirst(newObjective); // currentBoxesInTheWay--; // if(currentBoxesInTheWay == 0) // break; // } // for (Objective objective : currentObj) { // this.objectives.addFirst(objective); // } } else { Objective newObjective = new DockABox(new Field(3, 6), otherBox, fieldsToAvoid, blockedFields, boxesInTheWay.size(), 15); this.objectives.addFirst(newObjective); } } else { //Find an agent to move the box Agent otherAgent = Communication.FindAgentToMoveBox(otherBox, level); if (this.id<otherAgent.id || otherAgent.commandQueue.isEmpty()) { ArrayList<Field> fieldsToAvoid = new ArrayList<Field>(); fieldsToAvoid.addAll(Moves.getEscapeFieldsFromCommands(this, commandsNotCompleted)); otherAgent.conflict = new Conflict(this, fieldsToAvoid, obstacle, otherBox, this.priority); } } this.commandsNotCompleted.clear(); } obstacle = null; return; } // if(this.conflict != null && this.conflict.isPriority() < this.id){ //Another agent has a conflict with this agent if(this.conflict != null && this.conflict.isPriority() <= this.priority){ if(this.conflict.getObstacle() instanceof Box) { //A box is in the way. find which box //Agent has to move the box for another agent Box box = this.conflict.getMoveaBox(); //Get to box if(this.objectives.getFirst() instanceof Move){ //Find a route for the agent and the box. this.commandQueue.clear(); ArrayList<Field> candidates = new ArrayList<Field>(); candidates = Utils.getFreeFields(box.getAtField(),this.conflict.getAvoidFields(),15,false); // Queue<Command> commandQueue = null; differentEndLocations: for (Field field : candidates) { Moves.MoveABoxToLocation(this, box, field, level); } } else if(this.objectives.getFirst() instanceof GoalABox){ //Find a route for the agent and the box. this.commandQueue.clear(); ArrayList<Field> blockedFields = new ArrayList<Field>(); blockedFields.add(this.conflict.getHelpAgent().getAtField()); Field candidates; candidates = Utils.getFirstFreeField(box.getAtField(), this.conflict.getAvoidFields(), (Collection<Field>) blockedFields, 25, true); Moves.MoveABoxToLocation(this, box, candidates, level); } else { //Other agent not doing anything - get to the box and move it.. this.commandQueue.clear(); ArrayList<Field> blockedFields = new ArrayList<Field>(); blockedFields.add(this.conflict.getHelpAgent().getAtField()); for (Box current_box : level.boxes) { blockedFields.add(current_box.getAtField()); } Field candidates; this.conflict.avoidFields.addAll(blockedFields); candidates = Utils.getFirstFreeField(box.getAtField(), this.conflict.getAvoidFields(), (Collection<Field>) blockedFields, 25, true); Moves.MoveABoxToLocation(this, box, candidates, level); } } this.conflict = null; } if(!this.commandQueue.isEmpty()){ return; } Objective o = objectives.peek(); if (o==null){ if(!objectives.isEmpty()){ objectives.remove(); } return; } boolean successful = false; if (o instanceof GoalABox) { GoalABox gab = (GoalABox)o; if(Utils.GoalHasBox(gab.goal, level)){ successful = true; } else { successful = planner.goalABox(this, gab.box, gab.goal); } } else if (o instanceof Move) { Move mv = (Move)o; successful = planner.move(this, mv.escapeFromFields, mv.blockedFields, mv.numberOfRounds); } else if (o instanceof DockABox) { DockABox dab = (DockABox)o; successful = planner.dock(this, dab.box, dab.field, dab.fieldsToAvoid , dab.blockedFields, dab.moveTheBoxFieldsFurther, dab.numberOfRounds); } else if (o instanceof Move) { Wait mv = (Wait)o; successful = planner.wait(this, mv.numberOfRounds); } if (successful) this.tempObjective = objectives.removeFirst(); } public Field getAtField() { return atField; } public void setAtField(Field atField) { this.atField = atField; } public char getId() { return id; } public Color getColor() { return color; } // Only used by random walk clients. public Command act() { ArrayList<Command> possibleCommands = new ArrayList<Command>(); for (dir d : dir.values()) { randomWalkAddPossibleCommandsForDirection(d, possibleCommands); } if (possibleCommands.size() == 0) possibleCommands.add(new Command(dir.N)); //Dummy command return possibleCommands.get(rand.nextInt(possibleCommands.size())); } private void randomWalkAddPossibleCommandsForDirection(dir direction, ArrayList<Command> possibleCommands){ if (neighbourFree(this.atField,direction)) { possibleCommands.add(new Command(direction)); } else if (neighbourIsBoxOfSameColor(direction)) { //Find possible pull commands for (dir d : dir.values()) { //we cannot pull a box forward in the box's direction if (d != direction && neighbourFree(this.atField,d)){ possibleCommands.add(new Command("Pull",d,direction)); } } //Find possible push commands for (dir d : dir.values()) { //We cannot push a box backwards in the agents direction if (d != Constants.oppositeDir(direction) && neighbourFree(this.getAtField().neighbours[direction.ordinal()],d)){ possibleCommands.add(new Command("Push",direction,d)); } } } } public ArrayList<Command> addPossibleCommandsForDirection(dir direction, Field agentLocationInPlan, Field boxLocationInPlan) { ArrayList<Command> possibleCommands = new ArrayList<Command>(); /* Commented because we are not interested in move commands at current time. if (neighbourFreeInPlan(agentLocationInPlan, direction, boxLocationInPlan) && this.desire.goal == null) { possibleCommands.add(new Command(direction)); }*/ // Find possible pull commands for (dir d : dir.values()) { // we cannot pull a box forward in the box's direction if (d != direction && neighbourFreeInPlan(agentLocationInPlan, d)) { possibleCommands.add(new Command("Pull", d, direction)); } } // Find possible push commands for (dir d : dir.values()) { // We cannot push a box backwards in the agents direction if (d != Constants.oppositeDir(direction) && neighbourFreeInPlan(boxLocationInPlan,d)) { possibleCommands.add(new Command("Push", direction, d)); } } return possibleCommands; } public boolean neighbourFree(Field f, dir d){ //System.err.println(f); return (f.neighbours[d.ordinal()] != null && f.neighbours[d.ordinal()].object == null); } //Checks if neighbour is free in the plan. public boolean neighbourFreeInPlan(Field posInPlan, dir d){ if (neighbourFree(posInPlan, d)) { return true; } //If the neighbour is free in actual state then everything is good. If it is not, we need to check if //it is free in the plan, by checking if the neighbour is the agent's or the box's location. else if(posInPlan.neighbours[d.ordinal()] != null && (posInPlan.neighbours[d.ordinal()] == this.getAtField() || (this.desire != null && posInPlan.neighbours[d.ordinal()] == this.desire.box.getAtField()))){ return true; } return false; } private boolean neighbourIsBoxOfSameColor(dir d){ return (this.getAtField().neighbours[d.ordinal()] != null && this.getAtField().neighbours[d.ordinal()].object instanceof Box && ((Box) this.getAtField().neighbours[d.ordinal()].object).getColor() == this.color); } //Find the box's direction, relative to the agent, if they are on adjacent fields. public static dir getBoxDirection(Field agentField, Field boxField){ if (boxField == null) return null; for (dir d : dir.values()) { if (agentField.neighbours[d.ordinal()] != null && agentField.neighbours[d.ordinal()] == boxField) { return d; } } return null; } }
Java
package LevelObjects; import java.util.ArrayList; public class Level { public ArrayList<Agent> agents = new ArrayList<Agent>(); public ArrayList<Box> boxes = new ArrayList<Box>(); public ArrayList<Field> fields = new ArrayList<Field>(); public ArrayList<Goal> goals = new ArrayList<Goal>(); public Field[][] fieldMap; public Field[][] getFieldMap() { return fieldMap; } public void setFieldMap(Field[][] field_map) { this.fieldMap = field_map; } }
Java
package LevelObjects; import java.util.Comparator; import constants.Constants.dir; public class Field implements Comparator<Field> { // Order of directions. /*public static enum dir { N, W, E, S };*/ // Example: neighbours[Constants.Constants.dir.N] public Field[] neighbours = new Field[4]; public int x; //Increases from left to right. public int y; //Increases downwards public Object object; //Can be null (free), or box or agent. public Object getObject() { return object; } public void setObject(Object object) { this.object = object; } public Field(int x, int y){ this.x = x; this.y = y; this.object = null; } public Field(int x, int y, Object object){ this.x = x; this.y = y; this.object = object; } public Field neighborTo(dir d) { return neighbours[d.ordinal()]; } public boolean isNeighborFree(dir d){ return (neighbours[d.ordinal()] != null && neighbours[d.ordinal()].object == null); } @Override public int compare(Field arg0, Field arg1) { if (arg0.x==arg1.x && arg0.y == arg1.y) return 0; else return (Math.abs(arg0.x-arg1.x) + Math.abs(arg0.y-arg1.y)); } @Override public String toString(){ return "" + this.x + "." + this.y; } public Field getClone(){ return new Field(this.x, this.y); } }
Java
package LevelObjects; import java.util.ArrayList; public class Conflict { private Agent helpAgent; private Object obstacle; private Box moveaBox; private int priority; public ArrayList<Field> avoidFields = new ArrayList<Field>(); public Conflict(Agent helpAgent, ArrayList<Field> avoidFields, Object obstacle) { super(); this.helpAgent = helpAgent; this.avoidFields = avoidFields; this.obstacle = obstacle; } public Conflict(Agent helpAgent, ArrayList<Field> avoidFields, Object obstacle, Box moveaBox) { super(); this.helpAgent = helpAgent; this.obstacle = obstacle; this.avoidFields = avoidFields; this.moveaBox = moveaBox; } public Conflict(Agent helpAgent, ArrayList<Field> avoidFields, Object obstacle, Box moveaBox, int priority) { super(); this.helpAgent = helpAgent; this.obstacle = obstacle; this.avoidFields = avoidFields; this.moveaBox = moveaBox; this.priority = priority; } public Agent getHelpAgent() { return helpAgent; } public void setHelpAgent(Agent helpAgent) { this.helpAgent = helpAgent; } public Box getMoveaBox() { return moveaBox; } public void setMoveaBox(Box moveaBox) { this.moveaBox = moveaBox; } public int isPriority() { return priority; } public void setPriority(int priority) { this.priority = priority; } public ArrayList<Field> getAvoidFields() { return avoidFields; } public void setAvoidFields(ArrayList<Field> avoidFields) { this.avoidFields = avoidFields; } public Object getObstacle() { return obstacle; } public void setObstacle(Object obstacle) { this.obstacle = obstacle; } }
Java
package LevelObjects; public class Goal extends Field implements Comparable<Goal> { private char id; public int priority; public char getId() { return id; } public int getPriority() { return priority; } public void setPriority(int priority){ this.priority = priority; } public Goal(char id, int x, int y) { super(x, y); this.id = id; } public Goal(char id, int x, int y, Object object) { super(x, y, object); this.id = id; } @Override public int compareTo(Goal arg0) { return this.priority - arg0.priority; } public Goal(char id, int x, int y, Object object, int priority) { super(x, y, object); this.id = id; this.priority = priority; } public boolean hasBox(Level level){ for (Box box : level.boxes) { if(box.getAtField() == new Field(this.x, this.y)) return true; } return false; } }
Java